@linemap/studio 0.0.0-stage → 0.2.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +373 -0
- package/README.md +37 -2
- package/dist/linemap.html +1329 -0
- package/index.mjs +33 -0
- package/package.json +42 -3
- package/serve.mjs +90 -0
|
@@ -0,0 +1,1329 @@
|
|
|
1
|
+
<!doctype html>
|
|
2
|
+
<html lang="en">
|
|
3
|
+
<!--
|
|
4
|
+
linemap studio, © 2026 Michael Karlen. linemap is free software under the Mozilla Public License 2.0:
|
|
5
|
+
|
|
6
|
+
==============================================================================
|
|
7
|
+
|
|
8
|
+
Mozilla Public License Version 2.0
|
|
9
|
+
==================================
|
|
10
|
+
|
|
11
|
+
1. Definitions
|
|
12
|
+
--------------
|
|
13
|
+
|
|
14
|
+
1.1. "Contributor"
|
|
15
|
+
means each individual or legal entity that creates, contributes to
|
|
16
|
+
the creation of, or owns Covered Software.
|
|
17
|
+
|
|
18
|
+
1.2. "Contributor Version"
|
|
19
|
+
means the combination of the Contributions of others (if any) used
|
|
20
|
+
by a Contributor and that particular Contributor's Contribution.
|
|
21
|
+
|
|
22
|
+
1.3. "Contribution"
|
|
23
|
+
means Covered Software of a particular Contributor.
|
|
24
|
+
|
|
25
|
+
1.4. "Covered Software"
|
|
26
|
+
means Source Code Form to which the initial Contributor has attached
|
|
27
|
+
the notice in Exhibit A, the Executable Form of such Source Code
|
|
28
|
+
Form, and Modifications of such Source Code Form, in each case
|
|
29
|
+
including portions thereof.
|
|
30
|
+
|
|
31
|
+
1.5. "Incompatible With Secondary Licenses"
|
|
32
|
+
means
|
|
33
|
+
|
|
34
|
+
(a) that the initial Contributor has attached the notice described
|
|
35
|
+
in Exhibit B to the Covered Software; or
|
|
36
|
+
|
|
37
|
+
(b) that the Covered Software was made available under the terms of
|
|
38
|
+
version 1.1 or earlier of the License, but not also under the
|
|
39
|
+
terms of a Secondary License.
|
|
40
|
+
|
|
41
|
+
1.6. "Executable Form"
|
|
42
|
+
means any form of the work other than Source Code Form.
|
|
43
|
+
|
|
44
|
+
1.7. "Larger Work"
|
|
45
|
+
means a work that combines Covered Software with other material, in
|
|
46
|
+
a separate file or files, that is not Covered Software.
|
|
47
|
+
|
|
48
|
+
1.8. "License"
|
|
49
|
+
means this document.
|
|
50
|
+
|
|
51
|
+
1.9. "Licensable"
|
|
52
|
+
means having the right to grant, to the maximum extent possible,
|
|
53
|
+
whether at the time of the initial grant or subsequently, any and
|
|
54
|
+
all of the rights conveyed by this License.
|
|
55
|
+
|
|
56
|
+
1.10. "Modifications"
|
|
57
|
+
means any of the following:
|
|
58
|
+
|
|
59
|
+
(a) any file in Source Code Form that results from an addition to,
|
|
60
|
+
deletion from, or modification of the contents of Covered
|
|
61
|
+
Software; or
|
|
62
|
+
|
|
63
|
+
(b) any new file in Source Code Form that contains any Covered
|
|
64
|
+
Software.
|
|
65
|
+
|
|
66
|
+
1.11. "Patent Claims" of a Contributor
|
|
67
|
+
means any patent claim(s), including without limitation, method,
|
|
68
|
+
process, and apparatus claims, in any patent Licensable by such
|
|
69
|
+
Contributor that would be infringed, but for the grant of the
|
|
70
|
+
License, by the making, using, selling, offering for sale, having
|
|
71
|
+
made, import, or transfer of either its Contributions or its
|
|
72
|
+
Contributor Version.
|
|
73
|
+
|
|
74
|
+
1.12. "Secondary License"
|
|
75
|
+
means either the GNU General Public License, Version 2.0, the GNU
|
|
76
|
+
Lesser General Public License, Version 2.1, the GNU Affero General
|
|
77
|
+
Public License, Version 3.0, or any later versions of those
|
|
78
|
+
licenses.
|
|
79
|
+
|
|
80
|
+
1.13. "Source Code Form"
|
|
81
|
+
means the form of the work preferred for making modifications.
|
|
82
|
+
|
|
83
|
+
1.14. "You" (or "Your")
|
|
84
|
+
means an individual or a legal entity exercising rights under this
|
|
85
|
+
License. For legal entities, "You" includes any entity that
|
|
86
|
+
controls, is controlled by, or is under common control with You. For
|
|
87
|
+
purposes of this definition, "control" means (a) the power, direct
|
|
88
|
+
or indirect, to cause the direction or management of such entity,
|
|
89
|
+
whether by contract or otherwise, or (b) ownership of more than
|
|
90
|
+
fifty percent (50%) of the outstanding shares or beneficial
|
|
91
|
+
ownership of such entity.
|
|
92
|
+
|
|
93
|
+
2. License Grants and Conditions
|
|
94
|
+
--------------------------------
|
|
95
|
+
|
|
96
|
+
2.1. Grants
|
|
97
|
+
|
|
98
|
+
Each Contributor hereby grants You a world-wide, royalty-free,
|
|
99
|
+
non-exclusive license:
|
|
100
|
+
|
|
101
|
+
(a) under intellectual property rights (other than patent or trademark)
|
|
102
|
+
Licensable by such Contributor to use, reproduce, make available,
|
|
103
|
+
modify, display, perform, distribute, and otherwise exploit its
|
|
104
|
+
Contributions, either on an unmodified basis, with Modifications, or
|
|
105
|
+
as part of a Larger Work; and
|
|
106
|
+
|
|
107
|
+
(b) under Patent Claims of such Contributor to make, use, sell, offer
|
|
108
|
+
for sale, have made, import, and otherwise transfer either its
|
|
109
|
+
Contributions or its Contributor Version.
|
|
110
|
+
|
|
111
|
+
2.2. Effective Date
|
|
112
|
+
|
|
113
|
+
The licenses granted in Section 2.1 with respect to any Contribution
|
|
114
|
+
become effective for each Contribution on the date the Contributor first
|
|
115
|
+
distributes such Contribution.
|
|
116
|
+
|
|
117
|
+
2.3. Limitations on Grant Scope
|
|
118
|
+
|
|
119
|
+
The licenses granted in this Section 2 are the only rights granted under
|
|
120
|
+
this License. No additional rights or licenses will be implied from the
|
|
121
|
+
distribution or licensing of Covered Software under this License.
|
|
122
|
+
Notwithstanding Section 2.1(b) above, no patent license is granted by a
|
|
123
|
+
Contributor:
|
|
124
|
+
|
|
125
|
+
(a) for any code that a Contributor has removed from Covered Software;
|
|
126
|
+
or
|
|
127
|
+
|
|
128
|
+
(b) for infringements caused by: (i) Your and any other third party's
|
|
129
|
+
modifications of Covered Software, or (ii) the combination of its
|
|
130
|
+
Contributions with other software (except as part of its Contributor
|
|
131
|
+
Version); or
|
|
132
|
+
|
|
133
|
+
(c) under Patent Claims infringed by Covered Software in the absence of
|
|
134
|
+
its Contributions.
|
|
135
|
+
|
|
136
|
+
This License does not grant any rights in the trademarks, service marks,
|
|
137
|
+
or logos of any Contributor (except as may be necessary to comply with
|
|
138
|
+
the notice requirements in Section 3.4).
|
|
139
|
+
|
|
140
|
+
2.4. Subsequent Licenses
|
|
141
|
+
|
|
142
|
+
No Contributor makes additional grants as a result of Your choice to
|
|
143
|
+
distribute the Covered Software under a subsequent version of this
|
|
144
|
+
License (see Section 10.2) or under the terms of a Secondary License (if
|
|
145
|
+
permitted under the terms of Section 3.3).
|
|
146
|
+
|
|
147
|
+
2.5. Representation
|
|
148
|
+
|
|
149
|
+
Each Contributor represents that the Contributor believes its
|
|
150
|
+
Contributions are its original creation(s) or it has sufficient rights
|
|
151
|
+
to grant the rights to its Contributions conveyed by this License.
|
|
152
|
+
|
|
153
|
+
2.6. Fair Use
|
|
154
|
+
|
|
155
|
+
This License is not intended to limit any rights You have under
|
|
156
|
+
applicable copyright doctrines of fair use, fair dealing, or other
|
|
157
|
+
equivalents.
|
|
158
|
+
|
|
159
|
+
2.7. Conditions
|
|
160
|
+
|
|
161
|
+
Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted
|
|
162
|
+
in Section 2.1.
|
|
163
|
+
|
|
164
|
+
3. Responsibilities
|
|
165
|
+
-------------------
|
|
166
|
+
|
|
167
|
+
3.1. Distribution of Source Form
|
|
168
|
+
|
|
169
|
+
All distribution of Covered Software in Source Code Form, including any
|
|
170
|
+
Modifications that You create or to which You contribute, must be under
|
|
171
|
+
the terms of this License. You must inform recipients that the Source
|
|
172
|
+
Code Form of the Covered Software is governed by the terms of this
|
|
173
|
+
License, and how they can obtain a copy of this License. You may not
|
|
174
|
+
attempt to alter or restrict the recipients' rights in the Source Code
|
|
175
|
+
Form.
|
|
176
|
+
|
|
177
|
+
3.2. Distribution of Executable Form
|
|
178
|
+
|
|
179
|
+
If You distribute Covered Software in Executable Form then:
|
|
180
|
+
|
|
181
|
+
(a) such Covered Software must also be made available in Source Code
|
|
182
|
+
Form, as described in Section 3.1, and You must inform recipients of
|
|
183
|
+
the Executable Form how they can obtain a copy of such Source Code
|
|
184
|
+
Form by reasonable means in a timely manner, at a charge no more
|
|
185
|
+
than the cost of distribution to the recipient; and
|
|
186
|
+
|
|
187
|
+
(b) You may distribute such Executable Form under the terms of this
|
|
188
|
+
License, or sublicense it under different terms, provided that the
|
|
189
|
+
license for the Executable Form does not attempt to limit or alter
|
|
190
|
+
the recipients' rights in the Source Code Form under this License.
|
|
191
|
+
|
|
192
|
+
3.3. Distribution of a Larger Work
|
|
193
|
+
|
|
194
|
+
You may create and distribute a Larger Work under terms of Your choice,
|
|
195
|
+
provided that You also comply with the requirements of this License for
|
|
196
|
+
the Covered Software. If the Larger Work is a combination of Covered
|
|
197
|
+
Software with a work governed by one or more Secondary Licenses, and the
|
|
198
|
+
Covered Software is not Incompatible With Secondary Licenses, this
|
|
199
|
+
License permits You to additionally distribute such Covered Software
|
|
200
|
+
under the terms of such Secondary License(s), so that the recipient of
|
|
201
|
+
the Larger Work may, at their option, further distribute the Covered
|
|
202
|
+
Software under the terms of either this License or such Secondary
|
|
203
|
+
License(s).
|
|
204
|
+
|
|
205
|
+
3.4. Notices
|
|
206
|
+
|
|
207
|
+
You may not remove or alter the substance of any license notices
|
|
208
|
+
(including copyright notices, patent notices, disclaimers of warranty,
|
|
209
|
+
or limitations of liability) contained within the Source Code Form of
|
|
210
|
+
the Covered Software, except that You may alter any license notices to
|
|
211
|
+
the extent required to remedy known factual inaccuracies.
|
|
212
|
+
|
|
213
|
+
3.5. Application of Additional Terms
|
|
214
|
+
|
|
215
|
+
You may choose to offer, and to charge a fee for, warranty, support,
|
|
216
|
+
indemnity or liability obligations to one or more recipients of Covered
|
|
217
|
+
Software. However, You may do so only on Your own behalf, and not on
|
|
218
|
+
behalf of any Contributor. You must make it absolutely clear that any
|
|
219
|
+
such warranty, support, indemnity, or liability obligation is offered by
|
|
220
|
+
You alone, and You hereby agree to indemnify every Contributor for any
|
|
221
|
+
liability incurred by such Contributor as a result of warranty, support,
|
|
222
|
+
indemnity or liability terms You offer. You may include additional
|
|
223
|
+
disclaimers of warranty and limitations of liability specific to any
|
|
224
|
+
jurisdiction.
|
|
225
|
+
|
|
226
|
+
4. Inability to Comply Due to Statute or Regulation
|
|
227
|
+
---------------------------------------------------
|
|
228
|
+
|
|
229
|
+
If it is impossible for You to comply with any of the terms of this
|
|
230
|
+
License with respect to some or all of the Covered Software due to
|
|
231
|
+
statute, judicial order, or regulation then You must: (a) comply with
|
|
232
|
+
the terms of this License to the maximum extent possible; and (b)
|
|
233
|
+
describe the limitations and the code they affect. Such description must
|
|
234
|
+
be placed in a text file included with all distributions of the Covered
|
|
235
|
+
Software under this License. Except to the extent prohibited by statute
|
|
236
|
+
or regulation, such description must be sufficiently detailed for a
|
|
237
|
+
recipient of ordinary skill to be able to understand it.
|
|
238
|
+
|
|
239
|
+
5. Termination
|
|
240
|
+
--------------
|
|
241
|
+
|
|
242
|
+
5.1. The rights granted under this License will terminate automatically
|
|
243
|
+
if You fail to comply with any of its terms. However, if You become
|
|
244
|
+
compliant, then the rights granted under this License from a particular
|
|
245
|
+
Contributor are reinstated (a) provisionally, unless and until such
|
|
246
|
+
Contributor explicitly and finally terminates Your grants, and (b) on an
|
|
247
|
+
ongoing basis, if such Contributor fails to notify You of the
|
|
248
|
+
non-compliance by some reasonable means prior to 60 days after You have
|
|
249
|
+
come back into compliance. Moreover, Your grants from a particular
|
|
250
|
+
Contributor are reinstated on an ongoing basis if such Contributor
|
|
251
|
+
notifies You of the non-compliance by some reasonable means, this is the
|
|
252
|
+
first time You have received notice of non-compliance with this License
|
|
253
|
+
from such Contributor, and You become compliant prior to 30 days after
|
|
254
|
+
Your receipt of the notice.
|
|
255
|
+
|
|
256
|
+
5.2. If You initiate litigation against any entity by asserting a patent
|
|
257
|
+
infringement claim (excluding declaratory judgment actions,
|
|
258
|
+
counter-claims, and cross-claims) alleging that a Contributor Version
|
|
259
|
+
directly or indirectly infringes any patent, then the rights granted to
|
|
260
|
+
You by any and all Contributors for the Covered Software under Section
|
|
261
|
+
2.1 of this License shall terminate.
|
|
262
|
+
|
|
263
|
+
5.3. In the event of termination under Sections 5.1 or 5.2 above, all
|
|
264
|
+
end user license agreements (excluding distributors and resellers) which
|
|
265
|
+
have been validly granted by You or Your distributors under this License
|
|
266
|
+
prior to termination shall survive termination.
|
|
267
|
+
|
|
268
|
+
************************************************************************
|
|
269
|
+
* *
|
|
270
|
+
* 6. Disclaimer of Warranty *
|
|
271
|
+
* ------------------------- *
|
|
272
|
+
* *
|
|
273
|
+
* Covered Software is provided under this License on an "as is" *
|
|
274
|
+
* basis, without warranty of any kind, either expressed, implied, or *
|
|
275
|
+
* statutory, including, without limitation, warranties that the *
|
|
276
|
+
* Covered Software is free of defects, merchantable, fit for a *
|
|
277
|
+
* particular purpose or non-infringing. The entire risk as to the *
|
|
278
|
+
* quality and performance of the Covered Software is with You. *
|
|
279
|
+
* Should any Covered Software prove defective in any respect, You *
|
|
280
|
+
* (not any Contributor) assume the cost of any necessary servicing, *
|
|
281
|
+
* repair, or correction. This disclaimer of warranty constitutes an *
|
|
282
|
+
* essential part of this License. No use of any Covered Software is *
|
|
283
|
+
* authorized under this License except under this disclaimer. *
|
|
284
|
+
* *
|
|
285
|
+
************************************************************************
|
|
286
|
+
|
|
287
|
+
************************************************************************
|
|
288
|
+
* *
|
|
289
|
+
* 7. Limitation of Liability *
|
|
290
|
+
* -------------------------- *
|
|
291
|
+
* *
|
|
292
|
+
* Under no circumstances and under no legal theory, whether tort *
|
|
293
|
+
* (including negligence), contract, or otherwise, shall any *
|
|
294
|
+
* Contributor, or anyone who distributes Covered Software as *
|
|
295
|
+
* permitted above, be liable to You for any direct, indirect, *
|
|
296
|
+
* special, incidental, or consequential damages of any character *
|
|
297
|
+
* including, without limitation, damages for lost profits, loss of *
|
|
298
|
+
* goodwill, work stoppage, computer failure or malfunction, or any *
|
|
299
|
+
* and all other commercial damages or losses, even if such party *
|
|
300
|
+
* shall have been informed of the possibility of such damages. This *
|
|
301
|
+
* limitation of liability shall not apply to liability for death or *
|
|
302
|
+
* personal injury resulting from such party's negligence to the *
|
|
303
|
+
* extent applicable law prohibits such limitation. Some *
|
|
304
|
+
* jurisdictions do not allow the exclusion or limitation of *
|
|
305
|
+
* incidental or consequential damages, so this exclusion and *
|
|
306
|
+
* limitation may not apply to You. *
|
|
307
|
+
* *
|
|
308
|
+
************************************************************************
|
|
309
|
+
|
|
310
|
+
8. Litigation
|
|
311
|
+
-------------
|
|
312
|
+
|
|
313
|
+
Any litigation relating to this License may be brought only in the
|
|
314
|
+
courts of a jurisdiction where the defendant maintains its principal
|
|
315
|
+
place of business and such litigation shall be governed by laws of that
|
|
316
|
+
jurisdiction, without reference to its conflict-of-law provisions.
|
|
317
|
+
Nothing in this Section shall prevent a party's ability to bring
|
|
318
|
+
cross-claims or counter-claims.
|
|
319
|
+
|
|
320
|
+
9. Miscellaneous
|
|
321
|
+
----------------
|
|
322
|
+
|
|
323
|
+
This License represents the complete agreement concerning the subject
|
|
324
|
+
matter hereof. If any provision of this License is held to be
|
|
325
|
+
unenforceable, such provision shall be reformed only to the extent
|
|
326
|
+
necessary to make it enforceable. Any law or regulation which provides
|
|
327
|
+
that the language of a contract shall be construed against the drafter
|
|
328
|
+
shall not be used to construe this License against a Contributor.
|
|
329
|
+
|
|
330
|
+
10. Versions of the License
|
|
331
|
+
---------------------------
|
|
332
|
+
|
|
333
|
+
10.1. New Versions
|
|
334
|
+
|
|
335
|
+
Mozilla Foundation is the license steward. Except as provided in Section
|
|
336
|
+
10.3, no one other than the license steward has the right to modify or
|
|
337
|
+
publish new versions of this License. Each version will be given a
|
|
338
|
+
distinguishing version number.
|
|
339
|
+
|
|
340
|
+
10.2. Effect of New Versions
|
|
341
|
+
|
|
342
|
+
You may distribute the Covered Software under the terms of the version
|
|
343
|
+
of the License under which You originally received the Covered Software,
|
|
344
|
+
or under the terms of any subsequent version published by the license
|
|
345
|
+
steward.
|
|
346
|
+
|
|
347
|
+
10.3. Modified Versions
|
|
348
|
+
|
|
349
|
+
If you create software not governed by this License, and you want to
|
|
350
|
+
create a new license for such software, you may create and use a
|
|
351
|
+
modified version of this License if you rename the license and remove
|
|
352
|
+
any references to the name of the license steward (except to note that
|
|
353
|
+
such modified license differs from this License).
|
|
354
|
+
|
|
355
|
+
10.4. Distributing Source Code Form that is Incompatible With Secondary
|
|
356
|
+
Licenses
|
|
357
|
+
|
|
358
|
+
If You choose to distribute Source Code Form that is Incompatible With
|
|
359
|
+
Secondary Licenses under the terms of this version of the License, the
|
|
360
|
+
notice described in Exhibit B of this License must be attached.
|
|
361
|
+
|
|
362
|
+
Exhibit A - Source Code Form License Notice
|
|
363
|
+
-------------------------------------------
|
|
364
|
+
|
|
365
|
+
This Source Code Form is subject to the terms of the Mozilla Public
|
|
366
|
+
License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
367
|
+
file, You can obtain one at http://mozilla.org/MPL/2.0/.
|
|
368
|
+
|
|
369
|
+
If it is not possible or desirable to put the notice in a particular
|
|
370
|
+
file, then You may include the notice in a location (such as a LICENSE
|
|
371
|
+
file in a relevant directory) where a recipient would be likely to look
|
|
372
|
+
for such a notice.
|
|
373
|
+
|
|
374
|
+
You may add additional accurate notices of copyright ownership.
|
|
375
|
+
|
|
376
|
+
Exhibit B - "Incompatible With Secondary Licenses" Notice
|
|
377
|
+
---------------------------------------------------------
|
|
378
|
+
|
|
379
|
+
This Source Code Form is "Incompatible With Secondary Licenses", as
|
|
380
|
+
defined by the Mozilla Public License, v. 2.0.
|
|
381
|
+
|
|
382
|
+
==============================================================================
|
|
383
|
+
|
|
384
|
+
This file contains parts of MSAGL (Microsoft Automatic Graph Layout, MIT) and its
|
|
385
|
+
dependencies; their license texts are in the /*! ... */ comment in the script below.
|
|
386
|
+
-->
|
|
387
|
+
<head>
|
|
388
|
+
<meta charset="utf-8">
|
|
389
|
+
<meta name="viewport" content="width=device-width, initial-scale=1">
|
|
390
|
+
<title>linemap studio</title>
|
|
391
|
+
<link rel="icon" type="image/svg+xml" href="data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZpZXdCb3g9IjAgMCAxMjggMTI4IiB3aWR0aD0iMTI4IiBoZWlnaHQ9IjEyOCI+CiAgPHRpdGxlPmxpbmVtYXA8L3RpdGxlPgogIDxkZWZzPgogICAgPHBhdGggaWQ9ImdyZWVuIiBkPSJNNTYgNCBWNDggQTI4IDI4IDAgMCAwIDg0IDc2IEgxMjQiLz4KICAgIDxwYXRoIGlkPSJibHVlIiBkPSJNNDQgNCBWNDggQTQwIDQwIDAgMCAwIDg0IDg4IEgxMjQiLz4KICA8L2RlZnM+CiAgPCEtLSB0aGUgbmVvbiB0aGVtZSdzIHRyYXZlbGxpbmcgYXJyb3dzOiBvbmUgcnVucyBkb3duIGVhY2ggbGluZSBpbiB0dXJuLCBtYWdlbnRhLCBibHVlLCBsaW1lLCB0aGVuCiAgICAgICBhbGwgcmVzdCAxMCBzIGJlZm9yZSB0aGUgbmV4dCByb3VuZCAoYSBydW4gaXMgMC4yNyBzLCB0aGV5IHN0YXJ0IDAuMyBzIGFwYXJ0KS4KICAgICAgIEVhY2ggaXMgZHJhd24gYXQgdGhlIG9yaWdpbiBwb2ludGluZyByaWdodCBhbmQgcHV0IG9uIGl0cyBsaW5lIGJ5IGEgbW90aW9uIHBhdGg7IGl0IHdhaXRzCiAgICAgICBoaWRkZW4gdW50aWwgaXRzIHR1cm4uIFdpdGhvdXQgbW90aW9uIHBhdGhzLCBvciB3aXRoIHJlZHVjZWQgbW90aW9uLCB0aGV5IHN0YXkgaGlkZGVuLiAtLT4KICA8c3R5bGU+CiAgICAuYXJyb3cgeyBmaWxsOiAjZmZmOyBvcGFjaXR5OiAwOyB9CiAgICBAc3VwcG9ydHMgKG9mZnNldC1wYXRoOiBwYXRoKCdNMCwwJykpIHsKICAgICAgLmFycm93IHsgb2Zmc2V0LXJvdGF0ZTogYXV0bzsgYW5pbWF0aW9uOiBydW4gMTAuODdzIGxpbmVhciBpbmZpbml0ZSBiYWNrd2FyZHM7IH0KICAgICAgLmExIHsgb2Zmc2V0LXBhdGg6IHBhdGgoJ003MiA0IFYxMjQnKTsgfQogICAgICAuYTIgeyBvZmZzZXQtcGF0aDogcGF0aCgnTTU2IDQgVjQ4IEEyOCAyOCAwIDAgMCA4NCA3NiBIMTI0Jyk7IGFuaW1hdGlvbi1kZWxheTogMC4zczsgfQogICAgICAuYTMgeyBvZmZzZXQtcGF0aDogcGF0aCgnTTQ0IDQgVjQ4IEE0MCA0MCAwIDAgMCA4NCA4OCBIMTI0Jyk7IGFuaW1hdGlvbi1kZWxheTogMC42czsgfQogICAgfQogICAgLmEzIHsgZmlsbDogIzAwMDsgfSAvKiB3aGl0ZSBoYXJkbHkgc2hvd3Mgb24gbGltZSAqLwogICAgQGtleWZyYW1lcyBydW4gewogICAgICAwJSB7IG9mZnNldC1kaXN0YW5jZTogMCU7IG9wYWNpdHk6IDA7IH0KICAgICAgMC4zMyUgeyBvcGFjaXR5OiAwLjk1OyB9CiAgICAgIDIuMTUlIHsgb3BhY2l0eTogMC45NTsgfQogICAgICAyLjQ4JSwgMTAwJSB7IG9mZnNldC1kaXN0YW5jZTogMTAwJTsgb3BhY2l0eTogMDsgfQogICAgfQogICAgQG1lZGlhIChwcmVmZXJzLXJlZHVjZWQtbW90aW9uOiByZWR1Y2UpIHsgLmFycm93IHsgYW5pbWF0aW9uOiBub25lOyB9IH0KICA8L3N0eWxlPgogIDwhLS0gb3JhbmdlIHJ1bnMgdW5kZXIgZ3JlZW4gYW5kIGJsdWU6IHRoZXkgY3V0IGl0LCA0IHB4IHdpZGVyIHRoYW4gdGhlbXNlbHZlcyBvbiBlYWNoIHNpZGUgLS0+CiAgPG1hc2sgaWQ9InVuZGVyIiBtYXNrVW5pdHM9InVzZXJTcGFjZU9uVXNlIiB4PSIwIiB5PSIwIiB3aWR0aD0iMTI4IiBoZWlnaHQ9IjEyOCI+CiAgICA8cmVjdCB3aWR0aD0iMTI4IiBoZWlnaHQ9IjEyOCIgZmlsbD0iI2ZmZiIvPgogICAgPGcgZmlsbD0ibm9uZSIgc3Ryb2tlPSIjMDAwIiBzdHJva2Utd2lkdGg9IjIwIj48dXNlIGhyZWY9IiNncmVlbiIvPjx1c2UgaHJlZj0iI2JsdWUiLz48L2c+CiAgPC9tYXNrPgogIDxnIGZpbGw9Im5vbmUiIHN0cm9rZS13aWR0aD0iMTIiPgogICAgPGcgbWFzaz0idXJsKCN1bmRlcikiPgogICAgICA8cGF0aCBkPSJNNzIgNCBWMTI0IiBzdHJva2U9IiNmZjAwZDQiLz4KICAgICAgPHBvbHlnb24gY2xhc3M9ImFycm93IGExIiBwb2ludHM9IjcsMCAtNywtNC41IC03LDQuNSIgc3Ryb2tlPSJub25lIi8+CiAgICA8L2c+CiAgICA8dXNlIGhyZWY9IiNncmVlbiIgc3Ryb2tlPSIjM2Q1YWZlIi8+CiAgICA8cG9seWdvbiBjbGFzcz0iYXJyb3cgYTIiIHBvaW50cz0iNywwIC03LC00LjUgLTcsNC41IiBzdHJva2U9Im5vbmUiLz4KICAgIDx1c2UgaHJlZj0iI2JsdWUiIHN0cm9rZT0iI2M2ZmYwMCIvPgogICAgPHBvbHlnb24gY2xhc3M9ImFycm93IGEzIiBwb2ludHM9IjcsMCAtNywtNC41IC03LDQuNSIgc3Ryb2tlPSJub25lIi8+CiAgPC9nPgo8L3N2Zz4K">
|
|
392
|
+
<style>:root {
|
|
393
|
+
--bg: #eceef1;
|
|
394
|
+
--panel: #ffffff;
|
|
395
|
+
--ink: #232a33;
|
|
396
|
+
--muted: #68717c;
|
|
397
|
+
--faint: #9aa2ab;
|
|
398
|
+
--line: #e1e4e8;
|
|
399
|
+
--hover: #f1f3f5;
|
|
400
|
+
--press: #e8eef9;
|
|
401
|
+
--accent: #2f64c8;
|
|
402
|
+
--danger: #b3261e;
|
|
403
|
+
--radius: 8px;
|
|
404
|
+
--shadow: 0 1px 2px rgba(20, 30, 45, .06), 0 4px 16px rgba(20, 30, 45, .08);
|
|
405
|
+
--shadow-lg: 0 2px 6px rgba(20, 30, 45, .08), 0 12px 40px rgba(20, 30, 45, .16);
|
|
406
|
+
--tb-h: 44px;
|
|
407
|
+
--map-bg: #ffffff;
|
|
408
|
+
--sheet-edge: #d9dde2;
|
|
409
|
+
--tb-bg: rgba(255, 255, 255, .96);
|
|
410
|
+
--seg-bg: #eef0f3;
|
|
411
|
+
--seg-on: #ffffff;
|
|
412
|
+
--field: #f7f8fa;
|
|
413
|
+
font-family: system-ui, -apple-system, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif;
|
|
414
|
+
font-size: 13px;
|
|
415
|
+
color: var(--ink);
|
|
416
|
+
}
|
|
417
|
+
* { box-sizing: border-box; }
|
|
418
|
+
html, body { margin: 0; height: 100%; overflow: hidden; background: var(--bg); }
|
|
419
|
+
body { color: var(--ink); } /* again on body, so body.ui-dark's colours reach every control */
|
|
420
|
+
button, input, textarea { font: inherit; color: inherit; }
|
|
421
|
+
[hidden] { display: none !important; }
|
|
422
|
+
kbd {
|
|
423
|
+
font: 11px/1 ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
|
|
424
|
+
padding: 2px 5px; border: 1px solid var(--line); border-bottom-width: 2px; border-radius: 4px;
|
|
425
|
+
background: #fafbfc; color: var(--muted);
|
|
426
|
+
}
|
|
427
|
+
code { font: 12px ui-monospace, SFMono-Regular, Menlo, Consolas, monospace; background: var(--hover); padding: 1px 4px; border-radius: 4px; }
|
|
428
|
+
|
|
429
|
+
/* ---------- buttons ---------- */
|
|
430
|
+
.btn {
|
|
431
|
+
display: inline-flex; align-items: center; gap: 6px;
|
|
432
|
+
height: 30px; padding: 0 9px; border: 0; border-radius: 6px;
|
|
433
|
+
background: transparent; cursor: pointer; white-space: nowrap;
|
|
434
|
+
transition: background-color .12s, color .12s;
|
|
435
|
+
}
|
|
436
|
+
.btn:hover { background: var(--hover); }
|
|
437
|
+
.btn:active { background: var(--press); }
|
|
438
|
+
.btn:focus-visible, .seg button:focus-visible, .link:focus-visible { outline: 2px solid var(--accent); outline-offset: 1px; }
|
|
439
|
+
.btn[aria-pressed="true"] { background: var(--press); color: var(--accent); }
|
|
440
|
+
.btn.primary { background: var(--accent); color: #fff; }
|
|
441
|
+
.btn.primary:hover { background: #2858b2; }
|
|
442
|
+
.btn:disabled { opacity: .4; cursor: default; background: transparent; }
|
|
443
|
+
.icon { width: 16px; height: 16px; flex: none; fill: none; stroke: currentColor; stroke-width: 1.5; stroke-linecap: round; stroke-linejoin: round; }
|
|
444
|
+
.icon.small { width: 14px; height: 14px; color: var(--faint); }
|
|
445
|
+
.link { border: 0; background: none; padding: 0; color: var(--accent); cursor: pointer; }
|
|
446
|
+
.link:hover { text-decoration: underline; }
|
|
447
|
+
|
|
448
|
+
/* ---------- toolbar ---------- */
|
|
449
|
+
.toolbar {
|
|
450
|
+
position: fixed; inset: 0 0 auto 0; z-index: 20;
|
|
451
|
+
display: flex; align-items: center; flex-wrap: wrap; gap: 4px 6px;
|
|
452
|
+
min-height: 44px; padding: 6px 10px; /* not var(--tb-h): that is measured from this, and would never shrink */
|
|
453
|
+
background: var(--tb-bg); backdrop-filter: blur(6px);
|
|
454
|
+
border-bottom: 1px solid var(--line);
|
|
455
|
+
box-shadow: 0 1px 3px rgba(20, 30, 45, .04);
|
|
456
|
+
}
|
|
457
|
+
.tb-group { display: flex; align-items: center; gap: 2px; }
|
|
458
|
+
.tb-sep { width: 1px; height: 20px; background: var(--line); margin: 0 4px; }
|
|
459
|
+
.tb-label { color: var(--muted); margin: 0 6px 0 2px; }
|
|
460
|
+
.spacer { flex: 1; }
|
|
461
|
+
.brand { display: inline-flex; align-items: center; gap: 7px; font-weight: 650; letter-spacing: -.01em; margin: 0 6px 0 2px; color: var(--ink); }
|
|
462
|
+
.brand .logo { width: 22px; height: 22px; }
|
|
463
|
+
.file { position: relative; }
|
|
464
|
+
/* wide screens: the menu's box is transparent and its controls sit in the toolbar, the output
|
|
465
|
+
buttons after the search */
|
|
466
|
+
.tb-more { display: contents; }
|
|
467
|
+
.tb-more > *, .spacer { order: 1; }
|
|
468
|
+
.spacer { order: 2; }
|
|
469
|
+
.search { order: 3; }
|
|
470
|
+
.tb-more > .out-group { order: 4; }
|
|
471
|
+
.menu-btn { display: none; order: 5; }
|
|
472
|
+
.lbl.in-menu { display: none; }
|
|
473
|
+
.file-name { font-weight: 550; }
|
|
474
|
+
.file-name .name { overflow: hidden; text-overflow: ellipsis; }
|
|
475
|
+
|
|
476
|
+
.seg { display: inline-flex; padding: 2px; border-radius: 7px; background: var(--seg-bg); }
|
|
477
|
+
.seg button {
|
|
478
|
+
height: 26px; padding: 0 10px; border: 0; border-radius: 5px; background: transparent;
|
|
479
|
+
color: var(--muted); cursor: pointer; transition: background-color .12s, color .12s, box-shadow .12s;
|
|
480
|
+
}
|
|
481
|
+
.seg button:hover { color: var(--ink); }
|
|
482
|
+
.seg button[aria-checked="true"] { background: var(--seg-on); color: var(--ink); box-shadow: 0 1px 2px rgba(20, 30, 45, .14); }
|
|
483
|
+
|
|
484
|
+
.search { position: relative; display: flex; align-items: center; }
|
|
485
|
+
.search > .icon { position: absolute; left: 9px; color: var(--faint); pointer-events: none; }
|
|
486
|
+
.search input {
|
|
487
|
+
width: 220px; height: 30px; padding: 0 30px 0 30px; border: 1px solid var(--line); border-radius: 7px;
|
|
488
|
+
background: var(--field); outline: none; transition: border-color .12s, background-color .12s, box-shadow .12s;
|
|
489
|
+
}
|
|
490
|
+
.search input::-webkit-search-cancel-button { display: none; }
|
|
491
|
+
.search input:focus { background: var(--panel); border-color: #b9c8e6; box-shadow: 0 0 0 3px rgba(47, 100, 200, .12); }
|
|
492
|
+
.search kbd { position: absolute; right: 8px; pointer-events: none; }
|
|
493
|
+
.search input:focus ~ kbd, .search input:not(:placeholder-shown) ~ kbd { display: none; }
|
|
494
|
+
|
|
495
|
+
/* ---------- popovers ---------- */
|
|
496
|
+
.popover {
|
|
497
|
+
position: absolute; top: calc(100% + 6px); z-index: 30;
|
|
498
|
+
margin: 0; padding: 4px; list-style: none;
|
|
499
|
+
background: var(--panel); border: 1px solid var(--line); border-radius: var(--radius); box-shadow: var(--shadow-lg);
|
|
500
|
+
}
|
|
501
|
+
.menu { left: 0; min-width: 260px; max-width: 380px; }
|
|
502
|
+
.menu .item, .results li {
|
|
503
|
+
display: flex; align-items: center; gap: 8px; width: 100%;
|
|
504
|
+
padding: 6px 8px; border: 0; border-radius: 5px; background: none; text-align: left; cursor: pointer;
|
|
505
|
+
}
|
|
506
|
+
.menu .item:hover, .results li:hover, .results li[aria-selected="true"] { background: var(--hover); }
|
|
507
|
+
.menu .item .when, .results .kind { margin-left: auto; color: var(--faint); font-size: 12px; white-space: nowrap; }
|
|
508
|
+
.menu .item .nm { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
|
509
|
+
.menu .item[aria-current="true"] .nm { font-weight: 600; }
|
|
510
|
+
.menu .head { padding: 6px 8px 4px; color: var(--faint); font-size: 11px; text-transform: uppercase; letter-spacing: .04em; }
|
|
511
|
+
.menu hr { border: 0; border-top: 1px solid var(--line); margin: 4px 0; }
|
|
512
|
+
.menu .empty-note { padding: 8px; color: var(--muted); }
|
|
513
|
+
.results { right: 0; width: 320px; max-height: 60vh; overflow-y: auto; }
|
|
514
|
+
.results .lbl { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
|
515
|
+
.results mark { background: #fff0b3; color: inherit; border-radius: 2px; }
|
|
516
|
+
.results .none { color: var(--muted); cursor: default; }
|
|
517
|
+
.results .swatch { flex: none; width: 16px; height: 8px; border-radius: 3px; }
|
|
518
|
+
.results .none:hover { background: none; }
|
|
519
|
+
.sw { flex: none; width: 22px; height: 10px; }
|
|
520
|
+
|
|
521
|
+
/* ---------- banner ---------- */
|
|
522
|
+
.banner {
|
|
523
|
+
position: fixed; top: calc(var(--tb-h) + 10px); left: 50%; transform: translateX(-50%); z-index: 25;
|
|
524
|
+
display: flex; align-items: flex-start; gap: 8px; max-width: min(760px, calc(100vw - 24px));
|
|
525
|
+
padding: 10px 6px 10px 14px; border-radius: var(--radius);
|
|
526
|
+
background: #fff; border: 1px solid #f1c6c2; border-left: 4px solid var(--danger); box-shadow: var(--shadow-lg);
|
|
527
|
+
}
|
|
528
|
+
.banner .title { display: block; color: var(--danger); font-weight: 600; margin-bottom: 2px; }
|
|
529
|
+
.banner .msg { margin: 0; white-space: pre-wrap; word-break: break-word; font: 12px/1.5 ui-monospace, SFMono-Regular, Menlo, Consolas, monospace; max-height: 30vh; overflow: auto; }
|
|
530
|
+
.banner .close { height: 26px; padding: 0 5px; color: var(--muted); }
|
|
531
|
+
|
|
532
|
+
/* ---------- stage and map ---------- */
|
|
533
|
+
#stage { position: fixed; inset: var(--tb-h) 0 0 0; touch-action: none; cursor: grab; outline: none; }
|
|
534
|
+
#stage.panning { cursor: grabbing; }
|
|
535
|
+
#map, #map > svg { position: absolute; inset: 0; width: 100%; height: 100%; display: block; }
|
|
536
|
+
#map > svg { overflow: hidden; user-select: none; -webkit-user-select: none; }
|
|
537
|
+
/* the map's own background: a quiet edge so it reads as a sheet on the stage */
|
|
538
|
+
#map > svg > rect.lm-bg { stroke: var(--sheet-edge); stroke-width: 1px; vector-effect: non-scaling-stroke; }
|
|
539
|
+
#map > svg { transition: background-color .2s; }
|
|
540
|
+
|
|
541
|
+
/* theme buttons: a small swatch of the theme, then its name */
|
|
542
|
+
.theme-pick { position: relative; }
|
|
543
|
+
.theme-btn .cur { display: inline-flex; align-items: center; gap: 7px; }
|
|
544
|
+
.theme-menu { min-width: 180px; }
|
|
545
|
+
/* a row per theme: the plain one, then a sparkles button for its fancy variant */
|
|
546
|
+
.theme-menu .row { display: flex; align-items: center; gap: 2px; }
|
|
547
|
+
.theme-menu .row > .item:first-child { flex: 1; min-width: 0; }
|
|
548
|
+
.theme-menu .item.fancy { width: auto; flex: none; padding: 6px; color: var(--faint); }
|
|
549
|
+
.theme-menu .item.fancy:hover { color: inherit; }
|
|
550
|
+
.theme-menu .row.on > .item:first-child { background: var(--press); }
|
|
551
|
+
.theme-menu .row.on .nm { font-weight: 600; }
|
|
552
|
+
.theme-menu .item.fancy[aria-checked="true"] { background: var(--press); color: #d99a00; }
|
|
553
|
+
.theme-bar { display: flex; align-items: center; gap: 2px; }
|
|
554
|
+
.fancy-btn { padding: 0 7px; color: var(--faint); }
|
|
555
|
+
.fancy-btn:hover { color: inherit; }
|
|
556
|
+
.fancy-btn[aria-pressed="true"] { color: #d99a00; }
|
|
557
|
+
.icon.sparkles { fill: currentColor; stroke: none; }
|
|
558
|
+
.tsw {
|
|
559
|
+
position: relative; display: inline-block; width: 14px; height: 14px; border-radius: 4px; border: 1.5px solid;
|
|
560
|
+
overflow: hidden; flex: none;
|
|
561
|
+
}
|
|
562
|
+
.tsw i { position: absolute; left: 2px; right: 2px; height: 2.5px; border-radius: 1px; }
|
|
563
|
+
.tsw i:first-child { top: 3px; }
|
|
564
|
+
.tsw i:last-child { top: 7px; }
|
|
565
|
+
#map [data-line], #map g.node, #map g.note, #map g.group > text, #map g.group-tab { transition: opacity .14s ease; }
|
|
566
|
+
#map [data-line], #map g.node, #map g.note a, #map g.group > text, #map g.group-tab { cursor: pointer; }
|
|
567
|
+
#map svg.focus [data-line]:not(.on) { opacity: .12; }
|
|
568
|
+
#map svg.focus g.edge > path:not([data-line]) { opacity: .5; }
|
|
569
|
+
#map svg.focus g.node:not(.on), #map svg.focus g.note { opacity: .45; }
|
|
570
|
+
#map svg.focus g.node.on [data-line]:not(.on) { opacity: .15; }
|
|
571
|
+
#map .flash { animation: flash 1.1s ease-out 1; }
|
|
572
|
+
@keyframes flash { 0%, 30% { opacity: .25; } 15%, 45% { opacity: 1; } 60% { opacity: .4; } 100% { opacity: 1; } }
|
|
573
|
+
|
|
574
|
+
.busy {
|
|
575
|
+
position: fixed; top: calc(var(--tb-h) + 10px); right: 12px; z-index: 15; width: 16px; height: 16px;
|
|
576
|
+
border: 2px solid rgba(47, 100, 200, .25); border-top-color: var(--accent); border-radius: 50%;
|
|
577
|
+
animation: spin .7s linear infinite;
|
|
578
|
+
}
|
|
579
|
+
@keyframes spin { to { transform: rotate(360deg); } }
|
|
580
|
+
|
|
581
|
+
/* ---------- empty state ---------- */
|
|
582
|
+
.empty {
|
|
583
|
+
position: absolute; top: 50%; left: 50%; transform: translate(-50%, -46%);
|
|
584
|
+
width: min(460px, calc(100vw - 32px)); padding: 28px 30px 24px; cursor: default;
|
|
585
|
+
background: var(--panel); border-radius: 12px; box-shadow: var(--shadow);
|
|
586
|
+
}
|
|
587
|
+
.empty h1 { margin: 0 0 4px; font-size: 20px; font-weight: 650; letter-spacing: -.01em; }
|
|
588
|
+
.empty p { margin: 0 0 18px; color: var(--muted); }
|
|
589
|
+
.empty-actions { display: flex; gap: 8px; margin-bottom: 14px; }
|
|
590
|
+
.empty-actions .btn { height: 34px; padding: 0 14px; border: 1px solid var(--line); }
|
|
591
|
+
.empty-actions .btn.primary { border-color: transparent; }
|
|
592
|
+
.empty .flows { margin-bottom: 18px; }
|
|
593
|
+
.empty .flows h2 { margin-top: 0; }
|
|
594
|
+
.ways { margin: 0; padding: 0; list-style: none; color: var(--muted); line-height: 1.9; }
|
|
595
|
+
.empty h2 { margin: 18px 0 6px; font-size: 11px; font-weight: 600; text-transform: uppercase; letter-spacing: .05em; color: var(--faint); }
|
|
596
|
+
.empty .links { display: flex; flex-wrap: wrap; gap: 6px; }
|
|
597
|
+
.empty .links a, .empty .links button {
|
|
598
|
+
display: inline-flex; align-items: center; height: 28px; padding: 0 10px; border-radius: 14px;
|
|
599
|
+
border: 1px solid var(--line); background: #fafbfc; color: var(--ink); text-decoration: none; cursor: pointer;
|
|
600
|
+
}
|
|
601
|
+
.empty .links a:hover, .empty .links button:hover { background: var(--hover); border-color: #d3d8de; }
|
|
602
|
+
|
|
603
|
+
/* ---------- floating panels ---------- */
|
|
604
|
+
.panel { position: fixed; z-index: 10; background: var(--panel); border-radius: var(--radius); box-shadow: var(--shadow); }
|
|
605
|
+
.zoom { right: 14px; bottom: 14px; display: flex; flex-direction: column; padding: 3px; }
|
|
606
|
+
.zoom .btn { width: 32px; height: 32px; padding: 0; justify-content: center; }
|
|
607
|
+
/* touch screens zoom with a pinch; only fit stays */
|
|
608
|
+
@media (hover: none) and (pointer: coarse) {
|
|
609
|
+
#zoom-in, #zoom-out { display: none; }
|
|
610
|
+
}
|
|
611
|
+
|
|
612
|
+
.legend { left: 14px; bottom: 14px; width: 250px; max-height: calc(100vh - var(--tb-h) - 40px); display: flex; flex-direction: column; }
|
|
613
|
+
.legend .lg-head { display: flex; align-items: center; gap: 4px; padding: 6px 6px 6px 12px; }
|
|
614
|
+
.legend .lg-title { font-weight: 600; margin-right: auto; display: flex; align-items: center; gap: 6px; border: 0; background: none; padding: 4px 0; cursor: pointer; }
|
|
615
|
+
.legend .lg-title .icon { transition: transform .15s; }
|
|
616
|
+
.legend.collapsed .lg-title .icon { transform: rotate(-90deg); }
|
|
617
|
+
.legend .lg-title .count { color: var(--faint); font-weight: 400; }
|
|
618
|
+
.legend .lg-head .btn { height: 24px; padding: 0 7px; font-size: 12px; color: var(--muted); }
|
|
619
|
+
.legend .lg-head .btn:hover { color: var(--ink); }
|
|
620
|
+
.legend.collapsed .lg-head .btn { display: none; }
|
|
621
|
+
.legend ul { margin: 0; padding: 2px 4px 6px; list-style: none; overflow-y: auto; border-top: 1px solid var(--line); }
|
|
622
|
+
.legend.collapsed ul { display: none; }
|
|
623
|
+
.legend li {
|
|
624
|
+
display: flex; align-items: center; gap: 10px; padding: 5px 8px; border-radius: 5px; cursor: pointer;
|
|
625
|
+
transition: opacity .12s, background-color .12s;
|
|
626
|
+
}
|
|
627
|
+
.legend li:hover { background: var(--hover); }
|
|
628
|
+
.legend li.on { background: var(--press); }
|
|
629
|
+
.legend li .lb { flex: 1; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
|
630
|
+
.legend li .ct { color: var(--faint); font-size: 12px; font-variant-numeric: tabular-nums; }
|
|
631
|
+
.legend li.hidden { opacity: .4; }
|
|
632
|
+
.legend li.hidden .lb { text-decoration: line-through; text-decoration-color: rgba(0, 0, 0, .35); }
|
|
633
|
+
.legend .sw { width: 30px; height: 10px; }
|
|
634
|
+
|
|
635
|
+
/* ---------- tooltip ---------- */
|
|
636
|
+
.tooltip {
|
|
637
|
+
position: fixed; left: 0; top: 0; z-index: 40; pointer-events: none;
|
|
638
|
+
max-width: 320px; padding: 8px 10px; border-radius: 7px;
|
|
639
|
+
background: rgba(28, 33, 40, .94); color: #f4f6f8; box-shadow: 0 4px 18px rgba(0, 0, 0, .18);
|
|
640
|
+
font-size: 12.5px; line-height: 1.45;
|
|
641
|
+
}
|
|
642
|
+
.tooltip .tt-title { font-weight: 600; font-size: 13px; color: #fff; white-space: pre-line; }
|
|
643
|
+
.tooltip .tt-sub { color: #aab3bd; }
|
|
644
|
+
.tooltip .tt-url { color: #8ab4f8; word-break: break-all; margin-top: 2px; }
|
|
645
|
+
.tooltip .tt-row { display: flex; align-items: baseline; gap: 6px; margin-top: 4px; }
|
|
646
|
+
.tooltip .tt-row > .k { color: #8f99a4; flex: none; min-width: 34px; }
|
|
647
|
+
.tooltip .tt-lines { display: flex; flex-wrap: wrap; gap: 3px 10px; }
|
|
648
|
+
.tooltip .tt-line { display: inline-flex; align-items: center; gap: 5px; white-space: nowrap; }
|
|
649
|
+
.tooltip .dot { width: 14px; height: 6px; border-radius: 3px; flex: none; box-shadow: 0 0 0 1px rgba(255, 255, 255, .25); }
|
|
650
|
+
.tooltip .tt-hint { margin-top: 6px; padding-top: 5px; border-top: 1px solid rgba(255, 255, 255, .12); color: #8f99a4; font-size: 11.5px; }
|
|
651
|
+
.tooltip .tt-head { display: flex; align-items: center; gap: 8px; }
|
|
652
|
+
.tooltip .tt-head .dot { width: 22px; height: 8px; border-radius: 4px; }
|
|
653
|
+
.tooltip .tt-id { margin-left: auto; padding-left: 10px; color: #8f99a4; font: 11px ui-monospace, SFMono-Regular, Menlo, Consolas, monospace; }
|
|
654
|
+
|
|
655
|
+
.toast {
|
|
656
|
+
position: fixed; bottom: 22px; left: 50%; transform: translateX(-50%); z-index: 45;
|
|
657
|
+
padding: 8px 14px; border-radius: 18px; background: rgba(28, 33, 40, .92); color: #fff; box-shadow: var(--shadow);
|
|
658
|
+
animation: toast-in .16s ease-out;
|
|
659
|
+
}
|
|
660
|
+
@keyframes toast-in { from { opacity: 0; transform: translate(-50%, 6px); } }
|
|
661
|
+
|
|
662
|
+
.drop {
|
|
663
|
+
position: fixed; inset: 10px; z-index: 50; display: grid; place-items: center; pointer-events: none;
|
|
664
|
+
border: 2px dashed var(--accent); border-radius: 14px; background: rgba(47, 100, 200, .07);
|
|
665
|
+
}
|
|
666
|
+
.drop div { padding: 12px 18px; border-radius: var(--radius); background: #fff; box-shadow: var(--shadow); font-weight: 600; color: var(--accent); }
|
|
667
|
+
|
|
668
|
+
/* ---------- dialogs ---------- */
|
|
669
|
+
.dialog {
|
|
670
|
+
width: min(620px, calc(100vw - 32px)); padding: 20px 22px 16px; border: 0; border-radius: 12px; box-shadow: var(--shadow-lg);
|
|
671
|
+
color: var(--ink);
|
|
672
|
+
}
|
|
673
|
+
.dialog::backdrop { background: rgba(25, 32, 42, .28); }
|
|
674
|
+
.dialog h2 { margin: 0 0 12px; font-size: 16px; font-weight: 650; }
|
|
675
|
+
.dialog .hint { color: var(--muted); margin: -4px 0 12px; }
|
|
676
|
+
.dialog textarea {
|
|
677
|
+
width: 100%; resize: vertical; padding: 10px; border: 1px solid var(--line); border-radius: 7px; background: #fafbfc;
|
|
678
|
+
font: 12px/1.5 ui-monospace, SFMono-Regular, Menlo, Consolas, monospace; outline: none;
|
|
679
|
+
}
|
|
680
|
+
.dialog textarea:focus { border-color: #b9c8e6; box-shadow: 0 0 0 3px rgba(47, 100, 200, .12); background: #fff; }
|
|
681
|
+
.dialog-actions { display: flex; justify-content: flex-end; gap: 8px; margin-top: 14px; }
|
|
682
|
+
.dialog-actions .btn { height: 32px; padding: 0 14px; }
|
|
683
|
+
.help table { border-collapse: collapse; width: 100%; }
|
|
684
|
+
.help th { text-align: left; font-weight: 500; color: var(--muted); padding: 7px 16px 7px 0; white-space: nowrap; vertical-align: top; }
|
|
685
|
+
.help td { padding: 7px 0; }
|
|
686
|
+
.help tr + tr > * { border-top: 1px solid var(--line); }
|
|
687
|
+
.help .hint { margin: 14px 0 0; }
|
|
688
|
+
.help .about { display: flex; align-items: center; gap: 14px; margin: 2px 0 18px; padding-bottom: 16px; border-bottom: 1px solid var(--line); }
|
|
689
|
+
.help .about-logo { width: 48px; height: 48px; flex: none; }
|
|
690
|
+
.help .about-name { font-size: 20px; font-weight: 650; letter-spacing: -.01em; }
|
|
691
|
+
.help .about-tag { color: var(--muted); margin-top: 2px; }
|
|
692
|
+
.help .about-tag a { color: inherit; text-decoration: underline; text-underline-offset: 2px; text-decoration-color: var(--line); }
|
|
693
|
+
.help .about-tag a:hover { color: var(--ink); text-decoration-color: currentColor; }
|
|
694
|
+
.help .copyright { margin-top: 6px; }
|
|
695
|
+
|
|
696
|
+
/* before the first map: only the ways to load one */
|
|
697
|
+
body.nomap .through-group, body.nomap .theme-group, body.nomap .search, body.nomap #export, body.nomap #positions, body.nomap .tb-sep, body.nomap .zoom { display: none; }
|
|
698
|
+
|
|
699
|
+
/* ---------- narrow screens ---------- */
|
|
700
|
+
/* Labels go before the toolbar would wrap (width measured with a short file name; a longer one
|
|
701
|
+
is cut short with an ellipsis instead). */
|
|
702
|
+
.toolbar { flex-wrap: nowrap; }
|
|
703
|
+
.brand-group, .file { min-width: 0; }
|
|
704
|
+
.file-name { max-width: min(32ch, 100%); }
|
|
705
|
+
@media (max-width: 1200px) {
|
|
706
|
+
.btn .lbl, .tb-label, .brand-name { display: none; }
|
|
707
|
+
.search input { width: 150px; }
|
|
708
|
+
}
|
|
709
|
+
/* narrow screens: one row (file, search, menu button); the rest folds into a menu under it */
|
|
710
|
+
@media (max-width: 860px) {
|
|
711
|
+
.search { flex: 1 1 80px; min-width: 80px; max-width: 320px; margin-left: auto; }
|
|
712
|
+
.search input { width: 100%; }
|
|
713
|
+
.spacer { display: none; }
|
|
714
|
+
.menu-btn { display: inline-flex; flex: none; }
|
|
715
|
+
.toolbar.menu-open .menu-btn { background: var(--press); color: var(--accent); }
|
|
716
|
+
|
|
717
|
+
.tb-more {
|
|
718
|
+
display: none; position: absolute; top: calc(100% + 6px); right: 8px; z-index: 30;
|
|
719
|
+
width: min(300px, calc(100vw - 16px)); max-height: calc(100vh - var(--tb-h) - 20px); overflow-y: auto;
|
|
720
|
+
flex-direction: column; padding: 4px;
|
|
721
|
+
background: var(--panel); border: 1px solid var(--line); border-radius: var(--radius); box-shadow: var(--shadow-lg);
|
|
722
|
+
}
|
|
723
|
+
.toolbar.menu-open .tb-more { display: flex; }
|
|
724
|
+
.tb-more > * { order: 0; }
|
|
725
|
+
.tb-more .tb-group { flex-direction: column; align-items: stretch; gap: 0; }
|
|
726
|
+
.tb-more .btn { height: 36px; padding: 0 10px; gap: 10px; }
|
|
727
|
+
.tb-more .btn .lbl, .tb-more .tb-label { display: inline; }
|
|
728
|
+
.tb-more .tb-sep { width: auto; height: 1px; margin: 4px 0; }
|
|
729
|
+
.tb-more .through-group, .tb-more .theme-group { padding: 6px 10px 8px; gap: 6px; }
|
|
730
|
+
.tb-more .tb-label { margin: 0; font-size: 11px; text-transform: uppercase; letter-spacing: .04em; color: var(--faint); }
|
|
731
|
+
.tb-more .seg { display: flex; }
|
|
732
|
+
/* the theme list opens in place, inside the menu */
|
|
733
|
+
.tb-more .theme-btn { flex: 1; min-width: 0; border: 1px solid var(--line); background: var(--field); }
|
|
734
|
+
.tb-more .fancy-btn { border: 1px solid var(--line); }
|
|
735
|
+
.tb-more .theme-btn .icon.small { margin-left: auto; }
|
|
736
|
+
.tb-more .theme-menu { position: static; margin-top: 4px; min-width: 0; max-width: none; box-shadow: none; }
|
|
737
|
+
.tb-more .seg button { flex: 1; height: 30px; justify-content: center; }
|
|
738
|
+
.tb-more .out-group { border-top: 1px solid var(--line); margin-top: 4px; padding-top: 4px; }
|
|
739
|
+
body.nomap .tb-more .out-group { border-top: 0; margin-top: 0; padding-top: 0; }
|
|
740
|
+
}
|
|
741
|
+
@media (max-width: 560px) {
|
|
742
|
+
.search kbd { display: none; }
|
|
743
|
+
.search input { padding-right: 8px; }
|
|
744
|
+
.legend { width: calc(100vw - 80px); }
|
|
745
|
+
}
|
|
746
|
+
|
|
747
|
+
/* ---------- dark chrome, for dark map themes ---------- */
|
|
748
|
+
body.ui-dark {
|
|
749
|
+
--bg: #07090d;
|
|
750
|
+
--panel: #171c23;
|
|
751
|
+
--ink: #e4e8ed;
|
|
752
|
+
--muted: #9aa3ae;
|
|
753
|
+
--faint: #6c7581;
|
|
754
|
+
--line: #2a313b;
|
|
755
|
+
--hover: #222932;
|
|
756
|
+
--press: #1f2b3f;
|
|
757
|
+
--accent: #6c9cf0;
|
|
758
|
+
--sheet-edge: #2a313b;
|
|
759
|
+
--tb-bg: rgba(20, 24, 31, .94);
|
|
760
|
+
--seg-bg: #0f1318;
|
|
761
|
+
--seg-on: #2a313b;
|
|
762
|
+
--field: #0f1318;
|
|
763
|
+
--shadow: 0 1px 2px rgba(0, 0, 0, .3), 0 4px 16px rgba(0, 0, 0, .35);
|
|
764
|
+
--shadow-lg: 0 2px 6px rgba(0, 0, 0, .35), 0 12px 40px rgba(0, 0, 0, .5);
|
|
765
|
+
color-scheme: dark;
|
|
766
|
+
}
|
|
767
|
+
body.ui-dark kbd, body.ui-dark .empty .links a, body.ui-dark .empty .links button, body.ui-dark .dialog textarea { background: var(--field); }
|
|
768
|
+
body.ui-dark .dialog { background: var(--panel); }
|
|
769
|
+
body.ui-dark .banner, body.ui-dark .drop div { background: var(--panel); }
|
|
770
|
+
body.ui-dark .legend li.hidden .lb { text-decoration-color: rgba(255, 255, 255, .35); }
|
|
771
|
+
body.ui-dark .results mark { background: #5b4a12; }
|
|
772
|
+
body.ui-dark .btn.primary { color: #0b0e13; }
|
|
773
|
+
body.ui-dark .btn.primary:hover { background: #8ab0f4; }
|
|
774
|
+
body.ui-dark .search input:focus { border-color: #3d5a8a; box-shadow: 0 0 0 3px rgba(108, 156, 240, .18); }
|
|
775
|
+
</style>
|
|
776
|
+
</head>
|
|
777
|
+
<body>
|
|
778
|
+
<svg width="0" height="0" style="position:absolute" aria-hidden="true">
|
|
779
|
+
<defs>
|
|
780
|
+
<symbol id="i-open" viewBox="0 0 16 16"><path d="M1.8 4.2c0-.7.5-1.2 1.2-1.2h3l1.4 1.6h5.6c.7 0 1.2.5 1.2 1.2v6.4c0 .7-.5 1.2-1.2 1.2H3c-.7 0-1.2-.5-1.2-1.2z"/></symbol>
|
|
781
|
+
<symbol id="i-paste" viewBox="0 0 16 16"><rect x="3" y="2.8" width="10" height="11.4" rx="1.4"/><path d="M6 2.8V2h4v.8M5.8 7h4.4M5.8 9.8h4.4"/></symbol>
|
|
782
|
+
<symbol id="i-reload" viewBox="0 0 16 16"><path d="M13.2 8a5.2 5.2 0 1 1-1.6-3.8M13.2 2.2v2.6h-2.6"/></symbol>
|
|
783
|
+
<symbol id="i-eye" viewBox="0 0 16 16"><path d="M1.5 8S4 3.6 8 3.6 14.5 8 14.5 8 12 12.4 8 12.4 1.5 8 1.5 8z"/><circle cx="8" cy="8" r="2"/></symbol>
|
|
784
|
+
<symbol id="i-download" viewBox="0 0 16 16"><path d="M8 2.2v8M4.8 7.2 8 10.4l3.2-3.2M2.6 13.6h10.8"/></symbol>
|
|
785
|
+
<symbol id="i-pin" viewBox="0 0 16 16"><path d="M8 14.2s4.6-4.3 4.6-7.6a4.6 4.6 0 0 0-9.2 0c0 3.3 4.6 7.6 4.6 7.6z"/><circle cx="8" cy="6.6" r="1.6"/></symbol>
|
|
786
|
+
<symbol id="i-help" viewBox="0 0 16 16"><circle cx="8" cy="8" r="6.2"/><path d="M6.2 6.3a1.9 1.9 0 1 1 2.6 1.8c-.5.2-.8.6-.8 1.1v.4"/><circle cx="8" cy="11.4" r=".4"/></symbol>
|
|
787
|
+
<symbol id="i-plus" viewBox="0 0 16 16"><path d="M8 3v10M3 8h10"/></symbol>
|
|
788
|
+
<symbol id="i-minus" viewBox="0 0 16 16"><path d="M3 8h10"/></symbol>
|
|
789
|
+
<symbol id="i-fit" viewBox="0 0 16 16"><path d="M2.5 6V2.5H6M10 2.5h3.5V6M13.5 10v3.5H10M6 13.5H2.5V10"/></symbol>
|
|
790
|
+
<symbol id="i-search" viewBox="0 0 16 16"><circle cx="7" cy="7" r="4.3"/><path d="m10.2 10.2 3.4 3.4"/></symbol>
|
|
791
|
+
<symbol id="i-chevron" viewBox="0 0 16 16"><path d="m4.5 6.2 3.5 3.5 3.5-3.5"/></symbol>
|
|
792
|
+
<symbol id="i-menu" viewBox="0 0 16 16"><path d="M2.5 4h11M2.5 8h11M2.5 12h11"/></symbol>
|
|
793
|
+
<symbol id="i-sparkles" viewBox="0 0 16 16"><path d="M6.5 4.6c.4 3 1.4 4 4.4 4.4-3 .4-4 1.4-4.4 4.4-.4-3-1.4-4-4.4-4.4 3-.4 4-1.4 4.4-4.4zM12.4 1.6c.2 1.2.6 1.6 1.8 1.8-1.2.2-1.6.6-1.8 1.8-.2-1.2-.6-1.6-1.8-1.8 1.2-.2 1.6-.6 1.8-1.8z"/></symbol>
|
|
794
|
+
<symbol id="i-close" viewBox="0 0 16 16"><path d="m4 4 8 8M12 4l-8 8"/></symbol>
|
|
795
|
+
</defs>
|
|
796
|
+
</svg>
|
|
797
|
+
|
|
798
|
+
<header class="toolbar">
|
|
799
|
+
<div class="tb-group brand-group">
|
|
800
|
+
<span class="brand"><img class="logo" src="data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZpZXdCb3g9IjAgMCAxMjggMTI4IiB3aWR0aD0iMTI4IiBoZWlnaHQ9IjEyOCI+CiAgPHRpdGxlPmxpbmVtYXA8L3RpdGxlPgogIDxkZWZzPgogICAgPHBhdGggaWQ9ImdyZWVuIiBkPSJNNTYgNCBWNDggQTI4IDI4IDAgMCAwIDg0IDc2IEgxMjQiLz4KICAgIDxwYXRoIGlkPSJibHVlIiBkPSJNNDQgNCBWNDggQTQwIDQwIDAgMCAwIDg0IDg4IEgxMjQiLz4KICA8L2RlZnM+CiAgPCEtLSB0aGUgbmVvbiB0aGVtZSdzIHRyYXZlbGxpbmcgYXJyb3dzOiBvbmUgcnVucyBkb3duIGVhY2ggbGluZSBpbiB0dXJuLCBtYWdlbnRhLCBibHVlLCBsaW1lLCB0aGVuCiAgICAgICBhbGwgcmVzdCAxMCBzIGJlZm9yZSB0aGUgbmV4dCByb3VuZCAoYSBydW4gaXMgMC4yNyBzLCB0aGV5IHN0YXJ0IDAuMyBzIGFwYXJ0KS4KICAgICAgIEVhY2ggaXMgZHJhd24gYXQgdGhlIG9yaWdpbiBwb2ludGluZyByaWdodCBhbmQgcHV0IG9uIGl0cyBsaW5lIGJ5IGEgbW90aW9uIHBhdGg7IGl0IHdhaXRzCiAgICAgICBoaWRkZW4gdW50aWwgaXRzIHR1cm4uIFdpdGhvdXQgbW90aW9uIHBhdGhzLCBvciB3aXRoIHJlZHVjZWQgbW90aW9uLCB0aGV5IHN0YXkgaGlkZGVuLiAtLT4KICA8c3R5bGU+CiAgICAuYXJyb3cgeyBmaWxsOiAjZmZmOyBvcGFjaXR5OiAwOyB9CiAgICBAc3VwcG9ydHMgKG9mZnNldC1wYXRoOiBwYXRoKCdNMCwwJykpIHsKICAgICAgLmFycm93IHsgb2Zmc2V0LXJvdGF0ZTogYXV0bzsgYW5pbWF0aW9uOiBydW4gMTAuODdzIGxpbmVhciBpbmZpbml0ZSBiYWNrd2FyZHM7IH0KICAgICAgLmExIHsgb2Zmc2V0LXBhdGg6IHBhdGgoJ003MiA0IFYxMjQnKTsgfQogICAgICAuYTIgeyBvZmZzZXQtcGF0aDogcGF0aCgnTTU2IDQgVjQ4IEEyOCAyOCAwIDAgMCA4NCA3NiBIMTI0Jyk7IGFuaW1hdGlvbi1kZWxheTogMC4zczsgfQogICAgICAuYTMgeyBvZmZzZXQtcGF0aDogcGF0aCgnTTQ0IDQgVjQ4IEE0MCA0MCAwIDAgMCA4NCA4OCBIMTI0Jyk7IGFuaW1hdGlvbi1kZWxheTogMC42czsgfQogICAgfQogICAgLmEzIHsgZmlsbDogIzAwMDsgfSAvKiB3aGl0ZSBoYXJkbHkgc2hvd3Mgb24gbGltZSAqLwogICAgQGtleWZyYW1lcyBydW4gewogICAgICAwJSB7IG9mZnNldC1kaXN0YW5jZTogMCU7IG9wYWNpdHk6IDA7IH0KICAgICAgMC4zMyUgeyBvcGFjaXR5OiAwLjk1OyB9CiAgICAgIDIuMTUlIHsgb3BhY2l0eTogMC45NTsgfQogICAgICAyLjQ4JSwgMTAwJSB7IG9mZnNldC1kaXN0YW5jZTogMTAwJTsgb3BhY2l0eTogMDsgfQogICAgfQogICAgQG1lZGlhIChwcmVmZXJzLXJlZHVjZWQtbW90aW9uOiByZWR1Y2UpIHsgLmFycm93IHsgYW5pbWF0aW9uOiBub25lOyB9IH0KICA8L3N0eWxlPgogIDwhLS0gb3JhbmdlIHJ1bnMgdW5kZXIgZ3JlZW4gYW5kIGJsdWU6IHRoZXkgY3V0IGl0LCA0IHB4IHdpZGVyIHRoYW4gdGhlbXNlbHZlcyBvbiBlYWNoIHNpZGUgLS0+CiAgPG1hc2sgaWQ9InVuZGVyIiBtYXNrVW5pdHM9InVzZXJTcGFjZU9uVXNlIiB4PSIwIiB5PSIwIiB3aWR0aD0iMTI4IiBoZWlnaHQ9IjEyOCI+CiAgICA8cmVjdCB3aWR0aD0iMTI4IiBoZWlnaHQ9IjEyOCIgZmlsbD0iI2ZmZiIvPgogICAgPGcgZmlsbD0ibm9uZSIgc3Ryb2tlPSIjMDAwIiBzdHJva2Utd2lkdGg9IjIwIj48dXNlIGhyZWY9IiNncmVlbiIvPjx1c2UgaHJlZj0iI2JsdWUiLz48L2c+CiAgPC9tYXNrPgogIDxnIGZpbGw9Im5vbmUiIHN0cm9rZS13aWR0aD0iMTIiPgogICAgPGcgbWFzaz0idXJsKCN1bmRlcikiPgogICAgICA8cGF0aCBkPSJNNzIgNCBWMTI0IiBzdHJva2U9IiNmZjAwZDQiLz4KICAgICAgPHBvbHlnb24gY2xhc3M9ImFycm93IGExIiBwb2ludHM9IjcsMCAtNywtNC41IC03LDQuNSIgc3Ryb2tlPSJub25lIi8+CiAgICA8L2c+CiAgICA8dXNlIGhyZWY9IiNncmVlbiIgc3Ryb2tlPSIjM2Q1YWZlIi8+CiAgICA8cG9seWdvbiBjbGFzcz0iYXJyb3cgYTIiIHBvaW50cz0iNywwIC03LC00LjUgLTcsNC41IiBzdHJva2U9Im5vbmUiLz4KICAgIDx1c2UgaHJlZj0iI2JsdWUiIHN0cm9rZT0iI2M2ZmYwMCIvPgogICAgPHBvbHlnb24gY2xhc3M9ImFycm93IGEzIiBwb2ludHM9IjcsMCAtNywtNC41IC03LDQuNSIgc3Ryb2tlPSJub25lIi8+CiAgPC9nPgo8L3N2Zz4K" alt=""><span class="brand-name">linemap</span></span>
|
|
801
|
+
<div class="file">
|
|
802
|
+
<button id="file-name" class="btn file-name" title="Recent files" aria-haspopup="menu">
|
|
803
|
+
<span class="name">No file</span><svg class="icon small"><use href="#i-chevron"/></svg>
|
|
804
|
+
</button>
|
|
805
|
+
<div id="recent" class="popover menu" role="menu" hidden></div>
|
|
806
|
+
</div>
|
|
807
|
+
</div>
|
|
808
|
+
<!-- the controls that fold into the menu button on narrow screens; on wide ones the box is
|
|
809
|
+
transparent (display: contents) and they sit in the toolbar -->
|
|
810
|
+
<div id="tb-more" class="tb-more">
|
|
811
|
+
<div class="tb-group file-group">
|
|
812
|
+
<button id="open" class="btn" title="Open a DOT file"><svg class="icon"><use href="#i-open"/></svg><span class="lbl">Open</span></button>
|
|
813
|
+
<button id="paste" class="btn" title="Paste DOT text"><svg class="icon"><use href="#i-paste"/></svg><span class="lbl">Paste</span></button>
|
|
814
|
+
<button id="reload" class="btn" title="Reload (R)"><svg class="icon"><use href="#i-reload"/></svg><span class="lbl in-menu">Reload</span></button>
|
|
815
|
+
<button id="watch" class="btn" title="Watch the file: reload when it changes" aria-pressed="false" hidden><svg class="icon"><use href="#i-eye"/></svg><span class="lbl">Watch</span></button>
|
|
816
|
+
</div>
|
|
817
|
+
<div class="tb-sep"></div>
|
|
818
|
+
<div class="tb-group through-group">
|
|
819
|
+
<span class="tb-label">Through</span>
|
|
820
|
+
<div class="seg" id="through" role="radiogroup" aria-label="Lines through nodes">
|
|
821
|
+
<button data-mode="file" role="radio" title="As in the file">File</button>
|
|
822
|
+
<button data-mode="all" role="radio" title="Lines through every box, queue and cylinder">All</button>
|
|
823
|
+
<button data-mode="none" role="radio" title="Lines end at every node">None</button>
|
|
824
|
+
</div>
|
|
825
|
+
</div>
|
|
826
|
+
<div class="tb-group theme-group">
|
|
827
|
+
<span class="tb-label">Theme</span>
|
|
828
|
+
<div class="theme-pick">
|
|
829
|
+
<div class="theme-bar">
|
|
830
|
+
<button id="theme-btn" class="btn theme-btn" title="Theme (T: next)" aria-haspopup="menu" aria-expanded="false">
|
|
831
|
+
<span class="cur"></span><svg class="icon small"><use href="#i-chevron"/></svg>
|
|
832
|
+
</button>
|
|
833
|
+
<button id="fancy" class="btn fancy-btn" aria-pressed="false" hidden><svg class="icon sparkles"><use href="#i-sparkles"/></svg></button>
|
|
834
|
+
</div>
|
|
835
|
+
<div id="theme" class="popover menu theme-menu" role="menu" aria-label="Theme" hidden></div>
|
|
836
|
+
</div>
|
|
837
|
+
</div>
|
|
838
|
+
<div class="tb-group out-group">
|
|
839
|
+
<button id="export" class="btn" title="Download the map as SVG"><svg class="icon"><use href="#i-download"/></svg><span class="lbl">SVG</span></button>
|
|
840
|
+
<button id="positions" class="btn" title="Copy computed positions (pos="x,y") for unpinned items"><svg class="icon"><use href="#i-pin"/></svg><span class="lbl">Positions</span></button>
|
|
841
|
+
<button id="help-btn" class="btn" title="Keys and gestures (?)"><svg class="icon"><use href="#i-help"/></svg><span class="lbl in-menu">Help</span></button>
|
|
842
|
+
</div>
|
|
843
|
+
</div>
|
|
844
|
+
<div class="spacer"></div>
|
|
845
|
+
<div class="search">
|
|
846
|
+
<svg class="icon"><use href="#i-search"/></svg>
|
|
847
|
+
<input id="search" type="search" placeholder="Search" autocomplete="off" spellcheck="false" aria-label="Search nodes, containers and lines">
|
|
848
|
+
<kbd>/</kbd>
|
|
849
|
+
<ul id="results" class="popover results" role="listbox" hidden></ul>
|
|
850
|
+
</div>
|
|
851
|
+
<button id="menu-btn" class="btn menu-btn" title="Menu" aria-label="Menu" aria-expanded="false" aria-controls="tb-more"><svg class="icon"><use href="#i-menu"/></svg></button>
|
|
852
|
+
</header>
|
|
853
|
+
|
|
854
|
+
<div id="banner" class="banner" role="alert" hidden>
|
|
855
|
+
<div class="text"><strong class="title"></strong><pre class="msg"></pre></div>
|
|
856
|
+
<button class="btn close" title="Dismiss"><svg class="icon"><use href="#i-close"/></svg></button>
|
|
857
|
+
</div>
|
|
858
|
+
|
|
859
|
+
<main id="stage">
|
|
860
|
+
<div id="map"></div>
|
|
861
|
+
<section id="empty" class="empty" hidden>
|
|
862
|
+
<h1>Open a linemap</h1>
|
|
863
|
+
<p>Load a DOT file to explore it as a transit map.</p>
|
|
864
|
+
<div class="flows" hidden><h2>In this file</h2><div class="links"></div></div>
|
|
865
|
+
<div class="empty-actions">
|
|
866
|
+
<button class="btn primary" data-act="open"><svg class="icon"><use href="#i-open"/></svg>Open file</button>
|
|
867
|
+
<button class="btn" data-act="paste"><svg class="icon"><use href="#i-paste"/></svg>Paste text</button>
|
|
868
|
+
</div>
|
|
869
|
+
<ul class="ways">
|
|
870
|
+
<li>or drop a <code>.dot</code> file anywhere on this page</li>
|
|
871
|
+
<li>or add <code>?src=path/to/flow.dot</code> to the address (served over http)</li>
|
|
872
|
+
</ul>
|
|
873
|
+
<div class="examples" hidden><h2>Examples</h2><div class="links"></div></div>
|
|
874
|
+
<div class="recent-list" hidden><h2>Recent</h2><div class="links"></div></div>
|
|
875
|
+
</section>
|
|
876
|
+
<div id="busy" class="busy" hidden></div>
|
|
877
|
+
</main>
|
|
878
|
+
|
|
879
|
+
<aside id="legend" class="panel legend" hidden></aside>
|
|
880
|
+
|
|
881
|
+
<div class="panel zoom" role="group" aria-label="Zoom">
|
|
882
|
+
<button id="zoom-in" class="btn" title="Zoom in (+)"><svg class="icon"><use href="#i-plus"/></svg></button>
|
|
883
|
+
<button id="zoom-out" class="btn" title="Zoom out (-)"><svg class="icon"><use href="#i-minus"/></svg></button>
|
|
884
|
+
<button id="zoom-fit" class="btn" title="Fit (0)"><svg class="icon"><use href="#i-fit"/></svg></button>
|
|
885
|
+
</div>
|
|
886
|
+
|
|
887
|
+
<div id="tooltip" class="tooltip" role="tooltip" hidden></div>
|
|
888
|
+
<div id="toast" class="toast" hidden></div>
|
|
889
|
+
<div id="drop" class="drop" hidden><div>Drop a DOT file to open it</div></div>
|
|
890
|
+
<input id="file-input" type="file" accept=".dot,.gv,.txt,text/plain,text/vnd.graphviz" hidden>
|
|
891
|
+
|
|
892
|
+
<dialog id="paste-dialog" class="dialog">
|
|
893
|
+
<form method="dialog">
|
|
894
|
+
<h2>Paste DOT text</h2>
|
|
895
|
+
<textarea name="text" rows="14" spellcheck="false" placeholder="digraph flow { ... }"></textarea>
|
|
896
|
+
<div class="dialog-actions">
|
|
897
|
+
<button class="btn" value="cancel" formnovalidate>Cancel</button>
|
|
898
|
+
<button class="btn primary" value="ok">Show map</button>
|
|
899
|
+
</div>
|
|
900
|
+
</form>
|
|
901
|
+
</dialog>
|
|
902
|
+
|
|
903
|
+
<dialog id="positions-dialog" class="dialog">
|
|
904
|
+
<form method="dialog">
|
|
905
|
+
<h2>Positions</h2>
|
|
906
|
+
<p class="hint">Computed positions of unpinned nodes and notes; paste into the DOT file to pin them.</p>
|
|
907
|
+
<textarea name="text" rows="14" readonly spellcheck="false"></textarea>
|
|
908
|
+
<div class="dialog-actions"><button class="btn primary" value="ok">Close</button></div>
|
|
909
|
+
</form>
|
|
910
|
+
</dialog>
|
|
911
|
+
|
|
912
|
+
<dialog id="help" class="dialog help">
|
|
913
|
+
<form method="dialog">
|
|
914
|
+
<div class="about"><img class="about-logo" src="data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZpZXdCb3g9IjAgMCAxMjggMTI4IiB3aWR0aD0iMTI4IiBoZWlnaHQ9IjEyOCI+CiAgPHRpdGxlPmxpbmVtYXA8L3RpdGxlPgogIDxkZWZzPgogICAgPHBhdGggaWQ9ImdyZWVuIiBkPSJNNTYgNCBWNDggQTI4IDI4IDAgMCAwIDg0IDc2IEgxMjQiLz4KICAgIDxwYXRoIGlkPSJibHVlIiBkPSJNNDQgNCBWNDggQTQwIDQwIDAgMCAwIDg0IDg4IEgxMjQiLz4KICA8L2RlZnM+CiAgPCEtLSB0aGUgbmVvbiB0aGVtZSdzIHRyYXZlbGxpbmcgYXJyb3dzOiBvbmUgcnVucyBkb3duIGVhY2ggbGluZSBpbiB0dXJuLCBtYWdlbnRhLCBibHVlLCBsaW1lLCB0aGVuCiAgICAgICBhbGwgcmVzdCAxMCBzIGJlZm9yZSB0aGUgbmV4dCByb3VuZCAoYSBydW4gaXMgMC4yNyBzLCB0aGV5IHN0YXJ0IDAuMyBzIGFwYXJ0KS4KICAgICAgIEVhY2ggaXMgZHJhd24gYXQgdGhlIG9yaWdpbiBwb2ludGluZyByaWdodCBhbmQgcHV0IG9uIGl0cyBsaW5lIGJ5IGEgbW90aW9uIHBhdGg7IGl0IHdhaXRzCiAgICAgICBoaWRkZW4gdW50aWwgaXRzIHR1cm4uIFdpdGhvdXQgbW90aW9uIHBhdGhzLCBvciB3aXRoIHJlZHVjZWQgbW90aW9uLCB0aGV5IHN0YXkgaGlkZGVuLiAtLT4KICA8c3R5bGU+CiAgICAuYXJyb3cgeyBmaWxsOiAjZmZmOyBvcGFjaXR5OiAwOyB9CiAgICBAc3VwcG9ydHMgKG9mZnNldC1wYXRoOiBwYXRoKCdNMCwwJykpIHsKICAgICAgLmFycm93IHsgb2Zmc2V0LXJvdGF0ZTogYXV0bzsgYW5pbWF0aW9uOiBydW4gMTAuODdzIGxpbmVhciBpbmZpbml0ZSBiYWNrd2FyZHM7IH0KICAgICAgLmExIHsgb2Zmc2V0LXBhdGg6IHBhdGgoJ003MiA0IFYxMjQnKTsgfQogICAgICAuYTIgeyBvZmZzZXQtcGF0aDogcGF0aCgnTTU2IDQgVjQ4IEEyOCAyOCAwIDAgMCA4NCA3NiBIMTI0Jyk7IGFuaW1hdGlvbi1kZWxheTogMC4zczsgfQogICAgICAuYTMgeyBvZmZzZXQtcGF0aDogcGF0aCgnTTQ0IDQgVjQ4IEE0MCA0MCAwIDAgMCA4NCA4OCBIMTI0Jyk7IGFuaW1hdGlvbi1kZWxheTogMC42czsgfQogICAgfQogICAgLmEzIHsgZmlsbDogIzAwMDsgfSAvKiB3aGl0ZSBoYXJkbHkgc2hvd3Mgb24gbGltZSAqLwogICAgQGtleWZyYW1lcyBydW4gewogICAgICAwJSB7IG9mZnNldC1kaXN0YW5jZTogMCU7IG9wYWNpdHk6IDA7IH0KICAgICAgMC4zMyUgeyBvcGFjaXR5OiAwLjk1OyB9CiAgICAgIDIuMTUlIHsgb3BhY2l0eTogMC45NTsgfQogICAgICAyLjQ4JSwgMTAwJSB7IG9mZnNldC1kaXN0YW5jZTogMTAwJTsgb3BhY2l0eTogMDsgfQogICAgfQogICAgQG1lZGlhIChwcmVmZXJzLXJlZHVjZWQtbW90aW9uOiByZWR1Y2UpIHsgLmFycm93IHsgYW5pbWF0aW9uOiBub25lOyB9IH0KICA8L3N0eWxlPgogIDwhLS0gb3JhbmdlIHJ1bnMgdW5kZXIgZ3JlZW4gYW5kIGJsdWU6IHRoZXkgY3V0IGl0LCA0IHB4IHdpZGVyIHRoYW4gdGhlbXNlbHZlcyBvbiBlYWNoIHNpZGUgLS0+CiAgPG1hc2sgaWQ9InVuZGVyIiBtYXNrVW5pdHM9InVzZXJTcGFjZU9uVXNlIiB4PSIwIiB5PSIwIiB3aWR0aD0iMTI4IiBoZWlnaHQ9IjEyOCI+CiAgICA8cmVjdCB3aWR0aD0iMTI4IiBoZWlnaHQ9IjEyOCIgZmlsbD0iI2ZmZiIvPgogICAgPGcgZmlsbD0ibm9uZSIgc3Ryb2tlPSIjMDAwIiBzdHJva2Utd2lkdGg9IjIwIj48dXNlIGhyZWY9IiNncmVlbiIvPjx1c2UgaHJlZj0iI2JsdWUiLz48L2c+CiAgPC9tYXNrPgogIDxnIGZpbGw9Im5vbmUiIHN0cm9rZS13aWR0aD0iMTIiPgogICAgPGcgbWFzaz0idXJsKCN1bmRlcikiPgogICAgICA8cGF0aCBkPSJNNzIgNCBWMTI0IiBzdHJva2U9IiNmZjAwZDQiLz4KICAgICAgPHBvbHlnb24gY2xhc3M9ImFycm93IGExIiBwb2ludHM9IjcsMCAtNywtNC41IC03LDQuNSIgc3Ryb2tlPSJub25lIi8+CiAgICA8L2c+CiAgICA8dXNlIGhyZWY9IiNncmVlbiIgc3Ryb2tlPSIjM2Q1YWZlIi8+CiAgICA8cG9seWdvbiBjbGFzcz0iYXJyb3cgYTIiIHBvaW50cz0iNywwIC03LC00LjUgLTcsNC41IiBzdHJva2U9Im5vbmUiLz4KICAgIDx1c2UgaHJlZj0iI2JsdWUiIHN0cm9rZT0iI2M2ZmYwMCIvPgogICAgPHBvbHlnb24gY2xhc3M9ImFycm93IGEzIiBwb2ludHM9IjcsMCAtNywtNC41IC03LDQuNSIgc3Ryb2tlPSJub25lIi8+CiAgPC9nPgo8L3N2Zz4K" alt=""><div><div class="about-name">linemap</div><div class="about-tag">Flowcharts as metro maps · <a href="https://github.com/mergezalot/linemap" target="_blank" rel="noopener">github.com/mergezalot/linemap</a></div></div></div>
|
|
915
|
+
<h2>Keys and gestures</h2>
|
|
916
|
+
<table>
|
|
917
|
+
<tr><th>Zoom</th><td>wheel, pinch, <kbd>+</kbd> <kbd>-</kbd>, double-click</td></tr>
|
|
918
|
+
<tr><th>Fit</th><td><kbd>0</kbd></td></tr>
|
|
919
|
+
<tr><th>Pan</th><td>drag, arrow keys</td></tr>
|
|
920
|
+
<tr><th>Highlight a line</th><td>hover it, or its legend row</td></tr>
|
|
921
|
+
<tr><th>Pin a line</th><td>click it; <kbd>Shift</kbd>-click adds; <kbd>Esc</kbd> clears</td></tr>
|
|
922
|
+
<tr><th>Pin a node's lines</th><td>click the node; <kbd>Shift</kbd>-click adds</td></tr>
|
|
923
|
+
<tr><th>Open a node's link</th><td><kbd>Ctrl</kbd>-click (<kbd>⌘</kbd>-click on a Mac)</td></tr>
|
|
924
|
+
<tr><th>Hide a line</th><td>click its legend row; <kbd>Alt</kbd>/<kbd>Shift</kbd>-click: only this line</td></tr>
|
|
925
|
+
<tr><th>Search</th><td><kbd>/</kbd> or <kbd>Ctrl</kbd> <kbd>F</kbd></td></tr>
|
|
926
|
+
<tr><th>Next theme</th><td><kbd>T</kbd></td></tr>
|
|
927
|
+
<tr><th>Reload</th><td><kbd>R</kbd></td></tr>
|
|
928
|
+
<tr><th>Open / paste</th><td>drop a file, or paste DOT text anywhere</td></tr>
|
|
929
|
+
</table>
|
|
930
|
+
<p class="hint">The address keeps hidden lines, through settings, the theme and the view, so a link shows the same map.</p>
|
|
931
|
+
<p class="hint licenses">linemap is free software under the Mozilla Public License 2.0. It includes MSAGL (MIT, Microsoft). The license texts are in this page's source.</p>
|
|
932
|
+
<p class="hint copyright">© 2026 Michael Karlen</p>
|
|
933
|
+
<div class="dialog-actions"><button class="btn primary" value="ok">Close</button></div>
|
|
934
|
+
</form>
|
|
935
|
+
</dialog>
|
|
936
|
+
|
|
937
|
+
<script type="application/json" id="linemap-flows">[]</script>
|
|
938
|
+
<script>(()=>{var Q0=Object.seal({Graph:null,Digraph:null,Subgraph:null,Node:null,Edge:null});var gs=class extends Error{constructor(t,e){super(`AST node count (${t}) exceeds maximum allowed (${e}). Consider increasing 'maxASTNodes' option or simplifying the input.`),this.nodeCount=t,this.maxNodes=e,this.name="ASTNodeCountExceededError"}},sf=1e5,ps=class{constructor(t){this.options=t,this.maxNodes=t?.maxASTNodes??sf}nodeCount=0;maxNodes;getLocation(){return this.options?.locationFunction?.()??null}createElement(t,e,i=[]){if(this.nodeCount++,this.maxNodes>0&&this.nodeCount>this.maxNodes)throw new gs(this.nodeCount,this.maxNodes);return{location:this.getLocation(),...e,type:t,children:i}}resetNodeCount(){this.nodeCount=0}};function of(n){let t=new ps(n);return t.createElement.bind(t)}var _0=of(),Nr=class extends SyntaxError{constructor(t,e,i,r){super(t),this.expected=e,this.found=i,this.location=r,this.name="SyntaxError"}format(t){let e="Error: "+this.message;if(this.location){let i=null,r=t.find(l=>l.source===this.location.source);r&&(i=r.text.split(/\r\n|\n|\r/g));let s=this.location.start,o=this.location.source&&typeof this.location.source.offset=="function"?this.location.source.offset(s):s,a=this.location.source+":"+o.line+":"+o.column;if(i){let l=this.location.end,h="".padEnd(o.line.toString().length," "),u=i[s.line-1],c=(s.line===l.line?l.column:u.length+1)-s.column||1;e+=`
|
|
939
|
+
--> `+a+`
|
|
940
|
+
`+h+` |
|
|
941
|
+
`+o.line+" | "+u+`
|
|
942
|
+
`+h+" | "+"".padEnd(s.column-1," ")+"".padEnd(c,"^")}else e+=`
|
|
943
|
+
at `+a}return e}static buildMessage(t,e){function i(c){return c.codePointAt(0).toString(16).toUpperCase()}let r=Object.prototype.hasOwnProperty.call(RegExp.prototype,"unicode")?new RegExp("[\\p{C}\\p{Mn}\\p{Mc}]","gu"):null;function s(c){return r?c.replace(r,f=>"\\u{"+i(f)+"}"):c}function o(c){return s(c.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/\0/g,"\\0").replace(/\t/g,"\\t").replace(/\n/g,"\\n").replace(/\r/g,"\\r").replace(/[\x00-\x0F]/g,f=>"\\x0"+i(f)).replace(/[\x10-\x1F\x7F-\x9F]/g,f=>"\\x"+i(f)))}function a(c){return s(c.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,f=>"\\x0"+i(f)).replace(/[\x10-\x1F\x7F-\x9F]/g,f=>"\\x"+i(f)))}let l={literal(c){return'"'+o(c.text)+'"'},class(c){let f=c.parts.map(m=>Array.isArray(m)?a(m[0])+"-"+a(m[1]):a(m));return"["+(c.inverted?"^":"")+f.join("")+"]"+(c.unicode?"u":"")},any(){return"any character"},end(){return"end of input"},other(c){return c.description}};function h(c){return l[c.type](c)}function u(c){let f=c.map(h);if(f.sort(),f.length>0){let m=1;for(let P=1;P<f.length;P++)f[P-1]!==f[P]&&(f[m]=f[P],m++);f.length=m}switch(f.length){case 1:return f[0];case 2:return f[0]+" or "+f[1];default:return f.slice(0,-1).join(", ")+", or "+f[f.length-1]}}function d(c){return c?'"'+o(c)+'"':"end of input"}return"Expected "+u(t)+" but "+d(e)+" found."}};function af(n,t){t=t!==void 0?t:{};let e={},i=t.grammarSource,r={Dot:$l,Graph:Hl,Subgraph:Vo,Node:No,Edge:Mo,AttributeList:Go,Attribute:Do,ClusterStatements:ko},s=$l,o="strict",a="graph",l="digraph",h="{",u="}",d="node",c="edge",f="=",m="[",P="]",v="->",b="--",C=":",E="subgraph",w="n",F="ne",V="e",q="se",_="s",T="sw",B="w",z="nw",tt='"',O="/*",L="*/",U="//",st="#",W="-",K=".",at="<",ut=">",$="\\",Z=`
|
|
944
|
+
`,Q=`\r
|
|
945
|
+
`,ot=/^[,;]/,Xt=/^[$A-Z_a-z\xAA\xB5\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0370-\u0374\u0376-\u0377\u037A-\u037D\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u048A-\u0527\u0531-\u0556\u0559\u0561-\u0587\u05D0-\u05EA\u05F0-\u05F2\u0620-\u064A\u066E-\u066F\u0671-\u06D3\u06D5\u06E5-\u06E6\u06EE-\u06EF\u06FA-\u06FC\u06FF\u0710\u0712-\u072F\u074D-\u07A5\u07B1\u07CA-\u07EA\u07F4-\u07F5\u07FA\u0800-\u0815\u081A\u0824\u0828\u0840-\u0858\u08A0\u08A2-\u08AC\u0904-\u0939\u093D\u0950\u0958-\u0961\u0971-\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-\u0E46\u0E81-\u0E82\u0E84\u0E87-\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA-\u0EAB\u0EAD-\u0EB0\u0EB2-\u0EB3\u0EBD\u0EC0-\u0EC4\u0EC6\u0EDC-\u0EDF\u0F00\u0F40-\u0F47\u0F49-\u0F6C\u0F88-\u0F8C\u1000-\u102A\u103F\u1050-\u1055\u105A-\u105D\u1061\u1065-\u1066\u106E-\u1070\u1075-\u1081\u108E\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\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\u16EE-\u16F0\u1700-\u170C\u170E-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176C\u176E-\u1770\u1780-\u17B3\u17D7\u17DC\u1820-\u1877\u1880-\u18A8\u18AA\u18B0-\u18F5\u1900-\u191C\u1950-\u196D\u1970-\u1974\u1980-\u19AB\u19C1-\u19C7\u1A00-\u1A16\u1A20-\u1A54\u1AA7\u1B05-\u1B33\u1B45-\u1B4B\u1B83-\u1BA0\u1BAE-\u1BAF\u1BBA-\u1BE5\u1C00-\u1C23\u1C4D-\u1C4F\u1C5A-\u1C7D\u1CE9-\u1CEC\u1CEE-\u1CF1\u1CF5-\u1CF6\u1D00-\u1DBF\u1E00-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u2071\u207F\u2090-\u209C\u2102\u2107\u210A-\u2113\u2115\u2119-\u211D\u2124\u2126\u2128\u212A-\u212D\u212F-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2160-\u2188\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CEE\u2CF2-\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D80-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u2E2F\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303C\u3041-\u3096\u309D-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312D\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FCC\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA61F\uA62A-\uA62B\uA640-\uA66E\uA67F-\uA697\uA6A0-\uA6EF\uA717-\uA71F\uA722-\uA788\uA78B-\uA78E\uA790-\uA793\uA7A0-\uA7AA\uA7F8-\uA801\uA803-\uA805\uA807-\uA80A\uA80C-\uA822\uA840-\uA873\uA882-\uA8B3\uA8F2-\uA8F7\uA8FB\uA90A-\uA925\uA930-\uA946\uA960-\uA97C\uA984-\uA9B2\uA9CF\uAA00-\uAA28\uAA40-\uAA42\uAA44-\uAA4B\uAA60-\uAA76\uAA7A\uAA80-\uAAAF\uAAB1\uAAB5-\uAAB6\uAAB9-\uAABD\uAAC0\uAAC2\uAADB-\uAADD\uAAE0-\uAAEA\uAAF2-\uAAF4\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uABC0-\uABE2\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\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\uFF21-\uFF3A\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC]/,ae=/^[$0-9A-Z_a-z\xAA\xB5\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0370-\u0374\u0376-\u0377\u037A-\u037D\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u048A-\u0527\u0531-\u0556\u0559\u0561-\u0587\u05D0-\u05EA\u05F0-\u05F2\u0620-\u064A\u0660-\u0669\u066E-\u066F\u0671-\u06D3\u06D5\u06E5-\u06E6\u06EE-\u06FC\u06FF\u0710\u0712-\u072F\u074D-\u07A5\u07B1\u07C0-\u07EA\u07F4-\u07F5\u07FA\u0800-\u0815\u081A\u0824\u0828\u0840-\u0858\u08A0\u08A2-\u08AC\u0904-\u0939\u093D\u0950\u0958-\u0961\u0966-\u096F\u0971-\u0977\u0979-\u097F\u0985-\u098C\u098F-\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BD\u09CE\u09DC-\u09DD\u09DF-\u09E1\u09E6-\u09F1\u0A05-\u0A0A\u0A0F-\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32-\u0A33\u0A35-\u0A36\u0A38-\u0A39\u0A59-\u0A5C\u0A5E\u0A66-\u0A6F\u0A72-\u0A74\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2-\u0AB3\u0AB5-\u0AB9\u0ABD\u0AD0\u0AE0-\u0AE1\u0AE6-\u0AEF\u0B05-\u0B0C\u0B0F-\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32-\u0B33\u0B35-\u0B39\u0B3D\u0B5C-\u0B5D\u0B5F-\u0B61\u0B66-\u0B6F\u0B71\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99-\u0B9A\u0B9C\u0B9E-\u0B9F\u0BA3-\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BD0\u0BE6-\u0BEF\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C33\u0C35-\u0C39\u0C3D\u0C58-\u0C59\u0C60-\u0C61\u0C66-\u0C6F\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBD\u0CDE\u0CE0-\u0CE1\u0CE6-\u0CEF\u0CF1-\u0CF2\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D\u0D4E\u0D60-\u0D61\u0D66-\u0D6F\u0D7A-\u0D7F\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0E01-\u0E30\u0E32-\u0E33\u0E40-\u0E46\u0E50-\u0E59\u0E81-\u0E82\u0E84\u0E87-\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA-\u0EAB\u0EAD-\u0EB0\u0EB2-\u0EB3\u0EBD\u0EC0-\u0EC4\u0EC6\u0ED0-\u0ED9\u0EDC-\u0EDF\u0F00\u0F20-\u0F29\u0F40-\u0F47\u0F49-\u0F6C\u0F88-\u0F8C\u1000-\u102A\u103F-\u1049\u1050-\u1055\u105A-\u105D\u1061\u1065-\u1066\u106E-\u1070\u1075-\u1081\u108E\u1090-\u1099\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\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\u16EE-\u16F0\u1700-\u170C\u170E-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176C\u176E-\u1770\u1780-\u17B3\u17D7\u17DC\u17E0-\u17E9\u1810-\u1819\u1820-\u1877\u1880-\u18A8\u18AA\u18B0-\u18F5\u1900-\u191C\u1946-\u196D\u1970-\u1974\u1980-\u19AB\u19C1-\u19C7\u19D0-\u19D9\u1A00-\u1A16\u1A20-\u1A54\u1A80-\u1A89\u1A90-\u1A99\u1AA7\u1B05-\u1B33\u1B45-\u1B4B\u1B50-\u1B59\u1B83-\u1BA0\u1BAE-\u1BE5\u1C00-\u1C23\u1C40-\u1C49\u1C4D-\u1C7D\u1CE9-\u1CEC\u1CEE-\u1CF1\u1CF5-\u1CF6\u1D00-\u1DBF\u1E00-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u2071\u207F\u2090-\u209C\u2102\u2107\u210A-\u2113\u2115\u2119-\u211D\u2124\u2126\u2128\u212A-\u212D\u212F-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2160-\u2188\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CEE\u2CF2-\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D80-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u2E2F\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303C\u3041-\u3096\u309D-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312D\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FCC\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA62B\uA640-\uA66E\uA67F-\uA697\uA6A0-\uA6EF\uA717-\uA71F\uA722-\uA788\uA78B-\uA78E\uA790-\uA793\uA7A0-\uA7AA\uA7F8-\uA801\uA803-\uA805\uA807-\uA80A\uA80C-\uA822\uA840-\uA873\uA882-\uA8B3\uA8D0-\uA8D9\uA8F2-\uA8F7\uA8FB\uA900-\uA925\uA930-\uA946\uA960-\uA97C\uA984-\uA9B2\uA9CF-\uA9D9\uAA00-\uAA28\uAA40-\uAA42\uAA44-\uAA4B\uAA50-\uAA59\uAA60-\uAA76\uAA7A\uAA80-\uAAAF\uAAB1\uAAB5-\uAAB6\uAAB9-\uAABD\uAAC0\uAAC2\uAADB-\uAADD\uAAE0-\uAAEA\uAAF2-\uAAF4\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uABC0-\uABE2\uABF0-\uABF9\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\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\uFF10-\uFF19\uFF21-\uFF3A\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC]/,oe=/^[0-9]/,or=/^[<>]/,cn=/^[\n\r"\u2028-\u2029]/,og=/^[\r\u2028-\u2029]/,Ll=/^[\t-\n\r ]/,ag=/^[\n\r]/,lg=/^[ \t]/,hg=ft("strict",!0),Bl=ft("graph",!0),ug=ft("digraph",!0),Bo=ft("{",!1),Ro=ft("}",!1),is=ft(";",!1),dg=ft("node",!0),cg=ft("edge",!0),gg=ft("=",!1),rs=ii([",",";"],!1,!1,!1),pg=ft("[",!1),fg=ft("]",!1),mg=ft("->",!1),Pg=ft("--",!1),yg=ls("port"),Rl=ft(":",!1),Sg=ft("subgraph",!0),bg=ft("n",!1),Cg=ft("ne",!1),vg=ft("e",!1),xg=ft("se",!1),Eg=ft("s",!1),Ag=ft("sw",!1),wg=ft("w",!1),Ig=ft("nw",!1),ns=ft('"',!1),Tg=ft("/*",!1),Fo=ft("*/",!1),ei=Ip(),Og=ft("//",!1),Lg=ft("#",!1),Bg=ls("UNICODE_STRING"),Rg=ii(["$",["A","Z"],"_",["a","z"],"\xAA","\xB5","\xBA",["\xC0","\xD6"],["\xD8","\xF6"],["\xF8","\u02C1"],["\u02C6","\u02D1"],["\u02E0","\u02E4"],"\u02EC","\u02EE",["\u0370","\u0374"],["\u0376","\u0377"],["\u037A","\u037D"],"\u0386",["\u0388","\u038A"],"\u038C",["\u038E","\u03A1"],["\u03A3","\u03F5"],["\u03F7","\u0481"],["\u048A","\u0527"],["\u0531","\u0556"],"\u0559",["\u0561","\u0587"],["\u05D0","\u05EA"],["\u05F0","\u05F2"],["\u0620","\u064A"],["\u066E","\u066F"],["\u0671","\u06D3"],"\u06D5",["\u06E5","\u06E6"],["\u06EE","\u06EF"],["\u06FA","\u06FC"],"\u06FF","\u0710",["\u0712","\u072F"],["\u074D","\u07A5"],"\u07B1",["\u07CA","\u07EA"],["\u07F4","\u07F5"],"\u07FA",["\u0800","\u0815"],"\u081A","\u0824","\u0828",["\u0840","\u0858"],"\u08A0",["\u08A2","\u08AC"],["\u0904","\u0939"],"\u093D","\u0950",["\u0958","\u0961"],["\u0971","\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","\u0E46"],["\u0E81","\u0E82"],"\u0E84",["\u0E87","\u0E88"],"\u0E8A","\u0E8D",["\u0E94","\u0E97"],["\u0E99","\u0E9F"],["\u0EA1","\u0EA3"],"\u0EA5","\u0EA7",["\u0EAA","\u0EAB"],["\u0EAD","\u0EB0"],["\u0EB2","\u0EB3"],"\u0EBD",["\u0EC0","\u0EC4"],"\u0EC6",["\u0EDC","\u0EDF"],"\u0F00",["\u0F40","\u0F47"],["\u0F49","\u0F6C"],["\u0F88","\u0F8C"],["\u1000","\u102A"],"\u103F",["\u1050","\u1055"],["\u105A","\u105D"],"\u1061",["\u1065","\u1066"],["\u106E","\u1070"],["\u1075","\u1081"],"\u108E",["\u10A0","\u10C5"],"\u10C7","\u10CD",["\u10D0","\u10FA"],["\u10FC","\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"],["\u16EE","\u16F0"],["\u1700","\u170C"],["\u170E","\u1711"],["\u1720","\u1731"],["\u1740","\u1751"],["\u1760","\u176C"],["\u176E","\u1770"],["\u1780","\u17B3"],"\u17D7","\u17DC",["\u1820","\u1877"],["\u1880","\u18A8"],"\u18AA",["\u18B0","\u18F5"],["\u1900","\u191C"],["\u1950","\u196D"],["\u1970","\u1974"],["\u1980","\u19AB"],["\u19C1","\u19C7"],["\u1A00","\u1A16"],["\u1A20","\u1A54"],"\u1AA7",["\u1B05","\u1B33"],["\u1B45","\u1B4B"],["\u1B83","\u1BA0"],["\u1BAE","\u1BAF"],["\u1BBA","\u1BE5"],["\u1C00","\u1C23"],["\u1C4D","\u1C4F"],["\u1C5A","\u1C7D"],["\u1CE9","\u1CEC"],["\u1CEE","\u1CF1"],["\u1CF5","\u1CF6"],["\u1D00","\u1DBF"],["\u1E00","\u1F15"],["\u1F18","\u1F1D"],["\u1F20","\u1F45"],["\u1F48","\u1F4D"],["\u1F50","\u1F57"],"\u1F59","\u1F5B","\u1F5D",["\u1F5F","\u1F7D"],["\u1F80","\u1FB4"],["\u1FB6","\u1FBC"],"\u1FBE",["\u1FC2","\u1FC4"],["\u1FC6","\u1FCC"],["\u1FD0","\u1FD3"],["\u1FD6","\u1FDB"],["\u1FE0","\u1FEC"],["\u1FF2","\u1FF4"],["\u1FF6","\u1FFC"],"\u2071","\u207F",["\u2090","\u209C"],"\u2102","\u2107",["\u210A","\u2113"],"\u2115",["\u2119","\u211D"],"\u2124","\u2126","\u2128",["\u212A","\u212D"],["\u212F","\u2139"],["\u213C","\u213F"],["\u2145","\u2149"],"\u214E",["\u2160","\u2188"],["\u2C00","\u2C2E"],["\u2C30","\u2C5E"],["\u2C60","\u2CE4"],["\u2CEB","\u2CEE"],["\u2CF2","\u2CF3"],["\u2D00","\u2D25"],"\u2D27","\u2D2D",["\u2D30","\u2D67"],"\u2D6F",["\u2D80","\u2D96"],["\u2DA0","\u2DA6"],["\u2DA8","\u2DAE"],["\u2DB0","\u2DB6"],["\u2DB8","\u2DBE"],["\u2DC0","\u2DC6"],["\u2DC8","\u2DCE"],["\u2DD0","\u2DD6"],["\u2DD8","\u2DDE"],"\u2E2F",["\u3005","\u3007"],["\u3021","\u3029"],["\u3031","\u3035"],["\u3038","\u303C"],["\u3041","\u3096"],["\u309D","\u309F"],["\u30A1","\u30FA"],["\u30FC","\u30FF"],["\u3105","\u312D"],["\u3131","\u318E"],["\u31A0","\u31BA"],["\u31F0","\u31FF"],["\u3400","\u4DB5"],["\u4E00","\u9FCC"],["\uA000","\uA48C"],["\uA4D0","\uA4FD"],["\uA500","\uA60C"],["\uA610","\uA61F"],["\uA62A","\uA62B"],["\uA640","\uA66E"],["\uA67F","\uA697"],["\uA6A0","\uA6EF"],["\uA717","\uA71F"],["\uA722","\uA788"],["\uA78B","\uA78E"],["\uA790","\uA793"],["\uA7A0","\uA7AA"],["\uA7F8","\uA801"],["\uA803","\uA805"],["\uA807","\uA80A"],["\uA80C","\uA822"],["\uA840","\uA873"],["\uA882","\uA8B3"],["\uA8F2","\uA8F7"],"\uA8FB",["\uA90A","\uA925"],["\uA930","\uA946"],["\uA960","\uA97C"],["\uA984","\uA9B2"],"\uA9CF",["\uAA00","\uAA28"],["\uAA40","\uAA42"],["\uAA44","\uAA4B"],["\uAA60","\uAA76"],"\uAA7A",["\uAA80","\uAAAF"],"\uAAB1",["\uAAB5","\uAAB6"],["\uAAB9","\uAABD"],"\uAAC0","\uAAC2",["\uAADB","\uAADD"],["\uAAE0","\uAAEA"],["\uAAF2","\uAAF4"],["\uAB01","\uAB06"],["\uAB09","\uAB0E"],["\uAB11","\uAB16"],["\uAB20","\uAB26"],["\uAB28","\uAB2E"],["\uABC0","\uABE2"],["\uAC00","\uD7A3"],["\uD7B0","\uD7C6"],["\uD7CB","\uD7FB"],["\uF900","\uFA6D"],["\uFA70","\uFAD9"],["\uFB00","\uFB06"],["\uFB13","\uFB17"],"\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"],["\uFF21","\uFF3A"],["\uFF41","\uFF5A"],["\uFF66","\uFFBE"],["\uFFC2","\uFFC7"],["\uFFCA","\uFFCF"],["\uFFD2","\uFFD7"],["\uFFDA","\uFFDC"]],!1,!1,!1),Fg=ii(["$",["0","9"],["A","Z"],"_",["a","z"],"\xAA","\xB5","\xBA",["\xC0","\xD6"],["\xD8","\xF6"],["\xF8","\u02C1"],["\u02C6","\u02D1"],["\u02E0","\u02E4"],"\u02EC","\u02EE",["\u0370","\u0374"],["\u0376","\u0377"],["\u037A","\u037D"],"\u0386",["\u0388","\u038A"],"\u038C",["\u038E","\u03A1"],["\u03A3","\u03F5"],["\u03F7","\u0481"],["\u048A","\u0527"],["\u0531","\u0556"],"\u0559",["\u0561","\u0587"],["\u05D0","\u05EA"],["\u05F0","\u05F2"],["\u0620","\u064A"],["\u0660","\u0669"],["\u066E","\u066F"],["\u0671","\u06D3"],"\u06D5",["\u06E5","\u06E6"],["\u06EE","\u06FC"],"\u06FF","\u0710",["\u0712","\u072F"],["\u074D","\u07A5"],"\u07B1",["\u07C0","\u07EA"],["\u07F4","\u07F5"],"\u07FA",["\u0800","\u0815"],"\u081A","\u0824","\u0828",["\u0840","\u0858"],"\u08A0",["\u08A2","\u08AC"],["\u0904","\u0939"],"\u093D","\u0950",["\u0958","\u0961"],["\u0966","\u096F"],["\u0971","\u0977"],["\u0979","\u097F"],["\u0985","\u098C"],["\u098F","\u0990"],["\u0993","\u09A8"],["\u09AA","\u09B0"],"\u09B2",["\u09B6","\u09B9"],"\u09BD","\u09CE",["\u09DC","\u09DD"],["\u09DF","\u09E1"],["\u09E6","\u09F1"],["\u0A05","\u0A0A"],["\u0A0F","\u0A10"],["\u0A13","\u0A28"],["\u0A2A","\u0A30"],["\u0A32","\u0A33"],["\u0A35","\u0A36"],["\u0A38","\u0A39"],["\u0A59","\u0A5C"],"\u0A5E",["\u0A66","\u0A6F"],["\u0A72","\u0A74"],["\u0A85","\u0A8D"],["\u0A8F","\u0A91"],["\u0A93","\u0AA8"],["\u0AAA","\u0AB0"],["\u0AB2","\u0AB3"],["\u0AB5","\u0AB9"],"\u0ABD","\u0AD0",["\u0AE0","\u0AE1"],["\u0AE6","\u0AEF"],["\u0B05","\u0B0C"],["\u0B0F","\u0B10"],["\u0B13","\u0B28"],["\u0B2A","\u0B30"],["\u0B32","\u0B33"],["\u0B35","\u0B39"],"\u0B3D",["\u0B5C","\u0B5D"],["\u0B5F","\u0B61"],["\u0B66","\u0B6F"],"\u0B71","\u0B83",["\u0B85","\u0B8A"],["\u0B8E","\u0B90"],["\u0B92","\u0B95"],["\u0B99","\u0B9A"],"\u0B9C",["\u0B9E","\u0B9F"],["\u0BA3","\u0BA4"],["\u0BA8","\u0BAA"],["\u0BAE","\u0BB9"],"\u0BD0",["\u0BE6","\u0BEF"],["\u0C05","\u0C0C"],["\u0C0E","\u0C10"],["\u0C12","\u0C28"],["\u0C2A","\u0C33"],["\u0C35","\u0C39"],"\u0C3D",["\u0C58","\u0C59"],["\u0C60","\u0C61"],["\u0C66","\u0C6F"],["\u0C85","\u0C8C"],["\u0C8E","\u0C90"],["\u0C92","\u0CA8"],["\u0CAA","\u0CB3"],["\u0CB5","\u0CB9"],"\u0CBD","\u0CDE",["\u0CE0","\u0CE1"],["\u0CE6","\u0CEF"],["\u0CF1","\u0CF2"],["\u0D05","\u0D0C"],["\u0D0E","\u0D10"],["\u0D12","\u0D3A"],"\u0D3D","\u0D4E",["\u0D60","\u0D61"],["\u0D66","\u0D6F"],["\u0D7A","\u0D7F"],["\u0D85","\u0D96"],["\u0D9A","\u0DB1"],["\u0DB3","\u0DBB"],"\u0DBD",["\u0DC0","\u0DC6"],["\u0E01","\u0E30"],["\u0E32","\u0E33"],["\u0E40","\u0E46"],["\u0E50","\u0E59"],["\u0E81","\u0E82"],"\u0E84",["\u0E87","\u0E88"],"\u0E8A","\u0E8D",["\u0E94","\u0E97"],["\u0E99","\u0E9F"],["\u0EA1","\u0EA3"],"\u0EA5","\u0EA7",["\u0EAA","\u0EAB"],["\u0EAD","\u0EB0"],["\u0EB2","\u0EB3"],"\u0EBD",["\u0EC0","\u0EC4"],"\u0EC6",["\u0ED0","\u0ED9"],["\u0EDC","\u0EDF"],"\u0F00",["\u0F20","\u0F29"],["\u0F40","\u0F47"],["\u0F49","\u0F6C"],["\u0F88","\u0F8C"],["\u1000","\u102A"],["\u103F","\u1049"],["\u1050","\u1055"],["\u105A","\u105D"],"\u1061",["\u1065","\u1066"],["\u106E","\u1070"],["\u1075","\u1081"],"\u108E",["\u1090","\u1099"],["\u10A0","\u10C5"],"\u10C7","\u10CD",["\u10D0","\u10FA"],["\u10FC","\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"],["\u16EE","\u16F0"],["\u1700","\u170C"],["\u170E","\u1711"],["\u1720","\u1731"],["\u1740","\u1751"],["\u1760","\u176C"],["\u176E","\u1770"],["\u1780","\u17B3"],"\u17D7","\u17DC",["\u17E0","\u17E9"],["\u1810","\u1819"],["\u1820","\u1877"],["\u1880","\u18A8"],"\u18AA",["\u18B0","\u18F5"],["\u1900","\u191C"],["\u1946","\u196D"],["\u1970","\u1974"],["\u1980","\u19AB"],["\u19C1","\u19C7"],["\u19D0","\u19D9"],["\u1A00","\u1A16"],["\u1A20","\u1A54"],["\u1A80","\u1A89"],["\u1A90","\u1A99"],"\u1AA7",["\u1B05","\u1B33"],["\u1B45","\u1B4B"],["\u1B50","\u1B59"],["\u1B83","\u1BA0"],["\u1BAE","\u1BE5"],["\u1C00","\u1C23"],["\u1C40","\u1C49"],["\u1C4D","\u1C7D"],["\u1CE9","\u1CEC"],["\u1CEE","\u1CF1"],["\u1CF5","\u1CF6"],["\u1D00","\u1DBF"],["\u1E00","\u1F15"],["\u1F18","\u1F1D"],["\u1F20","\u1F45"],["\u1F48","\u1F4D"],["\u1F50","\u1F57"],"\u1F59","\u1F5B","\u1F5D",["\u1F5F","\u1F7D"],["\u1F80","\u1FB4"],["\u1FB6","\u1FBC"],"\u1FBE",["\u1FC2","\u1FC4"],["\u1FC6","\u1FCC"],["\u1FD0","\u1FD3"],["\u1FD6","\u1FDB"],["\u1FE0","\u1FEC"],["\u1FF2","\u1FF4"],["\u1FF6","\u1FFC"],"\u2071","\u207F",["\u2090","\u209C"],"\u2102","\u2107",["\u210A","\u2113"],"\u2115",["\u2119","\u211D"],"\u2124","\u2126","\u2128",["\u212A","\u212D"],["\u212F","\u2139"],["\u213C","\u213F"],["\u2145","\u2149"],"\u214E",["\u2160","\u2188"],["\u2C00","\u2C2E"],["\u2C30","\u2C5E"],["\u2C60","\u2CE4"],["\u2CEB","\u2CEE"],["\u2CF2","\u2CF3"],["\u2D00","\u2D25"],"\u2D27","\u2D2D",["\u2D30","\u2D67"],"\u2D6F",["\u2D80","\u2D96"],["\u2DA0","\u2DA6"],["\u2DA8","\u2DAE"],["\u2DB0","\u2DB6"],["\u2DB8","\u2DBE"],["\u2DC0","\u2DC6"],["\u2DC8","\u2DCE"],["\u2DD0","\u2DD6"],["\u2DD8","\u2DDE"],"\u2E2F",["\u3005","\u3007"],["\u3021","\u3029"],["\u3031","\u3035"],["\u3038","\u303C"],["\u3041","\u3096"],["\u309D","\u309F"],["\u30A1","\u30FA"],["\u30FC","\u30FF"],["\u3105","\u312D"],["\u3131","\u318E"],["\u31A0","\u31BA"],["\u31F0","\u31FF"],["\u3400","\u4DB5"],["\u4E00","\u9FCC"],["\uA000","\uA48C"],["\uA4D0","\uA4FD"],["\uA500","\uA60C"],["\uA610","\uA62B"],["\uA640","\uA66E"],["\uA67F","\uA697"],["\uA6A0","\uA6EF"],["\uA717","\uA71F"],["\uA722","\uA788"],["\uA78B","\uA78E"],["\uA790","\uA793"],["\uA7A0","\uA7AA"],["\uA7F8","\uA801"],["\uA803","\uA805"],["\uA807","\uA80A"],["\uA80C","\uA822"],["\uA840","\uA873"],["\uA882","\uA8B3"],["\uA8D0","\uA8D9"],["\uA8F2","\uA8F7"],"\uA8FB",["\uA900","\uA925"],["\uA930","\uA946"],["\uA960","\uA97C"],["\uA984","\uA9B2"],["\uA9CF","\uA9D9"],["\uAA00","\uAA28"],["\uAA40","\uAA42"],["\uAA44","\uAA4B"],["\uAA50","\uAA59"],["\uAA60","\uAA76"],"\uAA7A",["\uAA80","\uAAAF"],"\uAAB1",["\uAAB5","\uAAB6"],["\uAAB9","\uAABD"],"\uAAC0","\uAAC2",["\uAADB","\uAADD"],["\uAAE0","\uAAEA"],["\uAAF2","\uAAF4"],["\uAB01","\uAB06"],["\uAB09","\uAB0E"],["\uAB11","\uAB16"],["\uAB20","\uAB26"],["\uAB28","\uAB2E"],["\uABC0","\uABE2"],["\uABF0","\uABF9"],["\uAC00","\uD7A3"],["\uD7B0","\uD7C6"],["\uD7CB","\uD7FB"],["\uF900","\uFA6D"],["\uFA70","\uFAD9"],["\uFB00","\uFB06"],["\uFB13","\uFB17"],"\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"],["\uFF10","\uFF19"],["\uFF21","\uFF3A"],["\uFF41","\uFF5A"],["\uFF66","\uFFBE"],["\uFFC2","\uFFC7"],["\uFFCA","\uFFCF"],["\uFFD2","\uFFD7"],["\uFFDA","\uFFDC"]],!1,!1,!1),Ng=ls("NUMBER"),Gg=ft("-",!1),Fl=ft(".",!1),Br=ii([["0","9"]],!1,!1,!1),Dg=ft("<",!1),Mg=ft(">",!1),Nl=ii(["<",">"],!1,!1,!1),Vg=ii([`
|
|
946
|
+
`,"\r",'"',["\u2028","\u2029"]],!1,!1,!1),Gl=ft("\\",!1),kg=ls("end of line"),$g=ft(`
|
|
947
|
+
`,!1),Hg=ft(`\r
|
|
948
|
+
`,!1),Wg=ii(["\r",["\u2028","\u2029"]],!1,!1,!1),Dl=ii([[" ",`
|
|
949
|
+
`],"\r"," "],!1,!1,!1),zg=ii([`
|
|
950
|
+
`,"\r"],!1,!1,!1),qg=ii([" "," "],!1,!1,!1);function B0(p){return p}function R0(p){return p}function F0(p){return p}function N0(p){return p}function G0(p){return p}function D0(p){return p}function M0(p){return p}function V0(p){return p}function k0(p){return p}function $0(p){return p}function Ug(p,y,A){return _t.createElement("Dot",{},[...p,y,...A])}function jg(p,y,A,I){let k=!!p,yt=y.toLowerCase()==="digraph";for(let Mi of zo)yt?Mi.operator!=="->"&&as(`In digraph, it's necessary to describe with "->" operator to create edge.`,Mi.location):Mi.operator!=="--"&&as(`In graph, it's necessary to describe with "--" operator to create edge.`,Mi.location);return _t.createElement("Graph",A!==null?{id:A,directed:yt,strict:k}:{directed:yt,strict:k},I)}function Qg(p){return _t.createElement("Attribute",{...p},[])}function Xg(p,y){return _t.createElement("AttributeList",{kind:`${p.slice(0,1).toUpperCase()}${p.slice(1).toLowerCase()}`},y)}function Yg(p,y,A){return cs=0,_t.createElement("Edge",{targets:[p,...y]},A??[])}function Jg(p,y){return _t.createElement("Node",{id:p},y??[])}function Zg(p,y){return{key:p,value:y}}function Kg(p){return _t.createElement("Attribute",{...p,location:os()},[])}function H0(p){return p}function Ml(p,y){return y}function _g(p,y){return _t.createElement("NodeRefGroup",{},[p,...y])}function tp(p){return{operator:p,location:os()}}function ep(p,y,A){if(cs++,cs>ih){let I=os();as(`Edge chain depth exceeds maximum allowed depth of ${ih} at line ${I.start.line}, column ${I.start.column}. Consider breaking up long edge chains or increasing the 'maxEdgeChainDepth' option.`)}return zo.push(p),[y].concat(A||[])}function ip(p,y){return _t.createElement("NodeRef",{id:p,...y},[])}function rp(p,y){return y}function np(p,y){return["n","ne","e","se","s","sw","w","nw"].includes(p)?{compass:p}:y?{port:p,compass:y}:{port:p}}function W0(p){return p}function sp(p,y){let A=y??[];return _t.createElement("Subgraph",p?{id:p}:{},A)}function op(p){return{value:p,quoted:!1}}function ap(p){return{value:p,quoted:!0}}function lp(p){return _t.createElement("Literal",{...p},[])}function hp(p){return _t.createElement("Literal",{value:p,quoted:!1},[])}function z0(p){return p}function up(p){return _t.createElement("Comment",{kind:"Block",value:Wo(p.join("").replace(/[ \t]*\*/g,""))},[])}function dp(p){return _t.createElement("Comment",{kind:"Slash",value:Wo(p.join(`
|
|
951
|
+
`))},[])}function q0(p){return p}function cp(p){return p.join("")}function gp(p){return _t.createElement("Comment",{kind:"Macro",value:Wo(p.join(`
|
|
952
|
+
`))},[])}function U0(p){return p}function pp(p){return p.join("")}function fp(p,y){return p+y.join("")}function mp(p,y){return p+y}function Pp(p){return Vl()}function yp(p){return _t.createElement("Literal",{value:p.slice(1,p.length-1),quoted:"html"},[])}function Sp(){return ds>=eh&&as(`HTML nesting depth exceeds maximum allowed depth of ${eh}`),ds++,!0}function bp(p){return ds--,"<"+p.join("")+">"}function j0(p){return p}function Cp(p){return p.join("")}function vp(p){return _t.createElement("Literal",{value:p.join(""),quoted:!0},[])}function xp(){return Vl()}function Ep(p){return p[1]==='"'?'"':p[0]+p[1]}function Ap(){return""}let S=t.peg$currPos|0,nt=S,Rr=[{line:1,column:1}],He=S,ss=t.peg$maxFailExpected||[],H=t.peg$silentFails|0,gn;if(t.startRule){if(!(t.startRule in r))throw new Error(`Can't start parsing from rule "`+t.startRule+'".');s=r[t.startRule]}function Vl(){return n.substring(nt,S)}function os(){return hs(nt,S)}function as(p,y){throw y=y!==void 0?y:hs(nt,S),Op(p,y)}function wp(p=S){let y=n.codePointAt(p);return y===void 0?"":String.fromCodePoint(y)}function ft(p,y){return{type:"literal",text:p,ignoreCase:y}}function ii(p,y,A,I){return{type:"class",parts:p,inverted:y,ignoreCase:A,unicode:I}}function Ip(){return{type:"any"}}function Tp(){return{type:"end"}}function ls(p){return{type:"other",description:p}}function kl(p){let y=Rr[p],A;if(y)return y;if(p>=Rr.length)A=Rr.length-1;else for(A=p;!Rr[--A];);for(y=Rr[A],y={line:y.line,column:y.column};A<p;)n.charCodeAt(A)===10?(y.line++,y.column=1):y.column++,A++;return Rr[p]=y,y}function hs(p,y,A){let I=kl(p),k=kl(y);return{source:i,start:{offset:p,line:I.line,column:I.column},end:{offset:y,line:k.line,column:k.column}}}function X(p){S<He||(S>He&&(He=S,ss=[]),ss.push(p))}function Op(p,y){return new Nr(p,null,null,y)}function Lp(p,y,A){return new Nr(Nr.buildMessage(p,y),p,y,A)}function $l(){let p,y;return p=S,Lt(),y=Bp(),y!==e?(Lt(),nt=p,p=y):(S=p,p=e),p}function Hl(){let p,y;return p=S,Lt(),y=Rp(),y!==e?(Lt(),nt=p,p=y):(S=p,p=e),p}function No(){let p,y;return p=S,Lt(),y=Dp(),y!==e?(Lt(),nt=p,p=y):(S=p,p=e),p}function Go(){let p,y;return p=S,Lt(),y=Np(),y!==e?(Lt(),nt=p,p=y):(S=p,p=e),p}function Do(){let p,y;return p=S,Lt(),y=Fp(),y!==e?(Lt(),nt=p,p=y):(S=p,p=e),p}function Mo(){let p,y;return p=S,Lt(),y=Gp(),y!==e?(Lt(),nt=p,p=y):(S=p,p=e),p}function Vo(){let p,y;return p=S,Lt(),y=zp(),y!==e?(Lt(),nt=p,p=y):(S=p,p=e),p}function us(){let p,y;return p=S,Lt(),y=$p(),y!==e?(Lt(),nt=p,p=y):(S=p,p=e),p}function Wl(){let p,y;return p=S,Lt(),y=Mp(),y!==e?(Lt(),nt=p,p=y):(S=p,p=e),p}function Di(){let p,y;return p=S,Lt(),y=Up(),y!==e?(Lt(),nt=p,p=y):(S=p,p=e),p}function ko(){let p,y;for(p=[],y=Do(),y===e&&(y=Go(),y===e&&(y=Mo(),y===e&&(y=Vo(),y===e&&(y=No(),y===e&&(y=Di())))));y!==e;)p.push(y),y=Do(),y===e&&(y=Go(),y===e&&(y=Mo(),y===e&&(y=Vo(),y===e&&(y=No(),y===e&&(y=Di())))));return p}function Bp(){let p,y,A,I,k;for(p=S,y=[],A=Di();A!==e;)y.push(A),A=Di();if(A=Hl(),A!==e){for(I=[],k=Di();k!==e;)I.push(k),k=Di();nt=p,p=Ug(y,A,I)}else S=p,p=e;return p}function Rp(){let p,y,A,I,k,Y,yt;return p=S,y=n.substr(S,6),y.toLowerCase()===o?S+=6:(y=e,H===0&&X(hg)),y===e&&(y=null),Kt(),A=n.substr(S,5),A.toLowerCase()===a?S+=5:(A=e,H===0&&X(Bl)),A===e&&(A=n.substr(S,7),A.toLowerCase()===l?S+=7:(A=e,H===0&&X(ug))),A!==e?(Kt(),I=ar(),I===e&&(I=null),Lt(),n.charCodeAt(S)===123?(k=h,S++):(k=e,H===0&&X(Bo)),k!==e?(Y=ko(),Lt(),n.charCodeAt(S)===125?(yt=u,S++):(yt=e,H===0&&X(Ro)),yt!==e?(nt=p,p=jg(y,A,I,Y)):(S=p,p=e)):(S=p,p=e)):(S=p,p=e),p}function Fp(){let p,y;return p=S,y=zl(),y!==e?(Kt(),n.charCodeAt(S)===59?S++:H===0&&X(is),nt=p,p=Qg(y)):(S=p,p=e),p}function Np(){let p,y,A;return p=S,y=n.substr(S,5),y.toLowerCase()===a?S+=5:(y=e,H===0&&X(Bl)),y===e&&(y=n.substr(S,4),y.toLowerCase()===d?S+=4:(y=e,H===0&&X(dg)),y===e&&(y=n.substr(S,4),y.toLowerCase()===c?S+=4:(y=e,H===0&&X(cg)))),y!==e?(A=$o(),A!==e?(Kt(),n.charCodeAt(S)===59?S++:H===0&&X(is),nt=p,p=Xg(y,A)):(S=p,p=e)):(S=p,p=e),p}function Gp(){let p,y,A,I;return p=S,y=ql(),y!==e?(A=Ul(),A!==e?(I=$o(),I===e&&(I=null),Kt(),n.charCodeAt(S)===59?S++:H===0&&X(is),nt=p,p=Yg(y,A,I)):(S=p,p=e)):(S=p,p=e),p}function Dp(){let p,y,A;return p=S,y=ar(),y!==e?(Kt(),A=$o(),A===e&&(A=null),Kt(),n.charCodeAt(S)===59?S++:H===0&&X(is),nt=p,p=Jg(y,A)):(S=p,p=e),p}function zl(){let p,y,A,I;return p=S,y=ar(),y!==e?(Kt(),n.charCodeAt(S)===61?(A=f,S++):(A=e,H===0&&X(gg)),A!==e?(Kt(),I=ar(),I!==e?(nt=p,p=Zg(y,I)):(S=p,p=e)):(S=p,p=e)):(S=p,p=e),p}function Mp(){let p,y,A;return p=S,y=zl(),y!==e?(Kt(),A=n.charAt(S),ot.test(A)?S++:(A=e,H===0&&X(rs)),A===e&&(A=null),nt=p,p=Kg(y)):(S=p,p=e),p}function $o(){let p,y,A,I,k;if(p=S,Kt(),n.charCodeAt(S)===91?(y=m,S++):(y=e,H===0&&X(pg)),y!==e){for(A=[],I=Wl(),I===e&&(I=Di());I!==e;)A.push(I),I=Wl(),I===e&&(I=Di());I=Lt(),n.charCodeAt(S)===93?(k=P,S++):(k=e,H===0&&X(fg)),k!==e?(nt=p,p=A):(S=p,p=e)}else S=p,p=e;return p}function Vp(){let p,y,A,I,k,Y,yt;if(p=S,n.charCodeAt(S)===123?(y=h,S++):(y=e,H===0&&X(Bo)),y!==e)if(A=us(),A!==e){for(I=[],k=S,Y=n.charAt(S),ot.test(Y)?S++:(Y=e,H===0&&X(rs)),Y===e&&(Y=null),yt=us(),yt!==e?(nt=k,k=Ml(A,yt)):(S=k,k=e);k!==e;)I.push(k),k=S,Y=n.charAt(S),ot.test(Y)?S++:(Y=e,H===0&&X(rs)),Y===e&&(Y=null),yt=us(),yt!==e?(nt=k,k=Ml(A,yt)):(S=k,k=e);k=n.charAt(S),ot.test(k)?S++:(k=e,H===0&&X(rs)),k===e&&(k=null),Y=Lt(),n.charCodeAt(S)===125?(yt=u,S++):(yt=e,H===0&&X(Ro)),yt!==e?(nt=p,p=_g(A,I)):(S=p,p=e)}else S=p,p=e;else S=p,p=e;return p}function ql(){let p;return p=Vp(),p===e&&(p=us()),p}function kp(){let p,y;return p=S,n.substr(S,2)===v?(y=v,S+=2):(y=e,H===0&&X(mg)),y===e&&(n.substr(S,2)===b?(y=b,S+=2):(y=e,H===0&&X(Pg))),y!==e&&(nt=p,y=tp(y)),p=y,p}function Ul(){let p,y,A,I;return p=S,Kt(),y=kp(),y!==e?(Kt(),A=ql(),A!==e?(Kt(),I=Ul(),I===e&&(I=null),nt=p,p=ep(y,A,I)):(S=p,p=e)):(S=p,p=e),p}function $p(){let p,y,A;return p=S,y=ar(),y!==e?(A=Hp(),A===e&&(A=null),nt=p,p=ip(y,A)):(S=p,p=e),p}function Hp(){let p,y,A,I,k,Y;return H++,p=S,n.charCodeAt(S)===58?(y=C,S++):(y=e,H===0&&X(Rl)),y!==e?(A=ar(),A!==e?(I=S,n.charCodeAt(S)===58?(k=C,S++):(k=e,H===0&&X(Rl)),k!==e?(Y=qp(),Y!==e?(nt=I,I=rp(A,Y)):(S=I,I=e)):(S=I,I=e),I===e&&(I=null),nt=p,p=np(A,I)):(S=p,p=e)):(S=p,p=e),H--,p===e&&(y=e,H===0&&X(yg)),p}function Wp(){let p,y,A;return p=S,y=n.substr(S,8),y.toLowerCase()===E?S+=8:(y=e,H===0&&X(Sg)),y!==e?(Kt(),A=ar(),A===e&&(A=null),Kt(),nt=p,p=A):(S=p,p=e),p}function zp(){let p,y,A,I,k;return p=S,y=Wp(),y===e&&(y=null),n.charCodeAt(S)===123?(A=h,S++):(A=e,H===0&&X(Bo)),A!==e?(I=ko(),I===e&&(I=null),Lt(),n.charCodeAt(S)===125?(k=u,S++):(k=e,H===0&&X(Ro)),k!==e?(nt=p,p=sp(y,I)):(S=p,p=e)):(S=p,p=e),p}function jl(){let p;return n.charCodeAt(S)===110?(p=w,S++):(p=e,H===0&&X(bg)),p===e&&(n.substr(S,2)===F?(p=F,S+=2):(p=e,H===0&&X(Cg)),p===e&&(n.charCodeAt(S)===101?(p=V,S++):(p=e,H===0&&X(vg)),p===e&&(n.substr(S,2)===q?(p=q,S+=2):(p=e,H===0&&X(xg)),p===e&&(n.charCodeAt(S)===115?(p=_,S++):(p=e,H===0&&X(Eg)),p===e&&(n.substr(S,2)===T?(p=T,S+=2):(p=e,H===0&&X(Ag)),p===e&&(n.charCodeAt(S)===119?(p=B,S++):(p=e,H===0&&X(wg)),p===e&&(n.substr(S,2)===z?(p=z,S+=2):(p=e,H===0&&X(Ig))))))))),p}function qp(){let p,y,A,I,k;return p=S,y=S,A=jl(),A!==e&&(nt=y,A=op(A)),y=A,y===e&&(y=S,n.charCodeAt(S)===34?(A=tt,S++):(A=e,H===0&&X(ns)),A!==e?(I=jl(),I!==e?(n.charCodeAt(S)===34?(k=tt,S++):(k=e,H===0&&X(ns)),k!==e?(nt=y,y=ap(I)):(S=y,y=e)):(S=y,y=e)):(S=y,y=e)),y!==e&&(nt=p,y=lp(y)),p=y,p}function ar(){let p,y;return p=Kp(),p===e&&(p=Zp(),p===e&&(p=S,y=Yl(),y===e&&(y=Yp(),y===e&&(y=Zl())),y!==e&&(nt=p,y=hp(y)),p=y)),p}function Up(){let p;return p=jp(),p===e&&(p=Qp(),p===e&&(p=Xp())),p}function jp(){let p,y,A,I,k,Y;if(p=S,n.substr(S,2)===O?(y=O,S+=2):(y=e,H===0&&X(Tg)),y!==e){for(A=[],I=S,k=S,H++,n.substr(S,2)===L?(Y=L,S+=2):(Y=e,H===0&&X(Fo)),H--,Y===e?k=void 0:(S=k,k=e),k!==e?(n.length>S?(Y=n.charAt(S),S++):(Y=e,H===0&&X(ei)),Y!==e?(nt=I,I=Y):(S=I,I=e)):(S=I,I=e);I!==e;)A.push(I),I=S,k=S,H++,n.substr(S,2)===L?(Y=L,S+=2):(Y=e,H===0&&X(Fo)),H--,Y===e?k=void 0:(S=k,k=e),k!==e?(n.length>S?(Y=n.charAt(S),S++):(Y=e,H===0&&X(ei)),Y!==e?(nt=I,I=Y):(S=I,I=e)):(S=I,I=e);n.substr(S,2)===L?(I=L,S+=2):(I=e,H===0&&X(Fo)),I!==e?(nt=p,p=up(A)):(S=p,p=e)}else S=p,p=e;return p}function Qp(){let p,y,A;if(p=S,y=[],A=Ql(),A!==e)for(;A!==e;)y.push(A),A=Ql();else y=e;return y!==e&&(nt=p,y=dp(y)),p=y,p}function Ql(){let p,y,A,I,k,Y;if(p=S,Kt(),n.substr(S,2)===U?(y=U,S+=2):(y=e,H===0&&X(Og)),y!==e){for(A=[],I=S,k=S,H++,Y=Fr(),H--,Y===e?k=void 0:(S=k,k=e),k!==e?(n.length>S?(Y=n.charAt(S),S++):(Y=e,H===0&&X(ei)),Y!==e?(nt=I,I=Y):(S=I,I=e)):(S=I,I=e);I!==e;)A.push(I),I=S,k=S,H++,Y=Fr(),H--,Y===e?k=void 0:(S=k,k=e),k!==e?(n.length>S?(Y=n.charAt(S),S++):(Y=e,H===0&&X(ei)),Y!==e?(nt=I,I=Y):(S=I,I=e)):(S=I,I=e);I=Fr(),I===e&&(I=null),nt=p,p=cp(A)}else S=p,p=e;return p}function Xp(){let p,y,A;if(p=S,y=[],A=Xl(),A!==e)for(;A!==e;)y.push(A),A=Xl();else y=e;return y!==e&&(nt=p,y=gp(y)),p=y,p}function Xl(){let p,y,A,I,k,Y;if(p=S,Kt(),n.charCodeAt(S)===35?(y=st,S++):(y=e,H===0&&X(Lg)),y!==e){for(A=[],I=S,k=S,H++,Y=Fr(),H--,Y===e?k=void 0:(S=k,k=e),k!==e?(n.length>S?(Y=n.charAt(S),S++):(Y=e,H===0&&X(ei)),Y!==e?(nt=I,I=Y):(S=I,I=e)):(S=I,I=e);I!==e;)A.push(I),I=S,k=S,H++,Y=Fr(),H--,Y===e?k=void 0:(S=k,k=e),k!==e?(n.length>S?(Y=n.charAt(S),S++):(Y=e,H===0&&X(ei)),Y!==e?(nt=I,I=Y):(S=I,I=e)):(S=I,I=e);I=Fr(),I===e&&(I=null),nt=p,p=pp(A)}else S=p,p=e;return p}function Yl(){let p,y,A,I;if(H++,p=S,y=Jp(),y!==e){for(A=[],I=Jl();I!==e;)A.push(I),I=Jl();nt=p,p=fp(y,A)}else S=p,p=e;return H--,p===e&&(y=e,H===0&&X(Bg)),p}function Yp(){let p,y,A;return p=S,y=Zl(),y!==e?(A=Yl(),A!==e?(nt=p,p=mp(y,A)):(S=p,p=e)):(S=p,p=e),p}function Jp(){let p;return p=n.charAt(S),Xt.test(p)?S++:(p=e,H===0&&X(Rg)),p}function Jl(){let p;return p=n.charAt(S),ae.test(p)?S++:(p=e,H===0&&X(Fg)),p}function Zl(){let p,y,A,I,k,Y,yt,Mi,Vi;if(H++,p=S,y=S,n.charCodeAt(S)===45?(A=W,S++):(A=e,H===0&&X(Gg)),A===e&&(A=null),I=S,n.charCodeAt(S)===46?(k=K,S++):(k=e,H===0&&X(Fl)),k!==e){if(Y=[],yt=n.charAt(S),oe.test(yt)?S++:(yt=e,H===0&&X(Br)),yt!==e)for(;yt!==e;)Y.push(yt),yt=n.charAt(S),oe.test(yt)?S++:(yt=e,H===0&&X(Br));else Y=e;Y!==e?(k=[k,Y],I=k):(S=I,I=e)}else S=I,I=e;if(I===e){if(I=S,k=[],Y=n.charAt(S),oe.test(Y)?S++:(Y=e,H===0&&X(Br)),Y!==e)for(;Y!==e;)k.push(Y),Y=n.charAt(S),oe.test(Y)?S++:(Y=e,H===0&&X(Br));else k=e;if(k!==e){if(Y=S,n.charCodeAt(S)===46?(yt=K,S++):(yt=e,H===0&&X(Fl)),yt!==e){for(Mi=[],Vi=n.charAt(S),oe.test(Vi)?S++:(Vi=e,H===0&&X(Br));Vi!==e;)Mi.push(Vi),Vi=n.charAt(S),oe.test(Vi)?S++:(Vi=e,H===0&&X(Br));yt=[yt,Mi],Y=yt}else S=Y,Y=e;Y===e&&(Y=null),k=[k,Y],I=k}else S=I,I=e}return I!==e?(A=[A,I],y=A):(S=y,y=e),y!==e&&(nt=p,y=Pp()),p=y,H--,p===e&&(y=e,H===0&&X(Ng)),p}function Zp(){let p,y;return p=S,y=Ho(),y!==e&&(nt=p,y=yp(y)),p=y,p}function Ho(){let p,y,A,I,k;if(p=S,n.charCodeAt(S)===60?(y=at,S++):(y=e,H===0&&X(Dg)),y!==e)if(nt=S,A=Sp(),A?A=void 0:A=e,A!==e){for(I=[],k=Kl(),k===e&&(k=Ho());k!==e;)I.push(k),k=Kl(),k===e&&(k=Ho());n.charCodeAt(S)===62?(k=ut,S++):(k=e,H===0&&X(Mg)),k!==e?(nt=p,p=bp(I)):(S=p,p=e)}else S=p,p=e;else S=p,p=e;return p}function Kl(){let p,y,A,I,k;if(p=S,y=[],A=S,I=S,H++,k=n.charAt(S),or.test(k)?S++:(k=e,H===0&&X(Nl)),H--,k===e?I=void 0:(S=I,I=e),I!==e?(n.length>S?(k=n.charAt(S),S++):(k=e,H===0&&X(ei)),k!==e?(nt=A,A=k):(S=A,A=e)):(S=A,A=e),A!==e)for(;A!==e;)y.push(A),A=S,I=S,H++,k=n.charAt(S),or.test(k)?S++:(k=e,H===0&&X(Nl)),H--,k===e?I=void 0:(S=I,I=e),I!==e?(n.length>S?(k=n.charAt(S),S++):(k=e,H===0&&X(ei)),k!==e?(nt=A,A=k):(S=A,A=e)):(S=A,A=e);else y=e;return y!==e&&(nt=p,y=Cp(y)),p=y,p}function Kp(){let p,y,A,I;if(p=S,n.charCodeAt(S)===34?(y=tt,S++):(y=e,H===0&&X(ns)),y!==e){for(A=[],I=_l();I!==e;)A.push(I),I=_l();n.charCodeAt(S)===34?(I=tt,S++):(I=e,H===0&&X(ns)),I!==e?(nt=p,p=vp(A)):(S=p,p=e)}else S=p,p=e;return p}function _l(){let p,y,A;return p=_p(),p===e&&(p=S,y=S,H++,A=n.charAt(S),cn.test(A)?S++:(A=e,H===0&&X(Vg)),H--,A===e?y=void 0:(S=y,y=e),y!==e?(A=rf(),A!==e?(nt=p,p=xp()):(S=p,p=e)):(S=p,p=e),p===e&&(p=tf())),p}function _p(){let p,y,A,I;return p=S,y=S,n.charCodeAt(S)===92?(A=$,S++):(A=e,H===0&&X(Gl)),A!==e?(n.length>S?(I=n.charAt(S),S++):(I=e,H===0&&X(ei)),I!==e?(A=[A,I],y=A):(S=y,y=e)):(S=y,y=e),y!==e&&(nt=p,y=Ep(y)),p=y,p}function tf(){let p,y,A;return p=S,n.charCodeAt(S)===92?(y=$,S++):(y=e,H===0&&X(Gl)),y!==e?(A=ef(),A!==e?(nt=p,p=Ap()):(S=p,p=e)):(S=p,p=e),p}function ef(){let p;return H++,n.charCodeAt(S)===10?(p=Z,S++):(p=e,H===0&&X($g)),p===e&&(n.substr(S,2)===Q?(p=Q,S+=2):(p=e,H===0&&X(Hg)),p===e&&(p=n.charAt(S),og.test(p)?S++:(p=e,H===0&&X(Wg)))),H--,p===e&&H===0&&X(kg),p}function rf(){let p;return n.length>S?(p=n.charAt(S),S++):(p=e,H===0&&X(ei)),p}function Kt(){let p,y;for(H++,p=[],y=th();y!==e;)p.push(y),y=th();return H--,p}function Lt(){let p,y;for(H++,p=[],y=n.charAt(S),Ll.test(y)?S++:(y=e,H===0&&X(Dl));y!==e;)p.push(y),y=n.charAt(S),Ll.test(y)?S++:(y=e,H===0&&X(Dl));return H--,p}function Fr(){let p;return p=n.charAt(S),ag.test(p)?S++:(p=e,H===0&&X(zg)),p}function th(){let p;return p=n.charAt(S),lg.test(p)?S++:(p=e,H===0&&X(qg)),p}function Wo(p){let y=p.trim(),A=y.match(/\n([\t ]+|(?!\s).)/g);if(A){let I=A.map(Y=>Y.match(/[\t ]/g)?.length??0),k=new RegExp(`
|
|
953
|
+
[ ]{${Math.min(...I)}}`,"g");return y.replace(k,`
|
|
954
|
+
`)}return y}let zo=[],eh=t.maxHtmlNestingDepth??100,ih=t.maxEdgeChainDepth??1e3,ds=0,cs=0,_t=new ps({locationFunction:os,maxASTNodes:t.maxASTNodes});function nf(){_t.resetNodeCount(),ds=0,cs=0,zo.length=0}nf(),gn=s();let qo=gn!==e&&S===n.length;function rh(){throw gn!==e&&S<n.length&&X(Tp()),Lp(ss,He<n.length?wp(He):null,He<n.length?hs(He,He+1):hs(He,He))}if(t.peg$library)return{peg$result:gn,peg$currPos:S,peg$FAILED:e,peg$maxFailExpected:ss,peg$maxFailPos:He,peg$success:qo,peg$throw:qo?void 0:rh};if(qo)return gn;rh()}var lf=10*1024*1024;function nh(n,t){let{startRule:e,filename:i,maxHtmlNestingDepth:r,maxEdgeChainDepth:s,maxInputSize:o,maxASTNodes:a}=t??{},l=o??lf;if(l>0){let h=new TextEncoder().encode(n).length;if(h>l)throw new pn(`Input size (${h} bytes) exceeds maximum allowed size (${l} bytes). Consider increasing 'maxInputSize' option or reducing the input size.`)}try{return af(n,{startRule:e,filename:i,maxHtmlNestingDepth:r,maxEdgeChainDepth:s,maxASTNodes:a})}catch(h){throw h instanceof Nr?new pn(h.message,{cause:h}):h instanceof gs?new pn(h.message,{cause:h}):new Error("Unexpected parse error",{cause:h})}}var pn=class extends SyntaxError{constructor(...t){super(...t),this.name="DotSyntaxError"}};var tb={"\r":String.raw`\r`,"\n":String.raw`\n`,'"':String.raw`\"`};function sh(n){let t=n.value;return n.quoted==="html"?t=t.replace(/\s+/g," ").replace(/<br\s*\/?>/gi,`
|
|
955
|
+
`).replace(/<[^>]*>/g,"").replace(/</g,"<").replace(/>/g,">").replace(/"/g,'"').replace(/&#(\d+);/g,(e,i)=>String.fromCharCode(i)).replace(/&/g,"&"):t=t.replace(/\\\r?\n/g,"").replace(/\\([nlr\\])/g,(e,i)=>i==="\\"?"\\":`
|
|
956
|
+
`),t.split(`
|
|
957
|
+
`).map(e=>e.trim()).join(`
|
|
958
|
+
`).trim()}var fs=n=>Object.fromEntries(n.children.filter(t=>t.type==="Attribute").map(t=>[t.key.value,sh(t.value)])),ms=n=>`line ${n.location?.start.line??"?"}`;function oh(n){let t=nh(n).children.find(h=>h.type==="Graph");if(!t)throw new Error("no graph in DOT file");if(!t.directed)throw new Error("the graph must be a digraph");let e={id:t.id?.value??"graph",attrs:{},lines:[],clusters:[],nodes:[],edges:[]},i=new Map,r=new Map,s=(h,u,d,c,f=!1)=>{if(u.inLines)throw new Error(`DOT ${ms(c)}: only line declarations belong in "subgraph lines"`);let m=i.get(h);m||(m={id:h,attrs:{...u.node},clusters:new Set},i.set(h,m),e.nodes.push(m)),Object.assign(m.attrs,d),f&&(m.explicit=!0),u.cluster&&m.clusters.add(u.cluster)},o=(h,u)=>{if(h.type==="NodeRef")return[h.id.value];if(h.type==="NodeRefGroup")return h.children.filter(d=>d.type==="NodeRef").map(d=>d.id.value);throw new Error(`DOT ${ms(u)}: subgraphs as edge ends are not supported; use {a b} for several nodes, or the cluster id (a -> cluster_x) for its box`)},a=(h,u,d)=>{for(let c of h)if(c.type==="Attribute")d[c.key.value]=sh(c.value);else if(c.type==="AttributeList"){let f=fs(c);c.kind==="Node"?u.node={...u.node,...f}:c.kind==="Edge"?u.edge={...u.edge,...f}:Object.assign(d,f)}else if(c.type==="Node")if(u.inLines){if(e.lines.some(f=>f.id===c.id.value))throw new Error(`DOT ${ms(c)}: line "${c.id.value}" declared twice`);e.lines.push({id:c.id.value,attrs:{...u.node,...fs(c)}})}else s(c.id.value,u,fs(c),c,!0);else if(c.type==="Edge"){if(u.inLines)throw new Error(`DOT ${ms(c)}: edges do not belong in "subgraph lines"`);let f=c.targets.map(P=>o(P,c));for(let P of f)for(let v of P)s(v,u,{},c);let m={...u.edge,...fs(c)};for(let P=1;P<f.length;P++)for(let v of f[P-1])for(let b of f[P])e.edges.push({from:v,to:b,attrs:m,line:c.location?.start.line})}else if(c.type==="Subgraph"){let f=c.id?.value,m={...u},P={};if(f==="lines"&&!u.cluster)m.inLines=!0;else if(f?.startsWith("cluster")){let v=r.get(f);v||(v={id:f,attrs:{},parent:u.cluster},r.set(f,v),e.clusters.push(v)),m.cluster=v,P=v.attrs}a(c.children,m,P)}};a(t.children,{node:{},edge:{},cluster:null},e.attrs),e.nodes=e.nodes.filter(h=>{if(!r.has(h.id))return!0;if(h.explicit)throw new Error(`"${h.id}" is a cluster, so it cannot also be a node`);return!1});let l=h=>h?[h,...l(h.parent)]:[];for(let h of e.nodes){let u=[...h.clusters].sort((d,c)=>l(c).length-l(d).length)[0]??null;for(let d of h.clusters)if(!l(u).includes(d))throw new Error(`node ${h.id} is in both ${d.id} and ${u.id}`);h.cluster=u,delete h.clusters,delete h.explicit}return e}var Ps=["#2563eb","#e0362c","#16a34a","#f59e0b","#8b5cf6","#0ea5b7","#ec4899","#64748b","#8b5a2b","#f97316","#84cc16","#0f766e"],Qo=(n,t)=>{let e=t?.palette??Ps;return e[n%e.length]};function yn(n,t){for(let e of n)e.auto!==void 0&&(e.color=Qo(e.auto,t));return n}var fn="Inter, 'Helvetica Neue', Helvetica, Arial, sans-serif",ah=(n,t=1)=>({node:[{dy:1,blur:1.2,color:n,opacity:.1*t},{dy:6,blur:10,color:n,opacity:.12*t}],group:[{dy:2,blur:8,color:n,opacity:.05*t}],small:[{dy:1,blur:2,color:n,opacity:.1*t}]}),lr={light:{label:"Light",font:fn,bg:"#ffffff",ink:"#1f2933",muted:"#6b7683",node:{fill:"#ffffff",stroke:"#2b343f",width:2,weight:500},person:"#596573",note:{fill:"#f7f8fa",stroke:"#dfe3e8",ink:"#6b7683"},group:{fill:"#f3f5f7",stroke:"#dbe0e6",title:"#4b5663",width:1.25},accent:{fill:.93,stroke:.55,title:.3},edgeLabel:{fill:"#ffffff",stroke:"#cfd5dc",ink:"#1f2933"},noteLink:"#b9c0c8",legend:{fill:"#ffffff",stroke:"#dbe0e6"},radius:{node:14,group:22,note:8,label:99},shadow:ah("#0f1a2a")},dark:{label:"Dark",font:fn,bg:"#10141a",ink:"#e6e9ed",muted:"#8f99a5",node:{fill:"#1a2029",stroke:"#9aa5b3",width:1.75,weight:500,sheen:{color:"#ffffff",opacity:.07,depth:44}},person:"#9aa5b3",note:{fill:"#151a21",stroke:"#2b323c",ink:"#8f99a5"},group:{fill:"#151a21",stroke:"#2b323c",title:"#aeb7c2",width:1.25,titles:"tab"},accent:{fill:.92,stroke:.5,title:.6},edgeLabel:{fill:"#1a2029",stroke:"#3a434f",ink:"#e6e9ed"},noteLink:"#4a5461",legend:{fill:"#151a21",stroke:"#2b323c"},radius:{node:14,group:22,note:8,label:99},shadow:ah("#000000",4)},minimal:{label:"Minimal",font:fn,bg:"#f1f3f6",ink:"#1d2530",muted:"#6b7683",node:{fill:"#ffffff",stroke:"none",inner:"#d5dbe3",width:1.5,weight:500,sheen:{color:"#f1f4f8",opacity:1,depth:44}},person:"#4f5b69",note:{fill:"#fafbfc",stroke:"none",ink:"#6b7683"},group:{fill:"#e4e8ee",stroke:"#d3d9e1",title:"#3d4855",width:1,titles:"tab"},accent:{fill:.86,stroke:.7,title:.25},edgeLabel:{fill:"#ffffff",stroke:"none",ink:"#1d2530"},noteLink:"#b4bcc6",legend:{fill:"#ffffff",stroke:"none"},radius:{node:16,group:24,note:10,label:99},shadow:{node:[{dy:1,blur:1,color:"#0f1a2a",opacity:.08},{dy:8,blur:14,color:"#0f1a2a",opacity:.12}],small:[{dy:1,blur:2.5,color:"#0f1a2a",opacity:.14}]}},neon:{label:"Neon",font:fn,bg:"#f4f5ff",ink:"#12103a",muted:"#5a5f9e",grid:{minor:"rgba(61, 90, 254, 0.08)",major:"rgba(255, 0, 212, 0.13)",step:40},palette:["#3d5afe","#ff00d4","#5fb800","#00a8e0","#9d00ff","#ff5a00","#00b86b","#ff1f6b","#0072ff","#d4a000","#d100ff","#009c9c"],node:{fill:"#ffffff",stroke:"#3d5afe",width:2.25,weight:500,sheen:{color:"#00e5ff",opacity:.16,depth:40}},person:"#3d5afe",note:{fill:"#fdf5ff",stroke:"#ff9cf0",ink:"#7a2a8f"},group:{fill:"#f1ffcf",stroke:"#9ee000",title:"#c6ff00",tabInk:"#12103a",width:1.75,titles:"tab"},accent:{fill:.92,stroke:.3,title:.1},edgeLabel:{fill:"#ff00d4",stroke:"#ff00d4",ink:"#ffffff"},noteLink:"#ff7ae6",legend:{fill:"#ffffff",stroke:"#3d5afe"},radius:{node:12,group:18,note:6,label:99},shadow:{node:[{blur:1.5,color:"#3d5afe",opacity:.5},{blur:9,color:"#00e5ff",opacity:.35}],group:[{blur:10,color:"#c6ff00",opacity:.45}],small:[{blur:4,color:"#ff00d4",opacity:.45}]},line:{glow:[{grow:6,opacity:.3},{grow:16,opacity:.12}],flow:{color:"#ffffff",opacity:.95,length:11,half:3.3,period:72,speed:48}}},neond:{label:"Neon dark",font:fn,bg:"#08031a",ink:"#f2f0ff",muted:"#a49cdc",grid:{minor:"rgba(61, 90, 254, 0.09)",major:"rgba(255, 0, 212, 0.14)",step:40},palette:["#00e5ff","#ff00d4","#c6ff00","#5c7cff","#ffe600","#b026ff","#ff6a00","#00ffa3","#ff2d75","#7df9ff","#e600ff","#9dff00"],node:{fill:"#0f0a33",stroke:"#3d5afe",width:2.25,weight:500,sheen:{color:"#00e5ff",opacity:.16,depth:40}},person:"#00e5ff",note:{fill:"#14082a",stroke:"#8a2b9c",ink:"#e7a8ff"},group:{fill:"#0c0d1a",stroke:"#c6ff00",title:"#c6ff00",tabInk:"#08031a",width:1.5,titles:"tab"},accent:{fill:.88,stroke:.2,title:.3},edgeLabel:{fill:"#ff00d4",stroke:"#ff7ae6",ink:"#ffffff"},noteLink:"#8a2b9c",legend:{fill:"#0f0a33",stroke:"#3d5afe"},radius:{node:12,group:18,note:6,label:99},shadow:{node:[{blur:2,color:"#3d5afe",opacity:.8},{blur:10,color:"#00e5ff",opacity:.4}],group:[{blur:10,color:"#c6ff00",opacity:.28}],small:[{blur:5,color:"#ff00d4",opacity:.6}]},line:{glow:[{grow:7,opacity:.35},{grow:18,opacity:.15}],flow:{color:"#ffffff",opacity:.9,length:11,half:3.3,period:72,speed:48}}}},mn=(n,t={})=>{let{shadow:e,line:i,...r}=n,{flow:s,...o}=i??{};return{...r,...Object.keys(o).length?{line:o}:{},...t}},Pn=lr.minimal,jt={minimal:mn(Pn,{node:{...Pn.node,stroke:"#d5dbe3",width:1.25},note:{...Pn.note,stroke:"#e1e6ec"},edgeLabel:{...Pn.edgeLabel,stroke:"#d5dbe3"},legend:{...Pn.legend,stroke:"#d5dbe3"}}),light:mn(lr.light),dark:mn(lr.dark),neon:mn(lr.neon),neond:mn(lr.neond),...Object.fromEntries(["minimal","light","dark","neon","neond"].map(n=>[`${n}-fancy`,{...lr[n],label:`${lr[n].label} fancy`}]))},hr=Object.keys(jt),ri="minimal";function lh(n=ri){let t=jt[n];if(!t)throw new Error(`unknown theme "${n}" (known: ${hr.join(", ")})`);return t}var jo=n=>{let t=parseInt(n.slice(1),16);return[t>>16&255,t>>8&255,t&255]},hf=n=>`#${n.map(t=>Math.round(Math.max(0,Math.min(255,t))).toString(16).padStart(2,"0")).join("")}`,Uo=(n,t,e)=>{let[i,r]=[jo(n),jo(t)];return hf(i.map((s,o)=>s+(r[o]-s)*e))};function hh(n,t){return{fill:Uo(t,n.bg,n.accent.fill),stroke:n.accent.stroke==null?void 0:Uo(t,n.bg,n.accent.stroke),title:Uo(t,n.ink,n.accent.title)}}var Gr=n=>{let[t,e,i]=jo(n);return(.2126*t+.7152*e+.0722*i)/255};function uh(n,t){let e=n.group.tabInk??n.bg;return Math.abs(Gr(e)-Gr(t))>=.45?e:Math.abs(Gr(n.ink)-Gr(t))>Math.abs(Gr(n.bg)-Gr(t))?n.ink:n.bg}function Xo(n){let t=[],e=(i,r)=>t.push(`${i}{${Object.entries(r).filter(([,s])=>s!==void 0).map(([s,o])=>`${s}:${o}`).join(";")}}`);if(e(".lm-root",{"font-family":n.font,fill:n.ink}),e(".lm-bg",{fill:n.bg}),e(".lm-group-box",{fill:n.group.fill,stroke:n.group.stroke,"stroke-width":n.group.width,"stroke-dasharray":n.group.dash}),e(".lm-group-title",{fill:n.group.title,"font-weight":700}),e(".lm-shape",{fill:n.node.fill,stroke:n.node.stroke,"stroke-width":n.node.width,"stroke-linejoin":"round"}),e(".lm-shape-line",{fill:"none",stroke:n.node.inner??n.node.stroke,"stroke-width":n.node.width}),e(".lm-sheen",{stroke:"none","pointer-events":"none"}),e(".lm-group-tab",{fill:n.group.title,stroke:"none"}),e(".lm-group-title-tab",{fill:n.group.tabInk??n.bg,"font-weight":600}),e(".lm-person",{fill:n.person,stroke:"none"}),e(".lm-label",{fill:n.ink,"font-weight":n.node.weight}),e(".lm-halo",{stroke:n.bg}),e(".lm-halo-in",{stroke:n.node.fill}),e(".lm-note-box",{fill:n.note.fill,stroke:n.note.stroke,"stroke-width":1,"stroke-dasharray":n.note.dash}),e(".lm-note-text",{fill:n.note.ink,"font-style":"italic"}),e(".lm-note-link",{fill:"none",stroke:n.noteLink,"stroke-width":1.2,"stroke-dasharray":"5 4"}),e(".lm-casing",{fill:"none",stroke:n.bg,"stroke-linejoin":"round"}),e(".lm-casing-in",{stroke:n.node.fill}),e(".lm-strand",{fill:"none","stroke-linejoin":"round"}),e(".lm-edge-label-box",{fill:n.edgeLabel.fill,stroke:n.edgeLabel.stroke,"stroke-width":1}),e(".lm-edge-label",{fill:n.edgeLabel.ink,"font-weight":600}),e(".lm-legend-box",{fill:n.legend.fill,stroke:n.legend.stroke,"stroke-width":1}),e(".lm-legend-title",{fill:n.muted,"font-weight":700,"letter-spacing":"0.12em"}),e(".lm-legend-text",{fill:n.ink}),n.grid&&(e(".lm-grid-minor",{fill:"none",stroke:n.grid.minor,"stroke-width":1}),e(".lm-grid-major",{fill:"none",stroke:n.grid.major,"stroke-width":1})),n.line?.glow&&e(".lm-glow",{fill:"none","stroke-linejoin":"round","pointer-events":"none"}),n.line?.flow){let{color:i,opacity:r}=n.line.flow,s="var(--lm-t) linear infinite";e(".lm-arrow",{fill:i,"fill-opacity":r,"pointer-events":"none"}),t.push("@supports (offset-path:path('M0,0')){"),e(".lm-marks",{display:"none"}),e(".lm-arrows",{visibility:"visible"}),e(".lm-arrow",{"offset-path":"var(--lm-p)","offset-rotate":"auto","offset-distance":"calc(var(--lm-i)*var(--lm-s))",animation:`lm-arrow ${s}`}),e(".lm-arrow-in",{animation:`lm-arrow ${s},lm-arrow-in ${s}`}),e(".lm-arrow-out",{animation:`lm-arrow ${s},lm-arrow-out ${s}`}),e(".lm-arrow-in.lm-arrow-out",{animation:`lm-arrow ${s},lm-arrow-in ${s},lm-arrow-out ${s}`}),t.push("@keyframes lm-arrow{to{offset-distance:calc((var(--lm-i) + 1)*var(--lm-s))}}"),t.push("@keyframes lm-arrow-in{from{opacity:0}30%{opacity:1}}"),t.push("@keyframes lm-arrow-out{70%{opacity:1}to{opacity:0}}"),t.push("@media (prefers-reduced-motion:reduce){.lm-arrow{animation:none}}"),t.push("}")}return t.join(`
|
|
959
|
+
`)}function dh(n,t){let e=[],i={};for(let[r,s]of Object.entries(n.shadow??{})){if(!s?.length)continue;let o=`lm-shadow-${t}-${r}`;i[r]=o;let a=s.map((h,u)=>(h.blur?`<feGaussianBlur in="SourceAlpha" stdDeviation="${h.blur}" result="b${u}"/>`:"")+`<feOffset in="${h.blur?`b${u}`:"SourceAlpha"}" dx="${h.dx??0}" dy="${h.dy??0}" result="o${u}"/><feFlood flood-color="${h.color}" flood-opacity="${h.opacity}"/><feComposite in2="o${u}" operator="in" result="s${u}"/>`).join(""),l=s.map((h,u)=>`<feMergeNode in="s${u}"/>`).join("")+'<feMergeNode in="SourceGraphic"/>';e.push(`<filter id="${o}" x="-20%" y="-20%" width="140%" height="150%" color-interpolation-filters="sRGB">${a}<feMerge>${l}</feMerge></filter>`)}return{defs:e.length?`<defs>${e.join("")}</defs>`:"",filter:r=>i[r]?` filter="url(#${i[r]})"`:""}}var gt={font:15,lineHeight:19,notePad:12,groupPad:60,lineWidth:9,linePitch:9,markerSpacing:240},uf={"font-size":15},Sn={box:{size:[250,170]},diamond:{size:[300,200]},person:{size:[140,140],bold:!0},cylinder:{size:[250,170]},queue:{size:[250,170]},note:{"font-size":13,italic:!0}},df={rect:"box",rectangle:"box"},Yo=["box","queue","cylinder"],Ph=n=>n.kind==="node"&&Yo.includes(n.shape),cf={"font-size":18,bold:!0},ch=["color","fillcolor","fontcolor","fontsize"],gf={graph:["label","theme"],cluster:["label","class",...ch],line:["label","color"],node:["label","class","shape","pos","width","height","through","URL","href",...ch],edge:["label","lines","via"]},pf=new Set(["style","arrowhead","arrowtail","arrowsize","dir","rankdir","splines","penwidth","fontname","margin","ranksep","nodesep","compound","constraint","weight","labeljust","labelloc","tooltip","bgcolor","newrank","concentrate","fixedsize"]),bn=(n,t,e)=>{for(let i of Object.keys(e))if(!gf[n].includes(i)&&!pf.has(i))throw new Error(`${n} ${t}: unknown attribute "${i}"`)},ff=(n,t)=>{let e=/^(-?\d+(?:\.\d+)?)(px)?$/.exec(n);if(!e)throw new Error(`${t}: expected a number of px, got "${n}"`);return Number(e[1])},gh=(n,t)=>{if(!/^\d+(?:\.\d+)?$/.exec(n)||!(Number(n)>0))throw new Error(`${t}: expected a number of inches above zero, got "${n}"`);return Math.round(Number(n)*72)},ph=(n,t)=>{let e=/^\s*(-?\d+(?:\.\d+)?)\s*,\s*(-?\d+(?:\.\d+)?)\s*!?\s*$/.exec(n);if(!e)throw new Error(`${t}: expected "x,y", got "${n}"`);return[Number(e[1]),Number(e[2])]},ys=(n,t)=>{let e=/^#([0-9a-f]{3}|[0-9a-f]{6})$/i.exec(n);if(!e)throw new Error(`${t}: expected a colour like #1565c0, got "${n}"`);return`#${(e[1].length===3?[...e[1]].map(i=>i+i).join(""):e[1]).toLowerCase()}`},mf=(n,t)=>{if(/^(https?:|mailto:)/i.test(n)||!/^[^/?#]*:/.test(n))return n;throw new Error(`${t}: URL must be http(s), mailto or relative, got "${n}"`)};function fh(n,t){let e={};return n.color!==void 0&&(e.stroke=ys(n.color,`${t}: color`)),n.fillcolor!==void 0&&(e.fill=ys(n.fillcolor,`${t}: fillcolor`)),n.fontcolor!==void 0&&(e["font-color"]=ys(n.fontcolor,`${t}: fontcolor`)),n.fontsize!==void 0&&(e["font-size"]=ff(n.fontsize,`${t}: fontsize`)),n.width!==void 0&&(e.width=gh(n.width,`${t}: width`)),n.height!==void 0&&(e.height=gh(n.height,`${t}: height`)),e}var ni=(n,t)=>n.length*t*.56,Cn=n=>{let t=n.split(`
|
|
960
|
+
`);return{w:Math.max(...t.map(e=>ni(e,12)))+18,h:t.length*15+8}},mh=n=>({fill:n.fill,stroke:n.stroke,fontColor:n["font-color"],fontSize:n["font-size"],lineHeight:Math.round(n["font-size"]*1.27),italic:!!n.italic,bold:!!n.bold});function Ss(n){let t=oh(n);bn("graph",t.id,t.attrs);let e=t.attrs.theme??null;if(e&&!jt[e])throw new Error(`graph: unknown theme "${e}" (known: ${Object.keys(jt).join(", ")})`);let i=t.lines.map((f,m)=>(bn("line",f.id,f.attrs),f.attrs.color===void 0?{id:f.id,index:m,label:f.attrs.label??f.id,color:Qo(m),auto:m}:{id:f.id,index:m,label:f.attrs.label??f.id,color:ys(f.attrs.color,`line ${f.id}: color`)})),r=new Map(i.map(f=>[f.id,f])),s=t.clusters.map(f=>{bn("cluster",f.id,f.attrs);let{stroke:m,...P}=fh(f.attrs,`cluster ${f.id}`);return{id:f.id,label:f.attrs.label??f.id.replace(/^cluster_?/,""),accent:m??null,parent:f.parent?.id??null,classes:f.attrs.class??"",style:mh({...cf,...P})}}),o=[],a=[];for(let f of t.nodes){bn("node",f.id,f.attrs);let m=df[f.attrs.shape]??f.attrs.shape??"box";if(!Sn[m])throw new Error(`node ${f.id}: unknown shape "${m}" (known: ${Object.keys(Sn).join(", ")})`);let P=fh(f.attrs,`node ${f.id}`),v=mh({...uf,...Sn[m],...P}),b=f.attrs.pos!==void 0?ph(f.attrs.pos,`node ${f.id}: pos`):null,C=f.attrs.through===void 0?!1:f.attrs.through==="true"?!0:f.attrs.through==="false"?!1:null;if(C===null)throw new Error(`node ${f.id}: through must be true or false, got "${f.attrs.through}"`);if(C&&!Yo.includes(m))throw new Error(`node ${f.id}: through=true needs one of the shapes ${Yo.join(", ")}, not ${m}`);let E=f.attrs.href??f.attrs.URL,w={id:f.id,shape:m,label:f.attrs.label??f.id,style:v,classes:f.attrs.class??"",url:E!==void 0?mf(E,`node ${f.id}`):null,group:f.cluster?.id??null,pinned:!!b,through:C,x:b?.[0],y:b?.[1]};if(m==="note"){let F=w.label.split(`
|
|
961
|
+
`),V=gt.notePad;w.kind="note",w.attach=null,w.w=P.width??Math.ceil(Math.max(...F.map(q=>ni(q,v.fontSize))))+2*V,w.h=P.height??F.length*v.lineHeight+2*V,a.push(w)}else w.kind="node",w.w=P.width??Sn[m].size[0],w.h=P.height??Sn[m].size[1],o.push(w)}if(!o.length&&!a.length)throw new Error("the graph has no nodes");let l=new Map([...o,...a].map(f=>[f.id,f])),h=new Map(s.map(f=>[f.id,f])),u=(f,m)=>{for(let P=f.group;P;P=h.get(P).parent)if(P===m)return!0;return!1},d=new Map;for(let f of t.edges){let m=`${f.from}->${f.to}`;bn("edge",m,f.attrs);let[P,v]=[l.get(f.from)??h.get(f.from),l.get(f.to)??h.get(f.to)];if(f.from===f.to)throw new Error(`DOT line ${f.line}: edge ${m} is a loop`);for(let[w,F]of[[P,v],[v,P]])if(h.has(w.id)&&(u(F,w.id)||h.has(F.id)&&u({group:F.parent},w.id)))throw new Error(`DOT line ${f.line}: edge ${m} links container ${w.id} to something inside it`);if(P.kind==="note"||v.kind==="note"){if(h.has(P.id)||h.has(v.id))throw new Error(`DOT line ${f.line}: edge ${m}: a note attaches to a node, not a container`);if(P.kind===v.kind)throw new Error(`DOT line ${f.line}: edge ${m} links two notes`);if(f.attrs.lines)throw new Error(`DOT line ${f.line}: edge ${m} attaches a note, so it cannot carry lines`);let[w,F]=P.kind==="note"?[P,v]:[v,P];if(w.attach&&w.attach!==F.id)throw new Error(`note ${w.id}: attached to both ${w.attach} and ${F.id}`);w.attach=F.id;continue}let b=(f.attrs.lines??"").split(/[\s,]+/).filter(Boolean);if(!b.length)throw new Error(`DOT line ${f.line}: edge ${m} has no lines; set lines="..." on it or with edge [lines="..."]`);d.has(m)||d.set(m,{id:m,from:f.from,to:f.to,lines:[],label:null,via:[]});let C=d.get(m);for(let w of b){let F=r.get(w);if(!F)throw new Error(`DOT line ${f.line}: edge ${m}: unknown line "${w}"`);C.lines.includes(F)||C.lines.push(F)}let E=f.attrs.label;if(E){if(C.label&&C.label!==E)throw new Error(`edge ${m}: label "${E}" conflicts with "${C.label}"`);C.label=E}f.attrs.via&&(C.via=f.attrs.via.trim().split(/\s+/).map(w=>ph(w,`edge ${m}: via`)))}for(let f of d.values())f.lines.sort((m,P)=>m.index-P.index);let c=[...d.values()];return{theme:e,lines:i,groups:s,groupById:h,nodes:o,notes:a,items:l,edges:c,legend:{}}}function yh(n,t){let e=new Set;for(let i=t?.group;i;i=n.groupById.get(i).parent)e.add(i);return e}var We=(n,t=0)=>({x0:n.x-n.w/2-t,y0:n.y-n.h/2-t,x1:n.x+n.w/2+t,y1:n.y+n.h/2+t});function ki(n){let t=new Map,e=i=>{if(t.has(i.id))return t.get(i.id);let r=[...n.nodes,...n.notes].filter(o=>o.group===i.id&&o.x!==void 0).map(o=>We(o,gt.groupPad));for(let o of n.groups.filter(a=>a.parent===i.id)){let a=e(o);a&&r.push(We({x:(a.x0+a.x1)/2,y:(a.y0+a.y1)/2,w:a.x1-a.x0,h:a.y1-a.y0},gt.groupPad/2))}let s=r.length?{x0:Math.min(...r.map(o=>o.x0)),y0:Math.min(...r.map(o=>o.y0)),x1:Math.max(...r.map(o=>o.x1)),y1:Math.max(...r.map(o=>o.y1))}:null;return t.set(i.id,s),s};for(let i of n.groups)e(i);for(let[i,r]of t)r||t.delete(i);return t}var N=n=>Math.round(n*10)/10,le=(n,t)=>({x:n.x-t.x,y:n.y-t.y}),bs=(n,t,e=1)=>({x:n.x+t.x*e,y:n.y+t.y*e}),$i=n=>Math.hypot(n.x,n.y),vn=(n,t)=>Math.hypot(n.x-t.x,n.y-t.y),si=n=>{let t=$i(n)||1;return{x:n.x/t,y:n.y/t}},Cs=(n,t)=>n.x0<t.x1&&t.x0<n.x1&&n.y0<t.y1&&t.y0<n.y1,Jo=(n,t)=>t.x0>=n.x0&&t.x1<=n.x1&&t.y0>=n.y0&&t.y1<=n.y1;function vs(n,t,e){let i=0,r=1,s=t.x-n.x,o=t.y-n.y;for(let[a,l]of[[-s,n.x-e.x0],[s,e.x1-n.x],[-o,n.y-e.y0],[o,e.y1-n.y]]){if(Math.abs(a)<1e-9){if(l<0)return!1;continue}let h=l/a;if(a<0){if(h>r)return!1;h>i&&(i=h)}else{if(h<i)return!1;h<r&&(r=h)}}return!0}var Pf=Object.create,Pu=Object.defineProperty,yf=Object.getOwnPropertyDescriptor,Sf=Object.getOwnPropertyNames,bf=Object.getPrototypeOf,Cf=Object.prototype.hasOwnProperty,co=(n,t)=>()=>{try{return t||n((t={exports:{}}).exports,t),t.exports}catch(e){throw t=0,e}},vf=(n,t,e,i)=>{if(t&&typeof t=="object"||typeof t=="function")for(let r of Sf(t))!Cf.call(n,r)&&r!==e&&Pu(n,r,{get:()=>t[r],enumerable:!(i=yf(t,r))||i.enumerable});return n},ct=(n,t,e)=>(e=n!=null?Pf(bf(n)):{},vf(t||!n||!n.__esModule?Pu(e,"default",{value:n,enumerable:!0}):e,n)),yu=co(n=>{"use strict";Object.defineProperty(n,"__esModule",{value:!0});var t=class{constructor(...i){this._head=this._tail=null,this._length=0,i.length>0&&i.forEach(r=>{this.append(r)})}*iterator(){let i=this._head;for(;i;)yield i.value,i=i.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(i,r,s=!1){if(s&&this.isDuplicate(i))return!1;let o=new e(i),a=this._head;if(a)for(;;){if(a.value===r)return o.next=a.next,o.prev=a,a.next=o,o.next?o.next.prev=o:this._tail=o,this._length++,!0;if(a.next)a=a.next;else return!1}else return!1}append(i,r=!1){if(r&&this.isDuplicate(i))return!1;let s=new e(i);return this._tail?(this._tail.next=s,s.prev=this._tail,this._tail=s):this._head=this._tail=s,this._length++,!0}prepend(i,r=!1){if(r&&this.isDuplicate(i))return!1;let s=new e(i);return this._head?(s.next=this._head,this._head.prev=s,this._head=s):this._head=this._tail=s,this._length++,!0}remove(i){let r=this._head;if(r){if(r.value===i)return this._head=r.next,this._head.prev=null,r.next=r.prev=null,this._length--,r.value;for(;;){if(r.value===i)return r.next?(r.prev.next=r.next,r.next.prev=r.prev,r.next=r.prev=null):(r.prev.next=null,this._tail=r.prev,r.next=r.prev=null),this._length--,r.value;if(r.next)r=r.next;else return}}}removeHead(){let i=this._head;if(i)return this._head.next?(this._head.next.prev=null,this._head=this._head.next,i.next=i.prev=null):(this._head=null,this._tail=null),this._length--,i.value}removeTail(){let i=this._tail;if(i)return this._tail.prev?(this._tail.prev.next=null,this._tail=this._tail.prev,i.next=i.prev=null):(this._head=null,this._tail=null),this._length--,i.value}first(i){let r=this.iterator(),s=[],o=Math.min(i,this.length);for(let a=0;a<o;a++){let l=r.next();s.push(l.value)}return s}toArray(){return[...this]}isDuplicate(i){return new Set(this.toArray()).has(i)}};n.LinkedList=t;var e=class{constructor(i){this.value=i,this.next=null,this.prev=null}};n.LinkedListItem=e}),ti=co(n=>{"use strict";Object.defineProperty(n,"__esModule",{value:!0});var t=yu(),e=class extends t.LinkedList{constructor(...i){super(...i)}get top(){return this.head}get size(){return this.length}push(i){this.prepend(i)}pop(){return this.removeHead()}};n.Stack=e}),bi=co(n=>{"use strict";Object.defineProperty(n,"__esModule",{value:!0});var t=yu(),e=class extends t.LinkedList{constructor(...i){super(...i)}get front(){return this.head}enqueue(i){this.append(i)}dequeue(){return this.removeHead()}};n.Queue=e}),se=co(n=>{Object.defineProperty(n,"__esModule",{value:!0}),n.StringBuilder=n.String=n.emptyString=void 0,n.isNullOrWhiteSpace=e,n.joinString=i,n.formatString=r;var t=`\r
|
|
962
|
+
`;function e(a){return s.isNullOrWhiteSpace(a)}function i(a,...l){return s.join(a,...l)}function r(a,...l){return s.format(a,...l)}n.emptyString="";var s=class vt{static regexNumber=/{(\d+(:\w*)?)}/g;static regexObject=/{(\w+(:\w*)?)}/g;static empty="";static Empty="";static IsNullOrWhiteSpace(l){return vt.isNullOrWhiteSpace(l)}static Join(l,...h){return vt.join(l,...h)}static Format(l,...h){return vt.format(l,...h)}static isNullOrWhiteSpace(l){try{return l==null||l=="undefined"?!0:l.toString().replace(/\s/g,"").length<1}catch(h){return console.log(h),!1}}static join(l,...h){try{var u=h[0];if(Array.isArray(u)||u instanceof Array){let f=vt.empty;for(let m=0;m<u.length;m++){var d=u[m];m<u.length-1?f+=d+l:f+=d}return f}if(typeof u=="object"){let f=vt.empty,m=u;return Object.keys(u).forEach(P=>{f+=m[P]+l}),f=f.slice(0,f.length-l.length)}var c=h;return vt.joinString(l,...c)}catch(f){return console.log(f),vt.empty}}static format(l,...h){try{return l.match(vt.regexNumber)?vt.formatString(vt.regexNumber,l,h):l.match(vt.regexObject)?vt.formatString(vt.regexObject,l,h,!0):l}catch(u){return console.log(u),vt.empty}}static formatString(l,h,u,d=!1){return h.replace(l,function(c,f){var m=c.split(":");1<m.length&&(f=m[0].replace("{",""),c=m[1].replace("}",""));let P;return(P=(d?u[0]:u)[f])==null||P==null||c.match(/{\d+}/)||(P=vt.parsePattern(c,P))!==void 0&&P!=null?P:vt.empty})}static parsePattern(l,h){switch(l){case"L":return h=h.toLocaleLowerCase();case"U":return h=h.toLocaleUpperCase();case"d":if(typeof h=="string")return vt.getDisplayDateFromString(h);if(h instanceof Date)return vt.format("{0:00}.{1:00}.{2:0000}",h.getDate(),h.getMonth(),h.getFullYear());break;case"s":if(typeof h=="string")return vt.getSortableDateFromString(h);if(h instanceof Date)return vt.format("{0:0000}-{1:00}-{2:00}",h.getFullYear(),h.getMonth(),h.getDate());break;case"n":{var c=(h=typeof h!="string"?h.toString():h).replace(/,/g,".");if(isNaN(parseFloat(c))||c.length<=3)break;c=c.split(/\D+/g);let f=c;var c=(f=1<c.length?[vt.joinString("",...c.splice(0,c.length-1)),c[c.length-1]]:f)[0],u=c.length%3,d=0<u?c.substring(0,u):vt.empty,c=c.substring(u).match(/.{3}/g);return h=d+"."+vt.join(".",c)+(1<f.length?","+f[1]:"")}case"x":return this.decimalToHexString(h);case"X":return this.decimalToHexString(h,!0)}return typeof h!="number"&&isNaN(h)||isNaN(+l)||vt.isNullOrWhiteSpace(h)?h:vt.formatNumber(h,l)}static decimalToHexString(l,h=!1){return l=parseFloat(l).toString(16),h?l.toLocaleUpperCase():l}static getDisplayDateFromString(l){var h=l.split("-");if(h.length<=1)return l;let u=h[h.length-1];return l=h[h.length-2],h=h[h.length-3],(u=(u=u.split("T")[0]).split(" ")[0])+`.${l}.`+h}static getSortableDateFromString(l){var h=l.replace(",","").split(".");if(h.length<=1)return l;l=h[h.length-1].split(" ");let u=vt.empty,d=(1<l.length&&(u=l[l.length-1]),h[h.length-1].split(" ")[0]+`-${h[h.length-2]}-`+h[h.length-3]);return!vt.isNullOrWhiteSpace(u)&&1<u.length?d+="T"+u:d+="T00:00:00",d}static formatNumber(d,u){var u=u.length,d=d.toString();return u<=d.length?d:(u=u-d.length,++u,new Array(u).join("0")+d)}static joinString(l,...h){let u=vt.empty;for(let c=0;c<h.length;c++)if(!(typeof h[c]=="string"&&vt.isNullOrWhiteSpace(h[c])||typeof h[c]!="number"&&typeof h[c]!="string")){var d=""+h[c];u+=d;for(let f=c+1;f<h.length;f++)if(!vt.isNullOrWhiteSpace(h[f])){u+=l,c=f-1;break}}return u}};n.String=s;var o=class{Values;constructor(a=""){this.Values=[],s.isNullOrWhiteSpace(a)||(this.Values=new Array(a))}toString(){return this.Values.join(s.empty)}ToString(){return this.toString()}append(a){this.Values.push(a)}Append(a){this.append(a)}appendLine(a){this.Values.push(t+a)}AppendLine(a){this.appendLine(a)}appendFormat(a,...l){this.Values.push(s.format(a,...l))}AppendFormat(a,...l){this.appendFormat(a,...l)}appendLineFormat(a,...l){this.Values.push(t+s.format(a,...l))}AppendLineFormat(a,...l){return this.appendLineFormat(a,...l)}clear(){this.Values=[]}Clear(){this.clear()}};n.StringBuilder=o}),Wn=class Su{static{this.eps=1e-8}static solve(t,e,i,r,s,o){let a=t*s-r*e;if(!(Math.abs(a)<Su.eps))return{x:(i*s-o*e)/a,y:(t*o-r*i)/a}}},x=class fa{static{this.distanceEpsilonPrecision=6}static{this.mult=Math.pow(10,6)}static{this.defaultLeafBoxesOffset=.5}static{this.lineSegmentThreshold=.05}static{this.intersectionEpsilon=1e-4}static{this.distanceEpsilon=Math.pow(10,-fa.distanceEpsilonPrecision)}static{this.squareOfDistanceEpsilon=Math.pow(10,-fa.distanceEpsilonPrecision*2)}static{this.tolerance=1e-8}};function xf(n,t){return(n?1:0)-(t?1:0)}function Mt(n,t){let e=n-t;return e<0?-1:e===0?0:1}function Ns(n,t){return Mt(n.y,t.y)||Mt(n.x,t.x)}function lt(n,t){let e=n-t;return-x.distanceEpsilon<=e&&e<=x.distanceEpsilon}function Zo(n,t){return Js(n,t)>0}function Js(n,t){let e=n-t;return e<=-x.distanceEpsilon?-1:e>=x.distanceEpsilon?1:0}function ht(n,t){let e=n.x-t.x,i=n.y-t.y;return Math.sqrt(e*e+i*i)}var g=class St{static RoundPoint(t){return new St(St.RoundDouble(t.x),St.RoundDouble(t.y))}static RoundDouble(t){return Math.round(t*x.mult)/x.mult}toJSON(){return{x:this.x,y:this.y}}static fromJSON(t){return new St(t.x,t.y)}static ProjectionToLine(t,e,i){let r=e.sub(t),s=r.length;if(s<x.distanceEpsilon)return t;r=r.div(s);let o=i.sub(t).dot(r);return t.add(r.mul(o))}static RayIntersectsRayInteriors(t,e,i,r){let s=St.lineLineIntersection(t,t.add(e),i,i.add(r));if(s&&s.sub(t).dot(e.div(e.l1))>x.distanceEpsilon&&s.sub(i).dot(r.div(r.l1))>x.distanceEpsilon)return s}static IntervalIntersectsRay(t,e,i,r){let s=St.lineLineIntersection(t,e,i,i.add(r));if(!s)return;let o=t.sub(s),a=s.sub(e);if(!(o.dot(a)<=0)&&!(s.sub(i).dot(r)<0)&&o.dot(o)>x.squareOfDistanceEpsilon&&a.dot(a)>=x.squareOfDistanceEpsilon)return s}static PointToTheLeftOfLineOrOnLine(t,e,i){return St.signedDoubledTriangleArea(t,e,i)>=0}static PointToTheLeftOfLine(t,e,i){return St.signedDoubledTriangleArea(t,e,i)>0}static PointIsInsideCone(t,e,i,r){return St.PointToTheRightOfLineOrOnLine(t,e,i)&&St.PointToTheLeftOfLineOrOnLine(t,e,r)}static PointToTheRightOfLineOrOnLine(t,e,i){return St.signedDoubledTriangleArea(e,i,t)<=0}static PointToTheRightOfLine(t,e,i){return St.signedDoubledTriangleArea(e,i,t)<0}static closeIntersections(t,e){return St.close(t,e,x.intersectionEpsilon)}get l1(){return Math.abs(this.x)+Math.abs(this.y)}dot(t){return this.x*t.x+this.y*t.y}compareTo(t){let e=Mt(this.x,t.x);return e!==0?e:Mt(this.y,t.y)}toString(){return"("+this.x+","+this.y+")"}static close(t,e,i){return ht(t,e)<=i}static closeSquare(t,e,i){let r=e.x-t.x,s=e.y-t.y;return r*r+s*s<=i}static closeDistEps(t,e,i=x.distanceEpsilon){return ht(t,e)<=i}normalize(){let t=this.length;return new St(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 new St((t.x+e.x)/2,(t.y+e.y)/2)}scale(t,e){return new St(this.x*t,this.y*e)}add(t){return new St(this.x+t.x,this.y+t.y)}sub(t){return new St(this.x-t.x,this.y-t.y)}mul(t){return new St(this.x*t,this.y*t)}div(t){return new St(this.x/t,this.y/t)}equal(t){return t.x===this.x&&t.y===this.y}neg(){return new St(-this.x,-this.y)}addInPlace(t){return this.x+=t.x,this.y+=t.y,this}subInPlace(t){return this.x-=t.x,this.y-=t.y,this}mulInPlace(t){return this.x*=t,this.y*=t,this}divInPlace(t){return this.x/=t,this.y/=t,this}negInPlace(){return this.x=-this.x,this.y=-this.y,this}normalizeInPlace(){let t=this.length;return this.x/=t,this.y/=t,this}copyFrom(t){return this.x=t.x,this.y=t.y,this}set(t,e){return this.x=t,this.y=e,this}static lineLineIntersection(t,e,i,r){let s=e.sub(t),o=i.sub(r),a=i.sub(t),l=Wn.solve(s.x,o.x,a.x,s.y,o.y,a.y);if(l!==void 0)return t.add(s.mul(l.x))}static segSegIntersection(t,e,i,r){let s=e.sub(t),o=i.sub(r),a=i.sub(t),l=x.tolerance,h=Wn.solve(s.x,o.x,a.x,s.y,o.y,a.y);if(h!==void 0&&h.x>-l&&h.x<1+l&&h.y>-l&&h.y<1+l)return t.add(s.mul(h.x))}static parallelWithinEpsilon(t,e,i){let r=t.length,s=e.length;return r<i||s<i?!0:(t=t.div(r),e=e.div(s),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 St(-this.y,this.x)}rotate90Cw(){return new St(this.y,-this.x)}clone(){return new St(this.x,this.y)}rotate(t){let e=Math.cos(t),i=Math.sin(t);return new St(e*this.x-i*this.y,i*this.x+e*this.y)}static mkPoint(t,e,i,r){return e.mul(t).add(r.mul(i))}static convSum(t,e,i){return e.add(i.sub(e).mul(t))}static anglePCP(t,e,i){return St.angle(t.sub(e),i.sub(e))}static angle(t,e){let i=t.x,r=t.y,s=e.x,o=e.y,a=i*o-r*s,l=i*s+r*o;if(Math.abs(l)<x.tolerance)return Math.abs(a)<x.tolerance?0:a<-x.tolerance?3*Math.PI/2:Math.PI/2;if(Math.abs(a)<x.tolerance)return l<-x.tolerance?Math.PI:0;let h=Math.atan2(a,l);return a>=-x.tolerance?h:Math.PI*2+h}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){let r=St.signedDoubledTriangleArea(t,e,i);return r>x.distanceEpsilon?1:r<-x.distanceEpsilon?0:2}static getTriangleOrientationWithIntersectionEpsilon(t,e,i){let r=St.signedDoubledTriangleArea(t,e,i);return r>x.intersectionEpsilon?1:r<-x.intersectionEpsilon?0:2}static ClosestPointAtLineSegment(t,e,i){let r=i.sub(e),s=t.sub(e),o=r.dot(s),a=r.dot(r);return o<=0+x.tolerance?e:a<=o+x.tolerance?i:e.add(r.mul(o/a))}static pointToTheLeftOfLineOrOnLine(t,e,i){return St.signedDoubledTriangleArea(t,e,i)>=0}static pointToTheLeftOfLine(t,e,i){return St.signedDoubledTriangleArea(t,e,i)>0}static pointToTheRightOfLineOrOnLine(t,e,i){return St.signedDoubledTriangleArea(e,i,t)<=0}static pointToTheRightOfLine(t,e,i){return St.signedDoubledTriangleArea(e,i,t)<0}static canProject(t,e,i){let r=i.sub(e);return!(t.sub(e).dot(r)<0||t.sub(i).dot(r)>0)}static distToLineSegment(t,e,i){let r=i.sub(e),s=t.sub(e),o,a;if((o=r.dot(s))<=x.tolerance)return{par:0,dist:s.length};if((a=r.dot(r))<=o+x.tolerance)return{par:1,dist:t.sub(i).length};let l=o/a;return{par:l,dist:e.add(r.mul(l)).length}}},Ni=class bu{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){let e=new bu;return e.point=t,e}},ie=class he{contains(t){let e=t.sub(this.corner),i=x.distanceEpsilon,r=e.dot(this.bRot);if(r>this.abRot+i||r<-i)return!1;let s=e.dot(this.aRot);return s<=this.baRot+i&&s>=-i}get area(){return Math.abs(this.a.x*this.b.y-this.a.y*this.b.x)}vertex(t){switch(t){case 0:return this.corner;case 1:return this.aPlusCorner;case 2:return this.otherCorner;case 3:return this.bPlusCorner;default:return}}static parallelogramOfTwo(t,e){let i=new he,r=t.corner,s={minx:r.x,maxx:r.x,miny:r.y,maxy:r.y};return he.pumpMinMax(s,t.aPlusCorner),he.pumpMinMax(s,t.otherCorner),he.pumpMinMax(s,t.bPlusCorner),he.pumpMinMax(s,e.corner),he.pumpMinMax(s,e.aPlusCorner),he.pumpMinMax(s,e.otherCorner),he.pumpMinMax(s,e.bPlusCorner),i.corner=new g(s.minx,s.miny),i.a=new g(0,s.maxy-s.miny),i.b=new g(s.maxx-s.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 g(-i.a.y,i.a.x),i.aRot.length>.5&&(i.aRot=i.aRot.normalize()),i.bRot=new g(-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<x.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 he.separByA(t,e)||he.separByA(e,t)||he.separByB(t,e)||he.separByB(e,t)?!1:!(t.isSeg&&e.isSeg)||!g.parallelWithinEpsilon(t.otherCorner.sub(t.corner),e.otherCorner.sub(e.corner),1e-5)?!0:he.ParallelSegsIntersect(e,t)}static ParallelSegsIntersect(t,e){let i=t.corner,r=t.otherCorner,s=e.corner,o=e.otherCorner,a=r.sub(i),l=0,h=a.dot(a),u=s.sub(i).dot(a),d=o.sub(i).dot(a);if(u>d){let c=u;u=d,d=c}return!(d<l-x.distanceEpsilon||u>h+x.distanceEpsilon)}static separByB(t,e){let i=x.distanceEpsilon,r=e.vertex(0).sub(t.corner).dot(t.bRot),s=[1,2,3];if(r>t.abRot+i){for(let o of s)if(e.vertex(o).sub(t.corner).dot(t.bRot)<=t.abRot+i)return!1;return!0}else if(r<-i){for(let o of s)if(e.vertex(o).sub(t.corner).dot(t.bRot)>=-i)return!1;return!0}return!1}static separByA(t,e){let i=x.distanceEpsilon,r=e.corner.sub(t.corner),s=g.dot(r,t.aRot);return s>t.baRot+i?(r=e.aPlusCorner.sub(t.corner),!(g.dot(r,t.aRot)<=t.baRot+i||(r=e.bPlusCorner.sub(t.corner),g.dot(r,t.aRot)<=t.baRot+i)||(r=e.otherCorner.sub(t.corner),g.dot(r,t.aRot)<=t.baRot+i))):s<-i?(r=e.aPlusCorner.sub(t.corner),!(g.dot(r,t.aRot)>=-i||(r=e.bPlusCorner.sub(t.corner),g.dot(r,t.aRot)>=-i)||(r=e.otherCorner.sub(t.corner),g.dot(r,t.aRot)>=-i))):!1}static parallelogramByCornerSideSide(t,e,i){let r=new he;return r.corner=t,r.a=e,r.b=i,r.aRot=new g(-e.y,e.x),r.aRot.length>.5&&(r.aRot=r.aRot.normalize()),r.bRot=new g(-i.y,i.x),r.bRot.length>.5&&(r.bRot=r.bRot.normalize()),r.abRot=r.bRot.dot(e),r.baRot=i.dot(r.aRot),r.abRot<0&&(r.abRot=-r.abRot,r.bRot=r.bRot.neg()),r.baRot<0&&(r.baRot=-r.baRot,r.aRot=r.aRot.neg()),r.isSeg=e.sub(i).length<x.distanceEpsilon,r.aPlusCorner=e.add(t),r.otherCorner=i.add(r.aPlusCorner),r.bPlusCorner=i.add(t),r}static getParallelogramOfAGroup(t){let e=0,i=0,r=0,s=0,o=!0;for(let a of t){let l=Ef(a);for(let h of l){let u=h.x,d=h.y;o?(o=!1,e=i=u,r=s=d):(u<e?e=u:u>i&&(i=u),d<r?r=d:d>s&&(s=d))}}return he.parallelogramByCornerSideSide(new g(e,r),new g(0,s-r),new g(i-e,0))}};function*Ef(n){yield n.corner,yield n.aPlusCorner,yield n.otherCorner,yield n.bPlusCorner}var D=class oi{constructor(t,e,i,r){this.parStart=0,this.parEnd=1,this.start=new g(t,e),this.end=new g(i,r)}static fromJSON(t){return oi.mkPP(g.fromJSON(t.start),g.fromJSON(t.end))}toJSON(){return{start:this.start.toJSON(),end:this.end.toJSON()}}offsetCurve(t,e){return null}trim(t,e){if(t=Math.max(this.parStart,t),e=Math.min(this.parEnd,e),t>e)throw"wrong params in trimming";let i=this.value(t),r=this.value(e);return g.close(i,r,x.distanceEpsilon)?null:oi.mkPP(i,r)}value(t){return this.start.add(this.end.sub(this.start).mul(t))}trimWithWrap(t,e){return null}pNodeOverICurve(){let t=this.end.sub(this.start).mul(.5);return{parallelogram:ie.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 g(-t.y,t.x)}static mkPP(t,e){return new oi(t.x,t.y,e.x,e.y)}static mkLinePXY(t,e,i){return new oi(t.x,t.y,e,i)}derivative(t){return this.end.sub(this.start)}secondDerivative(t){return new g(0,0)}thirdDerivative(t){return new g(0,0)}reverse(){return oi.mkPP(this.end,this.start)}translate(t){this.start=this.start.add(t),this.end=this.end.add(t)}scaleFromOrigin(t,e){return oi.mkPP(this.start.scale(t,e),this.end.scale(t,e))}getParameterAtLength(t){let e=this.end.sub(this.start).length;if(e<x.tolerance)return 0;let i=t/e;return i>1?1:i<0?0:i}transform(t){return oi.mkPP(t.multiplyPoint(this.start),t.multiplyPoint(this.end))}closestParameterWithinBounds(t,e,i){let r=this.closestParameter(t);return r<e&&(r=e),r>i&&(r=i),r}lengthPartial(t,e){return this.value(e).sub(this.value(t)).length}get length(){return this.start.sub(this.end).length}get boundingBox(){return it.mkPP(this.start,this.end)}clone(){return oi.mkPP(this.start.clone(),this.end.clone())}static closestParameterOnLineSegment(t,e,i){let r=i.sub(e),s=t.sub(e),o=r.dot(s);if(o<=0+x.tolerance)return 0;let a=r.dot(r);return a<=o+x.tolerance?1:o/a}closestParameter(t){return oi.closestParameterOnLineSegment(t,this.start,this.end)}leftDerivative(t){return this.derivative(t)}rightDerivative(t){return this.derivative(t)}static IntersectPPPP(t,e,i,r){let s=g.lineLineIntersection(t,e,i,r);if(s!=null&&jr(s,t,e)&&jr(s,i,r))return s}curvature(t){return 0}curvatureDerivative(t){return 0}curvatureSecondDerivative(t){return 0}static minDistBetweenLineSegments(t,e,i,r){let s=e.sub(t),o=r.sub(i),a=t.sub(i),l=g.crossProduct(s,o),h=s.dot(s),u=s.dot(o),d=o.dot(o),c=s.dot(a),f=o.dot(a),m,P,v=Math.abs(l),b=v,C=v;v<x.tolerance?(m=0,b=1,P=f,C=d):(m=g.crossProduct(o,a),P=g.crossProduct(s,a),l<0&&(m=-m,P=-P),m<0?(m=0,P=f,C=d):m>b&&(m=b=1,P=f+u,C=d)),P<0?(P=0,-c<0?m=0:-c>h?m=b:(m=-c,b=h)):P>C&&(P=C=1,-c+u<0?m=0:-c+u>h?m=b:(m=-c+u,b=h));let E=Math.abs(m)<x.tolerance?0:m/b,w=Math.abs(P)<x.tolerance?0:P/C;return{parab:E,parcd:w,dist:a.add(s.mul(E).sub(o.mul(w))).length}}};function jr(n,t,e){return n.x>=Math.min(t.x,e.x)-x.distanceEpsilon&&n.y>=Math.min(t.y,e.y)-x.distanceEpsilon&&n.x<=Math.max(t.x,e.x)+x.distanceEpsilon&&n.y<=Math.max(t.y,e.y)+x.distanceEpsilon}function Cu(n,t,e,i){let r=g.getTriangleOrientation(n,t,e),s=g.getTriangleOrientation(n,t,i),o=g.getTriangleOrientation(e,i,n),a=g.getTriangleOrientation(e,i,t);return!!(r!=s&&o!=a||r==2&&jr(e,n,t)||s==2&&jr(i,n,t)||o==2&&jr(n,e,i)||a==2&&jr(t,e,i))}function Af(n,t,e,i,r){return{parallelogram:e,seg:i,leafBoxesOffset:r,node:{low:n,high:t,chord:null}}}var ci=class ze{static distToSegm(t,e,i){let r=i.sub(e);if(r.length<x.intersectionEpsilon)return t.sub(e.add(i).div(2)).length;let s=new g(-r.y,r.x);return s=s.mul(1/s.length),Math.abs(t.sub(e).dot(s))}static createParallelogramOnSubSeg(t,e,i){let r=i.derivative(t),s=i.derivative(e),o=new g(-s.y,s.x),a=i.value(t),l=i.value(e),h=l.sub(a).dot(o),u=r.dot(o),d=Math.abs(h)<x.distanceEpsilon;if(!d&&Math.abs(u)<x.distanceEpsilon)return;let c=d?0:h/u;return r=r.mul(c),ie.parallelogramByCornerSideSide(a,r,l.sub(a).sub(r))}static createParallelogramNodeForCurveSeg(t,e,i,r){if(t===i.parStart&&e===i.parEnd&&g.close(i.start,i.end,x.distanceEpsilon))return ze.createNodeWithSegmentSplit(t,e,i,r);let s=i.value(t),o=i.value(e),a=o.sub(s),l=i.value((t+e)/2);if(ze.distToSegm(l,s,o)<=x.intersectionEpsilon&&a.dot(a)<x.lineSegmentThreshold*x.lineSegmentThreshold&&e-t<x.lineSegmentThreshold){let h=D.mkPP(s,o),u=h.pNodeOverICurve();u.seg=i;let d=u.node;return d.low=t,d.high=e,d.chord=h,u}if(ze.WithinEpsilon(i,t,e,r)){let h=ze.createParallelogramOnSubSeg(t,e,i);if(h!==void 0)return Af(t,e,h,i,r)}return ze.createNodeWithSegmentSplit(t,e,i,r)}static WithinEpsilon(t,e,i,r){let s=(i-e)/3,o=t.value(e),a=t.value(i);return ze.distToSegm(t.value(e+s),o,a)>r?!1:ze.distToSegm(t.value(e+s*2),o,a)<=r}static createParallelogramNodeForCurveSegDefaultOffset(t){return ze.createParallelogramNodeForCurveSeg(t.parStart,t.parEnd,t,x.defaultLeafBoxesOffset)}static createNodeWithSegmentSplit(t,e,i,r){let s={parallelogram:null,seg:i,leafBoxesOffset:1,node:{children:[]}},o=s.node;return o.children.push(ze.createParallelogramNodeForCurveSeg(t,.5*(t+e),i,r)),o.children.push(ze.createParallelogramNodeForCurveSeg(.5*(t+e),e,i,r)),s.parallelogram=ie.parallelogramOfTwo(o.children[0].parallelogram,o.children[1].parallelogram),s}},Hi=class{constructor(n,t,e,i,r){this.par0=n,this.par1=t,this.x=e,this.seg0=i,this.seg1=r}},Zs=class{static closestPoint(n,t,e,i,r){let s=e,o=0,a=0,l,h=!1;do{let u=n.value(s),d=n.derivative(s),c=n.secondDerivative(s),f=d.dot(d)+u.sub(t).dot(c);if(Math.abs(f)<x.tolerance)return s;l=u.sub(t).dot(d.div(f)),s-=l,s>r+x.tolerance?(s=r,a++):s<i-x.tolerance&&(s=i,a++),o++}while(Math.abs(l)>x.tolerance&&!(h=o>=5||a>=5));return h&&n.value(e).sub(t).length<x.distanceEpsilon&&(s=e),s}},Dt=class Ie{isFullEllipse(){return this.parEnd===Math.PI*2&&this.parStart===0}static fromJSON(t){return new Ie(t.parStart,t.parEnd,g.fromJSON(t.axis0),g.fromJSON(t.axis1),g.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){let i=e.sub(this.center),r=g.angle(this.aAxis,i);if(this.aAxis.mul(Math.cos(r)).add(this.bAxis.mul(Math.sin(r))).length<i.length){let s=this.aAxis.length,o=this.bAxis.length;return Ie.mkEllipsePPP(this.aAxis.normalize().mul(s+t),this.bAxis.normalize().mul(o+t),this.center)}{let s=this.aAxis.length,o=this.bAxis.length;return Ie.mkEllipsePPP(this.aAxis.normalize().mul(s-t),this.bAxis.normalize().mul(o-t),this.center)}}reverse(){return null}static mkEllipsePPP(t,e,i){return new Ie(0,Math.PI*2,t,e,i)}constructor(t,e,i,r,s){for(this.parStart=t,this.parEnd=e,this.aAxis=i,this.bAxis=r,this.center=s,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 Ie(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(g.mkPoint(Math.cos(t),this.aAxis,Math.sin(t),this.bAxis))}derivative(t){return g.mkPoint(-Math.sin(t),this.aAxis,Math.cos(t),this.bAxis)}secondDerivative(t){return g.mkPoint(-Math.cos(t),this.aAxis,-Math.sin(t),this.bAxis)}thirdDerivative(t){return g.mkPoint(Math.sin(t),this.aAxis,-Math.cos(t),this.bAxis)}pNodeOverICurve(){return this.pNode!=null?this.pNode:this.pNode=ci.createParallelogramNodeForCurveSegDefaultOffset(this)}setBoundingBox(){if(lt(this.parStart,0)&<(this.parEnd,Math.PI*2))this.box=this.fullBox();else{this.box=it.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,r,s,o){return new Ie(t,e,i,r,new g(s,o))}static mkFullEllipsePPP(t,e,i){return new Ie(0,Math.PI*2,t,e,i)}static mkFullEllipseNNP(t,e,i){return new Ie(0,Math.PI*2,new g(t,0),new g(0,e),i)}static mkCircle(t,e){return Ie.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 Ie(this.parStart,this.parEnd,this.aAxis.mul(t),this.bAxis.mul(e),this.center.scale(t,e))}getParameterAtLength(t){let e=this.parStart,i=this.parEnd,r=t+.001,s=t-.001;for(;i-e>x.distanceEpsilon;){let o=.5*(i+e),a=this.lengthPartial(this.parStart,o);if(a>r)i=o;else if(a<s)e=o;else return o}return(i+e)/2}transform(t){if(t!=null){let e=t.multiplyPoint(this.aAxis).sub(t.offset()),i=t.multiplyPoint(this.bAxis).sub(t.offset());return new Ie(this.parStart,this.parEnd,e,i,t.multiplyPoint(this.center))}return this.clone()}closestParameterWithinBounds(t,e,i){let r=(i-e)/9,s=e,o=Number.MAX_VALUE;for(let l=0;l<=8;l++){let h=e+l*r,u=t.sub(this.value(h)),d=u.dot(u);d<o&&(o=d,s=h)}s===0&&i===Math.PI*2&&(e=-Math.PI);let a=Zs.closestPoint(this,t,s,e,i);return a<0&&(a+=2*Math.PI),a}lengthPartial(t,e){return G.lengthWithInterpolationAndThreshold(this.trim(t,e),x.lineSegmentThreshold/100)}get length(){return(this.aAxis.length+this.bAxis.length)*Math.abs(this.parEnd-this.parStart)/2}clone(){return new Ie(this.parStart,this.parEnd,this.aAxis.clone(),this.bAxis.clone(),this.center.clone())}closestParameter(t){let e=0,i=8,r=(this.parEnd-this.parStart)/(i+1),s=this.parStart,o=Number.MAX_VALUE;for(let h=0;h<=i;h++){let u=this.parStart+h*r,d=t.sub(this.value(u)),c=d.dot(d);c<o&&(o=c,s=u)}let a=!1;s===0&&this.parEnd===Math.PI*2&&(a=!0,e=this.parStart,this.parStart=-Math.PI);let l=Zs.closestPoint(this,t,s,this.parStart,this.parEnd);return l<0&&(l+=2*Math.PI),a&&(this.parStart=e),l}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 g.crossProduct(this.aAxis,this.bAxis)>0}fullBox(){let t=this.aAxis.add(this.bAxis);return it.mkPP(this.center.add(t),this.center.sub(t))}isArc(){return Math.abs(this.aAxis.dot(this.bAxis))<x.tolerance&&Math.abs(this.aAxis.length-this.bAxis.length)<x.tolerance&&g.closeDistEps(this.aAxis.rotate90Ccw(),this.bAxis)}},wf=class{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(n,t,e,i,r,s,o,a){this.curveA=n,this.curveB=t,this.aMin=e,this.bMin=r,this.aMax=i,this.bMax=s,this.aGuess=o,this.bGuess=a,this.si=o,this.ti=a}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(n,t,e,i){return n*i-e*t}solve(){let n=0,t=10,e=0,i=100,r=!1;if(this.initValues(),this.curveA instanceof D&&this.curveB instanceof D){let o=this.curveB.derivative(0);o=o.div(o.length);let a=this.curveA.normal(),l=Math.abs(a.dot(o));if(Math.abs(l)<x.distanceEpsilon||this.delta(this.Fss(),this.Fst(),this.Fst(),this.Ftt())<x.tolerance){this.success=!0,this.parallelLineSegLineSegMinDist();return}}let s;do{let o=this.delta(this.Fss(),this.Fst(),this.Fst(),this.Ftt());if(Math.abs(o)<x.tolerance){this.success=!1,r=!0;break}s={s:this.delta(-this.Fs(),this.Fst(),-this.Ft(),this.Ftt())/o,t:this.delta(this.Fss(),-this.Fs(),this.Fst(),-this.Ft())/o};let a=this.si+s.s,l=this.ti+s.t,h;a>this.aMax+x.distanceEpsilon||a<this.aMin-x.distanceEpsilon||l>this.bMax+x.distanceEpsilon||l<this.bMin-x.distanceEpsilon?(n++,this.chopDsDt(s),this.si+=s.s,this.ti+=s.t,h=!0):(h=!1,this.si=a,this.ti=l,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(),e++,r=n>=t||e>=i||s.s===0&&s.t===0&&h}while((Math.abs(s.s)>=x.tolerance||Math.abs(s.t)>=x.tolerance)&&!r);if(r){let o=this.curveA.value(this.aGuess).sub(this.curveB.value(this.bGuess));if(o.dot(o)<x.distanceEpsilon*x.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=!r}chopDsDt(n){if(n.s!==0&&n.t!==0){let t=1;this.si+n.s>this.aMax?t=(this.aMax-this.si)/n.s:this.si+n.s<this.aMin&&(t=(this.aMin-this.si)/n.s);let e=1;this.ti+n.t>this.bMax?e=(this.bMax-this.ti)/n.t:this.ti+n.t<this.bMin&&(e=(this.bMin-this.ti)/n.t);let i=Math.min(t,e);n.s*=i,n.t*=i}else n.s===0?this.ti+n.t>this.bMax?n.t=this.bMax-this.ti:this.ti+n.t<this.bMin&&(n.t=this.bMin-this.ti):this.si+n.s>this.aMax?n.s=this.aMax-this.si:this.si+n.s<this.aMin&&(n.s=this.aMin-this.si)}parallelLineSegLineSegMinDist(){let n=this.curveA,t=this.curveB,e=n.start,i=n.end,r=t.start,s=t.end,o=i.sub(e),a=o.length,l=0,h,u,d;if(a>x.distanceEpsilon){o=o.div(a),h=o.dot(i.sub(e)),u=o.dot(r.sub(e)),d=o.dot(s.sub(e));let c=!1;if(u>d){c=!0;let f=u;u=d,d=f}if(d<l)this.aSolution=0,this.bSolution=c?0:1;else if(u>h)this.aSolution=1,this.bSolution=c?1:0;else{let f=Math.min(h,d);this.aSolution=f/(h-l),this.bSolution=(f-u)/(d-u),c&&(this.bSolution=1-this.bSolution)}}else{let c=s.sub(r),f=c.length;if(f>x.distanceEpsilon)if(c=c.div(f),l=0,h=c.dot(s.sub(r)),u=c.dot(e.sub(r)),u<l)this.bSolution=0,this.aSolution=1;else if(u>h)this.bSolution=1,this.aSolution=0;else{let m=Math.min(h,u);this.bSolution=m/(h-l),this.aSolution=0}else this.aSolution=0,this.bSolution=0}this.aPoint=this.curveA.value(this.aSolution),this.bPoint=this.curveB.value(this.bSolution)}},Ke=class Se{constructor(t,e,i,r){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]=r,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)}toJSON(){return{b:this.b.map(t=>t.toJSON())}}static fromJSON(t){return Se.mkBezier(t.b.map(g.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=ci.createParallelogramNodeForCurveSegDefaultOffset(this)}value(t){let 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=Se.adjustParamTo01(t),e=Se.adjustParamTo01(e),t>e)return this.trim(e,t);if(t>1-x.tolerance)return new Se(this.b[3],this.b[3],this.b[3],this.b[3]);let i=new Array(3),r=new Array(2),s=this.casteljau(t,i,r),o=new Se(s,r[1],i[2],this.b[3]),a=o.casteljau((e-t)/(1-t),i,r);return new Se(o.b[0],i[0],r[0],a)}trimWithWrap(t,e){throw"NotImplementedException()"}casteljau(t,e,i){let r=1-t;for(let s=0;s<3;s++)e[s]=g.mkPoint(r,this.b[s],t,this.b[s+1]);for(let s=0;s<2;s++)i[s]=g.mkPoint(r,e[s],t,e[s+1]);return g.mkPoint(r,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 g.mkPoint(6*t,this.l,2,this.e)}thirdDerivative(t){return this.l.mul(6)}get start(){return this.b[0]}get end(){return this.b[3]}reverse(){return new Se(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=it.translate(this.bbox,t)),this.pBoxNode=null}scaleFromOrigin(t,e){return new Se(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 Se.lengthOnControlPolygon(this.b[0],this.b[1],this.b[2],this.b[3])}static lengthOnControlPolygon(t,e,i,r){let s=[t.x,t.y,e.x,e.y,i.x,i.y,r.x,r.y],o=0;for(;s.length>0;){let a=s.pop(),l=s.pop(),h=s.pop(),u=s.pop(),d=s.pop(),c=s.pop(),f=s.pop(),m=s.pop(),P=l-m,v=a-f,b=Math.sqrt(P*P+v*v),C=c-m,E=d-f,w=u-c,F=h-d,V=l-u,q=a-h,_=Math.sqrt(C*C+E*E)+Math.sqrt(w*w+F*F)+Math.sqrt(V*V+q*q);if(_-b>x.lineSegmentThreshold){let T=(m+c)/2,B=(f+d)/2,z=(c+u)/2,tt=(d+h)/2,O=(u+l)/2,L=(h+a)/2,U=(T+z)/2,st=(B+tt)/2,W=(O+z)/2,K=(L+tt)/2,at=(U+W)/2,ut=(st+K)/2;s.push(at,ut,W,K,O,L,l,a),s.push(m,f,T,B,U,st,at,ut)}else o+=(_+b)/2}return o}get boundingBox(){return this.bbox?this.bbox:this.bbox=it.mkOnPoints(this.b)}transform(t){return new Se(t.multiplyPoint(this.b[0]),t.multiplyPoint(this.b[1]),t.multiplyPoint(this.b[2]),t.multiplyPoint(this.b[3]))}closestParameterWithinBounds(t,e,i){let r=(i-e)/8,s=0,o=Number.MAX_VALUE;for(let a=0;a<9;a++){let l=t.sub(this.value(a*r+e)),h=l.dot(l);h<o&&(o=h,s=a*r+e)}return Zs.closestPoint(this,t,s,e,i)}clone(){return new Se(this.b[0],this.b[1],this.b[2],this.b[3])}static mkBezier(t){return new Se(t[0],t[1],t[2],t[3])}curvature(t){let 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){let e=this.Xp(t),i=this.Yp(t),r=e*e+i*i;return Math.sqrt(r*r*r)}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){let 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 e=0,i=Number.MAX_VALUE;for(let r=0;r<9;r++){let s=t.sub(this.value(r*.125)),o=s.dot(s);o<i&&(i=o,e=r*.125)}return Zs.closestPoint(this,t,e,0,1)}curvatureSecondDerivative(t){let 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){let e=this.Xp(t),i=this.Yp(t),r=this.Xpp(t),s=this.Ypp(t),o=this.Xppp(t),a=this.Yppp(t),l=Math.sqrt(e*e+i*i),h=e*r+i*s;return 3*(h*h/l+l*(r*r+e*o+s*s+i*a))}Gp(t){let e=this.Xp(t),i=this.Yp(t),r=this.Xpp(t),s=this.Ypp(t);return 3*Math.sqrt(e*e+i*i)*(e*r+i*s)}getParameterAtLength(t){let e=0,i=1;for(;i-e>x.tolerance;){let r=(i+e)/2,s=this.evaluateError(t,r);if(s>0)i=r;else if(s<0)e=r;else return r}return(e+i)/2}evaluateError(t,e){let i=1-e,r=g.mkPoint(i,this.b[0],e,this.b[1]),s=g.mkPoint(i,this.b[1],e,this.b[2]),o=g.mkPoint(i,this.b[2],e,this.b[3]),a=g.mkPoint(i,r,e,s),l=g.mkPoint(i,s,e,o),h=g.mkPoint(i,a,e,l),u=Se.lengthOnControlPolygon(this.b[0],r,a,h);return u>t+x.distanceEpsilon?1:u<t-x.distanceEpsilon?-1:0}};function If(n){return n.seg.value(n.par)}function Tf(n){return n.seg.derivative(n.par)}function Of(n){return n.seg.secondDerivative(n.par)}function Lf(n){return n.seg.thirdDerivative(n.par)}function Bf(n){if(n instanceof Dt)return{tag:"ellipse",segData:n.toJSON()};if(n instanceof D)return{tag:"lineSegment",segData:n.toJSON()};if(n instanceof Ke)return{tag:"bezier",segData:n.toJSON()};throw new Error("not implemented")}var G=class M{static fromJSON(t){let e=new M;for(let i of t.segs)switch(i.tag){case"bezier":e.addSegment(Ke.fromJSON(i.segData));break;case"ellipse":e.addSegment(Dt.fromJSON(i.segData));break;case"lineSegment":e.addSegment(D.fromJSON(i.segData));break;default:throw new Error("not implemented")}return e}toJSON(){return{segs:this.segs.map(t=>Bf(t))}}static CurvesIntersect(t,e){return t===e||M.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){let i={start:t,end:e};this.adjustStartEndEndParametersToDomain(i);let r=this.getSegIndexParam(t),s=this.getSegIndexParam(e);if(r.segIndex<s.segIndex){let o=this.segs[r.segIndex],a=o.lengthPartial(r.par,o.parEnd);for(let l=r.segIndex+1;l<s.segIndex;l++)a+=this.segs[l].length;return o=this.segs[s.segIndex],a+o.lengthPartial(o.parStart,s.par)}else throw new Error("not implemented.")}reverse(){let t=new M;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(let e of t)this.parEnd_+=M.paramSpan(e)}get start(){return this.segs[0].start}get end(){return this.segs[this.segs.length-1].end}scaleFromOrigin(t,e){let i=new M;for(let r of this.segs)i.addSegment(r.scaleFromOrigin(t,e));return i}trim(t,e){let i={start:t,end:e};this.adjustStartEndEndParametersToDomain(i);let r=this.getSegIndexParam(i.start),s=this.getSegIndexParam(i.end);if(r.segIndex===s.segIndex)return this.segs[r.segIndex].trim(r.par,s.par);let o=new M;r.par<this.segs[r.segIndex].parEnd&&(o=o.addSegment(this.segs[r.segIndex].trim(r.par,this.segs[r.segIndex].parEnd)));for(let a=r.segIndex+1;a<s.segIndex;a++)o=o.addSegment(this.segs[a]);return this.segs[s.segIndex].parStart<s.par&&(o=o.addSegment(this.segs[s.segIndex].trim(this.segs[s.segIndex].parStart,s.par))),o}translate(t){for(let e of this.segs)e.translate(t);this.boundingBox_&&(this.boundingBox_=it.translate(this.boundingBox_,t)),this.pBNode=null}adjustStartEndEndParametersToDomain(t){if(t.start>t.end){let 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);let i=new M;return i.addSegment(this.trim(t,this.parEnd)),i.addSegment(this.trim(this.parStart,e)),i}addSegs(t){for(let e of t)this.addSegment(e);return this}addSegment(t){if(t==null)return this;if(this.boundingBox_=null,!(t instanceof M))this.segs.push(t),this.parEnd_+=M.paramSpan(t);else for(let e of t.segs)this.segs.push(e),this.parEnd_+=M.paramSpan(e);return this}pNodeOverICurve(){if(this.pBNode!=null)return this.pBNode;let t=[],e=[];for(let i of this.segs){let r=i.pNodeOverICurve();t.push(r.parallelogram),e.push(r)}return this.pBNode={parallelogram:ie.getParallelogramOfAGroup(t),seg:this,leafBoxesOffset:x.defaultLeafBoxesOffset,node:{children:e}},this.pBNode}static intersectionOne(t,e,i){let r=M.curveCurveXWithParallelogramNodesOne(t.pNodeOverICurve(),e.pNodeOverICurve());return i&&r!=null&&(r=M.liftIntersectionToCurves(t,e,r)),r}static getAllIntersections(t,e,i){return t instanceof D?M.getAllIntersectionsOfLineAndICurve(t,e,i):M.getAllIntersectionsInternal(t,e,i)}static getAllIntersectionsInternal(t,e,i){let r=[];if(M.curveCurveXWithParallelogramNodes(t.pNodeOverICurve(),e.pNodeOverICurve(),r),i)for(let s=0;s<r.length;s++)r[s]=M.liftIntersectionToCurves(t,e,r[s]);return r}static getAllIntersectionsOfLineAndICurve(t,e,i){return e instanceof et?M.getAllIntersectionsOfLineAndPolyline(t,e):e instanceof M?M.getAllIntersectionsOfLineAndCurve(t,e,i):e instanceof Dt&&e.isArc()?M.getAllIntersectionsOfLineAndArc(t,e):M.getAllIntersectionsInternal(t,e,i)}static getAllIntersectionsOfLineAndCurve(t,e,i){let r=[],s=t.pNodeOverICurve(),o=e.pNodeOverICurve();if(ie.intersect(s.parallelogram,o.parallelogram)===!1)return r;let a=0;for(let l of e.segs){let h=M.getAllIntersections(t,l,!1);if(i){for(let u of h)u.par1+=a-l.parStart,u.seg1=e;a+=l.parEnd-l.parStart}for(let u of h)M.alreadyInside(r,u)||r.push(u)}return r}static closeIntersections(t,e){return g.close(t.x,e.x,x.intersectionEpsilon)}static closeIntersectionPoints(t,e){return g.close(t,e,x.intersectionEpsilon)}static alreadyInside(t,e){for(let i=0;i<t.length;i++){let r=t[i];if(M.closeIntersections(r,e))return!0}return!1}static getAllIntersectionsOfLineAndArc(t,e){let i=t.end.sub(t.start),r=[],s=i.length;if(s<x.distanceEpsilon){let d=t.start.sub(e.center);if(lt(d.length,e.aAxis.length)){let c=g.angle(e.aAxis,d);e.parStart-x.tolerance<=c&&(c=Math.max(c,e.parStart),c<=e.parEnd+x.tolerance&&(c=Math.min(e.parEnd,c),r.push(new Hi(0,c,t.start,t,e))))}return r}let o=i.rotate90Ccw().div(s),a=t.start.sub(e.center).dot(o),l=e.center.add(o.mul(a)),h=e.aAxis.length,u=Math.abs(a);if(h<u-x.distanceEpsilon)return r;if(i=o.rotate90Cw(),lt(h,u))M.tryToAddPointToLineCircleCrossing(t,e,r,l,s,i);else{let d=Math.sqrt(h*h-a*a),c=i.mul(d);M.tryToAddPointToLineCircleCrossing(t,e,r,l.add(c),s,i),M.tryToAddPointToLineCircleCrossing(t,e,r,l.sub(c),s,i)}return r}static tryToAddPointToLineCircleCrossing(t,e,i,r,s,o){let a=r.sub(t.start).dot(o);if(a<-x.distanceEpsilon||(a=Math.max(a,0),a>s+x.distanceEpsilon))return;a=Math.min(a,s),a/=s;let l=g.angle(e.aAxis,r.sub(e.center));e.parStart-x.tolerance<=l&&(l=Math.max(l,e.parStart),l<=e.parEnd+x.tolerance&&(l=Math.min(e.parEnd,l),i.push(new Hi(a,l,r,t,e))))}static getAllIntersectionsOfLineAndPolyline(t,e){let i=[],r=0,s=e.startPoint;for(;s!=null&&s.getNext()!=null;s=s.getNext()){let o=M.crossTwoLineSegs(t.start,t.end,s.point,s.getNext().point,0,1,0,1);o&&(M.adjustSolution(t.start,t.end,s.point,s.getNext().point,o),M.oldIntersection(i,o.x)||i.push(new Hi(o.aSol,r+o.bSol,o.x,t,e))),r++}if(e.closed){let o=M.crossTwoLineSegs(t.start,t.end,s.point,e.start,0,1,0,1);o&&(M.adjustSolution(t.start,t.end,s.point,e.start,o),M.oldIntersection(i,o.x)||i.push(new Hi(o.aSol,r+o.bSol,o.x,t,e)))}return i}static adjustSolution(t,e,i,r,s){M.closeIntersectionPoints(s.x,t)?(s.x=t,s.aSol=0):M.closeIntersectionPoints(s.x,e)&&(s.x=e,s.aSol=1),M.closeIntersectionPoints(s.x,i)?(s.x=i,s.bSol=Math.floor(s.bSol)):M.closeIntersectionPoints(s.x,r)&&(s.x=r,s.bSol=Math.ceil(s.bSol))}static curveCurveXWithParallelogramNodesOne(t,e){if(!ie.intersect(t.parallelogram,e.parallelogram))return null;let i=t.node,r=e.node,s=i.hasOwnProperty("children"),o=r.hasOwnProperty("children");if(s&&o)for(let a of i.children)for(let l of r.children){let h=M.curveCurveXWithParallelogramNodesOne(a,l);if(h!=null)return h}else if(o)for(let a of r.children){let l=M.curveCurveXWithParallelogramNodesOne(t,a);if(l!=null)return l}else if(s)for(let a of i.children){let l=M.curveCurveXWithParallelogramNodesOne(a,e);if(l!=null)return l}else return M.crossOverIntervalsOne(t,e);return null}static curveCurveXWithParallelogramNodes(t,e,i){if(!ie.intersect(t.parallelogram,e.parallelogram))return;let r=t.node.hasOwnProperty("children"),s=e.node.hasOwnProperty("children");if(r&&s)for(let o of t.node.children)for(let a of e.node.children)M.curveCurveXWithParallelogramNodes(o,a,i);else if(s)for(let o of e.node.children)M.curveCurveXWithParallelogramNodes(t,o,i);else if(r)for(let o of t.node.children)M.curveCurveXWithParallelogramNodes(o,e,i);else i=M.crossOverLeaves(t,e,i)}static crossOverIntervalsOne(t,e){let i=t.node,r=e.node,s=(i.high-i.low)/2,o=(r.high-r.low)/2;for(let a=1;a<2;a++){let l=a*s+i.low;for(let h=1;h<2;h++){let u=h*o+r.low,d;if(i.chord==null&&r.chord==null?d=M.crossWithinIntervalsWithGuess(t.seg,e.seg,i.low,i.high,r.low,r.high,l,u):i.chord!=null&&r.chord==null?d=M.crossWithinIntervalsWithGuess(i.chord,e.seg,0,1,r.low,r.high,.5*a,u):i.chord==null?(d=M.crossWithinIntervalsWithGuess(t.seg,r.chord,i.low,i.high,0,1,l,.5*h),d&&(d.bSol=r.low+d.bSol*(r.high-r.low))):(d=M.crossWithinIntervalsWithGuess(i.chord,r.chord,0,1,0,1,.5*a,.5*h),d&&(d.aSol=i.low+d.aSol*(i.high-i.low),d.bSol=r.low+d.bSol*(r.high-r.low))),d)return M.createIntersectionOne(t,e,d.aSol,d.bSol,d.x)}}return M.goDeeperOne(t,e)}static crossOverLeaves(t,e,i){let r=t.node,s=e.node,o=!1,a=(r.high-r.low)/2+r.low,l=(s.high-s.low)/2+s.low,h;return r.chord==null&&s.chord==null?h=M.crossWithinIntervalsWithGuess(t.seg,e.seg,r.low,r.high,s.low,s.high,a,l):r.chord!=null&&s.chord==null?(h=M.crossWithinIntervalsWithGuess(r.chord,e.seg,0,1,s.low,s.high,.5,l),h&&(h.aSol=r.low+h.aSol*(r.high-r.low))):r.chord==null?(h=M.crossWithinIntervalsWithGuess(t.seg,s.chord,r.low,r.high,0,1,a,.5),h&&(h.bSol=s.low+h.bSol*(s.high-s.low))):(h=M.crossWithinIntervalsWithGuess(r.chord,s.chord,0,1,0,1,.5,.5),h&&(h.bSol=s.low+h.bSol*(s.high-s.low),h.aSol=r.low+h.aSol*(r.high-r.low))),h&&(M.addIntersection(t,e,i,h),o=!0),o||M.goDeeper(i,t,e),i}static addIntersection(t,e,i,r){let s=t.node;M.closeIntersectionPoints(r.x,t.seg.value(s.low))?(r.x=t.seg.value(s.low),r.aSol=s.low):M.closeIntersectionPoints(r.x,t.seg.value(s.high))&&(r.x=t.seg.value(s.high),r.aSol=s.high);let o=e.node;if(M.closeIntersectionPoints(r.x,e.seg.value(o.low))?(r.x=e.seg.value(o.low),r.bSol=o.low):M.closeIntersectionPoints(r.x,e.seg.value(o.high))&&(r.x=e.seg.value(o.high),r.bSol=o.high),!M.oldIntersection(i,r.x)){let a=new Hi(r.aSol,r.bSol,r.x,t.seg,e.seg);i.push(a)}}static oldIntersection(t,e){for(let i of t)if(e.sub(i.x).length<x.distanceEpsilon*100)return!0;return!1}static createIntersectionOne(t,e,i,r,s){let o=t.node,a=e.node;return M.closeIntersectionPoints(s,t.seg.value(o.low))?(s=t.seg.value(o.low),i=o.low):M.closeIntersectionPoints(s,t.seg.value(o.high))&&(s=t.seg.value(o.high),i=o.high),M.closeIntersectionPoints(s,e.seg.value(a.low))?(s=e.seg.value(a.low),r=a.low):M.closeIntersectionPoints(s,e.seg.value(a.high))&&(s=e.seg.value(a.high),r=a.high),new Hi(i,r,s,t.seg,e.seg)}static liftIntersectionToCurves_(t,e,i,r,s,o,a){let l=t instanceof M?M.liftParameterToCurve(t,i-o.parStart,o):i,h=e instanceof M?M.liftParameterToCurve(e,r-a.parStart,a):r;return new Hi(l,h,s,t,e)}static DropIntersectionToSegs(t){let e,i;if(t.seg0 instanceof M){let o=t.seg0.getSegParam(t.par0);e=o.seg,i=o.par}else i=t.par0,e=t.seg0;let r,s;if(t.seg1 instanceof M){let o=t.seg1.getSegParam(t.par1);s=o.par,r=o.seg}else s=t.par1,r=t.seg1;return new Hi(i,s,t.x,e,r)}static liftIntersectionToCurves(t,e,i){return M.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;let r=t,s=0;for(let o of r.segs){if(o===i)return e+s;s+=M.paramSpan(o)}throw"bug in liftParameterToCurve"}static paramSpan(t){return t.parEnd-t.parStart}static goDeeperOne(t,e){let i=t.node,r=e.node;if(t.leafBoxesOffset>x.distanceEpsilon&&e.leafBoxesOffset>x.distanceEpsilon){let a=ci.createParallelogramNodeForCurveSeg(i.low,i.high,t.seg,t.leafBoxesOffset/2),l=ci.createParallelogramNodeForCurveSeg(r.low,r.high,e.seg,e.leafBoxesOffset/2);return M.curveCurveXWithParallelogramNodesOne(a,l)}if(t.leafBoxesOffset>x.distanceEpsilon){let a=ci.createParallelogramNodeForCurveSeg(i.low,i.high,t.seg,t.leafBoxesOffset/2);return M.curveCurveXWithParallelogramNodesOne(a,e)}if(e.leafBoxesOffset>x.distanceEpsilon){let a=ci.createParallelogramNodeForCurveSeg(r.low,r.high,e.seg,e.leafBoxesOffset/2);return M.curveCurveXWithParallelogramNodesOne(t,a)}let s=t.seg.value(i.low),o=t.seg.value(i.high);if(!g.closeDistEps(s,o)){let a=e.seg.value(r.low),l=e.seg.value(r.high);if(!g.closeDistEps(a,l)){let h=t.seg instanceof D?t.seg:D.mkPP(s,o),u=e.seg instanceof D?e.seg:D.mkPP(a,l),d=M.crossWithinIntervalsWithGuess(h,u,0,1,0,1,.5,.5);if(d)return M.adjustParameters(t,h,e,u,d),M.createIntersectionOne(t,e,d.aSol,d.bSol,d.x)}}return null}static goDeeper(t,e,i){let r=e.node,s=i.node,o=e.leafBoxesOffset>x.distanceEpsilon,a=i.leafBoxesOffset>x.distanceEpsilon;if(o&&a){let l=ci.createParallelogramNodeForCurveSeg(r.low,r.high,e.seg,e.leafBoxesOffset/2),h=ci.createParallelogramNodeForCurveSeg(s.low,s.high,i.seg,i.leafBoxesOffset/2);M.curveCurveXWithParallelogramNodes(l,h,t)}else if(o){let l=ci.createParallelogramNodeForCurveSeg(r.low,r.high,e.seg,e.leafBoxesOffset/2);M.curveCurveXWithParallelogramNodes(l,i,t)}else if(a){let l=ci.createParallelogramNodeForCurveSeg(s.low,s.high,i.seg,i.leafBoxesOffset/2);M.curveCurveXWithParallelogramNodes(e,l,t)}else{let l=e.seg.value(r.low),h=e.seg.value(r.high);if(!g.closeDistEps(l,h)){let u=i.seg.value(s.low),d=i.seg.value(s.high);if(!g.closeDistEps(u,d)){let c=e.seg instanceof D?e.seg:D.mkPP(l,h),f=i.seg instanceof D?i.seg:D.mkPP(u,d),m=M.crossWithinIntervalsWithGuess(c,f,0,1,0,1,.5,.5);m&&(M.adjustParameters(e,c,i,f,m),M.addIntersection(e,i,t,m))}}}}static adjustParameters(t,e,i,r,s){if(e!==t.seg&&!(t.seg instanceof et))s.aSol=t.seg.closestParameter(s.x);else{let o=t.node;s.aSol=o.low+s.aSol*(o.high-o.low)}if(r!==i.seg&&!(i.seg instanceof et))s.bSol=i.seg.closestParameter(s.x);else{let o=i.node;s.bSol=o.low+s.bSol*(o.high-o.low)}}getSegParam(t){let e=this.parStart;for(let r of this.segs){let s=e+r.parEnd-r.parStart;if(t>=e&&t<=s)return{par:t-e+r.parStart,seg:r};e=s}let i=this.segs[this.segs.length-1];return{seg:i,par:i.parEnd}}getSegIndexParam(t){let e=0,i=this.segs.length;for(let s=0;s<i;s++){let o=this.segs[s],a=e+o.parEnd-o.parStart;if(t>=e&&t<=a)return{segIndex:s,par:t-e+o.parStart};e=a}let r=this.segs[i-1];return{segIndex:i-1,par:r.parEnd}}value(t){return If(this.getSegParam(t))}derivative(t){return Tf(this.getSegParam(t))}secondDerivative(t){return Of(this.getSegParam(t))}thirdDerivative(t){return Lf(this.getSegParam(t))}static crossWithinIntervalsWithGuess(t,e,i,r,s,o,a,l){if(t instanceof D&&e instanceof D){let d=M.crossTwoLineSegs(t.start,t.end,e.start,e.end,i,r,s,o);if(d!==void 0)return d}let h=M.minDistWithinIntervals(t,e,i,r,s,o,a,l);if(h==null)return;let u=h.aX.sub(h.bX);return u.dot(u)>=x.distanceEpsilon?void 0:{aSol:h.aSol,bSol:h.bSol,x:g.middle(h.aX,h.bX)}}static crossTwoLineSegs(t,e,i,r,s,o,a,l){let h=e.sub(t),u=i.sub(r),d=i.sub(t),c=Wn.solve(h.x,u.x,d.x,h.y,u.y,d.y);if(c==null)return;let f=c.x,m=c.y,P=t.add(h.mul(f));if(!(f<s-x.tolerance)&&(f=Math.max(f,s),!(f>o+x.tolerance)&&(f=Math.min(f,o),!(m<a-x.tolerance)&&(m=Math.max(m,a),!(m>l+x.tolerance)))))return m=Math.min(m,l),{aSol:f,bSol:m,x:P}}static PointRelativeToCurveLocation(t,e){if(!e.boundingBox.contains(t))return 0;let i=2*e.boundingBox.diagonal,r=Math.PI/180,s=0;for(let o=13;o<360;o+=13){let a=new g(Math.cos(o*r),Math.sin(o*r)),l=D.mkPP(t,t.add(a.mul(i))),h=this.getAllIntersectionsOfLineAndICurve(l,e,!0);if(M.AllIntersectionsAreGood(h,e)){for(let u of h)if(g.closeDistEps(u.x,t))return 1;if(h.length%2===1?s++:s--,s>=2)return 2;if(s<=-2)return 0}}return 1}static AllIntersectionsAreGood(t,e){let i=e.hasOwnProperty("segs"),r=null;if(i||e instanceof et&&(r=e.toCurve()),r){for(let s of t)if(!M.RealCut(M.DropIntersectionToSegs(s),r,!1))return!1}return!0}static RealCut(t,e,i){let r=t.seg0,s=t.seg1,o=t.par0,a=t.par1,l=t.x,h=r.derivative(o).normalize(),u=s.derivative(a).normalize().rotate(Math.PI/2);if(g.closeDistEps(l,s.end)){let c=null;for(let m=0;m<e.segs.length-1;m++)if(e.segs[m]===s){c=e.segs[m+1];break}if(c==null)return!1;let f=h.rotate(Math.PI/2);return!(f.dot(s.derivative(s.parEnd))*f.dot(c.derivative(c.parStart))<x.tolerance)}if(g.closeDistEps(l,s.start)){let c=null;for(let m=e.segs.length-1;m>0;m--)if(e.segs[m]===s){c=e.segs[m-1];break}if(c==null)return!1;let f=h.rotate(Math.PI/2);return!(f.dot(s.derivative(s.parStart))*f.dot(c.derivative(c.parEnd))<x.tolerance)}let d=h.dot(u);return i?d>x.distanceEpsilon:Math.abs(d)>x.distanceEpsilon}static realCutWithClosedCurve(t,e,i){let r=t.seg0,s=t.seg1,o=t.par0,a=t.par1,l=t.x,h=r.derivative(o).normalize(),u=s.derivative(a).normalize().rotate(Math.PI/2);if(g.closeDistEps(l,s.end)){let c=null;for(let m=0;m<e.segs.length;m++)if(e.segs[m]===s){c=e.segs[(m+1)%e.segs.length];break}if(c==null)throw new Error;let f=h.rotate(Math.PI/2);return!(f.dot(s.derivative(s.parEnd))*f.dot(c.derivative(c.parStart))<x.tolerance)}if(g.closeDistEps(l,s.start)){let c=null;for(let m=0;m<e.segs.length;m++)if(e.segs[m]===s){c=e.segs[m>0?m-1:e.segs.length-1];break}let f=h.rotate(Math.PI/2);return!(f.dot(s.derivative(s.parStart))*f.dot(c.derivative(c.parEnd))<x.tolerance)}let d=h.dot(u);return i?d>x.distanceEpsilon:Math.abs(d)>x.distanceEpsilon}static minDistWithinIntervals(t,e,i,r,s,o,a,l){let h=new wf(t,e,i,r,s,o,a,l);return h.solve(),h.success?{aSol:h.aSolution,bSol:h.bSolution,aX:h.aPoint,bX:h.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_=it.mkEmpty();else{let 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(){let t=new M;for(let e of this.segs)t.addSegment(e.clone());return this.boundingBox_!=null&&(t.boundingBox_=this.boundingBox_.clone()),t}getParameterAtLength(t){let e=0;for(let i of this.segs){let r=i.length;if(r>=t)return e+i.getParameterAtLength(t);t-=r,e+=i.parEnd-i.parStart}return this.parEnd}get length(){let t=0;for(let e of this.segs)t+=e.length;return t}transform(t){let e=new M;for(let i of this.segs)e.addSegment(i.transform(t));return this.boundingBox_&&(e.boundingBox_=this.boundingBox_.transform(t)),e}closestParameterWithinBounds(t,e,i){let r=0,s=Number.MAX_VALUE,o=0;for(let a of this.segs){if(o>i)break;let l=M.paramSpan(a);if(o+l>=e){let h=Math.max(a.parStart,a.parStart+(e-o)),u=Math.min(a.parEnd,a.parStart+(i-o)),d=a.closestParameterWithinBounds(t,h,u),c=t.sub(a.value(d)),f=c.dot(c);f<s&&(r=o+d-a.parStart,s=f)}o+=l}return r}closestParameter(t){let e=0,i=Number.MAX_VALUE,r=0;for(let s of this.segs){let o=s.closestParameter(t),a=t.sub(s.value(o)),l=a.dot(a);if(l<i){if(e=r+o-s.parStart,l===0)break;i=l}r+=M.paramSpan(s)}return e}static addLineSegment(t,e,i){return t.addSegment(D.mkPP(e,i))}static addLineSegmentCNNP(t,e,i,r){return M.addLineSegment(t,new g(e,i),r)}static addLineSegmentCNNNN(t,e,i,r,s){M.addLineSegment(t,new g(e,i),new g(r,s))}static continueWithLineSegmentNN(t,e,i){M.addLineSegment(t,t.end,new g(e,i))}static continueWithLineSegmentP(t,e){M.addLineSegment(t,t.end,e)}static closeCurve(t){return M.continueWithLineSegmentP(t,t.start),t}leftDerivative(t){let e=this.tryToGetLeftSegment(t);return e!=null?e.derivative(e.parEnd):this.derivative(t)}rightDerivative(t){let e=this.tryToGetRightSegment(t);return e!=null?e.derivative(e.parStart):this.derivative(t)}tryToGetLeftSegment(t){if(Math.abs(t-this.parStart)<x.tolerance)return this.start.equal(this.end)?this.segs[this.segs.length-1]:null;for(let e of this.segs)if(t-=M.paramSpan(e),Math.abs(t)<x.tolerance)return e;return null}tryToGetRightSegment(t){if(Math.abs(t-this.parEnd)<x.tolerance)return this.start===this.end?this.segs[0]:null;for(let e of this.segs){if(Math.abs(t)<x.tolerance)return e;t-=M.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;let i=M.getAllIntersections(t,e,!0);if(i.length===0)return M.NonIntersectingCurveIsInsideOther(t,e);if(i.length===1)return t.start.equal(i[0].x)?M.PointRelativeToCurveLocation(t.value((t.parStart+t.parEnd)/2),e)==2:M.PointRelativeToCurveLocation(t.start,e)===2;for(let r of M.PointsBetweenIntersections(t,i))if(M.PointRelativeToCurveLocation(r,e)===0)return!1;return!0}static*PointsBetweenIntersections(t,e){e.sort((a,l)=>a.par0-l.par0);for(let a=0;a<e.length-1;a++)yield t.value((e[a].par0+e[a+1].par0)/2);let i=e[e.length-1].par0,r=e[0].par0,s=t.parEnd-i+(r-t.parStart),o=i+s/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){let r=M.PointRelativeToCurveLocation(t.value(i),e);if(r!==1)return r===2}return M.PointRelativeToCurveLocation(t.end,e)!==0}static ClosedCurveInteriorsIntersect(t,e){if(!e.boundingBox.intersects(t.boundingBox))return!1;let i=M.getAllIntersections(t,e,!0);if(i.length===0)return M.NonIntersectingCurveIsInsideOther(t,e)||M.NonIntersectingCurveIsInsideOther(e,t);if(i.length===1)return t.start.equal(i[0].x)?M.PointRelativeToCurveLocation(t.value((t.parStart+t.parEnd)/2),e)===2||!e.start.equal(i[0].x)?M.PointRelativeToCurveLocation(e.start,t)===2:M.PointRelativeToCurveLocation(e.value((e.parStart+e.parEnd)/2),t)===2:M.PointRelativeToCurveLocation(t.start,e)===2;for(let r of M.PointsBetweenIntersections(t,i))if(M.PointRelativeToCurveLocation(r,e)===2)return!0;return!0}curvature(t){let 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,r,s){let o=g.mkPoint(t,i.point,1-t,r.point),a=g.mkPoint(e,s.point,1-e,r.point),l=r.point.mul(2/3);return new Ke(o,o.div(3).add(l),l.add(a.div(3)),a)}static createBezierSegN(t,e,i,r){let s=i.mul(r);return new Ke(t,t.add(s),e.add(s),e)}static findCorner(t){let e=t.next;if(e.next==null)return;let i=e.next;if(i!=null)return{b:e,c:i}}static trimEdgeSplineWithNodeBoundaries(t,e,i,r){let s=i.parStart,o=i.parEnd;t!=null&&(s=M.findNewStart(i,s,t,r)),e!=null&&(o=M.findNewEnd(i,e,r,o));let a=Math.min(s,o),l=Math.max(s,o);return a<l?i.trim(a,l):i}static findNewEnd(t,e,i,r){let s=M.getAllIntersections(t,e,!0);if(s.length===0)return r=t.parEnd,r;if(i){r=t.parEnd;for(let o of s)o.par0<r&&(r=o.par0)}else{r=t.parStart;for(let o of s)o.par0>r&&(r=o.par0)}return r}static findNewStart(t,e,i,r){let s=M.getAllIntersections(t,i,!0);if(s.length===0){e=t.parStart;return}if(r){e=t.parStart;for(let o of s)o.par0>e&&(e=o.par0)}else{e=t.parEnd;for(let o of s)o.par0<e&&(e=o.par0)}return e}static polylineAroundClosedCurve(t){if(t instanceof Dt)return M.refineEllipse(t);if(t instanceof et)return t;if(t instanceof M&&M.allSegsAreLines(t)){let e=new et;for(let 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(let e of t.segs)if(!(e instanceof D))return!1;return!0}static refineEllipse(t){let e=t.boundingBox.perimeter(),i=Math.PI/4,r=t.boundingBox.width,s=t.boundingBox.height,o=Math.sqrt(r*r+s*s),a=[];for(let h=0;h<4;h++){let u=i+h*Math.PI/2,d=t.value(u),c=t.derivative(u).normalize().mul(o),f=D.mkPP(d.sub(c),d.add(c));for(let m of M.getAllIntersections(e,f,!0))a.push(m)}a.sort((h,u)=>h.par0<u.par0?-1:h.par0>u.par0?1:0);let l=new et;return a.forEach(h=>l.addPoint(h.x)),l.closed=!0,l}static polyFromBox(t){let e=new et;return e.addPoint(t.leftTop),e.addPoint(t.rightTop),e.addPoint(t.rightBottom),e.addPoint(t.leftBottom),e.closed=!0,e}},et=class Ne{constructor(){this.initIsRequired=!0,this.isClosed_=!1}toJSON(){return{points:Array.from(this).map(t=>t.toJSON())}}static fromJSON(t){return Ne.mkFromPoints(t.points.map(e=>g.fromJSON(e)))}RemoveStartPoint(){let t=this.startPoint.next;t.prev=null,this.startPoint=t,this.setInitIsRequired()}RemoveEndPoint(){let t=this.endPoint.prev;t.next=null,this.endPoint=t,this.setInitIsRequired()}setInitIsRequired(){this.initIsRequired=!0}addPointXY(t,e){this.addPoint(new g(t,e))}isClockwise(){return g.getTriangleOrientation(this.startPoint.point,this.startPoint.next.point,this.startPoint.next.next.point)==0}addPoint(t){let e=new Ni;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){let e=Ni.mkFromPoint(t);e.polyline=this,this.startPoint!=null?g.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){let i=e.sub(t).div(2);return ie.parallelogramByCornerSideSide(t,i,i)}static mkFromPoints(t){let e=new Ne;for(let i of t)e.addPoint(i);return e}static mkClosedFromPoints(t){let e=Ne.mkFromPoints(t);return e.closed=!0,e}calculatePbNode(){let t=[],e=[],i=this.startPoint,r=0;for(;i.next!=null;){let s=Ne.parallelogramOfLineSeg(i.point,i.next.point);t.push(s),e.push({parallelogram:s,seg:this,leafBoxesOffset:0,node:{low:r,high:r+1,chord:D.mkPP(i.point,i.next.point)}}),i=i.next,r++}if(this.isClosed_){let s=Ne.parallelogramOfLineSeg(this.endPoint.point,this.startPoint.point);t.push(s),e.push({parallelogram:s,seg:this,leafBoxesOffset:0,node:{low:r,high:r+1,chord:D.mkPP(this.endPoint.point,this.startPoint.point)}})}this.pBNode={parallelogram:ie.getParallelogramOfAGroup(t),seg:this,leafBoxesOffset:0,node:{children:e}}}init(){this.bBox=it.rectangleOnPoint(this.startPoint.point);for(let 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();let e=this.getAdjustedParamAndStartEndPoints(t);return g.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){let e=this.getAdjustedParamAndStartEndPoints(t);return e.b.sub(e.a)}secondDerivative(t){return new g(0,0)}thirdDerivative(t){return new g(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){let e=new Ne;e.addPoint(t.start);for(let 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 G?Ne.polylineFromCurve(i):Ne.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(){let t=new Ne;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){let e=new Ne;for(let 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,r=0,s=this.startPoint;for(;s.next!=null;){let o=D.mkPP(s.point,s.next.point),a=o.closestParameter(t),l=o.value(a).sub(t),h=l.dot(l);h<i&&(i=h,e=a+r),s=s.next,r++}if(this.closed){let o=D.mkPP(this.endPoint.point,this.startPoint.point),a=o.closestParameter(t),l=o.value(a).sub(t);l.dot(l)<i&&(e=a+r)}return e}clone(){let t=new Ne;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){return t.next??(this.closed?this.startPoint:null)}prev(t){return t.prev??(this.closed?this.endPoint:null)}toCurve(){let t=new G;G.addLineSegment(t,this.startPoint.point,this.startPoint.next.point);let e=this.startPoint.next;for(;(e=e.next)!=null;)G.continueWithLineSegmentP(t,e.point);return this.closed&&G.continueWithLineSegmentP(t,this.startPoint.point),t}RemoveCollinearVertices(){for(let t=this.startPoint.next;t.next!=null;t=t.next)g.getTriangleOrientation(t.prev.point,t.point,t.next.point)===2&&(t.prev.next=t.next,t.next.prev=t.prev);return this.setInitIsRequired(),this}},fi=class{pad(n){this.width+=n*2}constructor(n,t=n){this.width=n,this.height=t}},it=class Ht{transform(t){return Ht.mkPP(t.multiplyPoint(this.leftTop),t.multiplyPoint(this.rightBottom))}translate(t){return Ht.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 lt(this.left_,t.left)&<(this.right_,t.right)&<(this.top_,t.top)&<(this.bottom_,t.bottom)}static mkSizeCenter(t,e){let i=t.width/2,r=t.height/2;return new Ht({left:e.x-i,right:e.x+i,bottom:e.y-r,top:e.y+r})}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 Ht.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)){let o=Ht.mkEmpty();return o.setToEmpty(),o}let e=Math.max(this.left,t.left),i=Math.min(this.right,t.right),r=Math.max(this.bottom,t.bottom),s=Math.min(this.top,t.top);return new Ht({left:e,bottom:r,right:i,top:s})}get center(){return new g((this.left_+this.right_)/2,(this.top_+this.bottom_)/2)}set center(t){let e=t.x-(this.left_+this.right_)/2,i=t.y-(this.top_+this.bottom_)/2;this.left_+=e,this.right_+=e,this.top_+=i,this.bottom+=i}intersectsOnY(t){return!(t.bottom_>this.top_+x.distanceEpsilon||t.top_<this.bottom_-x.distanceEpsilon)}intersectsOnX(t){return!(t.left>this.right_+x.distanceEpsilon||t.right<this.left_-x.distanceEpsilon)}static mkEmpty(){return new Ht({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 g(this.left_,this.bottom_)}set leftBottom(t){this.left_=t.x,this.bottom=t.y}get rightTop(){return new g(this.right_,this.top_)}set rightTop(t){this.right_=t.x,this.top_=t.y}get leftTop(){return new g(this.left_,this.top_)}set leftTop(t){this.left_=t.x,this.top_=t.y}get rightBottom(){return new g(this.right_,this.bottom_)}set rightBottom(t){this.right_=t.x,this.bottom=t.y}onUpdated(){}static mkPP(t,e){let i=new Ht({left:t.x,right:t.x,top:t.y,bottom:t.y});return i.add(e),i}static rectangleOnPoint(t){return new Ht({left:t.x,right:t.x,top:t.y,bottom:t.y})}static mkLeftBottomSize(t,e,i){let r=t+i.width,s=e+i.height;return new Ht({left:t,right:r,top:s,bottom:e})}static getRectangleOnCoords(t,e,i,r){let s=new Ht({left:t,bottom:e,right:t,top:e});return s.add(new g(i,r)),s}static mkOnPoints(t){let e=Ht.mkEmpty();for(let i of t)e.add(i);return e}static mkOnRectangles(t){let e=Ht.mkEmpty();for(let i of t)e.addRecSelf(i);return e}get width(){return this.right_-this.left_}set width(t){let 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){let e=t/2,i=(this.top_+this.bottom_)/2;this.top_=i+e,this.bottom=i-e}static rectangleOfTwo(t,e){let i=new Ht({left:t.left_,right:t.right_,top:t.top_,bottom:t.bottom_});return i.addRecSelf(e),i}containsWithPadding(t,e){return this.left_-e-x.distanceEpsilon<=t.x&&t.x<=this.right_+e+x.distanceEpsilon&&this.bottom_-e-x.distanceEpsilon<=t.y&&t.y<=this.top_+e+x.distanceEpsilon}get area(){return(this.right_-this.left_)*(this.top_-this.bottom_)}add(t){this.addCoords(t.x,t.y)}addCoords(t,e){this.isEmpty()?(this.left_=this.right_=t,this.top_=this.bottom=e):(this.left_>t&&(this.left_=t),this.top_<e&&(this.top_=e),this.right_<t&&(this.right_=t),this.bottom_>e&&(this.bottom=e))}addRecSelf(t){this.addCoords(t.left_,t.top_),this.addCoords(t.right_,t.bottom_)}addRec(t){let e=this.clone();return e.addCoords(t.left_,t.top_),e.addCoords(t.right_,t.bottom_),e}static translate(t,e){return new Ht({left:t.left_+e.x,right:t.right_+e.x,bottom:t.bottom_+e.y,top:t.top_+e.y})}static transform(t,e){return Ht.mkPP(e.multiplyPoint(t.leftTop),e.multiplyPoint(t.rightBottom))}contains(t){return this.containsWithPadding(t,0)}containsRect(t){return this.containsWithPadding_LRTB(t.left_,t.right_,t.top_,t.bottom_,0)}containsRectWithPadding(t,e){return this.containsWithPadding_LRTB(t.left_,t.right_,t.top_,t.bottom_,e)}containsWithPadding_LRTB(t,e,i,r,s){let o=x.distanceEpsilon;return this.left_-s-o<=t&&e<=this.right_+s+o&&this.bottom_-s-o<=r&&i<=this.top_+s+o}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)?Ht.mkPP(new g(Math.max(t.left,e.left),Math.max(t.bottom,e.bottom)),new g(Math.min(t.right,e.right),Math.min(t.top,e.top))):Ht.mkEmpty()}perimeter(){let t=new et;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 Ht({left:this.left,right:this.right,top:this.top,bottom:this.bottom})}get size(){return new fi(this.width,this.height)}set size(t){this.width=t.width,this.height=t.height}static creatRectangleWithSize(t,e){let i=t.width/2,r=e.x-i,s=e.x+i,o=t.height/2,a=e.y-o,l=e.y+o;return new Ht({left:r,right:s,top:l,bottom:a})}addPointWithSize(t,e){let i=t.width/2,r=t.height/2;this.addCoords(e.x-i,e.y-r),this.addCoords(e.x+i,e.y-r),this.addCoords(e.x-i,e.y+r),this.addCoords(e.x+i,e.y+r)}},Rf=ct(ti(),1),mt=class{constructor(n,t){this.x=n,this.y=t}get source(){return this.x}get target(){return this.y}isDiagonal(){return this.x===this.y}},Jr=class{isEmpty(){if(this.arrayOfMaps.length===0)return!0;for(let n of this.arrayOfMaps)if(n.size>0)return!1;return!0}set(n,t,e){let i=this.arrayOfMaps[n];i===void 0&&(this.arrayOfMaps[n]=i=new Map),i.set(t,e)}setPair(n,t){this.set(n.x,n.y,t)}delete(n,t){if(n<0||n>=this.arrayOfMaps.length)return;let e=this.arrayOfMaps[n];e!==void 0&&(e.delete(t),e.size===0&&(this.arrayOfMaps[n]=void 0))}has(n,t){if(n<0||n>=this.arrayOfMaps.length)return!1;let e=this.arrayOfMaps[n];return e===void 0?!1:e.has(t)}get(n,t){if(n<0||n>=this.arrayOfMaps.length)return null;let e=this.arrayOfMaps[n];return e===void 0?null:e.get(t)}getI(n){return this.get(n.x,n.y)}constructor(){this.arrayOfMaps=new Array}*keys(){for(let n=0;n<this.arrayOfMaps.length;n++){let t=this.arrayOfMaps[n];if(t!==void 0)for(let e of t)yield new mt(n,e[0])}}*keyValues(){for(let n=0;n<this.arrayOfMaps.length;n++){let t=this.arrayOfMaps[n];if(t!==void 0)for(let e of t)yield[new mt(n,e[0]),e[1]]}}*values(){for(let n=0;n<this.arrayOfMaps.length;n++){let t=this.arrayOfMaps[n];if(t!==void 0)for(let e of t)yield e[1]}}get size(){let n=0;for(let t=0;t<this.arrayOfMaps.length;t++){let e=this.arrayOfMaps[t];e!==void 0&&(n+=e.size)}return n}},Ff=class{constructor(n,t){this.v=n,this.i=t}},zn=class ma{static getFeedbackSetWithConstraints(t,e){throw new Error("Method not implemented.")}static push(t,e,i,r){e[i]=1,t.push(new Ff(i,r))}static getFeedbackSet(t){let e=new Jr;if(t==null||t.nodeCount===0)return[];let i=new Array(t.nodeCount).fill(0);for(let r=0;r<t.nodeCount;r++){if(i[r]===2)continue;let s=new Rf.Stack,o=0;for(ma.push(s,i,r,o);s.size>0;){let a=s.pop();r=a.v,i[r]=2,o=a.i;let l=t.outEdges[r];for(;o<l.length;o++){let h=l[o];if(h.source===h.target)continue;let u=i[h.target];u===1?e.set(h.source,h.target,h):u===0&&(ma.push(s,i,r,o+1),r=h.target,i[h.target]=2,l=t.outEdges[r],o=-1)}}}return Array.from(e.values())}},Nf=ct(bi(),1);function Ks(n){let t=new Ar;return t.SetEdges(n,Ar.vertexCount(n)),t}function vu(n){let t=new Ar;return t.SetEdges(n,Ar.vertexCount(n)),t}function yi(n,t){let e=new Ar;return e.SetEdges(n,t),e}var Ar=class zi{constructor(){this.nodeCount=0}*incidentEdges(t){for(let e of this.outEdges[t])yield e;for(let e of this.inEdges[t])yield e}static deleteFromArray(t,e){let i=t.indexOf(e,0);i>-1&&t.splice(i,1)}removeEdge(t){zi.deleteFromArray(this.edges,t),t.source!==t.target?(zi.deleteFromArray(this.outEdges[t.source],t),zi.deleteFromArray(this.inEdges[t.target],t)):zi.deleteFromArray(this.selfEdges[t.source],t)}static vertexCount(t){let e=0;for(let 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;let i=new Array(this.nodeCount).fill(0),r=new Array(this.nodeCount).fill(0),s=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(let o of this.edges)o.source!==o.target?(i[o.source]++,r[o.target]++):s[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(r[o]),r[o]=0,this.selfEdges[o]=new Array(s[o]),s[o]=0;for(let o of this.edges){let a=o.source,l=o.target;a!==l?(this.outEdges[a][i[a]++]=o,this.inEdges[l][r[l]++]=o):this.selfEdges[a][s[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;let t=new Set,e=new Nf.Queue,i=this.edges[0].source;for(zi.enqueue(t,e,i),yield i;e.length>0;){i=e.dequeue();for(let r of this.outEdges[i]){let s=r.target;t.has(s)||(zi.enqueue(t,e,s),yield s)}for(let r of this.inEdges[i]){let s=r.source;t.has(s)||(zi.enqueue(t,e,s),yield s)}}}*pred(t){for(let e of this.inEdges[t])yield e.source}*succ(t){for(let e of this.outEdges[t])yield e.target}static enqueue(t,e,i){e.enqueue(i),t.add(i)}},Zi=class{constructor(){this.isEmpty=!0}AddValue(n){this.isEmpty?(this.max=n,this.min=n,this.isEmpty=!1):n<this.min?this.min=n:n>this.max&&(this.max=n)}get length(){return this.max-this.min}static sign(n){return n>x.distanceEpsilon?1:n<-x.distanceEpsilon?-1:0}},Pe=class{constructor(n,t){Ns(n,t)<0?(this._first=n,this._second=t):(this._first=t,this._second=n)}get first(){return this._first}get second(){return this._second}get Length(){return ht(this._first,this._second)}CompareTo(n){let t=Ns(this._first,n._first);return t!==0?t:Ns(this._second,n._second)}static equal(n,t){return n._first.equal(t._first)&&n._second.equal(t._second)}toString(){return this._first+(" "+this._second)}},Zt=class xu{constructor(){this.size_=0,this.mapOfSets=new Map}delete(t){return this.deletexy(t.x,t.y)}clear(){this.mapOfSets.clear(),this.size_=0}get size(){return this.size_}static mk(t){let e=new xu;for(let 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){let 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)}forEach(t,e){for(let i of this)t(i,i,e)}*entries(){for(let t of this)yield[t,t]}keys(){return this.values()}*values(){for(let t of this.mapOfSets)for(let e of t[1])yield new g(t[0],e)}[Symbol.iterator](){return this.values()}};function Zr(n,t){let e=new Set;for(let i of n)t.has(i)||e.add(i);return e}function Gf(n,t){let e=new Zt;for(let i of n)t.has(i)||e.add(i);return e}function ir(n,t){let e=new Set(n);for(let i of t)e.add(i);return e}function Yi(n,t){for(let e of t)n.push(e)}function Ri(n,t){let e=new Set;if(n.size<t.size)for(let i of n)t.has(i)&&e.add(i);else for(let i of t)n.has(i)&&e.add(i);return e}function Df(n){if(n.length===0)return new Set;let t=n[0];for(let e=1;e<n.length;e++)t=Ri(t,n[e]);return t}function Li(n,t){for(let e of t)n.add(e)}function qn(n,t){if(n.size!==t.size)return!1;for(let e of n)if(!t.has(e))return!1;return!0}function Xn(n,t){let e=[];for(let i of n)for(let r of t(i))e.push(r);return e}function _s(n,t,e){let i=n.get(t);i||(i=new Set,n.set(t,i)),i.add(e)}function Dr(n,t,e){let i=n.get(t);i||(i=new Array,n.set(t,i)),i.push(e)}function Eu(n,t,e){let i=n.get(t);i||(i=new Set,n.set(t,i)),i.add(e)}function Mf(n,t,e){Eu(n,new Pe(t[0],t[1]),e)}function Vf(n,t,e){let i=n.get(t);i&&i.delete(e)}function Sh(n,t,e){Vf(n,new Pe(t[0],t[1]),e)}var bh=ct(ti(),1),kf=ct(se(),1),$f=ct(se(),1),Pa=class Au{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,r){let s=new Au(t);return s.Left=t,s.Right=e,s.Gap=i,s.IsEquality=r,s.Lagrangian=0,s.IsActive=!1,s}constructor(t){this.Right=t,this.Left=t}ToString(){return $f.String.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=Mt(this.Gap,t.Gap)),e}},Hf=ct(se(),1),Ko=class wu{static constructorDCVV(t,e,i,r){let s=new wu(e);return s.Set(t,e,i,r),s}constructor(t){this.ConstraintToEval=t,this.Depth=-1}Set(t,e,i,r){return this.Parent=t,this.ConstraintToEval=e,this.VariableToEval=i,this.VariableDoneEval=r,this.Depth=0,this.ChildrenHaveBeenPushed=!1,e.Lagrangian=0,this}get IsLeftToRight(){return this.VariableToEval===this.ConstraintToEval.Right}toString(){return Hf.String.format("{0} {1}{2} - {3}{4} ({5})","",this.IsLeftToRight?"":"*",this.ConstraintToEval.Left.Name,this.IsLeftToRight?"*":"",this.ConstraintToEval.Right.Name,this.Depth)}},Wf=class{constructor(n,t){this.Constraint=n,this.IsForward=t}},Ch=class Iu{constructor(t,e){this.Variables=new Array,t!=null&&this.AddVariable(t),this.allConstraints=e}toString(){return kf.String.format("[Block: nvars = {0} refpos = {1:F5} scale = {2:F5}]",this.Variables.length,this.ReferencePos,this.Scale)}ComputeDfDv(t){this.allConstraints.DfDvStack=new bh.Stack;let e=new Pa(t);this.dfDvDummyParentNode=new Ko(e);let i=this.GetDfDvNode(this.dfDvDummyParentNode,e,t,null);for(this.allConstraints.DfDvStack.push(i);;){let r=this.allConstraints.DfDvStack.top,s=this.allConstraints.DfDvStack.length;if(!r.ChildrenHaveBeenPushed){r.ChildrenHaveBeenPushed=!0;for(let o of r.VariableToEval.LeftConstraints)if(o.IsActive&&o.Right!==r.VariableDoneEval){let a=this.GetDfDvNode(r,o,o.Right,r.VariableToEval);o.Right.ActiveConstraintCount===1?this.ProcessDfDvLeafNodeDirectly(a):this.PushDfDvNode(a)}for(let o of r.VariableToEval.RightConstraints)if(o.IsActive&&o.Left!==r.VariableDoneEval){let a=this.GetDfDvNode(r,o,o.Left,r.VariableToEval);o.Left.ActiveConstraintCount===1?this.ProcessDfDvLeafNodeDirectly(a):this.PushDfDvNode(a)}if(this.allConstraints.DfDvStack.length>s)continue}if(this.allConstraints.DfDvStack.pop(),this.ProcessDfDvLeafNode(r),r===i)break}}ProcessDfDvLeafNode(t){let 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,r){let s=this.allConstraints.DfDvRecycleStack.size>0?this.allConstraints.DfDvRecycleStack.pop().Set(t,e,i,r):Ko.constructorDCVV(t,e,i,r);return s.Depth=s.Parent.Depth+1,this.allConstraints.MaxConstraintTreeDepth<s.Depth&&(this.allConstraints.MaxConstraintTreeDepth=s.Depth),s}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 Wf(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(let 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}let i=new Array;this.GetConnectedVariables(i,t.Right,t.Left);let r=t.Violation,s=i.length;for(let o=0;o<s;o++)i[o].OffsetInBlock=i[o].OffsetInBlock+r;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,r=this.Variables.length;for(let s=0;s<r;s++)for(let o of this.Variables[s].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 Iu(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;let t=this.Variables.length;for(let e=0;e<t;e++)this.AddVariableToBlockSums(this.Variables[e]);this.UpdateReferencePosFromSums()}AddVariableToBlockSums(t){let e=this.Scale/t.Scale,i=t.OffsetInBlock/t.Scale,r=e*t.Weight;this.sumAd+=r*t.DesiredPos,this.sumAb+=r*i,this.sumA2+=r*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(){let t=this.Scale*this.ReferencePos,e=this.Variables.length;for(let i=0;i<e;i++){let r=this.Variables[i];r.ActualPos=(t+r.OffsetInBlock)/r.Scale}}GetConnectedVariables(t,e,i){this.RecurseGetConnectedVariables(t,e,i)}RecurseGetConnectedVariables(t,e,i){this.allConstraints.DfDvStack=new bh.Stack;let r=new Pa(e);for(this.dfDvDummyParentNode=new Ko(r),this.allConstraints.DfDvStack.push(this.GetDfDvNode(this.dfDvDummyParentNode,r,e,i)),t.push(e);this.allConstraints.DfDvStack.length>0;){let s=this.allConstraints.DfDvStack.top,o=this.allConstraints.DfDvStack.length;if(!s.ChildrenHaveBeenPushed){s.ChildrenHaveBeenPushed=!0;for(let a of s.VariableToEval.LeftConstraints)a.IsActive&&a.Right!==s.VariableDoneEval&&(a.Right.ActiveConstraintCount===1?t.push(a.Right):this.AddVariableAndPushDfDvNode(t,this.GetDfDvNode(s,a,a.Right,s.VariableToEval)));for(let a of s.VariableToEval.RightConstraints)a.IsActive&&a.Left!==s.VariableDoneEval&&(a.Left.ActiveConstraintCount===1?t.push(a.Left):this.AddVariableAndPushDfDvNode(t,this.GetDfDvNode(s,a,a.Left,s.VariableToEval)))}this.allConstraints.DfDvStack.length>o||this.allConstraints.RecycleDfDvNode(this.allConstraints.DfDvStack.pop())}}TransferConnectedVariables(t,e,i){this.GetConnectedVariables(t.Variables,e,i);let r=t.Variables.length;for(let o=0;o<r;o++)t.Variables[o].Block=t;let s=this.Variables.length-1;for(let o=this.Variables.length-1;o>=0;o--)this.Variables[o].Block===t&&(o<s&&(this.Variables[o]=this.Variables[s]),s--);if(this.Variables=this.Variables.slice(0,s+1),this.Variables.length===0){for(let o=0;o<r;o++){let a=t.Variables[o];this.Variables.push(a),a.Block=this}t.Variables=[]}}},zf=class{get Count(){return this.Vector.length}item(n){return this.Vector[n]}constructor(){this.Vector=new Array}Add(n){n.VectorIndex=this.Vector.length,this.Vector.push(n)}Remove(n){let t=this.Vector[this.Vector.length-1];this.Vector[n.VectorIndex]=t,t.VectorIndex=n.VectorIndex,this.Vector.pop()}toString(){return this.Vector.toString()}},vh=ct(ti(),1),qf=class{constructor(){this.nextConstraintIndex=0,this.DfDvStack=new vh.Stack,this.DfDvRecycleStack=new vh.Stack}get IsEmpty(){return this.Vector==null}Create(n){this.Vector=new Array(n),this.firstActiveConstraintIndex=n}Add(n){n.SetVectorIndex(this.nextConstraintIndex),this.Vector[this.nextConstraintIndex++]=n}ActivateConstraint(n){this.firstActiveConstraintIndex--,this.SwapConstraint(n)}DeactivateConstraint(n){this.SwapConstraint(n),this.firstActiveConstraintIndex++}SwapConstraint(n){let t=this.Vector[this.firstActiveConstraintIndex];t.SetVectorIndex(n.VectorIndex),this.Vector[n.VectorIndex]=t,this.Vector[this.firstActiveConstraintIndex]=n,n.SetActiveState(!n.IsActive,this.firstActiveConstraintIndex)}Reinitialize(){if(this.Vector!=null){for(let n of this.Vector)n.Reinitialize();this.firstActiveConstraintIndex=this.Vector.length}}RecycleDfDvNode(n){this.DfDvRecycleStack.length<1024&&this.DfDvRecycleStack.push(n)}toString(){return this.Vector.toString()}},Uf=class Tu{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 jf}Clone(){let t=this.MemberwiseClone();return t.Advanced=this.Advanced.Clone(),t}MemberwiseClone(){let t=new Tu;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}},jf=class Ou{constructor(){this.ForceQpsc=!1,this.ScaleInQpsc=!0,this.MinSplitLagrangianThreshold=-1e-7,this.UseViolationCache=!0,this.ViolationCacheMinBlocksDivisor=10,this.ViolationCacheMinBlocksCount=100}Clone(){let t=new Ou;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}},Qf=class{constructor(n){this.Variable=n,this.OrigWeight=n.Weight,this.OrigScale=n.Scale,this.OrigDesiredPos=this.Variable.DesiredPos}},Xf=class{constructor(n,t){this.Value=n,this.Column=t}},Yf=class Ge{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(let 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 Xf(this.vectorPrevY[e]*2,e)),this.vectorPrevY[e]=0);this.matrixQ[t.Ordinal]=Array.from(this.newMatrixRow),this.newMatrixRow=[],this.vectorQpscVars[t.Ordinal]=new Qf(t),t.Weight=1}VariablesComplete(){for(let t of this.vectorQpscVars){let e=t.Variable;for(let 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++){let 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(let r of this.vectorQpscVars)this.vectorCurY[r.Variable.Ordinal]=r.Variable.ActualPos;if(this.MatrixVectorMultiply(this.vectorCurY,this.gradientVector),this.HasConverged())return!1;Ge.VectorVectorAdd(this.gradientVector,this.vectorWiDi,this.gradientVector);let t=Ge.VectorVectorMultiply(this.gradientVector,this.gradientVector),e=0;if(t!==0&&(this.MatrixVectorMultiply(this.gradientVector,this.vectorQg),e=Ge.VectorVectorMultiply(this.vectorQg,this.gradientVector)),e===0)return!1;let i=t/e;Ge.VectorCopy(this.vectorPrevY,this.vectorCurY),Ge.VectorScaledVectorSubtract(this.vectorPrevY,i,this.gradientVector,this.vectorCurY);for(let r=0;r<this.vectorCurY.length;r++)this.vectorQpscVars[r].Variable.DesiredPos=this.vectorCurY[r];return!0}PostProject(){for(let i of this.vectorQpscVars)this.vectorCurY[i.Variable.Ordinal]=i.Variable.ActualPos;Ge.VectorVectorSubtract(this.vectorPrevY,this.vectorCurY,this.vectorCurY);let t=Ge.VectorVectorMultiply(this.gradientVector,this.vectorCurY),e=0;if(t!==0){this.MatrixVectorMultiply(this.vectorCurY,this.vectorQg);let i=Ge.VectorVectorMultiply(this.vectorQg,this.vectorCurY);e=i===0?1:t/i,e>1?e=1:e<0&&(e=0)}return Ge.VectorScaledVectorSubtract(this.vectorPrevY,e,this.vectorCurY,this.vectorCurY),this.isFirstProjectCall=!1,e>0}QpscComplete(){for(let 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(){let t=this.GetFunctionValue(this.vectorCurY),e=!1;if(!this.isFirstProjectCall){let i=this.previousFunctionValue-t,r=0;if(i!==0){let s=this.previousFunctionValue!==0?this.previousFunctionValue:t;r=Math.abs(i/s)}(Math.abs(i)<this.solverParameters.QpscConvergenceEpsilon||Math.abs(r)<this.solverParameters.QpscConvergenceQuotient)&&(e=!0)}return this.previousFunctionValue=t,e}GetFunctionValue(t){return Ge.VectorVectorMultiply(this.gradientVector,t)/2+Ge.VectorVectorMultiply(this.vectorWiDi,t)}static VectorVectorMultiply(t,e){let i=0;for(let r=0;r<t.length;r++)i=i+t[r]*e[r];return i}MatrixVectorMultiply(t,e){let i=0;for(let r of this.matrixQ){let s=0;for(let o of r)s=s+o.Value*t[o.Column];e[i++]=s}}static VectorVectorAdd(t,e,i){for(let r=0;r<t.length;r++)i[r]=t[r]+e[r]}static VectorVectorSubtract(t,e,i){for(let r=0;r<t.length;r++)i[r]=t[r]-e[r]}static VectorScaledVectorSubtract(t,e,i,r){for(let s=0;s<t.length;s++)r[s]=t[s]-e*i[s]}static VectorCopy(t,e){for(let i=0;i<e.length;i++)t[i]=e[i]}},xh=class Lu{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(){let t=new Lu;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}},Jf=ct(se(),1),Zf=class{constructor(n,t){this.Neighbor=n,this.Weight=t}},Kf=class{constructor(n,t,e,i,r){if(this.ActiveConstraintCount=0,i<=0)throw new Error("weight");if(r<=0)throw new Error("scale");let s=e*i;if(!Number.isFinite(s)||Number.isNaN(s))throw new Error("desiredPos");if(s=e*r,!Number.isFinite(s)||Number.isNaN(s))throw new Error("desiredPos");this.Ordinal=n,this.UserData=t,this.DesiredPos=e,this.Weight=i,this.Scale=r,this.OffsetInBlock=0,this.ActualPos=this.DesiredPos}get DfDv(){return 2*(this.Weight*(this.ActualPos-this.DesiredPos))/this.Scale}Reinitialize(){this.ActiveConstraintCount=0,this.OffsetInBlock=0,this.ActualPos=this.DesiredPos}AddNeighbor(n,t){this.Neighbors==null&&(this.Neighbors=new Array),this.Neighbors.push(new Zf(n,t))}toString(){return Jf.String.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(n,t){this.LeftConstraints=n,this.RightConstraints=t}CompareTo(n){return Mt(this.Ordinal,n.Ordinal)}},_f=class ya{static{this.MaxConstraints=20}get IsFull(){return this.numConstraints===ya.MaxConstraints}Clear(){this.LowViolation=0,this.numConstraints=0,this.constraints||(this.constraints=new Array(ya.MaxConstraints))}FilterBlock(t){this.LowViolation=Number.MAX_VALUE;let e=this.numConstraints>0;for(let i=this.numConstraints-1;i>=0;i--){let r=this.constraints[i];if(r.Left.Block===t||r.Right.Block===t||r.IsActive||r.IsUnsatisfiable)i<this.numConstraints-1&&(this.constraints[i]=this.constraints[this.numConstraints-1]),this.numConstraints--;else{let s=r.Left.ActualPos*r.Left.Scale+(r.Gap-r.Right.ActualPos*r.Right.Scale);s<this.LowViolation&&(this.LowViolation=s)}}return this.numConstraints===0&&(this.LowViolation=0),e}FindIfGreater(t){let e=null;for(let i=0;i<this.numConstraints;i++){let r=this.constraints[i],s=r.Left.ActualPos*r.Left.Scale+(r.Gap-r.Right.ActualPos*r.Right.Scale);s>t&&(t=s,e=r)}return e}Insert(t,e){let i=0,r=e,s=e;for(let o=0;o<this.numConstraints;o++){let a=this.constraints[o],l=a.Left.ActualPos*a.Left.Scale+(a.Gap-a.Right.ActualPos*a.Right.Scale);l<r?(s=r,i=o,r=l):l<s&&(s=l)}this.IsFull?(this.constraints[i]=t,this.LowViolation=s):(this.constraints[this.numConstraints++]=t,this.IsFull&&(this.LowViolation=r))}},Eh=class{constructor(n,t){this.NumberOfLeftConstraints=0,this.Constraints=n,this.NumberOfLeftConstraints=t}},tm=class{constructor(){this.allBlocks=new zf,this.allConstraints=new qf,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 _f,this.violationCacheMinBlockCutoff=0,this.nextVariableOrdinal=0,this.solverParams=new Uf,this.solverSolution=new xh}get IsQpsc(){return this.hasNeighbourPairs||this.solverParams.Advanced.ForceQpsc}AddVariableAN(n,t){return this.AddVariableANNN(n,t,1,1)}AddVariableANN(n,t,e){return this.AddVariableANNN(n,t,e,1)}AddVariableANNN(n,t,e,i){if(!this.allConstraints.IsEmpty)throw new Error("Cannot add Variables or Constraints once Solve() has been called");let r=new Kf(this.nextVariableOrdinal++,n,t,e,i),s=new Ch(r,this.allConstraints);return r.Block=s,this.allBlocks.Add(s),this.numberOfVariables++,this.loadedVariablesAndConstraintLists.set(r,new Eh(new Array,0)),r}UpdateVariables(){for(let n of this.allBlocks.Vector)n.UpdateReferencePos()}get Variables(){return Xn(this.allBlocks.Vector,n=>n.Variables)}get VariableCount(){return this.numberOfVariables}*Constraints(){if(this.allConstraints.IsEmpty)for(let n of this.loadedVariablesAndConstraintLists.keys()){let t=this.loadedVariablesAndConstraintLists.get(n);if(t.Constraints!=null){let e=t.Constraints.length;for(let i=0;i<e;i++){let r=t.Constraints[i];if(n===r.Left)return yield,r}}}else for(let n of this.allConstraints.Vector)yield n}get ConstraintCount(){return this.numberOfConstraints}AddEqualityConstraint(n,t,e){return this.AddConstraintVVNB(n,t,e,!0)}AddConstraintVVNB(n,t,e,i){if(!this.allConstraints.IsEmpty)throw new Error("Cannot add Variables or Constraints once Solve() has been called");if(n===t)throw new Error("Cannot add a constraint between a variable and itself");let r=this.loadedVariablesAndConstraintLists.get(n),s=this.loadedVariablesAndConstraintLists.get(t),o=Pa.constructorVVNB(n,t,e,i);return this.loadedVariablesAndConstraintLists.set(n,new Eh(r.Constraints,r.NumberOfLeftConstraints+1)),r.Constraints.push(o),s.Constraints.push(o),this.numberOfConstraints++,i&&this.equalityConstraints.push(o),o}AddConstraint(n,t,e){return this.AddConstraintVVNB(n,t,e,!1)}SetConstraintUpdate(n,t){t!==n.Gap&&this.updatedConstraints.push([n,t])}AddNeighborPair(n,t,e){if(e<=0||Number.isNaN(e)||!Number.isFinite(e))throw new Error("relationshipWeight");if(n===t)throw new Error;n.AddNeighbor(t,e),t.AddNeighbor(n,e),this.hasNeighbourPairs=!0}Solve(){return this.SolvePar(null)}SolvePar(n){n&&(this.solverParams=n.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));let t=!this.allConstraints.IsEmpty;if(this.CheckForUpdatedConstraints(),this.solverSolution=new xh,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 t||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 n=this.IsQpsc;for(let[t,e]of this.updatedConstraints){let i=t;if(i.UpdateGap(e),!n&&!i.IsEquality){this.SplitOnConstraintIfActive(i);continue}n=!0}this.updatedConstraints=[],n&&this.ReinitializeBlocks()}SplitOnConstraintIfActive(n){if(n.IsActive){let t=n.Left.Block.SplitOnConstraint(n);t!=null&&this.allBlocks.Add(t)}}SetupConstraints(){this.allConstraints.Create(this.numberOfConstraints);for(let n of this.loadedVariablesAndConstraintLists.keys()){let t=this.loadedVariablesAndConstraintLists.get(n),e=t.Constraints,i=0,r=0,s=0;e!=null&&(i=e.length,r=t.NumberOfLeftConstraints,s=i-r);let o=this.emptyConstraintList;r!==0&&(o=new Array(r));let a=this.emptyConstraintList;s!==0&&(a=new Array(s)),n.SetConstraints(o,a);let l=0,h=0;for(let u=0;u<i;u++){let d=e[u];n===d.Left?o[l++]=d:a[h++]=d}for(let u of n.LeftConstraints)this.allConstraints.Add(u)}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;let n=this.allBlocks.Count;for(let t=0;t<n;t++){let e=this.allBlocks.item(t),i=e.Variables.length;for(let r=0;r<i;r++){let s=e.Variables[r];this.solverSolution.GoalFunctionValue+=s.Weight*(s.ActualPos*s.ActualPos),this.solverSolution.GoalFunctionValue-=2*(s.Weight*(s.DesiredPos*s.ActualPos))}}}SolveQpsc(){if(this.solverSolution.AlgorithmUsed=this.solverParams.Advanced.ScaleInQpsc?1:2,!this.QpscMakeFeasible())return;let n=new Yf(this.solverParams,this.numberOfVariables);for(let e of this.allBlocks.Vector)for(let i of e.Variables)n.AddVariable(i);n.VariablesComplete(),this.ReinitializeBlocks(),this.MergeEqualityConstraints();let t=!1;for(;!(!n.PreProject()&&!t||(t=this.SplitBlocks(),!this.RunProject())||!n.PostProject()&&!t););this.solverSolution.GoalFunctionValue=n.QpscComplete()}QpscMakeFeasible(){return this.RunProject()}ReinitializeBlocks(){let n=Array.from(this.allBlocks.Vector);this.allBlocks.Vector=[];for(let t of n)for(let e of t.Variables){e.Reinitialize();let i=new Ch(e,this.allConstraints);this.allBlocks.Add(i)}this.allConstraints.Reinitialize(),this.violationCache.Clear()}MergeEqualityConstraints(){for(let n of this.equalityConstraints){if(n.Left.Block===n.Right.Block){Math.abs(n.Violation)>this.solverParams.GapTolerance&&(n.IsUnsatisfiable=!0,this.allConstraints.NumberOfUnsatisfiableConstraints++);continue}this.MergeBlocks(n)}}Project(){if(this.numberOfConstraints===0)return!1;this.violationCache.Clear(),this.lastModifiedBlock=null;let n=this.allBlocks.Count>this.violationCacheMinBlockCutoff,t=1,e={maxViolation:0},i=this.GetMaxViolatedConstraint(e,n);if(!i)return!1;for(;i;){if(i.Left.Block===i.Right.Block?(i.Left.Block.Expand(i),i.IsUnsatisfiable&&this.violationCache.Clear(),this.lastModifiedBlock=i.Left.Block):this.lastModifiedBlock=this.MergeBlocks(i),this.solverParams.InnerProjectIterationsLimit>0&&t>=this.solverParams.InnerProjectIterationsLimit){this.solverSolution.InnerProjectIterationsLimitExceeded=!0;break}n=this.allBlocks.Count>this.violationCacheMinBlockCutoff,n||this.violationCache.Clear(),t++;let r={maxViolation:0};i=this.GetMaxViolatedConstraint(r,n)}return this.solverSolution.InnerProjectIterationsTotal=this.solverSolution.InnerProjectIterationsTotal+t,this.solverSolution.MaxInnerProjectIterations<t&&(this.solverSolution.MaxInnerProjectIterations=t),this.solverSolution.MinInnerProjectIterations>t&&(this.solverSolution.MinInnerProjectIterations=t),!0}MergeBlocks(n){let t=n.Left.Block,e=n.Right.Block,i=n.Left.OffsetInBlock+(n.Gap-n.Right.OffsetInBlock);e.Variables.length>t.Variables.length&&(t=n.Right.Block,e=n.Left.Block,i=-i);let r=e.Variables.length;for(let s=0;s<r;s++){let o=e.Variables[s];o.OffsetInBlock+=i,t.AddVariable(o)}return t.UpdateReferencePosFromSums(),this.allConstraints.ActivateConstraint(n),this.allBlocks.Remove(e),t}SplitBlocks(){let n=new Array,t=this.allBlocks.Count;for(let i=0;i<t;i++){let r=this.allBlocks.item(i).Split(this.IsQpsc);r!=null&&n.push(r)}let e=n.length;for(let i=0;i<e;i++){let r=n[i];this.allBlocks.Add(r)}return n.length!==0}GetMaxViolatedConstraint(n,t){return n.maxViolation=this.solverParams.GapTolerance,this.SearchViolationCache(n.maxViolation)??this.SearchAllConstraints(n.maxViolation,t)}SearchViolationCache(n){let t=null;if(this.lastModifiedBlock==null)return;this.lastModifiedBlock.Variables.length<this.numberOfVariables+1&&this.violationCache.FilterBlock(this.lastModifiedBlock);let e=this.lastModifiedBlock.Variables.length;for(let r=0;r<e;r++){let s=this.lastModifiedBlock.Variables[r];for(let o of s.LeftConstraints)if(!o.IsActive&&!o.IsUnsatisfiable){let a=o.Left.ActualPos*o.Left.Scale+(o.Gap-o.Right.ActualPos*o.Right.Scale);Zo(a,n)&&(t!=null&&n>this.violationCache.LowViolation&&this.violationCache.Insert(t,n),n=o.Violation,t=o)}for(let o of s.RightConstraints)if(!o.IsActive&&!o.IsUnsatisfiable&&o.Left.Block!==this.lastModifiedBlock){let a=o.Left.ActualPos*o.Left.Scale+(o.Gap-o.Right.ActualPos*o.Right.Scale);Zo(a,n)&&(t!=null&&n>this.violationCache.LowViolation&&this.violationCache.Insert(t,n),n=a,t=o)}}let i=this.violationCache.FindIfGreater(n);return i!=null&&(t!=null&&n>this.violationCache.LowViolation&&this.violationCache.Insert(t,n),t=i),t}SearchAllConstraints(n,t){let e=null;this.violationCache.Clear();for(let i of this.allConstraints.Vector){if(i.IsActive)break;if(i.IsUnsatisfiable)continue;let r=i.Left.ActualPos*i.Left.Scale+(i.Gap-i.Right.ActualPos*i.Right.Scale),s=null,o=0;Zo(r,n)&&(n>this.violationCache.LowViolation&&(s=e,o=n),n=r,e=i),t&&(s==null&&i!==e&&(!this.violationCache.IsFull||r>this.violationCache.LowViolation)&&(s=i,o=r),s!=null&&o>this.violationCache.LowViolation&&this.violationCache.Insert(s,o))}return e}},em=class Sa{constructor(){this.variables=new Map,this.fixedVars=new Map,this.FailToAdjustEpsilon=.001,this.InitSolver()}static{this.FixedVarWeight=1e9}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,r){let s=this.GetVariable(t);if(s==null)return;let o=this.GetVariable(e);o!=null&&this.solver.AddConstraintVVNB(s,o,i,r)}AddLeftRightSeparationConstraintNNN(t,e,i){this.AddLeftRightSeparationConstraintNNNB(t,e,i,!1)}AddGoalTwoVariablesAreCloseNNN(t,e,i){let r=this.GetVariable(t);if(r==null)return;let s=this.GetVariable(e);s!=null&&this.solver.AddNeighborPair(r,s,i)}AddGoalTwoVariablesAreClose(t,e){this.AddGoalTwoVariablesAreCloseNNN(t,e,1)}GetVariable(t){return this.variables.get(t)}Solve(){this.SolveP(null)}SolveP(t){let e={executionLimitExceeded:!1};this.SolvePNS(t,e)}SolvePNS(t,e){let i;do{this.solution=null;let r=null;if(t!=null&&(r=t,r==null))throw new Error("parameters");this.solution=this.solver.SolvePar(r),e.executionLimitExceeded=this.solution.ExecutionLimitExceeded,i=this.AdjustConstraintsForMovedFixedVars()}while(i&&this.solution.ExecutionLimitExceeded===!1);return this.solution.ExecutionLimitExceeded===!1}AdjustConstraintsForMovedFixedVars(){let t=new Set;for(let[e,i]of this.fixedVars.entries())Sa.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(let i of t){e=i;break}if(!this.AdjustSubtreeOfFixedVar(e,t))return!1}return!0}AdjustSubtreeOfFixedVar(t,e){let i={successInAdjusting:!1},r=this.AdjustConstraintsOfNeighborsOfFixedVariable(t,i);if(!i.successInAdjusting||r.length===0)return!1;for(let s of r)e.delete(s);return!0}AdjustConstraintsOfNeighborsOfFixedVariable(t,e){let i=this.variables.get(t).Block.Variables,r=new Zi,s=new Zi,o=1;for(let a of i)this.fixedVars.has(a.UserData)&&(r.AddValue(a.ActualPos),s.AddValue(a.DesiredPos),s.length>0&&(o=Math.max(o,r.length/s.length)));return o===1&&(o=2),e.successInAdjusting=this.FixActiveConstraints(i,o),i.map(a=>a.UserData)}FixActiveConstraints(t,e){let i=!1;for(let r of t)for(let s of r.LeftConstraints)s.IsActive&&(s.Gap>this.FailToAdjustEpsilon&&(i=!0),this.solver.SetConstraintUpdate(s,s.Gap/e));return i}GetVariableResolvedPosition(t){let e=this.GetVariable(t);return e==null?0:e.ActualPos}InitSolver(){this.solver=new tm,this.variables.clear()}AddFixedVariable(t,e){this.AddVariableWithIdealPositionNNN(t,e,Sa.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}},im=class{constructor(){this.lowBound=Number.NEGATIVE_INFINITY,this.upperBound=Number.POSITIVE_INFINITY}get Position(){return this.position}set Position(n){n<this.lowBound?this.position=this.lowBound:n>this.upperBound?this.position=this.upperBound:this.position=n}get LowBound(){return this.lowBound}set LowBound(n){this.lowBound=n}get UpperBound(){return this.upperBound}set UpperBound(n){this.upperBound=n}toString(){return this.lowBound+(" "+(this.Position+(" "+this.upperBound)))}},rm=class{constructor(n){this.idealPositions=new Map,this.varList=new Array,this.constraints=new Set,this.solverShell=new em,this.boundsToInt=new Map,this.varSepartion=n}SetLowBound(n,t){let e=this.Var(t);e.LowBound=Math.max(n,e.LowBound)}Var(n){return this.varList[n]}SetUpperBound(n,t){let e=this.Var(n);e.UpperBound=Math.min(t,e.UpperBound)}Solve(){this.SolveByRegularSolver()}SolveByRegularSolver(){this.CreateVariablesForBounds();for(let n=0;n<this.varList.length;n++){let t=this.varList[n];t.IsFixed?this.solverShell.AddFixedVariable(n,t.Position):(this.solverShell.AddVariableWithIdealPositionNN(n,this.idealPositions.get(n)),t.LowBound!==Number.NEGATIVE_INFINITY&&this.constraints.add(new mt(this.GetBoundId(t.LowBound),n)),t.UpperBound!==Number.POSITIVE_INFINITY&&this.constraints.add(new mt(n,this.GetBoundId(t.UpperBound))))}this.CreateGraphAndRemoveCycles();for(let n of this.graph.edges){let t=0;n.x<this.varList.length&&(t+=this.varList[n.x].Width),n.y<this.varList.length&&(t+=this.varList[n.y].Width),t/=2,this.solverShell.AddLeftRightSeparationConstraintNNN(n.x,n.y,this.varSepartion+t)}this.solverShell.Solve();for(let n=0;n<this.varList.length;n++)this.varList[n].Position=this.solverShell.GetVariableResolvedPosition(n)}GetBoundId(n){return this.boundsToInt.get(n)}CreateVariablesForBounds(){for(let n of this.varList)n.IsFixed||(n.LowBound!==Number.NEGATIVE_INFINITY&&this.RegisterBoundVar(n.LowBound),n.UpperBound!==Number.POSITIVE_INFINITY&&this.RegisterBoundVar(n.UpperBound))}RegisterBoundVar(n){if(!this.boundsToInt.has(n)){let t=this.varList.length+this.boundsToInt.size;this.boundsToInt.set(n,t),this.solverShell.AddFixedVariable(t,n)}}CreateGraphAndRemoveCycles(){this.graph=yi(Array.from(this.constraints),this.varList.length+this.boundsToInt.size);let n=zn.getFeedbackSet(this.graph);if(n!=null)for(let t of n)this.graph.removeEdge(t)}GetVariablePosition(n){return this.varList[n].Position}AddConstraint(n,t){this.constraints.add(new mt(n,t))}AddVariableNNNN(n,t,e,i){this.idealPositions.set(n,e),this.AddVariableNNBN(n,t,!1,i)}AddFixedVariable(n,t){this.AddVariableNNBN(n,t,!0,0)}AddVariableNNBN(n,t,e,i){let r=new im;r.Position=t,r.IsFixed=e,r.Width=i,this.varList.push(r)}},R=class be{static{this.differenceEpsilon=x.distanceEpsilon/2}static get DifferenceEpsilon(){return be.differenceEpsilon}static EqualPP(t,e){return be.Equal(t.x,e.x)&&be.Equal(t.y,e.y)}static Equal(t,e){return be.Compare(t,e)===0}static Compare(t,e){let i=0;return t+be.DifferenceEpsilon<e?i=-1:e+be.DifferenceEpsilon<t&&(i=1),i}static ComparePP(t,e){let i=be.Compare(t.x,e.x);return i===0&&(i=be.Compare(t.y,e.y)),i}static LessOrEqual(t,e){let i=be.Compare(t,e);return i<0||i===0}static Less(t,e){return be.Compare(t,e)<0}static GetDirections(t,e){return J.DirectionFromPointToPoint(t,e)}static IsPureDirection(t,e){return J.IsPureDirection(be.GetDirections(t,e))}static IsPureDirectionD(t){return J.IsPureDirection(t)}static IsPureLower(t,e){let i=be.GetDirections(t,e);return i===2||i===1}static GetPureDirectionVV(t,e){return be.GetDirections(t.point,e.point)}},J=class ai{constructor(t){this.Dir=t}get Right(){return new ai(ai.RotateRight(this.Dir))}static RotateRight(t){switch(t){case 1:return 2;case 2:return 4;case 4:return 8;case 8:return 1;default:throw new Error}}static RotateLeft(t){switch(t){case 1:return 8;case 8:return 4;case 4:return 2;case 2:return 1;default:throw new Error}}static ToIndex(t){switch(t){case 1:return 0;case 2:return 1;case 4:return 2;case 8:return 3;default:throw new Error}}static VectorDirection(t){let e=0;return t.x>R.DifferenceEpsilon?e=2:t.x<-R.DifferenceEpsilon&&(e=8),t.y>R.DifferenceEpsilon?e=e|1:t.y<-R.DifferenceEpsilon&&(e=e|4),e}static VectorDirectionPP(t,e){let i=0,r=e.x-t.x,s=e.y-t.y;return r>R.DifferenceEpsilon?i=2:-r>R.DifferenceEpsilon&&(i=8),s>R.DifferenceEpsilon?i|=1:-s>R.DifferenceEpsilon&&(i|=4),i}static DirectionFromPointToPoint(t,e){return ai.VectorDirectionPP(t,e)}static OppositeDir(t){switch(t){case 1:return 4;case 8:return 2;case 4:return 1;case 2:return 8;default:return 0}}static IsPureDirection(t){switch(t){case 1:return!0;case 2:return!0;case 4:return!0;case 8:return!0;default:return!1}}static IsPureDirectionPP(t,e){return ai.IsPureDirection(ai.DirectionFromPointToPoint(t,e))}static DirectionsAreParallel(t,e){return t===e||t===ai.OppositeDir(e)}ToPoint(){let t=0,e=0;return(this.Dir&2)===2&&t++,(this.Dir&1)===1&&e++,(this.Dir&8)===8&&t--,(this.Dir&4)===4&&e--,new g(t,e)}static toPoint(t){return new ai(t).ToPoint()}static negate(t){return new ai(ai.OppositeDir(t.Dir))}},It=class gr{clone(){let t=new gr;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,r,s,o,a=!1){let l=new gr;return l.transparency=t,l.width=e,l.color=i,l.icurve=r,l.label=s,l.dashArray=o,l.drawPN=a,l}static mkDebugCurveTWCI(t,e,i,r){return gr.mkDebugCurveTWCILD(t,e,i,r,null,null)}static mkDebugCurveWCI(t,e,i){return gr.mkDebugCurveTWCI(255,t,e,i)}static mkDebugCurveCI(t,e){return gr.mkDebugCurveWCI(1,t,e)}static mkDebugCurveI(t){return gr.mkDebugCurveCI("Black",t)}static{this.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"]}},nm=ct(bi(),1),_e=class{deleteP(n){return this.delete(n.x,n.y)}clear(){this.m.clear()}get size(){return this.m.size}setxy(n,t,e){this.m.set(xs(n,t),e)}set(n,t){this.setxy(n.x,n.y,t)}delete(n,t){return this.m.delete(xs(n,t))}hasxy(n,t){return this.m.has(xs(n,t))}has(n){return this.hasxy(n.x,n.y)}getxy(n,t){return this.m.get(xs(n,t))}get(n){return this.getxy(n.x,n.y)}constructor(){this.m=new Map}*keys(){for(let n of this.m.keys()){let t=n.split(",");yield new g(Number(t[0]),Number(t[1]))}}*[Symbol.iterator](){for(let[n,t]of this.m){let e=n.split(",");yield[new g(Number(e[0]),Number(e[1])),t]}}*values(){yield*this.m.values()}};function xs(n,t){return n.toString()+","+t.toString()}var sm=ct(se(),1),Kr=class Ln{static{this.u=new g(545.833,840.458)}static{this.v=new g(606.1667261889578,786.2917261889578)}static closeuv(t,e){return g.closeDistEps(t.point,Ln.u,.1)&&g.closeDistEps(e.point,Ln.v,.1)}constructor(t,e,i=1){this.Source=t,this.Target=e,this.Weight=i}static{this.DefaultWeight=1}get SourcePoint(){return this.Source.point}get TargetPoint(){return this.Target.point}get Length(){return this.SourcePoint.sub(this.TargetPoint).length}toString(){return sm.String.format("{0}->{1} ({2})",this.Source,this.Target,this.Weight)}ReversedClone(){return new Ln(this.Target,this.Source)}Clone(){return new Ln(this.Source,this.Target)}},_o=class{constructor(n,t,e,i,r){this.color=n,t!==void 0&&(this.item=t),e!==void 0&&(this.parent=e),i!==void 0&&(this.left=i),r!==void 0&&(this.right=r)}toString(){return this.item.toString()}},Re=class{[Symbol.iterator](){return this.allNodes()}constructor(n){this.comparer=n,this.count=0,this.root=this.nil=new _o(1)}clear(){this.root=this.nil=new _o(1)}toNull(n){return n!==this.nil?n:null}isEmpty(){return this.root===this.nil}getComparer(){return this.comparer}getRoot(){return this.root}find(n,t=this.root){let e;for(;t!==this.nil&&(e=this.comparer(n,t.item))!==0;)t=e<0?t.left:t.right;return this.toNull(t)}findFirst(n,t=this.root){if(t===this.nil)return null;let e=null;for(;t!==this.nil;)t=n(t.item)?(e=t).left:t.right;return e}findLast(n,t=this.root){if(t===this.nil)return null;let e=null;for(;t!==this.nil;)t=n(t.item)?(e=t).right:t.left;return e}treeMinimum(n=this.root){for(;n.left!==this.nil;)n=n.left;return this.toNull(n)}treeMaximum(n=this.root){for(;n.right!==this.nil;)n=n.right;return this.toNull(n)}next(n){if(n.right!==this.nil)return this.treeMinimum(n.right);let t=n.parent;for(;t!==this.nil&&n===t.right;)n=t,t=t.parent;return this.toNull(t)}previous(n){if(n.left!==this.nil)return this.treeMaximum(n.left);let t=n.parent;for(;t!==this.nil&&n===t.left;)n=t,t=t.parent;return this.toNull(t)}leftRotate(n){let t=n.right;n.right=t.left,t.left!==this.nil&&(t.left.parent=n),t.parent=n.parent,n.parent===this.nil?this.root=t:n===n.parent.left?n.parent.left=t:n.parent.right=t,t.left=n,n.parent=t}rightRotate(n){let t=n.left;n.left=t.right,t.right!==this.nil&&(t.right.parent=n),t.parent=n.parent,n.parent===this.nil?this.root=t:n===n.parent.right?n.parent.right=t:n.parent.left=t,t.right=n,n.parent=t}deleteFixup(n){for(;n!==this.root&&n.color===1;)if(n===n.parent.left){let t=n.parent.right;t.color===0&&(t.color=1,n.parent.color=0,this.leftRotate(n.parent),t=n.parent.right),t.left.color===1&&t.right.color===1?(t.color=0,n=n.parent):(t.right.color===1&&(t.left.color=1,t.color=0,this.rightRotate(t),t=n.parent.right),t.color=n.parent.color,n.parent.color=1,t.right.color=1,this.leftRotate(n.parent),n=this.root)}else{let t=n.parent.left;t.color===0&&(t.color=1,n.parent.color=0,this.rightRotate(n.parent),t=n.parent.left),t.right.color===1&&t.left.color===1?(t.color=0,n=n.parent):(t.left.color===1&&(t.right.color=1,t.color=0,this.leftRotate(t),t=n.parent.left),t.color=n.parent.color,n.parent.color=1,t.left.color=1,this.rightRotate(n.parent),n=this.root)}n.color=1}deleteSubTree(n){let t;if(n.left===this.nil||n.right===this.nil)t=n;else for(t=n.right;t.left!==this.nil;)t=t.left;let e=t.left!==this.nil?t.left:t.right;return e.parent=t.parent,t.parent===this.nil?this.root=e:t===t.parent.left?t.parent.left=e:t.parent.right=e,t!==n&&(n.item=t.item),t.color===1&&this.deleteFixup(e),this.toNull(n)}deleteNodeInternal(n){this.count--,this.deleteSubTree(n)}remove(n){let t=this.find(n);return t!=null?(this.count--,this.deleteSubTree(t)):null}insert(n){let t=this.treeInsert(n);return this.insertPrivate(t),this.toNull(t)}treeInsert(n){let t=this.nil,e=this.root,i=0;for(;e!==this.nil;)t=e,i=this.comparer(n,e.item),e=i<0?e.left:e.right;let r=new _o(1,n,t,this.nil,this.nil);return t===this.nil?this.root=r:i<0?t.left=r:t.right=r,this.toNull(r)}insertPrivate(n){for(this.count++,n.color=0;n!==this.root&&n.parent.color===0;)if(n.parent===n.parent.parent.left){let t=n.parent.parent.right;t.color===0?(n.parent.color=1,t.color=1,n.parent.parent.color=0,n=n.parent.parent):(n===n.parent.right&&(n=n.parent,this.leftRotate(n)),n.parent.color=1,n.parent.parent.color=0,this.rightRotate(n.parent.parent))}else{let t=n.parent.parent.left;t.color===0?(n.parent.color=1,t.color=1,n.parent.parent.color=0,n=n.parent.parent):(n===n.parent.left&&(n=n.parent,this.rightRotate(n)),n.parent.color=1,n.parent.parent.color=0,this.leftRotate(n.parent.parent))}this.root.color=1}*allNodes(){if(this.isEmpty())return;let n=this.treeMinimum();for(;n!=null;)yield n.item,n=this.next(n)}toString(){let n="{",t=0;for(let e of this.allNodes())n+=e.toString(),t!==this.count-1&&(n+=`
|
|
963
|
+
`),t++;return n+"}"}},Bu=class Gs{constructor(t){this._inEdges=new Array,this._outEdges=new Re((e,i)=>this.Compare(e,i)),this.point=t}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}toString(){return this.point.toString()}RemoveOutEdge(t){this.OutEdges.remove(t)}RemoveInEdge(t){let e=this._inEdges.indexOf(t);if(e===-1)return;let i=this._inEdges.length-1;e!==i&&(this._inEdges[e]=this._inEdges[i]),this._inEdges.pop()}static FindFirst(t,e){return Gs.FindFirst_t(t.root,t,e)}static FindFirst_t(t,e,i){if(t===e.nil)return null;let r=null;for(;t!==e.nil;)t=t.item.TargetPoint.compareTo(i)>=0?(r=t).left:t.right;return r}get(t){let e=Gs.FindFirst(this.OutEdges,t.point);return e!=null&&e.item.Target===t||(e=Gs.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=[]}},zt=class{constructor(){this.activeVertices=new Set,this.VertexFactory=n=>new Bu(n),this.pointToVertexMap=new _e}*edges_(){for(let n of this.pointToVertexMap.values())for(let t of n.OutEdges)yield t}get Edges(){return this.edges_()}ClearPrevEdgesTable(){for(let n of this.activeVertices)n.prevEdge=null;this.activeVertices.clear()}PreviosVertex(n){let t=n.prevEdge;return t?t.Source===n?t.Target:t.Source:null}SetPreviousEdge(n,t){this.activeVertices.add(n),n.prevEdge=t}AddHole(n){let t=n.startPoint;for(;t!==n.endPoint;)this.AddEdgePlPl(t,t.next),t=t.next;this.AddEdgePlPl(n.endPoint,n.startPoint)}static*OrientHolesClockwise(n){for(let t of n)for(let e=t.startPoint;;e=e.next){let i=g.getTriangleOrientation(e.point,e.next.point,e.next.next.point);if(i!==2){yield i===0?t:t.reverse();break}}}AddVertexP(n){let t=this.pointToVertexMap.get(n);if(t)return t;let e=this.VertexFactory(n);return this.pointToVertexMap.set(n,e),e}AddVertexV(n){this.pointToVertexMap.set(n.point,n)}ContainsVertex(n){return this.pointToVertexMap.has(n)}static AddEdgeVV(n,t){let e;if(e=n.get(t))return e;if(n===t)throw new Error("Self-edges are not allowed");let i=new Kr(n,t);return n.OutEdges.insert(i),t.InEdges.push(i),i}AddEdgePlPl(n,t){this.AddEdgePP(n.point,t.point)}static AddEdge(n){n.Source.OutEdges.insert(n),n.Target.addInEdge(n)}AddEdgeF(n,t,e){let i=this.FindVertex(n),r=null;if(i!=null&&(r=this.FindVertex(t),r!=null)){let o=i.get(r);if(o)return o}i==null?(i=this.AddVertexP(n),r=this.AddVertexP(t)):r==null&&(r=this.AddVertexP(t));let s=e(i,r);return i.OutEdges.insert(s),r.addInEdge(s),s}AddEdgePP(n,t){return this.AddEdgeF(n,t,(e,i)=>new Kr(e,i))}FindVertex(n){return this.pointToVertexMap.get(n)}Vertices(){return this.pointToVertexMap.values()}RemoveVertex(n){for(let t of n.OutEdges)t.Target.RemoveInEdge(t);for(let t of n.InEdges)t.Source.RemoveOutEdge(t);this.pointToVertexMap.deleteP(n.point)}FindEdgePP(n,t){let e=this.FindVertex(n);if(e==null)return null;let i=this.FindVertex(t);return i==null?null:e.get(i)}static RemoveEdge(n){n.Source.RemoveOutEdge(n),n.Target.RemoveInEdge(n)}ClearEdges(){for(let n of this.Vertices())n.ClearEdges()}},om=class extends Kr{constructor(n,t){super(n,t),this.RightNeighbors=new Set,this.setOfLongestSegs=new Set,this.RightBound=Number.POSITIVE_INFINITY,this.LeftBound=Number.NEGATIVE_INFINITY,this.Direction=J.DirectionFromPointToPoint(n.point,t.point)}AddRightNeighbor(n){this.RightNeighbors.add(n)}get LongestNudgedSegments(){return this.setOfLongestSegs}AddLongestNudgedSegment(n){this.setOfLongestSegs.add(n)}BoundFromRight(n){n=Math.max(n,this.LeftBound),this.RightBound=Math.min(n,this.RightBound)}BoundFromLeft(n){n=Math.min(n,this.RightBound),this.LeftBound=Math.max(n,this.LeftBound)}},wr=class Ru{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){let e=new Ru(t),i=this.Next;this.Next=e,e.Next=i}},Ah=class Fu{constructor(t,e){this.IsFixed=!1,this.Reversed=!1,this.index=-1,this.AxisEdge=t,this.Width=e}toString(){return this.Source+(" "+this.Target)}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 lt(t.x*e.y-t.y*e.x,0)}static EdgesAreParallel(t,e){return Fu.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}},am=class pe{constructor(t){this.pathVisibilityGraph=new zt,this.axisEdgesToPathOrders=new Map,this.OriginalPaths=t}static{this.NotOrdered=Number.MAX_VALUE}get PathVisibilityGraph(){return this.pathVisibilityGraph}GetOrder(){return this.FillTheVisibilityGraphByWalkingThePaths(),this.InitPathOrder(),this.OrderPaths(),this.axisEdgesToPathOrders}FillTheVisibilityGraphByWalkingThePaths(){for(let t of this.OriginalPaths)this.FillTheVisibilityGraphByWalkingPath(t)}FillTheVisibilityGraphByWalkingPath(t){let e=this.CreatePathEdgesFromPoints(r(),t.Width),i=e.next();for(i.done||t.SetFirstEdge(i.value);(i=e.next()).done===!1;)t.AddEdge(i.value);function*r(){if(t.PathPoints instanceof wr)for(let s=t.PathPoints;s!=null;s=s.Next)yield s.Point;else for(let s of t.PathPoints)yield s}}*CreatePathEdgesFromPoints(t,e){let i=t.next(),r=i.value;for(;!(i=t.next()).done;)yield this.CreatePathEdge(r,i.value,e),r=i.value}CreatePathEdge(t,e,i){switch(J.DirectionFromPointToPoint(t,e)){case 2:case 1:return new Ah(this.GetAxisEdge(t,e),i);case 4:case 8:{let r=new Ah(this.GetAxisEdge(e,t),i);return r.Reversed=!0,r}default:throw new Error("Not a rectilinear path")}}GetAxisEdge(t,e){return this.PathVisibilityGraph.AddEdgeF(t,e,(i,r)=>new om(i,r))}InitPathOrder(){for(let t of this.PathVisibilityGraph.Edges)this.axisEdgesToPathOrders.set(t,new Array);for(let t of this.OriginalPaths)for(let e of t.PathEdges())this.axisEdgesToPathOrders.get(e.AxisEdge).push(e)}OrderPaths(){for(let t of pe.WalkGraphEdgesInTopologicalOrderIfPossible(this.PathVisibilityGraph))this.OrderPathEdgesSharingEdge(t)}OrderPathEdgesSharingEdge(t){let e=this.PathOrderOfVisEdge(t);e.sort(pe.CompareTwoPathEdges);let i=0;for(let r of e)r.Index=i++}static CompareTwoPathEdges(t,e){if(t===e)return 0;let i=pe.CompareInDirectionStartingFromAxisEdge(t,e,t.AxisEdge,t.AxisEdge.Direction);return i!==0?i:-pe.CompareInDirectionStartingFromAxisEdge(t,e,t.AxisEdge,J.OppositeDir(t.AxisEdge.Direction))}static CompareInDirectionStartingFromAxisEdge(t,e,i,r){for(;;){if(t=pe.GetNextPathEdgeInDirection(t,i,r),t==null||(e=pe.GetNextPathEdgeInDirection(e,i,r),e==null))return 0;if(t.AxisEdge===e.AxisEdge){r=pe.FindContinuedDirection(i,r,t.AxisEdge),i=t.AxisEdge;let h=pe.GetExistingOrder(t,e);if(h===pe.NotOrdered)continue;return r===i.Direction?h:-h}let s=r===i.Direction?i.Target:i.Source,o=pe.OtherVertex(t.AxisEdge,s),a=pe.OtherVertex(e.AxisEdge,s),l=pe.ProjectionForCompare(i,r!==i.Direction);return Mt(l(o.point),l(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===1?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){let i=t.Index;if(i===-1)return pe.NotOrdered;let r=e.Index;return Mt(i,r)}PathOrderOfVisEdge(t){return this.axisEdgesToPathOrders.get(t)}static InitQueueOfSources(t,e,i){for(let r of i.Vertices()){let s=r.InEdgesLength();e.set(r,s),s===0&&t.enqueue(r)}}static*WalkGraphEdgesInTopologicalOrderIfPossible(t){let e=new nm.Queue,i=new Map;for(pe.InitQueueOfSources(e,i,t);e.length>0;){let r=e.dequeue();for(let s of r.OutEdges){let o=i.get(s.Target);i.set(s.Target,o-1),o===1&&e.enqueue(s.Target),yield s}}}},Ka=class{get Direction(){return this.End.sub(this.Start)}toString(){return this.Start+" "+this.End}},_a=class extends Ka{Init(n){this.StartVertex=n}constructor(n){super(),this.Init(n)}get Polyline(){return this.StartVertex.polyline}get Start(){return this.StartVertex.point}get End(){return this.EndVertex.point}},Qr=class extends _a{constructor(n){super(n),this.end=n.nextOnPolyline.point}get End(){return this.end}get EndVertex(){return this.StartVertex.nextOnPolyline}},Gi=class{},nn=class extends Gi{get Site(){return this.Vertex.point}constructor(n){super(),this.Vertex=n}get Polyline(){return this.Vertex.polyline}},Cr=class extends nn{constructor(n){super(n)}},Xr=class extends _a{constructor(n){super(n),this.end=n.prevOnPolyline.point}get End(){return this.end}get EndVertex(){return this.StartVertex.prevOnPolyline}},vr=class extends nn{constructor(n){super(n)}},tl=class{constructor(n){this.heapSize=0,this.A=[],this.compare=n}*[Symbol.iterator](){for(let n=1;n<=this.heapSize;n++)yield this.A[n]}Enqueue(n){let t=this.heapSize+1;this.A[t]=n,this.heapSize++;let e=t>>1,i,r;for(;t>1&&this.Less(i=this.A[t],r=this.A[e]);)this.A[e]=i,this.A[t]=r,t=e,e=t>>1}Dequeue(){if(this.heapSize<1)throw new Error;let n=this.A[1],t=this.A[this.heapSize];return this.heapSize--,this.ChangeMinimum(t),n}ChangeMinimum(n){this.A[1]=n;let t=1,e=2,i=!1;for(;e<this.heapSize&&!i;){i=!0;let r=this.A[e],s=this.A[e+1];this.compare(r,s)<0?this.compare(r,n)<0&&(this.A[t]=r,this.A[e]=n,i=!1,t=e,e=t<<1):this.compare(s,n)<0&&(this.A[t]=s,this.A[e+1]=n,i=!1,t=e+1,e=t<<1)}if(e===this.heapSize){let r=this.A[e];this.compare(r,n)<0&&(this.A[t]=r,this.A[e]=n)}}get Count(){return this.heapSize}Less(n,t){return this.compare(n,t)<0}GetMinimum(){return this.A[1]}},lm=class extends nn{constructor(n){super(n)}},hm=class{constructor(n){this.lineSweeper=n}Compare(n,t){switch(g.getTriangleOrientation(t.Start,t.End,this.x)){case 2:return 0;case 0:return 1;default:return-1}}SetOperand(n){this.x=this.IntersectionOfSideAndSweepLine(n)}IntersectionOfSideAndSweepLine(n){let t=n.Direction.dot(this.lineSweeper.SweepDirection),e=(this.lineSweeper.Z-n.Start.dot(this.lineSweeper.SweepDirection))/t;return n.Start.add(n.Direction.mul(e))}},um=class extends Gi{constructor(n){super(),this.site=n}get Site(){return this.site}},Nu=class{constructor(n,t){this.PreviousZ=Number.NEGATIVE_INFINITY,this.z=Number.NEGATIVE_INFINITY,this.Obstacles=n??[],this.SweepDirection=t,this.DirectionPerp=t.rotate(-Math.PI/2),this.EventQueue=new tl((e,i)=>this.Compare(e,i)),this.ObstacleSideComparer=new hm(this),this.LeftObstacleSideTree=new Re((e,i)=>this.ObstacleSideComparer.Compare(e,i)),this.RightObstacleSideTree=new Re((e,i)=>this.ObstacleSideComparer.Compare(e,i))}get EventQueue(){return this.eventQueue}set EventQueue(n){this.eventQueue=n}get DirectionPerp(){return this.directionPerp}set DirectionPerp(n){this.directionPerp=n}get Z(){return this.z}set Z(n){n>this.z+x.tolerance&&(this.PreviousZ=this.z),this.z=n}GetZS(n){return this.SweepDirection.dot(n.Site)}GetZP(n){return this.SweepDirection.dot(n)}SegmentIsNotHorizontal(n,t){return Math.abs(n.sub(t).dot(this.SweepDirection))>x.distanceEpsilon}RemoveLeftSide(n){this.ObstacleSideComparer.SetOperand(n),this.LeftObstacleSideTree.remove(n)}RemoveRightSide(n){this.ObstacleSideComparer.SetOperand(n),this.RightObstacleSideTree.remove(n)}InsertLeftSide(n){this.ObstacleSideComparer.SetOperand(n),this.LeftObstacleSideTree.insert(n)}InsertRightSide(n){this.ObstacleSideComparer.SetOperand(n),this.RightObstacleSideTree.insert(n)}FindFirstObstacleSideToTheLeftOfPoint(n){let t=this.RightObstacleSideTree.findLast(e=>g.pointToTheRightOfLineOrOnLine(n,e.Start,e.End));return t==null?null:t.item}FindFirstObstacleSideToToTheRightOfPoint(n){let t=this.LeftObstacleSideTree.findFirst(e=>!g.pointToTheRightOfLineOrOnLine(n,e.Start,e.End));return t==null?null:t.item}EnqueueEvent(n){this.eventQueue.Enqueue(n)}InitQueueOfEvents(){for(let n of this.Obstacles)this.EnqueueLowestPointsOnObstacles(n);if(this.Ports!=null)for(let n of this.Ports.values())this.EnqueueEvent(new um(n))}EnqueueLowestPointsOnObstacles(n){let t=this.GetLowestPoint(n);this.EnqueueEvent(new lm(t))}GetLowestPoint(n){let t=n.startPoint,e=n.startPoint.next;for(;e!=null;e=e.next)this.Less(e.point,t.point)&&(t=e);return t}Compare(n,t){let e=n.Site,i=t.Site;return this.ComparePoints(e,i)}Less(n,t){return this.ComparePoints(n,t)<0}ComparePoints(n,t){let e=this.SweepDirection.dot(n),i=this.SweepDirection.dot(t);return e<i?-1:e>i?1:(e=this.directionPerp.dot(n),i=this.directionPerp.dot(t),e<i?-1:e>i?1:0)}},dm=class extends Gi{constructor(n,t){super(),this.site=t,this.AxisEdge=n}get Site(){return this.site}},wh=class extends Gi{constructor(n,t){super(),this.site=t,this.AxisEdge=n}get Site(){return this.site}},cm=class{constructor(n){this.edges=new Set,this.Source=n}get Edges(){return this.edges}AddEdge(n){this.UpPoint=n.TargetPoint,this.edges.add(n)}RemoveAxis(n){this.edges.delete(n)}IsEmpty(){return this.edges.size===0}},gm=class pr extends Nu{static{this.AreaComparisonEpsilon=x.intersectionEpsilon}constructor(t,e,i,r,s){super(e,new J(t).ToPoint()),this.DirectionPerp=new J(t).Right.ToPoint(),this.PathOrders=r,this.xProjection=t===1?o=>o.x:o=>-o.y,this.edgeContainersTree=new Re((o,a)=>this.CompareAA(o,a)),this.SweepPole=J.VectorDirection(this.SweepDirection),this.AxisEdges=s,this.AxisEdgesToObstaclesTheyOriginatedFrom=i}FindFreeSpace(){this.InitTheQueueOfEvents(),this.ProcessEvents()}ProcessEvents(){for(;this.EventQueue.Count>0;)this.ProcessEvent(this.EventQueue.Dequeue())}ProcessEvent(t){t instanceof nn?this.ProcessVertexEvent(t):(this.Z=this.GetZP(t.Site),t instanceof wh?this.ProcessLowEdgeEvent(t):this.ProcessHighEdgeEvent(t))}ProcessHighEdgeEvent(t){let e=t.AxisEdge;this.RemoveEdge(e),this.ConstraintEdgeWithObstaclesAtZ(e,e.Target.point)}ProcessLowEdgeEvent(t){let e=t.AxisEdge,i=this.GetOrCreateAxisEdgesContainer(e);i.item.AddEdge(e);let r=this.edgeContainersTree.previous(i);if(r!=null)for(let o of r.item.edges)for(let a of i.item.edges)this.TryToAddRightNeighbor(o,a);let s=this.edgeContainersTree.next(i);if(s!=null)for(let o of i.item.Edges)for(let a of s.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===1?!(t.TargetPoint.y<e.SourcePoint.y-x.distanceEpsilon||e.TargetPoint.y<t.SourcePoint.y-x.distanceEpsilon):!(t.TargetPoint.x<e.SourcePoint.x-x.distanceEpsilon||e.TargetPoint.x<t.SourcePoint.x-x.distanceEpsilon)}GetObstacleBoundaries(t){return this.Obstacles.map(e=>It.mkDebugCurveWCI(1,t,e))}ConstraintEdgeWithObstaclesAtZ(t,e){this.ConstraintEdgeWithObstaclesAtZFromLeft(t,e),this.ConstraintEdgeWithObstaclesAtZFromRight(t,e)}ConstraintEdgeWithObstaclesAtZFromRight(t,e){let i=this.GetActiveSideFromRight(e);if(i==null||this.NotRestricting(t,i.item.Polyline))return;let r=this.ObstacleSideComparer.IntersectionOfSideAndSweepLine(i.item);t.BoundFromRight(r.dot(this.DirectionPerp))}GetActiveSideFromRight(t){return this.LeftObstacleSideTree.findFirst(e=>pr.PointToTheLeftOfLineOrOnLineLocal(t,e.Start,e.End))}ConstraintEdgeWithObstaclesAtZFromLeft(t,e){let i=this.GetActiveSideFromLeft(e);if(i==null||this.NotRestricting(t,i.item.Polyline))return;let r=this.ObstacleSideComparer.IntersectionOfSideAndSweepLine(i.item);t.BoundFromLeft(r.dot(this.DirectionPerp))}static PointToTheLeftOfLineOrOnLineLocal(t,e,i){return g.signedDoubledTriangleArea(t,e,i)>-pr.AreaComparisonEpsilon}static PointToTheRightOfLineOrOnLineLocal(t,e,i){return g.signedDoubledTriangleArea(e,i,t)<pr.AreaComparisonEpsilon}GetActiveSideFromLeft(t){return this.RightObstacleSideTree.findLast(e=>pr.PointToTheRightOfLineOrOnLineLocal(t,e.Start,e.End))}static EdgeMidPoint(t){return g.middle(t.SourcePoint,t.TargetPoint)}GetOrCreateAxisEdgesContainer(t){let e=t.Source.point;return this.GetAxisEdgesContainerNode(e)??this.edgeContainersTree.insert(new cm(e))}GetAxisEdgesContainerNode(t){let e=this.xProjection(t),i=this.edgeContainersTree.findFirst(r=>this.xProjection(r.Source)>=e-x.distanceEpsilon/2);return i!=null&&this.xProjection(i.item.Source)<=e+x.distanceEpsilon/2?i:null}ProcessVertexEvent(t){this.Z=this.GetZS(t),t instanceof Cr?this.ProcessLeftVertex(t,t.Vertex.nextOnPolyline):t instanceof vr?this.ProcessRightVertex(t,t.Vertex.prevOnPolyline):(this.ProcessLeftVertex(t,t.Vertex.nextOnPolyline),this.ProcessRightVertex(t,t.Vertex.prevOnPolyline))}ProcessRightVertex(t,e){let i=t.Site;this.ProcessPrevSegmentForRightVertex(t,i);let r=e.point.sub(t.Site),s=r.dot(this.DirectionPerp),o=r.dot(this.SweepDirection);o<=x.distanceEpsilon?s>0&&o>=0?this.EnqueueEvent(new vr(e)):this.RestrictEdgeContainerToTheRightOfEvent(t.Vertex):(this.InsertRightSide(new Xr(t.Vertex)),this.EnqueueEvent(new vr(e)),this.RestrictEdgeContainerToTheRightOfEvent(t.Vertex))}RestrictEdgeContainerToTheRightOfEvent(t){let e=t.point,i=this.xProjection(e),r=this.edgeContainersTree.findFirst(s=>i<=this.xProjection(s.Source));if(r!=null)for(let s of r.item.Edges)this.NotRestricting(s,t.polyline)||s.BoundFromLeft(this.DirectionPerp.dot(e))}NotRestricting(t,e){return this.AxisEdgesToObstaclesTheyOriginatedFrom.get(t)===e}ProcessPrevSegmentForRightVertex(t,e){let i=t.Vertex.nextOnPolyline.point;e.sub(i).dot(this.SweepDirection)>x.distanceEpsilon&&this.RemoveRightSide(new Xr(t.Vertex.nextOnPolyline))}RemoveEdge(t){let e=this.GetAxisEdgesContainerNode(t.Source.point);e.item.RemoveAxis(t),e.item.IsEmpty()&&this.edgeContainersTree.deleteNodeInternal(e)}ProcessLeftVertex(t,e){let i=t.Site;this.ProcessPrevSegmentForLeftVertex(t,i);let r=e.point.sub(t.Site),s=r.dot(this.DirectionPerp),o=r.dot(this.SweepDirection);o<=x.distanceEpsilon?s<0&&o>=0&&this.EnqueueEvent(new Cr(e)):(this.InsertLeftSide(new Qr(t.Vertex)),this.EnqueueEvent(new Cr(e))),this.RestrictEdgeFromTheLeftOfEvent(t.Vertex)}RestrictEdgeFromTheLeftOfEvent(t){let e=t.point,i=this.GetContainerNodeToTheLeftOfEvent(e);if(i!=null)for(let r of i.item.Edges)this.NotRestricting(r,t.polyline)||r.BoundFromRight(e.dot(this.DirectionPerp))}GetContainerNodeToTheLeftOfEvent(t){let e=this.xProjection(t);return this.edgeContainersTree.findLast(i=>this.xProjection(i.Source)<=e)}ProcessPrevSegmentForLeftVertex(t,e){let i=t.Vertex.prevOnPolyline.point;e.sub(i).dot(this.SweepDirection)>x.distanceEpsilon&&this.RemoveLeftSide(new Qr(t.Vertex.prevOnPolyline))}InitTheQueueOfEvents(){this.InitQueueOfEvents();for(let t of this.AxisEdges)this.EnqueueEventsForEdge(t)}EnqueueEventsForEdge(t){this.EdgeIsParallelToSweepDir(t)&&(this.EnqueueEvent(pr.EdgeLowPointEvent(t,t.Source.point)),this.EnqueueEvent(pr.EdgeHighPointEvent(t,t.Target.point)))}EdgeIsParallelToSweepDir(t){return t.Direction===this.SweepPole||t.Direction===J.OppositeDir(this.SweepPole)}static EdgeHighPointEvent(t,e){return new dm(t,e)}static EdgeLowPointEvent(t,e){return new wh(t,e)}CompareAA(t,e){return Mt(t.Source.dot(this.DirectionPerp),e.Source.dot(this.DirectionPerp))}},pm=class extends Ka{constructor(n){super(),this.CompassDirection=0,this.edges=new Array,this._isFixed=!1,this.Id=-1,this.IdealPosition=0,this.Id=n}get Start(){return this.start}get End(){return this.end}get Edges(){return this.edges}AddEdge(n){if(this.Edges.length===0){let t=J.VectorDirectionPP(n.Source,n.Target);switch(t){case 4:t=1;break;case 8:t=2;break}this.CompassDirection=t,this.start=n.Source,this.end=n.Source}switch(this.CompassDirection){case 1:this.TryPointForStartAndEndNorth(n.Source),this.TryPointForStartAndEndNorth(n.Target);break;case 2:this.TryPointForStartAndEndEast(n.Source),this.TryPointForStartAndEndEast(n.Target);break}this.Edges.push(n)}TryPointForStartAndEndNorth(n){n.y<this.start.y?this.start=n:n.y>this.end.y&&(this.end=n)}TryPointForStartAndEndEast(n){n.x<this.start.x?this.start=n:n.x>this.end.x&&(this.end=n)}get IsFixed(){return this._isFixed}set IsFixed(n){this._isFixed=n}get Width(){let n=0;for(let t of this.edges)n=Math.max(n,t.Width);return n}GetLeftBound(){if(!this.IsFixed){let n=Number.NEGATIVE_INFINITY;for(let t of this.edges)n=Math.max(n,t.AxisEdge.LeftBound);return n}return this.CompassDirection===1?this.Edges[0].Source.x:-this.Edges[0].Source.y}GetRightBound(){if(!this.IsFixed){let n=Number.POSITIVE_INFINITY;for(let t of this.edges)n=Math.min(n,t.AxisEdge.RightBound);return n}return this.Position()}Position(){return this.CompassDirection===1?this.Edges[0].Source.x:-this.Edges[0].Source.y}},fm=ct(se(),1),mm=class{constructor(n,t,e){this.indexToA=n,this.priority=t,this.v=e}},nr=class{constructor(n=Mt){this.heapSize=0,this.compare=n,this.cache=new Map,this.A=[]}get count(){return this.heapSize}ContainsElement(n){return this.cache.has(n)}SwapWithParent(n){let t=this.A[n>>1];this.PutAtI(n>>1,this.A[n]),this.PutAtI(n,t)}Enqueue(n,t){let e=++this.heapSize,i=new mm(e,t,n);for(this.cache.set(n,i),this.A[e]=i;e>1&&this.compare(this.A[e>>1].priority,t)>0;)this.SwapWithParent(e),e>>=1}IsEmpty(){return this.heapSize===0}PutAtI(n,t){this.A[n]=t,t.indexToA=n}Dequeue(){if(this.heapSize===0)throw new Error("dequeue on an empty queue");let n=this.A[1].v;return this.MoveQueueOneStepForward(n),n}DequeueAndGetPriority(n){if(this.heapSize===0)throw new Error("dequeue on an empty queue");let t=this.A[1].v;return n.priority=this.A[1].priority,this.MoveQueueOneStepForward(t),t}MoveQueueOneStepForward(n){this.cache.delete(n),this.PutAtI(1,this.A[this.heapSize]);let t=1;for(;;){let e=t,i=t<<1;i<=this.heapSize&&this.compare(this.A[i].priority,this.A[t].priority)<0&&(e=i);let r=i+1;if(r<=this.heapSize&&this.compare(this.A[r].priority,this.A[e].priority)<0&&(e=r),e!==t)this.SwapWithParent(e);else break;t=e}this.heapSize--}DecreasePriority(n,t){let e=this.cache.get(n);if(!e)return;e.priority=t;let i=e.indexToA;for(;i>1&&this.compare(this.A[i].priority,this.A[i>>1].priority)<0;)this.SwapWithParent(i),i>>=1}*GetEnumerator(){for(let n=1;n<=this.heapSize;n++)yield this.A[n].v}Peek(n){if(this.count===0){n.priority=0;return}return n.priority=this.A[1].priority,this.A[1].v}toString(){let n=new fm.StringBuilder;for(let t of this.A)n.Append(t+",");return n.ToString()}},Pm=class Ei{constructor(t,e){this.tree=new Re((i,r)=>Mt(i.Point.x,r.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();){let t={priority:0},e=this.Queue.DequeueAndGetPriority(t);this.ProcessEvent(e,t.priority)}}ProcessEvent(t,e){lt(t.Next.Point.x,t.Point.x)?e===Ei.Low(t)?this.ProcessLowLinkedPointEvent(t):this.ProcessHighLinkedPointEvent(t):this.IntersectWithTree(t)}IntersectWithTree(t){let e,i,r,s=t.Y;if(t.Point.x<t.Next.Point.x?(i=t.Point.x,e=t.Next.Point.x,r=!0):(e=t.Point.x,i=t.Next.Point.x,r=!1),r)for(let o=this.tree.findFirst(a=>i<=a.Point.x);o!=null&&o.item.Point.x<=e;o=this.tree.next(o)){let a=new g(o.item.Point.x,s);t=Ei.TrySplitHorizontalPoint(t,a,!0),Ei.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)){let a=new g(o.item.Point.x,s);t=Ei.TrySplitHorizontalPoint(t,a,!1),Ei.TrySplitVerticalPoint(o.item,a)}}static TrySplitVerticalPoint(t,e){Ei.Low(t)+x.distanceEpsilon<e.y&&e.y+x.distanceEpsilon<Ei.High(t)&&t.SetNewNext(e)}static TrySplitHorizontalPoint(t,e,i){return i&&t.X+x.distanceEpsilon<e.x&&e.x+x.distanceEpsilon<t.Next.X||!i&&t.Next.X+x.distanceEpsilon<e.x&&e.x+x.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 nr(Mt);for(let t of this.VerticalPoints)this.Queue.Enqueue(t,Ei.Low(t));for(let 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)}},ym=class Bn{constructor(t){this.verticesToPathOffsets=new _e,this.Paths=t}MergePaths(){this.InitVerticesToPathOffsetsAndRemoveSelfCycles();for(let t of this.Paths)this.ProcessPath(t)}ProcessPath(t){let e=new Map,i=null;for(let r=t.PathPoints;r!=null;r=r.Next){let s=this.verticesToPathOffsets.get(r.Point);if(i!=null){if(e.size>0)for(let[o,a]of s){let l=e.get(o);l&&(this.CollapseLoopingPath(o,l,a,t,r),e.delete(o))}for(let[o,a]of i)s.has(o)||e.set(o,a)}i=s}}CollapseLoopingPath(t,e,i,r,s){let o=Bn.FindLinkedPointInPath(r,e.Point),a=Array.from(Bn.GetPointsInBetween(o,s));Bn.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,r){let s=t;for(let o of i){let a=new wr(o);s.Next=a,s=a,this.verticesToPathOffsets.get(o).set(r,s)}s.Next=e}CleanDisappearedPiece(t,e,i){for(let r of Bn.GetPointsInBetween(t,e))this.verticesToPathOffsets.get(r).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(let 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);let r=i.get(t);r?(this.CleanDisappearedPiece(r,e,t),r.Next=e.Next):i.set(t,e)}}},Sm=class fe{static RefinePaths(t,e){fe.AdjustPaths(t);let i=fe.CreatePathsToFirstLinkedVerticesMap(t);fe.Refine(Array.from(i.values())),fe.CrossVerticalAndHorizontalSegs(i.values()),fe.ReconstructPathsFromLinkedVertices(i),e&&new ym(t).MergePaths()}static AdjustPaths(t){for(let e of t)e.PathPoints=fe.AdjustPathPoints(e.PathPoints)}static AdjustPathPoints(t){if(!t||t.length===0)return;let e=[],i=g.RoundPoint(t[0]);e.push(i);for(let r=1;r<t.length;r++){let s=g.RoundPoint(t[r]);i.equal(s)||(i=s,e.push(i))}return e}static CrossVerticalAndHorizontalSegs(t){let e=new Array,i=new Array;for(let r of t)for(let s=r;s.Next!=null;s=s.Next)lt(s.Point.x,s.Next.Point.x)?i.push(s):e.push(s);new Pm(e,i).SplitPoints()}static ReconstructPathsFromLinkedVertices(t){for(let[e,i]of t)e.PathPoints=i}static Refine(t){fe.RefineInDirection(1,t),fe.RefineInDirection(2,t)}static*groupByProj(t,e){let i=new Map;for(let r of e){let s=t(r.Point),o=i.get(s);o||(o=new Array,i.set(s,o)),o.push(r)}for(let r of i.values())yield r}static RefineInDirection(t,e){let i={projectionToPerp:void 0,projectionToDirection:void 0};fe.GetProjectionsDelegates(t,i);let r=Array.from(fe.GetAllLinkedVertsInDirection(i.projectionToPerp,e)),s=fe.groupByProj(i.projectionToPerp,r);for(let o of s)fe.RefineCollinearBucket(o,i.projectionToDirection)}static GetProjectionsDelegates(t,e){t===2?(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(let i of e)for(let r=i;r.Next!=null;r=r.Next)lt(t(r.Point),t(r.Next.Point))&&(yield r)}static RefineCollinearBucket(t,e){let i=new Set,r=new Array;for(let a of t){let l=e(a.Point);i.has(l)||(i.add(l),r.push([a.Point,l])),l=e(a.Next.Point),i.has(l)||(i.add(l),r.push([a.Next.Point,l]))}r.sort((a,l)=>a[1]-l[1]);let s=r.map(a=>a[0]),o=new Map;for(let a=0;a<r.length;a++)o.set(r[a][1],a);for(let a of t){let l=o.get(e(a.Point)),h=o.get(e(a.Next.Point));Math.abs(h-l)>1&&fe.InsertPoints(a,s,l,h)}}static InsertPoints(t,e,i,r){i<r?t.InsertVerts(i,r,e):t.InsertVertsInReverse(r,i,e)}static CreatePathsToFirstLinkedVerticesMap(t){let e=new Map;for(let i of t)e.set(i,fe.CreateLinkedVertexOfEdgePath(i));return e}static CreateLinkedVertexOfEdgePath(t){let e=t.PathPoints,i=new wr(e[0]),r=i;for(let s=1;s<e.length;s++)i.Next=new wr(e[s]),i=i.Next;return r}},Oe=class kr{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 lt(this.elements[0][0],1)&<(this.elements[0][1],0)&<(this.elements[0][2],0)&<(this.elements[1][0],0)&<(this.elements[1][1],1)&<(this.elements[1][2],0)}offset(){return new g(this.getElem(0,2),this.getElem(1,2))}static getIdentity(){return new kr(1,0,0,0,1,0)}constructor(t,e,i,r,s,o){this.elements=[[t,e,i],[r,s,o]]}static rotation(t){let e=Math.cos(t),i=Math.sin(t);return new kr(e,-i,0,i,e,0)}static scaleAroundCenterTransformation(t,e,i){let r=1-t,s=1-e;return new kr(t,0,r*i.x,0,e,s*i.y)}multiplyPoint(t){return new g(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 kr(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(){let 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,r=-this.getElem(1,0)/t,s=this.getElem(0,0)/t,o=-e*this.getElem(0,2)-i*this.getElem(1,2),a=-r*this.getElem(0,2)-s*this.getElem(1,2);return new kr(e,i,o,r,s,a)}},ce=class Ai{static mkEllipse(t,e,i){return Dt.mkFullEllipseNNP(t,e,i)}static createParallelogram(t,e,i){let r=e/2,s=t/2,o=i.x,a=i.y,l=80*Math.PI/180,h=r/Math.tan(l);return et.mkClosedFromPoints([new g(-s-h+o,-r+a),new g(s+o,-r+a),new g(s+o+h,r+a),new g(-s+o,r+a)])}static createHexagon(t,e,i){let r=e/2,s=t/2,o=i.x,a=i.y;return et.mkClosedFromPoints([new g(-s+o,-r+a),new g(s+o,-r+a),new g(s+(r+o),0+a),new g(s+o,r+a),new g(-s+o,r+a),new g(-(s-r)+o,0+a)])}static{this.octagonPad=1/4}static createOctagon(t,e,i){let r=t/2,s=e/2,o=new Array(8);o[0]=new g(r+Ai.octagonPad*r,s-s*Ai.octagonPad),o[3]=new g(o[0].x*-1,o[0].y),o[4]=new g(o[3].x,o[3].y*-1),o[7]=new g(o[0].x,o[0].y*-1),o[1]=new g(r-r*Ai.octagonPad,s+s*Ai.octagonPad),o[2]=new g(o[1].x*-1,o[1].y),o[6]=new g(o[1].x,o[1].y*-1),o[5]=new g(o[2].x,o[2].y*-1);for(let a=0;a<8;a++)o[a]=o[a].add(i);return et.mkClosedFromPoints(o)}static createInvertedHouse(t,e,i){let r=Ai.createHouse(t,e,i);return Ai.rotateCurveAroundCenterByDegree(r,i,180)}static createHouse(t,e,i){let r=t/2,s=e/2,o=i.x,a=i.y,l=new G;return G.addLineSegmentCNNNN(l,o-r,a-s,o+r,a-s),G.continueWithLineSegmentNN(l,o+r,a+s),G.continueWithLineSegmentNN(l,o,a+2*s),G.continueWithLineSegmentNN(l,o-r,a+s),G.closeCurve(l)}static mkDiamond(t,e,i){let r=t,s=e,o=i.x,a=i.y,l=new G,h=[new g(o,a-s),new g(o+r,a),new g(o,a+s),new g(o-r,a)];return l.addSegs([D.mkPP(h[0],h[1]),D.mkPP(h[1],h[2]),D.mkPP(h[2],h[3]),D.mkPP(h[3],h[0])]),l}static rotateCurveAroundCenterByDegree(t,e,i){return Ai.rotateCurveAroundCenterByRadian(t,e,i*Math.PI/180)}static rotateCurveAroundCenterByRadian(t,e,i){let r=Math.cos(i),s=Math.sin(i),o=new Oe(1,0,e.x,0,1,e.y).multiply(new Oe(r,-s,0,s,r,0)).multiply(new Oe(1,0,-e.x,0,1,-e.y));return t.transform(o)}static mkCircle(t,e){return Dt.mkCircle(t,e)}static createRectangle(t,e,i){let r=t/2,s=e/2,o=i.x,a=i.y,l=new G,h=[new g(o-r,a-s),new g(o+r,a-s),new g(o+r,a+s),new g(o-r,a+s)];return l.addSegs([D.mkPP(h[0],h[1]),D.mkPP(h[1],h[2]),D.mkPP(h[2],h[3]),D.mkPP(h[3],h[0])]),l}static isRoundedRect(t){if(!(t instanceof G))return;let e=t.segs;if(e.length!==8&&e.length!==4)return;let i=e.length===8,r,s;for(let o=0;o<4;o++){let a=i?2*o+1:o;if(o===0){if(!(e[a]instanceof Dt))return;let l=e[a];r=l.aAxis.length,s=l.bAxis.length}else{if(!(e[a]instanceof Dt))return;let l=e[a];if(r!==l.aAxis.length||s!==l.bAxis.length)return}}return{radX:r,radY:s}}static mkRectangleWithRoundedCorners(t,e,i,r,s=new g(0,0)){if(i===0||r===0)return Ai.createRectangle(t,e,s);let o=new G,a=t/2;i>a/2&&(i=a/2);let l=e/2;r>l/2&&(r=l/2);let h=s.x,u=s.y,d=a-i,c=l-r,f=u+l,m=u-l,P=h-a,v=h+a,b=new g(i,0),C=new g(0,r);return d>0&&o.addSegment(D.mkPP(new g(h-d,m),new g(h+d,m))),o.addSegment(Dt.mkEllipse(1.5*Math.PI,2*Math.PI,b,C,h+d,u-c)),c>0&&o.addSegment(D.mkPP(new g(v,u-c),new g(v,u+c))),o.addSegment(Dt.mkEllipse(0,.5*Math.PI,b,C,h+d,u+c)),d>0&&o.addSegment(D.mkPP(new g(h+d,f),new g(h-d,f))),o.addSegment(Dt.mkEllipse(.5*Math.PI,Math.PI,b,C,h-d,u+c)),c>0&&o.addSegment(D.mkPP(new g(P,u+c),new g(P,u-c))),o.addSegment(Dt.mkEllipse(Math.PI,1.5*Math.PI,b,C,h-d,u-c)),o}};function Xi(n){return n.parEnd-n.parStart}var Es=ct(ti(),1);function bm(n,t,e,i,r,s){for(let o=0;o<n.length;o++){if(o===t||o===e)continue;let a=s.box0.add_rect(n[o].irect),l=a.area-s.box0.area,h=s.box1.add_rect(n[o].irect),u=h.area-s.box1.area;i.length*2<r.length?(i.push(n[o]),s.box0=a):r.length*2<i.length?(r.push(n[o]),s.box1=h):l<u?(i.push(n[o]),s.box0=a):u<l?(r.push(n[o]),s.box1=h):s.box0.area<s.box1.area?(i.push(n[o]),s.box0=a):(r.push(n[o]),s.box1=h)}}function qt(n){if(n.length===0)return null;if(n.length===1)return n[0];let t={b0:n[0].irect,seed0:1},e=Cm(n,t),i=[],r=[];i.push(n[t.seed0]),r.push(n[e]);let s={box0:n[t.seed0].irect,box1:n[e].irect};bm(n,t.seed0,e,i,r,s);let o=Gu(n.length);return o.irect=s.box0.add_rect(s.box1),o.Left=qt(i),o.Right=qt(r),o}function Ih(n,t){return n.add_rect(t).area}function Cm(n,t){let e=Ih(t.b0,n[t.seed0].irect);for(let r=2;r<n.length;r++){let s=Ih(t.b0,n[r].irect);s>e&&(t.seed0=r,e=s)}let i;for(let r=0;r<n.length;r++)if(r!==t.seed0){i=r;break}e=n[t.seed0].irect.add_rect(n[i].irect).area;for(let r=0;r<n.length;r++){if(r===t.seed0)continue;let s=n[t.seed0].irect.add_rect(n[r].irect).area;s>e&&(i=r,e=s)}return i}function to(n,t){if(n==null||t==null)return null;let e=Array.from(n).map(i=>ne(i,t(i)));return qt(e)}function Gu(n){let t=new el;return t.Count=n,t}function ne(n,t){let e=new el;return e.UserData=n,e.irect=t,e.Count=1,e}function ba(n,t,e){return n.irect.intersects_rect(e)?t(n.UserData)===0?n.Left!=null?ba(n.Left,t,e)===0&&ba(n.Right,t,e)===0?0:1:0:1:0}var el=class{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(n){this.left!=null&&this.left.Parent===this&&(this.left.Parent=null),this.left=n,this.left!=null&&(this.left.Parent=this)}get Right(){return this.right}set Right(n){this.right!=null&&this.right.Parent===this&&(this.right.Parent=null),this.right=n,this.right!=null&&(this.right.Parent=this)}get IsLeftChild(){return this===this.Parent.Left}FirstIntersectedNode(n){return n.intersects_rect(this.irect)?this.IsLeaf?this:this.Left.FirstIntersectedNode(n)??this.Right.FirstIntersectedNode(n):null}FirstHitNodeWithPredicate(n,t){return this.irect.contains_point(n)?this.IsLeaf?t(n,this.UserData)===1?this:null:this.Left.FirstHitNodeWithPredicate(n,t)??this.Right.FirstHitNodeWithPredicate(n,t):null}FirstHitByRectWithPredicate(n,t){return this.irect.intersects_rect(n)?this.IsLeaf?t(this.UserData)===1?this:null:this.Left.FirstHitByRectWithPredicate(n,t)??this.Right.FirstHitByRectWithPredicate(n,t):null}FirstHitNode(n){return this.irect.contains_point(n)?this.IsLeaf?this:this.Left.FirstHitNode(n)??this.Right.FirstHitNode(n):null}*AllHitItems(n,t=null){let e=new Es.Stack;for(e.push(this);e.size>0;){let i=e.pop();i.irect.intersects_rect(n)&&(i.IsLeaf?(t==null||t(i.UserData))&&(yield i.UserData):(e.push(i.left),e.push(i.right)))}}*AllHitItems_(n){let t=new Es.Stack;for(t.push(this);t.size>0;){let e=t.pop();e.irect.contains_point(n)&&(e.IsLeaf?yield e.UserData:(t.push(e.left),t.push(e.right)))}}VisitTree(n,t){ba(this,n,t)}Clone(){let n=Gu(this.Count);return n.UserData=this.UserData,n.irect=this.irect,this.Left!=null&&(n.Left=this.Left.Clone()),this.Right!=null&&(n.Right=this.Right.Clone()),n}*GetNodeItemsIntersectingRectangle(n){for(let t of this.GetLeafRectangleNodesIntersectingRectangle(n))yield t.UserData}*GetLeafRectangleNodesIntersectingRectangle(n){let t=new Es.Stack;for(t.push(this);t.size>0;){let e=t.pop();e.irect.intersects_rect(n)&&(e.IsLeaf?yield e:(t.push(e.left),t.push(e.right)))}}*GetAllLeaves(){for(let n of this.GetAllLeafNodes())yield n.UserData}*GetAllLeafNodes(){for(let n of this.EnumRectangleNodes(!0))yield n}*EnumRectangleNodes(n){let t=new Es.Stack;for(t.push(this);t.size>0;){let e=t.pop();(e.IsLeaf||!n)&&(yield e),e.IsLeaf||(t.push(e.left),t.push(e.right))}}TraverseHierarchy(n,t){t(n),n.Left!=null&&this.TraverseHierarchy(n.Left,t),n.Right!=null&&this.TraverseHierarchy(n.Right,t)}};function Vn(n){return new eo(qt(n.map(([t,e])=>ne(e,t))))}function vm(n,t){n.UserData=t.UserData,n.Left=t.Left,n.Right=t.Right,n.Count--,n.irect=t.irect}function Th(n){for(let t=n.Parent;t!=null;t=t.Parent)t.Count--,t.irect=t.Left.irect.add_rect(t.Right.irect)}function xm(n,t){let e=new Array;for(let r of n.GetAllLeafNodes())r!==t&&e.push(r);let i=qt(e);n.Count=i.Count,n.Left=i.Left,n.Right=i.Right,n.irect=i.Left.irect.add_rect(i.Right.irect)}function Em(n){for(let t=n.Parent;t!=null;t=t.Parent)if(!Du(t))return t;return null}function Du(n){return 2*n.Left.Count>=n.Right.Count&&2*n.Right.Count>=n.Left.Count}function Ca(n,t,e,i){return n.irect.intersects_rect(t)?n.IsLeaf?i(n.UserData)?--e.bound!==0:!0:Ca(n.Left,t,e,i)&&Ca(n.Right,t,e,i):!0}var eo=class{clear(){this.RootNode=null}NumberOfIntersectedIsLessThanBound(n,t,e){return Ca(this._rootNode,n,{bound:t},e)}get RootNode(){return this._rootNode}set RootNode(n){this._rootNode=n}constructor(n){this._rootNode=n}*GetAllLeaves(){if(this._rootNode!=null&&this.Count>0)for(let n of this._rootNode.GetAllLeaves())yield n}get Count(){return this._rootNode==null?0:this._rootNode.Count}Add(n,t){this.AddNode(ne(t,n))}AddNode(n){this._rootNode==null?this._rootNode=n:this.Count<=2?this._rootNode=qt(Array.from(this._rootNode.GetAllLeafNodes()).concat([n])):this.AddNodeToTreeRecursive(n,this._rootNode)}Rebuild(){this._rootNode=qt(Array.from(this._rootNode.GetAllLeafNodes()))}AddNodeToTreeRecursive(n,t){if(t.IsLeaf)t.Left=ne(t.UserData,t.irect),t.Right=n,t.Count=2;else{t.Count++;let e,i;if(2*t.Left.Count<t.Right.Count)this.AddNodeToTreeRecursive(n,t.Left),t.Left.irect=t.Left.irect.add_rect(n.irect);else if(2*t.Right.Count<t.Left.Count)this.AddNodeToTreeRecursive(n,t.Right),t.Right.irect=t.Right.irect.add_rect(n.irect);else{e=t.Left.irect.add_rect(n.irect);let r=e.area-t.Left.irect.area;i=t.Right.irect.add_rect(n.irect);let s=i.area-t.Right.irect.area;r<s?(this.AddNodeToTreeRecursive(n,t.Left),t.Left.irect=e):r>s?(this.AddNodeToTreeRecursive(n,t.Right),t.Right.irect=i):e.area<i.area?(this.AddNodeToTreeRecursive(n,t.Left),t.Left.irect=e):(this.AddNodeToTreeRecursive(n,t.Right),t.Right.irect=i)}}t.irect=t.Left.irect.add_rect(t.Right.irect)}GetAllIntersecting(n){return this._rootNode==null||this.Count===0?[]:Array.from(this._rootNode.GetNodeItemsIntersectingRectangle(n))}OneIntersecting(n){if(this._rootNode==null||this.Count===0)return;let t=this._rootNode.FirstIntersectedNode(n);if(t!=null)return{intersectedLeaf:t.UserData}}GetAllLeavesIntersectingRectangle(n){return this._rootNode==null||this.Count===0?[]:this._rootNode.GetLeafRectangleNodesIntersectingRectangle(n)}IsIntersecting(n){if(this._rootNode==null||this.Count===0)return!1;for(let t of this._rootNode.GetNodeItemsIntersectingRectangle(n))return!0;return!1}Contains(n,t){if(this._rootNode==null)return!1;for(let e of this._rootNode.GetLeafRectangleNodesIntersectingRectangle(n))if(e.UserData===t)return!0;return!1}Remove(n,t){if(this._rootNode==null)return;let e;for(let i of this._rootNode.GetLeafRectangleNodesIntersectingRectangle(n))i.UserData===t&&(e=i);if(e!=null)return this.RootNode.Count===1?this.RootNode=null:this.RemoveLeaf(e),e.UserData}RemoveLeaf(n){let t=Em(n);if(t!=null)xm(t,n),Th(t);else{let e=n.Parent;e==null?this._rootNode=new el:(vm(e,n.IsLeftChild?e.Right:e.Left),Th(e))}}UnbalancedNode(n){for(let t=n.Parent;t!=null;t=t.Parent)if(!Du(t))return t;return null}},ur=class{constructor(n,t){this.Points=n,this.I=t}static equal(n,t){return n.I===t.I&&n.Points===t.Points}get Start(){return this.Points[this.I]}get End(){return this.Points[this.I+1]}},Am=class $r{constructor(t,e){this.segTree=new eo(null),this.crossedOutPaths=new Set,this.HierarchyOfObstacles=new eo(e),this.Paths=t}static RemoveStaircases(t,e){new $r(t,e).Calculate()}Calculate(){this.InitHierarchies();let t;do{t=!1;for(let e of this.Paths.filter(i=>!this.crossedOutPaths.has(i)))this.ProcessPath(e)&&(t=!0)}while(t)}ProcessPath(t){let e={pts:t.PathPoints,canHaveStaircase:!1};return this.ProcessPoints(e)?(t.PathPoints=e.pts,!0):(e.canHaveStaircase||this.crossedOutPaths.add(t),!1)}ProcessPoints(t){let 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;let e=[new ur(t.pts,0),new ur(t.pts,1),new ur(t.pts,2),new ur(t.pts,3)],i=0;for(let r=0;;){let s={canHaveStaircaseAtI:!1};if(this.IsStaircase(t.pts,r,e,s))return t.canHaveStaircase=!0,r;if(t.canHaveStaircase=t.canHaveStaircase||s.canHaveStaircaseAtI,r++,t.pts.length<r+5)return-1;e[i]=new ur(t.pts,r+3),i++,i%=4}}static GetFlippedPoint(t,e){return lt(t[e].y,t[e+1].y)?new g(t[e+4].x,t[e].y):new g(t[e].x,t[e+4].y)}Crossing(t,e,i){return $r.IsCrossing(D.mkPP(t,e),this.segTree,i)}static IsCrossing(t,e,i){for(let r of e.GetAllIntersecting(t.boundingBox))if(i.findIndex(s=>s===r)===-1)return!0;return!1}IntersectObstacleHierarchyPPP(t,e,i){return this.IntersectObstacleHierarchyL(D.mkPP(t,e))||this.IntersectObstacleHierarchyL(D.mkPP(e,i))}IntersectObstacleHierarchyL(t){return this.HierarchyOfObstacles.GetAllIntersecting(t.boundingBox).some(e=>G.intersectionOne(t,e,!1)!=null)}IsStaircase(t,e,i,r){let s=t[e],o=t[e+1],a=t[e+2],l=t[e+3],h=t[e+4];return r.canHaveStaircaseAtI=!1,J.DirectionFromPointToPoint(s,o)!==J.DirectionFromPointToPoint(a,l)||J.DirectionFromPointToPoint(o,a)!==J.DirectionFromPointToPoint(l,h)||(a=$r.GetFlippedPoint(t,e),this.IntersectObstacleHierarchyPPP(o,a,l))?!1:(r.canHaveStaircaseAtI=!0,!this.Crossing(o,a,i))}RemoveStaircasePN(t,e){let i=t[e],r=t[e+1],s=Math.abs(i.y-r.y)<x.distanceEpsilon/2;return this.RemoveStaircasePNB(t,e,s)}RemoveStaircasePNB(t,e,i){this.RemoveSegs(t);let r=new Array(t.length-2);Im(t,r,e+1);let s=t[e+1],o=t[e+3];return r[e+1]=i?new g(o.x,s.y):new g(s.x,o.y),wm(t,e+4,r,e+2,r.length-e-2),this.InsertNewSegs(r,e),r}RemoveSegs(t){for(let e=0;e<t.length-1;e++)this.RemoveSeg(new ur(t,e))}RemoveSeg(t){this.segTree.Remove($r.Rect(t),t)}InsertNewSegs(t,e){this.InsSeg(t,e),this.InsSeg(t,e+1)}InitHierarchies(){for(let 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){let i=new ur(t,e);this.segTree.Add($r.Rect(i),i)}static Rect(t){return it.mkPP(t.Start,t.End)}};function wm(n,t,e,i,r){for(;r-- >0;)e[i++]=n[t++]}function Im(n,t,e){let i=0;for(;e-- >0;)t[i++]=n[i++]}var Tm=class Bt{get HasGroups(){return this.HierarchyOfGroups!=null&&this.HierarchyOfGroups.Count>0}constructor(t,e,i,r){this.AncestorsSets=r,this.HierarchyOfGroups=qt(Array.from(r.keys()).filter(s=>s.IsGroup).map(s=>ne(s,s.BoundingBox))),this.Obstacles=i,this.EdgeSeparation=2*e,this.Paths=t,this.HierarchyOfObstacles=qt(i.map(s=>ne(s,s.boundingBox))),this.MapPathsToTheirObstacles()}MapPathsToTheirObstacles(){this.PathToObstacles=new Map;for(let t of this.Paths)this.MapPathToItsObstacles(t)}MapPathToItsObstacles(t){if(!t.PathPoints||t.PathPoints.length===0)return;let e=t.PathPoints,i=this.HierarchyOfObstacles.FirstHitNodeWithPredicate(e[0],Bt.ObstacleTest),r=this.HierarchyOfObstacles.FirstHitNodeWithPredicate(e[e.length-1],Bt.ObstacleTest);i!=null&&r!=null&&this.PathToObstacles.set(t,[i.UserData,r.UserData])}static ObstacleTest(t,e){return G.PointRelativeToCurveLocation(t,e)!==0?1:0}Calculate(t,e){this.NudgingDirection=t,Sm.RefinePaths(this.Paths,e),this.GetPathOrdersAndPathGraph(),this.MapAxisEdgesToTheirObstacles(),this.DrawPaths()}MapAxisEdgesToTheirObstacles(){this.axisEdgesToObstaclesTheyOriginatedFrom=new Map;for(let t of this.Paths)this.MapPathEndAxisEdgesToTheirObstacles(t);for(let t of this.Paths)this.UmmapPathInteriourFromStrangerObstacles(t)}UmmapPathInteriourFromStrangerObstacles(t){let e=this.FindFirstUnmappedEdge(t);if(e==null)return;let i=this.FindLastUnmappedEdge(t);for(let r=e;r!=null&&r!==i;r=r.Next)this.axisEdgesToObstaclesTheyOriginatedFrom.delete(r.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){let 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(){let t=new am(this.Paths);this.PathOrders=t.GetOrder(),this.PathVisibilityGraph=t.PathVisibilityGraph}static GetCurvesForShow(t,e){let i=new Array;for(let r of t){let s=new et;for(let o of r.PathPoints)s.addPoint(o);i.push(s)}return i.concat(Array.from(e))}DrawPaths(){this.SetWidthsOfArrowheads(),this.CreateLongestNudgedSegments(),this.FindFreeSpaceInDirection(Array.from(this.PathVisibilityGraph.Edges)),this.MoveLongestSegsIdealPositionsInsideFeasibleIntervals(),this.PositionShiftedEdqges()}SetWidthsOfArrowheads(){for(let t of this.Paths)Bt.SetWidthsOfArrowheadsForEdge(t)}static SetWidthsOfArrowheadsForEdge(t){let e=t.GeomEdge;if(e.targetArrowhead!=null){let i=t.LastEdge;i.Width=Math.max(e.targetArrowhead.width,i.Width)}if(e.sourceArrowhead!=null){let i=t.FirstEdge;i.Width=Math.max(e.sourceArrowhead.width,i.Width)}}PositionShiftedEdqges(){this.Solver=new rm(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++){let e=this.LongestNudgedSegs[t];Bt.MoveLongestSegIdealPositionsInsideFeasibleInterval(e)}}static MoveLongestSegIdealPositionsInsideFeasibleInterval(t){if(t.IsFixed)return;let e=t.GetLeftBound(),i=t.GetRightBound();t.IdealPosition<e?t.IdealPosition=e:t.IdealPosition>i&&(t.IdealPosition=i)}ShiftPathEdges(){for(let t of this.Paths)t.PathPoints=this.GetShiftedPoints(t)}GetShiftedPoints(t){return Bt.RemoveSwitchbacksAndMiddlePoints(this.GetShiftedPointsSimple(t))}static Rectilinearise(t,e){if(t.x===e.x||t.y===e.y)return e;let i=Math.abs(t.x-e.x),r=Math.abs(t.y-e.y);return i<r?new g(t.x,e.y):new g(e.x,t.y)}GetShiftedPointsSimple(t){let e=[],i=t.FirstEdge;e.push(this.ShiftedPoint(i.Source,i.LongestNudgedSegment));for(let r of t.PathEdges())e.push(this.ShiftedEdgePositionOfTarget(r));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;let i=this.Solver.GetVariablePosition(e.Id);return this.NudgingDirection===1?new g(i,t.y):new g(t.x,-i)}static LineSegOfLongestSeg(t,e){let i=e===2?s=>s.x:s=>s.y,r={min:Number.POSITIVE_INFINITY,max:Number.NEGATIVE_INFINITY};for(let s of t.Edges)Bt.UpdateMinMaxWithPoint(r,i,s.Source),Bt.UpdateMinMaxWithPoint(r,i,s.Target);return e===2?new D(r.min,-t.IdealPosition,r.max,-t.IdealPosition):new D(t.IdealPosition,r.min,t.IdealPosition,r.max)}static UpdateMinMaxWithPoint(t,e,i){let r=e(i);t.min>r&&(t.min=r),t.max<r&&(t.max=r)}CreateConstraintsBetweenLongestSegments(){for(let t of this.LongestNudgedSegs)this.CreateConstraintsBetweenLongestSegmentsForSegment(t)}CreateConstraintsBetweenLongestSegmentsForSegment(t){let e=new Set;for(let i of t.Edges){let r=i.AxisEdge;if(r!=null)for(let s of r.RightNeighbors)for(let o of s.LongestNudgedSegments)e.add(o)}for(let i of e)this.ConstraintTwoLongestSegs(t,i)}CreateConstraintsOfTheOrder(){for(let t of this.PathOrders)Bt.ParallelToDirection(t[0],this.NudgingDirection)&&this.CreateConstraintsOfThePathOrder(t[1])}static ParallelToDirection(t,e){switch(e){case 1:case 4:return lt(t.SourcePoint.x,t.TargetPoint.x);default:return lt(t.SourcePoint.y,t.TargetPoint.y)}}CreateConstraintsOfThePathOrder(t){let e=null;for(let i of t.filter(r=>r.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,Bt.SegmentPosition(t,this.NudgingDirection));else{let e=t.GetLeftBound(),i=t.GetRightBound();e>=i?(this.Solver.AddFixedVariable(t.Id,Bt.SegmentPosition(t,this.NudgingDirection)),t.IsFixed=!0):(this.Solver.AddVariableNNNN(t.Id,Bt.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===1?t.Start.x:-t.Start.y}FindFreeSpaceInDirection(t){this.BoundAxisEdgesByRectsKnownInAdvance(),new gm(this.NudgingDirection,this.Obstacles,this.axisEdgesToObstaclesTheyOriginatedFrom,this.PathOrders,t).FindFreeSpace()}BoundAxisEdgesByRectsKnownInAdvance(){for(let t of this.Paths)this.HasGroups&&this.BoundPathByMinCommonAncestors(t),this.BoundAxisEdgesAdjacentToSourceAndTargetOnEdge(t)}BoundPathByMinCommonAncestors(t){for(let e of this.GetMinCommonAncestors(t.GeomEdge)){let i=e.BoundingBox;for(let r of t.PathEdges()){let s=r.AxisEdge;s.Direction===this.NudgingDirection&&this.BoundAxisEdgeByRect(i,s)}}}GetMinCommonAncestors(t){this.PortToShapes==null&&(this.PortToShapes=Bt.MapPortsToShapes(this.AncestorsSets.keys()));let e=Om(this.AncestorsForPort(t.sourcePort),this.AncestorsForPort(t.targetPort));return Array.from(e).filter(i=>!i.Children.some(r=>e.has(r)))}AncestorsForPort(t){let e=this.PortToShapes.get(t);return e?this.AncestorsSets.get(e):new Set(this.HierarchyOfGroups.AllHitItems(it.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===1?(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===1?(e.BoundFromLeft(t.left),e.BoundFromRight(t.right)):(e.BoundFromLeft(t.top*-1),e.BoundFromRight(t.bottom*-1)))}CreateLongestNudgedSegments(){let t=this.NudgingDirection===2?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),Bt.CalculateIdealPositionsForLongestSegs(t,e)}static CalculateIdealPositionsForLongestSegs(t,e){let i=null,r=null,s=e(t.Start);for(let o of t.PathEdges())if(o.LongestNudgedSegment!=null){if(i=o.LongestNudgedSegment,r!=null){let a;Bt.SetIdealPositionForSeg(r,a=e(r.start),s,e(i.Start)),s=a,r=null}}else i!=null&&(r=i,i=null);r!=null?Bt.SetIdealPositionForSeg(r,e(r.Start),s,e(t.End)):i!=null&&(i.IdealPosition=e(i.Start))}static SetIdealPositionForSeg(t,e,i,r){let s=Math.max(i,r),o=Math.min(i,r);o+x.distanceEpsilon<e?e<s?t.IdealPosition=.5*(s+o):t.IdealPosition=s:t.IdealPosition=o}GoOverPathAndCreateLongSegs(t){let e=null,i=J.OppositeDir(this.NudgingDirection);for(let r of t.PathEdges()){let s=r.Direction;s===this.NudgingDirection||s===i?(e==null?(r.LongestNudgedSegment=e=new pm(this.LongestNudgedSegs.length),this.LongestNudgedSegs.push(e)):r.LongestNudgedSegment=e,r.IsFixed&&(e.IsFixed=!0)):(r.LongestNudgedSegment=null,e=null)}}static BuildPolylineForPath(t){let e={points:t.PathPoints.map(i=>i.clone())};return Bt.ExtendPolylineToPorts(e,t),e.points}static ExtendPolylineToPorts(t,e){Bt.ExtendPolylineToSourcePort(t,e.GeomEdge.sourcePort.Location),Bt.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){let i=t.points.length-1,r=J.VectorDirectionPP(t.points[i-1],t.points[i]);if(Bt.ProjectionsAreClose(t.points[i-1],r,e)){t.points=t.points.slice(0,i);return}let s=t.points[i];r===2||r===8?t.points[i]=new g(e.x,s.y):t.points[i]=new g(s.x,e.y)}static ProjectionsAreClose(t,e,i){return e===2||e===8?lt(t.x,i.x):lt(t.y,i.y)}static ExtendPolylineToSourcePort(t,e){let i=J.VectorDirectionPP(t.points[0],t.points[1]);if(Bt.ProjectionsAreClose(t.points[1],i,e)){t.points=t.points.slice(1);return}let r=t.points[0];i===2||i===8?t.points[0]=new g(e.x,r.y):t.points[0]=new g(r.x,e.y)}static RemoveSwitchbacksAndMiddlePoints(t){let e=[],i=t[0];e.push(i);let r=t[1],s=J.VectorDirectionPP(i,r),o=1;for(;++o<t.length;){let a=J.VectorDirectionPP(r,t[o]);a===s||J.OppositeDir(a)===s||a===0||(g.closeDistEps(i,r)||e.push(i=Bt.Rectilinearise(i,r)),s=a),r=t[o]}return g.closeDistEps(i,r)||e.push(Bt.Rectilinearise(i,r)),e}static NudgePaths(t,e,i,r,s){if(t.length===0)return;let o=new Bt(t,e,i,r);o.Calculate(1,!0),o.Calculate(2,!1),o.Calculate(1,!1),s&&o.RemoveStaircases();for(let a of t)a.GeomEdge.curve=et.mkFromPoints(Bt.BuildPolylineForPath(a))}RemoveStaircases(){Am.RemoveStaircases(this.Paths,this.HierarchyOfObstacles)}static MapPortsToShapes(t){let e=new Map;for(let i of t)for(let r of i.Ports)e.set(r,i);return e}static*GetEdgePathFromPathEdgesAsDebugCurves(t,e,i,r){let s=r.ArrayOfPathPoints(),o=s.length,a=o>1?(e-t)/(o-1):1;for(let l=0;l<s.length-1;l++)yield It.mkDebugCurveTWCI(200,t+a*l,i,D.mkPP(s[l],s[l+1]))}};function Om(n,t){let e=new Set;if(n.size<t.size)for(let i of n)t.has(i)&&e.add(i);else for(let i of t)n.has(i)&&e.add(i);return e}var Mu=class{bind(n){this.entity&&this.entity.setAttr(n,this)}constructor(n,t){this.entity=n,this.bind(t)}},tr=class{static{this.GeomObjectIndex=0}static{this.DrawingObjectIndex=1}static{this.AlgorithmDataIndex=2}static{this.ViewerIndex=3}},Tt=class Vu extends Mu{constructor(t){super(t,tr.GeomObjectIndex)}static getGeom(t){return t==null?null:t.getAttr(tr.GeomObjectIndex)}get parent(){let t=this.entity.parent;return t?Vu.getGeom(t):null}rebind(t){this.entity=t,this.bind(tr.GeomObjectIndex)}*getAncestors(){let t=this.parent;for(;t!=null;)yield t,t=t.parent}},re=class Rn{constructor(){this.previouisBezierCoefficient=.5,this.nextBezierCoefficient=.5,this.previousTangentCoefficient=1/3,this.nextTangentCoefficient=1/3}static mkSiteP(t){let e=new Rn;return e.point=t,e}static mkSiteSP(t,e){let i=new Rn;return i.point=e,i.prev=t,t.next=i,i}static mkSiteSPS(t,e,i){let r=new Rn;return r.prev=t,r.point=e,r.next=i,t.next=r,i.prev=r,r}get turn(){return this.next==null||this.prev==null?0:g.getTriangleOrientation(this.prev.point,this.point,this.next.point)}clone(){let t=new Rn;return t.previouisBezierCoefficient=this.previouisBezierCoefficient,t.point=this.point,t}},Ot=class Ds{static mkFromPoints(t){let e=null,i=null;for(let r of t)if(i==null)i=re.mkSiteP(r),e=new Ds(i);else{let s=re.mkSiteP(r);s.prev=i,i.next=s,i=s}return e}clone(){let t=this.headSite,e=null,i,r=null;for(;t!=null;)i=t.clone(),i.prev=e,e!=null?e.next=i:r=i,t=t.next,e=i;return new Ds(r)}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(){let t=new G,e=this.headSite;do{let i=G.findCorner(e);if(i==null)break;let r=Ds.createBezierSegOnSite(i.b);t.segs.length===0?g.closeDistEps(e.point,r.start)||G.addLineSegment(t,e.point,r.start):g.closeDistEps(t.end,r.start)||G.continueWithLineSegmentP(t,r.start),t.addSegment(r),e=i.b}while(!0);return t.segs.length===0?g.closeDistEps(e.point,e.next.point)?t.segs.push(new Ke(e.point,e.point.add(new g(5,5)),e.point.add(new g(-5,5)),e.next.point)):G.addLineSegment(t,e.point,e.next.point):g.closeDistEps(t.end,e.next.point)||G.continueWithLineSegmentP(t,e.next.point),t}static createBezierSegOnSite(t){let e=t.previouisBezierCoefficient,i=t.nextBezierCoefficient,r=t.prev,s=t.next,o=r.point.mul(e).add(t.point.mul(1-e)),a=s.point.mul(i).add(t.point.mul(1-i)),l=o.mul(t.previousTangentCoefficient).add(t.point.mul(1-t.previousTangentCoefficient)),h=a.mul(t.nextTangentCoefficient).add(t.point.mul(1-t.nextTangentCoefficient));return Ke.mkBezier([o,l,h,a])}},il=class ku extends Tt{constructor(t,e){super(t),this._isPositioned=!1,e&&(this.boundingBox=it.mkPP(new g(0,0),new g(e.width,e.height)))}clone(){let t=new ku(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}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}},Fe=class $u extends Tt{constructor(t){super(t),this.lineWidth=1}*getSmoothPolyPoints(){yield this.source.center,this.curve instanceof G?yield*this.getCurvePoints(this.curve):this.curve instanceof D?(yield this.curve.start,yield this.curve.end):this.curve instanceof Dt?(yield this.curve.start,yield this.curve.value((this.curve.parStart+this.curve.parEnd)/.5),yield this.curve.end):this.curve instanceof Ke&&(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(let e of t.segs)if(yield e.start,e instanceof Ke){let i=Lm(e);i&&(yield i)}yield t.end}static getGeom(t){return Tt.getGeom(t)}clone(){let t=new $u(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?Tt.getGeom(this.edge.label):null}set label(t){this.edge.label.setAttr(tr.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){let e=il.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 Tt.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(){let t=it.mkEmpty();if(this.smoothedPolyline!=null)for(let i of this.smoothedPolyline)t.add(i);this.curve!=null&&t.addRecSelf(this.curve.boundingBox);for(let i of this.sourceArrowheadPoints(25))t.add(i);for(let i of this.targetArrowheadPoints(25))t.add(i);this.label&&t.addRecSelf(this.label.boundingBox);let 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 Tt.getGeom(this.edge.target)}toString(){return this.source.toString()+"->"+this.target}static RouteSelfEdge(t,e,i){let r=t.boundingBox.width,s=t.boundingBox.height,o=t.boundingBox.center,a=new g(o.x-r/4,o.y),l=new g(o.x-r/4,o.y-s/2-e),h=new g(o.x+r/4,o.y-s/2-e),u=new g(o.x+r/4,o.y);return i.smoothedPolyline=Ot.mkFromPoints([a,l,h,u]),i.smoothedPolyline.createCurve()}underCollapsedGraph(){return this.source.underCollapsedGraph()||this.target.underCollapsedGraph()}EdgeToAncestor(){return this.edge.EdgeToAncestor()}};function Lm(n){return g.lineLineIntersection(n.b[0],n.b[1],n.b[2],n.b[3])}var Nt=class{ProgressStep(){}constructor(n){this.cancelToken=n}},Hu=ct(bi(),1),Wt=class{static assert(n,t=null){if(!n)throw t!=null?(console.log(t),new Error(t)):new Error("condition does not hold")}},rl=class{constructor(){this.attrs=[],this._parent=null}addEvent(n){this.events.push(n)}removeEvent(n){let t=this.events.indexOf(n);t>=0&&(this.events=this.events.splice(t,1))}raiseEvents(n){this.events.forEach(t=>t(n))}clearAttr(){this.attrs=[]}setAttr(n,t){this.attrs[n]=t}getAttr(n){return this.attrs[n]}get parent(){return this._parent}set parent(n){this._parent=n}*getAncestors(){let n=this.parent;for(;n!=null;)yield n,n=n.parent}isDescendantOf(n){for(let t of this.getAncestors())if(t===n)return!0;return!1}},Yn=class extends rl{constructor(n,t){super(),this.source=n,this.target=t,n!==t?(n.outEdges.add(this),t.inEdges.add(this)):n.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 Be&&this.target.isDescendantOf(this.source)?1:this.target instanceof Be&&this.source.isDescendantOf(this.target)?2:0}},sn=class extends rl{constructor(n){super(),this.inEdges=new Set,this.outEdges=new Set,this.selfEdges=new Set,this.id=n}removeOutEdge(n){this.outEdges.delete(n)}removeInEdge(n){this.inEdges.delete(n)}get id(){return this._id}set id(n){this._id=n}toString(){return this.id}*_edges(){for(let n of this.inEdges)yield n;for(let n of this.outEdges)yield n;for(let n of this.selfEdges)yield n}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}},Bm=class{constructor(){this.nodeMap=new Map}remove(n){this.nodeMap.delete(n.id)}get size(){return this.nodeMap.size}*nodes_(){for(let n of this.nodeMap.values())yield n}*graphs_(){for(let n of this.nodes_())n instanceof Be&&(yield n)}findShallow(n){return this.nodeMap.get(n)}get nodesShallow(){return this.nodes_()}get graphs(){return this.graphs_()}*_edges(){for(let n of this.nodeMap.values()){for(let t of n.outEdges)yield t;for(let t of n.selfEdges)yield t}}interGraphEdges(){throw new Error("not implemented")}get nodeShallowCount(){return this.nodeMap.size}get edgeCount(){let n=0;for(let t of this.nodeMap.values())n+=t.outDegree+t.selfDegree;return n}get edges(){return this._edges()}addNode(n){this.nodeMap.set(n.id,n)}nodeIsConsistent(n){for(let t of n.outEdges)if(t.source!==n||t.source===t.target)return!1;for(let t of n.inEdges)if(t.target!==n||t.source===t.target)return!1;for(let t of n.selfEdges)if(t.target!==t.source||t.source!==n)return!1;return!0}isConsistent(){for(let n of this.nodeMap.values())if(!this.nodeIsConsistent(n))return!1;return!0}},Be=class wi extends sn{constructor(t="__graph__"){super(t),this.nodeCollection=new Bm}remove(t){this.nodeCollection.remove(t)}removeSubgraph(){let t=this.parent;t&&t.removeNode(this);for(let e of this.outGoingEdges())e.attachedAtSource?e.node.removeOutEdge(e.edge):e.node.removeInEdge(e.edge)}*outGoingEdges(){for(let t of this.outEdges){let e=t.target;this.isAncestor(e)||(yield{edge:t,node:e,attachedAtSource:!1})}for(let t of this.inEdges){let e=t.source;this.isAncestor(e)||(yield{edge:t,node:e,attachedAtSource:!0})}for(let t of this.nodesBreadthFirst){for(let e of t.outEdges){let i=e.target;i!==this&&(this.isAncestor(i)||(yield{edge:e,node:i,attachedAtSource:!1}))}for(let e of t.inEdges){let i=e.source;i!==this&&(this.isAncestor(i)||(yield{edge:e,node:i,attachedAtSource:!0}))}}}isAncestor(t){for(let e of t.getAncestors())if(e===this)return!0;return!1}*getClusteredConnectedComponents(){let t=new Set,e=new Hu.Queue;for(let i of this.nodesBreadthFirst){if(t.has(i))continue;t.add(i),e.enqueue(i);let r=new Set;do{let s=e.dequeue();s.parent===this&&r.add(s);for(let o of this.reachableFrom(s))t.has(o)||(t.add(o),e.enqueue(o))}while(e.length>0);yield Array.from(r)}}*reachableFrom(t){for(let e of t.outEdges)yield e.target;for(let e of t.inEdges)yield e.source;t instanceof wi&&(yield*t.shallowNodes),t.parent!=this&&(yield t.parent)}hasSomeAttrOnIndex(t){for(let e of this.nodesBreadthFirst)if(e.getAttr(t))return!0;for(let e of this.deepEdges)if(e.getAttr(t))return!0;return!1}*graphs(){for(let t of this.nodeCollection.graphs)yield t}noEmptySubgraphs(){for(let t of this.subgraphsBreadthFirst())if(t.shallowNodeCount===0)return!1;return!0}hasSubgraphs(){for(let t of this.shallowNodes)if(t instanceof wi)return!0;return!1}*subgraphsBreadthFirst(){for(let t of this.nodesBreadthFirst)t instanceof wi&&(yield t)}isEmpty(){return this.shallowNodeCount===0}setEdge(t,e){let i=this.nodeCollection.findShallow(t);if(i==null)return;let r=this.nodeCollection.findShallow(e);if(r!=null)return new Yn(i,r)}get shallowNodes(){return this.nodeCollection.nodesShallow}get nodesBreadthFirst(){return this.nodesBreadthFirst_()}*nodesBreadthFirst_(){for(let t of this.nodeCollection.nodesShallow)yield t,t instanceof wi&&(yield*t.nodesBreadthFirst)}findNodeRecursive(t){let e=this.nodeCollection.findShallow(t);if(e)return e;for(let i of this.shallowNodes)if(i instanceof wi){let r=i.findNodeRecursive(t);if(r)return r}return null}findNode(t){return this.nodeCollection.findShallow(t)}get shallowEdges(){return this.nodeCollection.edges}get deepEdges(){return this.deepEdgesIt()}*deepEdgesIt(){for(let t of this.nodesBreadthFirst){for(let e of t.outEdges)yield e;for(let e of t.selfEdges)yield e;for(let 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(let e of t.outEdges)e.target.inEdges.delete(e);for(let e of t.inEdges)e.source.outEdges.delete(e);this.nodeCollection.remove(t);for(let e of this.subgraphsBreadthFirst())e.removeNode(t)}addNode(t){return Wt.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(let e of this.shallowNodes)e instanceof wi&&(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(let e of this.nodesBreadthFirst)t+=e.outDegree+e.selfDegree;return t}eachNodeIdIsUnique(){let t=new Set;for(let e of this.nodesBreadthFirst){if(t.has(e.id))return!1;t.add(e.id)}return!0}*allElements(){for(let t of this.allSuccessorsWidthFirst()){yield t;for(let e of t.selfEdges)yield e;for(let e of t.outEdges)yield e;for(let e of t.inEdges)this.isAncestor(e.source)||(yield e)}yield*this.edges}*allSuccessorsWidthFirst(){for(let t of this.shallowNodes)yield t;for(let t of this.shallowNodes)t instanceof wi&&(yield*t.allSuccessorsWidthFirst())}*allSuccessorsDepthFirst(){for(let t of this.shallowNodes)t instanceof wi&&(yield*t.allSuccessorsDepthFirst()),yield t}};function*Rm(n){let t=new Set,e=new Hu.Queue;for(let s of n.shallowNodes){if(t.has(s))continue;let o=new Array;for(r(s,e,t);e.length>0;){let a=e.dequeue();o.push(a);for(let l of i(a))r(l,e,t)}yield o}function*i(s){for(let o of s.outEdges)yield o.target;for(let o of s.inEdges)yield o.source}function r(s,o,a){a.has(s)||(o.enqueue(s),a.add(s))}}function ta(n,t){return t.has(n.source)&&t.has(n.target)}var ke=class Hr extends Tt{clone(){let t=new Hr(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}}static{this.minHeight=2}static{this.minWidth=3}get node(){return this.entity}get boundaryCurve(){return this._boundaryCurve}set boundaryCurve(t){t!=null&&t.boundingBox&&(t.boundingBox.height<Hr.minHeight||t.boundingBox.width<Hr.minWidth)&&(t=ce.mkCircle(Hr.minWidth,t.boundingBox.center)),this._boundaryCurve=t}get id(){return this.node.id}toString(){return this.id}static mkNode(t,e){let i=new Hr(e);return i.boundaryCurve=t,i}get center(){return this.boundaryCurve.boundingBox.center}set center(t){let e=t.sub(this.center);this.boundaryCurve.translate(e)}fitBoundaryCurveToTarget(t){if(this.boundaryCurve!=null){let e=ce.isRoundedRect(this.boundaryCurve);if(e==null){let i=t.width/this.boundaryCurve.boundingBox.width,r=t.height/this.boundaryCurve.boundingBox.height;this.boundaryCurve=this.boundaryCurve.scaleFromOrigin(i,r),this.boundaryCurve.translate(t.center.sub(this.boundaryCurve.boundingBox.center))}else this.boundaryCurve=ce.mkRectangleWithRoundedCorners(t.width,t.height,e.radX,e.radY,t.center)}}static getGeom(t){return t.getAttr(tr.GeomObjectIndex)}*inEdges(){for(let t of this.node.inEdges)yield Tt.getGeom(t)}*outEdges(){for(let t of this.node.outEdges)yield Tt.getGeom(t)}*selfEdges(){for(let t of this.node.selfEdges)yield Tt.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(){let t=this.node.parent;if(t==null)return!1;let e=Tt.getGeom(t);return e==null?!1:e.isCollapsed?!0:e.underCollapsedGraph()}*getAncestors(){for(let t of this.node.getAncestors())yield Tt.getGeom(t)}},Oh=class Wu{static{this.GoldenRatio=(1+Math.sqrt(5))/2}static{this.GoldenRatioRemainder=2-Wu.GoldenRatio}},Fm=class fr extends Nt{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}static{this.MaxSteps=1e3}Pack(t,e,i){let r=fr.GetGoldenSectionStep(t,e),s=Math.max(i/10,(e-t)/fr.MaxSteps);e+=s,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&&fr.GoldenSectionSearch(a=>this.PackLimit(a),t,r,e,s);let 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){let 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,r,s){if(Math.abs(e-r)<s)return t(e)<t(r)?e:r;let o=fr.GetGoldenSectionStep(i,r),a=t(i),l=t(o),h=()=>fr.GoldenSectionSearch(t,o,i,e,s),u=()=>fr.GoldenSectionSearch(t,i,o,r,s);if(l<a)return u();if(l>a)return h();let d=u(),c=h();return t(c)<t(d)?c:d}static GetGoldenSectionStep(t,e){return t<e?t+Oh.GoldenRatioRemainder*(e-t):t-Oh.GoldenRatioRemainder*(t-e)}},Nm=ct(ti(),1),Gm=class extends Nt{get PackedWidth(){return this.packedWidth}set PackedWidth(n){this.packedWidth=n}get PackedHeight(){return this.packedHeight}set PackedHeight(n){this.packedHeight=n}get PackedAspectRatio(){return this.PackedWidth/this.PackedHeight}getRects(){let n=[];for(let[t,e]of this.rectsToCenters)t.center=e,n.push(t);return n}},Lh=class zu extends Gm{constructor(t,e,i=!1){super(null),this.rectsToCenters=new Map,this.rectanglesByDescendingHeight=i?t:zu.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;let t=new Nm.Stack,e=!1,i=0,r=0,s=0,o=this.rectanglesByDescendingHeight;for(let a=0;e||a<o.length;){let l=o[a],h=t.length>0?t.top:null;if(h==null||h.right+l.width<=this.wrapWidth&&i+l.height<=h.top){let u=new g(h?h.right:0,i).add(new g(l.width/2,l.height/2));l.center=u,this.rectsToCenters.set(l,u),r=Math.max(r,l.right),s=Math.max(s,l.top),t.push(l),e=!1}else i=h.top,t.pop(),e=!0;e||a++}this.PackedWidth=r,this.PackedHeight=s}},qu=class extends Fm{constructor(n,t){super(Lh.SortRectangles(n),t),this.createPacking=(e,i)=>new Lh(e,i,!0)}run(){let n=Number.MAX_VALUE,t=0,e=0;for(let i of this.rectangles){let r=i.width;e+=r,n=Math.min(n,r),t=Math.max(t,r)}this.Pack(t,e,n)}},Dm=class extends it{constructor(n){super(n),this.radX=n.radX,this.radY=n.radY,this.roundedRect_=ce.mkRectangleWithRoundedCorners(this.width,this.height,n.radX,n.radY,this.center)}onUpdated(){this.isEmpty||(this.roundedRect_=ce.mkRectangleWithRoundedCorners(this.width,this.height,this.radX,this.radY,this.center))}isOk(){return this.isEmpty()?!0:this.roundedRect_.boundingBox.equalEps(this)}setRect(n){this.left=n.left,this.right=n.right,this.top=n.top,this.bottom=n.bottom,this.isEmpty()||(this.roundedRect_=ce.mkRectangleWithRoundedCorners(n.width,n.height,this.radX,this.radY,this.center))}};function Mm(n,t){let e=t.map(s=>[s,s.boundingBox]),i=e.map(s=>s[1]),r=new qu(i,1.5);r.run();for(let[s,o]of e){let a=o.leftBottom.sub(s.boundingBox.leftBottom);s.translate(a)}n.boundingBox=new it({left:0,bottom:0,right:r.PackedWidth,top:r.PackedHeight})}var we=class Wr extends ke{constructor(t){super(t),this.margins={left:10,top:10,bottom:10,right:10},this.radX=10,this.radY=10,this.rrect=new Dm({left:0,right:-1,top:20,bottom:0,radX:this.radX,radY:this.radY})}isAncestor(t){return this.graph.isAncestor(t.node)}deepTranslate(t){for(let e of this.nodesBreadthFirst){e instanceof Wr?e.boundingBox=e.boundingBox.translate(t):e.translate(t);for(let i of e.selfEdges())i.translate(t);for(let i of e.outEdges())this.graph.isAncestor(i.target.node)&&i.translate(t)}this.boundingBox=this.boundingBox.translate(t)}clone(){let t=new Wr(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(){let t=it.mkEmpty();for(let e of this.shallowNodes)t.addRecSelf(e.boundingBox);return t.padEverywhere(this.margins),t}*allSuccessorsWidthFirst(){for(let t of this.graph.allSuccessorsWidthFirst())yield ke.getGeom(t)}static getGeom(t){return Tt.getGeom(t)}edgeCurveOrArrowheadsIntersectRect(t,e){for(let s of t.sourceArrowheadPoints(25))if(e.contains(s))return!0;for(let s of t.targetArrowheadPoints(25))if(e.contains(s))return!0;let i=t.curve,r=e.perimeter();return G.intersectionOne(i,r,!1)!=null||G.PointRelativeToCurveLocation(i.start,r)===2}isEmpty(){return this.graph.isEmpty()}setSettingsRecursively(t){this.layoutSettings=t;for(let e of this.nodesBreadthFirst){let 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(let e of this.shallowNodes)e.transform(t);for(let 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(let t of this.graph.nodesBreadthFirst)yield Tt.getGeom(t)}setEdge(t,e){let i=this.graph.setEdge(t,e);return new Fe(i)}getPumpedGraphWithMarginsBox(){let t={b:it.mkEmpty()};return nl(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 g(0,0)}set center(t){let e=t.sub(this.center),i=new Oe(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(let t of this.graph.shallowNodes)yield Tt.getGeom(t)}get deepEdges(){return this.deepEdgesIt()}*deepEdgesIt(){for(let t of this.graph.deepEdges)yield Tt.getGeom(t)}get shallowEdges(){return this.shallowEdgesIt()}*shallowEdgesIt(){for(let t of this.graph.shallowEdges)yield Tt.getGeom(t)}static mk(t,e=new fi(0,0)){let i=new Wr(new Be(t));return i.labelSize=e,i}get Clusters(){return this.subgraphs()}*subgraphs(){for(let t of this.graph.subgraphsBreadthFirst())yield Tt.getGeom(t)}static mkWithGraphAndLabel(t,e){let i=new Wr(t);return i.labelSize=e,i}get deepNodeCount(){let t=0;for(let e of this.graph.nodesBreadthFirst)t++;return t}get subgraphsDepthFirst(){return this.getSubgraphsDepthFirst()}*getSubgraphsDepthFirst(){for(let t of this.graph.allSuccessorsDepthFirst())t instanceof Be&&(yield Wr.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){let e=this.graph.liftNode(t.node);return e?Tt.getGeom(e):null}findNode(t){let e=this.graph.findNode(t);return e?Tt.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 nl(n,t){for(let i of n.shallowEdges){if(!e(i))continue;let r=i.curve.boundingBox;if(t.b.addRecSelf(r),i.edge.label!=null){let s=Tt.getGeom(i.edge.label);s&&t.b.addRecSelf(s.boundingBox)}}for(let i of n.shallowNodes)"shallowEdges"in i&&nl(i,t),!(i.underCollapsedGraph()||!i.boundingBox)&&t.b.addRecSelf(i.boundingBox);n instanceof we&&n.addLabelToGraphBB(t.b);function e(i){if(i==null||i.curve==null||i.underCollapsedGraph())return!1;if(n instanceof we){let r=n.entity;return r.isAncestor(i.source.entity)&&r.isAncestor(i.target.entity)}else return!0}}var sl=class{},Le=class Uu extends sl{constructor(t){super(),this.adjustmentAngle=Math.PI/10,this.hookSize=9,this.curve=t,this.location=this.curve().start}mk(t,e){let i=new Uu(t);return i.HookSize=e,i}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}},ve=class extends sl{constructor(n,t){super(),this.curve=this.curve,this.location=t.clone()}get Location(){return this.location}set Location(n){this.location=n}Translate(n){this.location=this.location.add(n)}get Curve(){return this.curve}set Curve(n){this.curve=n}},Si=class ju extends ve{static mk(t,e){return new ju(t,e,new g(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()}},Pi=class Qu extends Si{get LoosePolyline(){return this.loosePolyline}set LoosePolyline(t){this.loosePolyline=t}constructor(t,e,i=new g(0,0)){super(t,e,i)}static mk(t,e){return new Qu(t,e)}},Bh=ct(bi(),1),Ir=class Xu{constructor(t=null){this.parents=new Set,this.children=new Set,this.ports=new Set,this.BoundaryCurve=t}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 Xu(null)}get IsGroup(){return this.children.size>0}*Descendants(){let t=new Bh.Queue;for(let e of this.Children)t.enqueue(e);for(;t.length>0;){let e=t.dequeue();yield e;for(let i of e.Children)t.enqueue(i)}}*Ancestors(){let t=new Bh.Queue;for(let e of this.Parents)t.enqueue(e);for(;t.length>0;){let e=t.dequeue();yield e;for(let 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"}},io=class extends Ir{get BoundaryCurve(){return this.node.boundaryCurve}set BoundaryCurve(n){if(n)throw new Error("Cannot set BoundaryCurve directly for RelativeShape")}constructor(n){super(null),this.node=n}},_r=class Ii{static GetShapes(t,e=Array.from(t.shallowEdges)){let i=new Map;Yu(t,i);for(let r of e){let s=i.get(r.source);s&&r.sourcePort!=null&&s.Ports.add(r.sourcePort),s=i.get(r.target),s&&r.targetPort!=null&&s.Ports.add(r.targetPort)}return Array.from(i.values())}static CreateShapeWithCenterPort(t){let e=new io(t),i=Si.mk(()=>t.boundaryCurve,()=>t.center);e.Ports.add(i);for(let r of t.inEdges())Ii.FixPortAtTarget(i,r);for(let r of t.outEdges())Ii.FixPortAtSource(i,r);for(let r of t.selfEdges())Ii.FixPortAtSource(i,r),Ii.FixPortAtTarget(i,r);return e}static CreateShapeWithClusterBoundaryPort(t){let e=new io(t),i=Pi.mk(()=>t.boundaryCurve,()=>t.center);e.Ports.add(i);let r;for(let s of t.inEdges())s.EdgeToAncestor()===2?(r==null&&(r=new Le(()=>t.boundaryCurve)),s.targetPort=r):Ii.FixPortAtTarget(i,s);for(let s of t.outEdges())s.EdgeToAncestor()===1?(r==null&&(r=new Le(()=>t.boundaryCurve)),s.sourcePort=r):Ii.FixPortAtSource(i,s);for(let s of t.selfEdges())Ii.FixPortAtSource(i,s),Ii.FixPortAtTarget(i,s);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 Yu(n,t){for(let e of n.shallowNodes)if(e instanceof we){let i=_r.CreateShapeWithClusterBoundaryPort(e);t.set(e,i);let r=e;if(!r.isCollapsed){Yu(r,t);for(let s of r.shallowNodes)i.AddChild(t.get(s))}}else t.set(e,_r.CreateShapeWithCenterPort(e))}var ge=class De{constructor(){this.length=De.defaultArrowheadLength,this.width=0,this.length=De.defaultArrowheadLength}static{this.defaultArrowheadLength=5}toJSON(){let t="{";return this.tipPosition&&(t+='"tipPosition": '+this.tipPosition.toJSON()),t+="}",t}clone(){let t=new De;return t.length=this.length,t.width=this.width,t.tipPosition=this.tipPosition,t}static calculateArrowheads(t){if(t.sourceArrowhead==null&&t.targetArrowhead==null)return!0;let e=De.findTrimStartForArrowheadAtSource(t);if(e==null)return!1;let i=De.findTrimEndForArrowheadAtTarget(t);if(i==null||e>i-x.intersectionEpsilon||G.closeIntersectionPoints(t.curve.value(e),t.curve.value(i)))return!1;let r=t.curve.trim(e,i);return r==null?!1:(t.sourceArrowhead!=null&&(t.sourceArrowhead.tipPosition=t.curve.start),t.targetArrowhead!=null&&(t.targetArrowhead.tipPosition=t.curve.end),t.curve=r,!0)}static getIntersectionsWithArrowheadCircle(t,e,i){let r=Dt.mkFullEllipseNNP(e,e,i);return G.getAllIntersections(r,t,!0)}static findTrimEndForArrowheadAtTarget(t){let e=x.distanceEpsilon*x.distanceEpsilon,i=t.curve.parEnd;if(t.targetArrowhead==null||t.targetArrowhead.length<=x.distanceEpsilon)return i;let r=t.curve,s=t.targetArrowhead.length,o,a,l=10;do{if(l--,l===0)return;a=De.getIntersectionsWithArrowheadCircle(r,s,r.end),i=a.length!==0?Math.max(...a.map(h=>h.par1)):r.parEnd,o=t.curve.value(i),s/=2}while(o.sub(r.start).lengthSquared<e||a.length===0);return i}static findTrimStartForArrowheadAtSource(t){if(t.sourceArrowhead==null||t.sourceArrowhead.length<=x.distanceEpsilon)return t.curve.parStart;let e=x.distanceEpsilon*x.distanceEpsilon,i=t.sourceArrowhead.length,r,s=t.curve,o,a=10,l;for(;--a>0;){if(o=De.getIntersectionsWithArrowheadCircle(s,i,s.start),o.length===0)return s.parStart;if(l=Math.min(...o.map(h=>h.par1)),r=o.filter(h=>h.par1===l)[0].x,r.sub(s.end).lengthSquared>=e)return l;i/=2}}static trimSplineAndCalculateArrowheads(t,e,i){return De.trimSplineAndCalculateArrowheadsII(t,t.source.boundaryCurve,t.target.boundaryCurve,e,i)}static trimSplineAndCalculateArrowheadsII(t,e,i,r,s){if(t.curve=G.trimEdgeSplineWithNodeBoundaries(e,i,r,s),t.curve==null)return!1;if((t.sourceArrowhead==null||t.sourceArrowhead.length<x.distanceEpsilon)&&(t.targetArrowhead==null||t.targetArrowhead.length<x.distanceEpsilon))return!0;let o=!1,a=t.sourceArrowhead!=null?t.sourceArrowhead.length:0,l=t.targetArrowhead!=null?t.targetArrowhead.length:0,h=t.curve.end.sub(t.curve.start).length;t.sourceArrowhead!=null&&(t.sourceArrowhead.length=Math.min(h,a)),t.targetArrowhead!=null&&(t.targetArrowhead.length=Math.min(h,l));let u=10;for(;(t.sourceArrowhead!=null&&t.sourceArrowhead.length>x.intersectionEpsilon||t.targetArrowhead!=null&&t.targetArrowhead.length>x.intersectionEpsilon)&&!o&&(o=De.calculateArrowheads(t),o||(t.sourceArrowhead!=null&&(t.sourceArrowhead.length*=.5),t.targetArrowhead!=null&&(t.targetArrowhead.length*=.5)),u--,u!==0););return o||(t.sourceArrowhead!=null&&(t.sourceArrowhead.tipPosition=r.start),t.targetArrowhead!=null&&(t.targetArrowhead.tipPosition=r.end)),t.sourceArrowhead!=null&&(t.sourceArrowhead.length=a),t.targetArrowhead!=null&&(t.targetArrowhead.length=l),o}static createBigEnoughSpline(t){let e=t.source.center,i=t.target.center,r=i.sub(e),s=r.length,o;s<.001?(o=new g(1,0),i=e.add(o.rotate(Math.PI/2))):o=r.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 l=1;l<1e4;l=l*2){let h=G.createBezierSegN(e,i,o,l);if(De.trimSplineAndCalculateArrowheadsII(t,t.source.boundaryCurve,t.target.boundaryCurve,h,!1))return}De.createEdgeCurveWithNoTrimming(t,e,i)}static createEdgeCurveWithNoTrimming(t,e,i){let r=i.sub(e).normalize(),s=e,o=i,a=t.targetArrowhead;a!=null&&(a.tipPosition=i,o=i.sub(r.mul(a.length)));let l=t.sourceArrowhead;l!=null&&(l.tipPosition=e,s=e.add(r.mul(l.length))),t.curve=D.mkPP(s,o)}},Vm=ct(se(),1),km=class{constructor(n,t){this.constrained=!1,this.Capacity=1e6,Ae.AbovePP(n.point,t.point)===1?(this.upperSite=n,this.lowerSite=t):(this.lowerSite=n,this.upperSite=t),this.upperSite.AddEdgeToSite(this)}get CcwTriangle(){return this.ccwTriangle}set CcwTriangle(n){this.ccwTriangle=n}get CwTriangle(){return this.cwTriangle}set CwTriangle(n){this.cwTriangle=n}GetOtherTriangle_c(n){return this.cwTriangle.Contains(n)?this.ccwTriangle:this.cwTriangle}IsAdjacent(n){return n===this.upperSite||n===this.lowerSite}GetOtherTriangle_T(n){return this.ccwTriangle===n?this.cwTriangle:this.ccwTriangle}toString(){return Vm.String.format("({0},{1})",this.upperSite,this.lowerSite)}OtherSite(n){return this.upperSite===n?this.lowerSite:this.upperSite}},ea=class Ju{constructor(t){this.Owner=null,this.InEdges=new Array,this.point=t}cleanRemovedEdges(){for(let t of this.Edges)t.CcwTriangle===null&&t.CwTriangle===null&&this.Edges.splice(this.Edges.indexOf(t),1)}static mkSO(t,e){let i=new Ju(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(let 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{let 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{let 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()}},Rh=ct(ti(),1),Mr=class{get x(){return this.LeftSite.point.x}constructor(n,t){this.RightSite=t.upperSite===n?t.lowerSite:t.upperSite,this.LeftSite=n,this.Edge=t}toString(){return"("+this.LeftSite.toString()+", "+this.Edge.toString()+","+this.RightSite.toString()+")"}},Fh=class{has(n){return n===this.item0||n===this.item1||n===this.item2}index(n){return n===this.item0?0:n===this.item1?1:n===this.item2?2:-1}getItem(n){switch(n){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(n,t){switch(n){case 0:case 3:case-3:this.item0=t;break;case 1:case 4:case-2:this.item1=t;break;case 2:case 5:case-1:this.item2=t;break;default:throw new Error}}[Symbol.iterator](){return this.GetEnumerator()}*GetEnumerator(){yield this.item0,yield this.item1,yield this.item2}},dr=class qi{constructor(){this.Edges=new Fh,this.Sites=new Fh}containsPoint(t){return qi.PointLocationForTriangle(t,this)!==0}static PointLocationForTriangle(t,e){let i=!1;for(let r=0;r<3;r++){let s=g.signedDoubledTriangleArea(t,e.Sites.getItem(r).point,e.Sites.getItem(r+1).point);if(s<-x.distanceEpsilon)return 0;s<x.distanceEpsilon&&(i=!0)}return i?1:2}intersectsLine(t,e,i){if(qi.PointLocationForTriangle(t,this)!=0||qi.PointLocationForTriangle(e,this)!=0)return!0;for(let r of this.Edges)if(this.abIntersectsTrianglSide(t,e,r))return!0;return!1}abIntersectsTrianglSide(t,e,i){return Cu(t,e,i.lowerSite.point,i.upperSite.point)}static mkSSSD(t,e,i,r){let s=g.getTriangleOrientation(t.point,e.point,i.point),o=new qi;switch(s){case 1:o.FillCcwTriangle(t,e,i,r);break;case 0:o.FillCcwTriangle(t,i,e,r);break;default:throw new Error}return o}static mkSED(t,e,i){let r=new qi;switch(g.getTriangleOrientation(e.upperSite.point,e.lowerSite.point,t.point)){case 1:e.CcwTriangle=r,r.Sites.setItem(0,e.upperSite),r.Sites.setItem(1,e.lowerSite);break;case 0:e.CwTriangle=r,r.Sites.setItem(0,e.lowerSite),r.Sites.setItem(1,e.upperSite);break;default:throw new Error}return r.Edges.setItem(0,e),r.Sites.setItem(2,t),r.CreateEdge(1,i),r.CreateEdge(2,i),r}static mkSSSEE(t,e,i,r,s,o){let a=qi.mkSSSD(t,e,i,o);return a.Edges.setItem(0,r),a.Edges.setItem(1,s),a.BindEdgeToTriangle(t,r),a.BindEdgeToTriangle(e,s),a.CreateEdge(2,o),a}BindEdgeToTriangle(t,e){t===e.upperSite?e.CcwTriangle=this:e.CwTriangle=this}FillCcwTriangle(t,e,i,r){this.Sites.setItem(0,t),this.Sites.setItem(1,e),this.Sites.setItem(2,i);for(let s=0;s<3;s++)this.CreateEdge(s,r)}CreateEdge(t,e){let i=this.Sites.getItem(t),r=this.Sites.getItem(t+1),s=e(i,r);this.Edges.setItem(t,s),this.BindEdgeToTriangle(i,s)}Contains(t){return this.Sites.has(t)}OppositeEdge(t){let e=this.Sites.index(t);return this.Edges.getItem(e+1)}OppositeSite(t){let e=this.Edges.index(t);return this.Sites.getItem(e+2)}BoundingBox(){let t=it.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,r,s,o){let a=new qi;return a.Sites.setItem(0,t),a.Sites.setItem(1,e),a.Sites.setItem(2,i),a.Edges.setItem(0,r),a.Edges.setItem(1,s),a.BindEdgeToTriangle(t,r),a.BindEdgeToTriangle(e,s),a.CreateEdge(2,o),a}toString(){return this.Sites.getItem(0).toString()+","+this.Sites.getItem(1).toString()+","+this.Sites.getItem(2).toString()}},Nh=class{constructor(n){this.Edge=n}},$m=class ue extends Nt{constructor(t,e,i,r){if(super(null),this.front=new Re((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=r;let s=dr.mkSSSD(e,i,this.listOfSites[0],r);this.triangles.add(s),this.front.insert(new Mr(e,s.Edges.getItem(2))),this.front.insert(new Mr(this.listOfSites[0],s.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{let 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,g.getTriangleOrientation(e.Start.point,e.End.point,i.End.point)===1)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(let t of this.triangles)for(let e of t.Edges)if(e.GetOtherTriangle_T(t)==null)return e;return null}CreateDoubleLinkedListOfPerimeter(){let t=this.FindFirsePerimeterEdge(),e=t,i=null,r,s=null,o=new Array;do r=ue.CreatePerimeterElementFromEdge(e),o.push(D.mkPP(r.Start.point,r.End.point)),e=ue.FindNextEdgeOnPerimeter(e),s!=null?(r.Prev=s,s.Next=r):i=r,s=r;while(e!==t);return i.Prev=r,r.Next=i,i}static FindNextEdgeOnPerimeter(t){let e=t.CwTriangle??t.CcwTriangle;for(t=e.Edges.getItem(e.Edges.index(t)+2);t.CwTriangle!=null&&t.CcwTriangle!=null;)e=t.GetOtherTriangle_T(e),t=e.Edges.getItem(e.Edges.index(t)+2);return t}static CreatePerimeterElementFromEdge(t){let e=new Nh(t);return t.CwTriangle!=null?(e.Start=t.upperSite,e.End=t.lowerSite):(e.End=t.upperSite,e.Start=t.lowerSite),e}RemoveP1AndP2Triangles(){let t=new Set;for(let e of this.triangles)(e.Sites.has(this.p_1)||e.Sites.has(this.p_2))&&t.add(e);for(let e of t)ue.RemoveTriangleWithEdges(this.triangles,e)}static RemoveTriangleWithEdges(t,e){t.delete(e);for(let i of e.Edges)i.CwTriangle===e?i.CwTriangle=null:i.CcwTriangle=null,i.CwTriangle==null&&i.CcwTriangle==null&&va(i.upperSite.Edges,i)}static RemoveTriangleButLeaveEdges(t,e){t.delete(e);for(let 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++){let i=t.Edges[e];i.constrained&&this.EdgeEvent(i)}}EdgeEvent(t){ue.EdgeIsProcessed(t)||(this.traversingEdge=t,this.runEdgeInserter())}static EdgeIsProcessed(t){return t.CwTriangle!=null||t.CcwTriangle!=null}ShowFrontWithSite(t,e=null){let i=new Array;if(t.Edges!=null)for(let r of t.Edges)i.push(It.mkDebugCurveTWCI(200,.8,r.constrained?"Pink":"Brown",D.mkPP(r.upperSite.point,r.lowerSite.point)));i.push(It.mkDebugCurveTWCI(200,1,"Brown",Dt.mkFullEllipseNNP(.5,.5,t.point)));for(let r of this.triangles)for(let s=0;s<3;s++){let o=r.Edges.getItem(s);i.push(It.mkDebugCurveTWCI(o.constrained?155:100,o.constrained?.8:.4,o.constrained?"Pink":"Navy",D.mkPP(o.upperSite.point,o.lowerSite.point)))}if(e!=null)for(let r of e)i.push(It.mkDebugCurveTWCI(100,.5,"Red",r));for(let r of this.front)i.push(It.mkDebugCurveTWCI(100,5.5,"Green",D.mkPP(r.Edge.upperSite.point,r.Edge.lowerSite.point)))}Show(t){ue.ShowCdt(Array.from(this.triangles.values()),this.front,null,null,[],t)}static ShowCdt(t,e,i,r,s,o){let a=new Array;if(i!=null)for(let l of i)a.push(It.mkDebugCurveTWCI(200,.1,"Red",l));if(r!=null)for(let l of r)a.push(It.mkDebugCurveTWCI(200,.1,"Blue",l));if(e!=null)for(let l of e)a.push(It.mkDebugCurveTWCI(200,.1,"Green",D.mkPP(l.Edge.upperSite.point,l.Edge.lowerSite.point)));for(let l of t)for(let h=0;h<3;h++){let u=l.Edges.getItem(h);a.push(ue.GetDebugCurveOfCdtEdge(u))}a=a.concat(s)}static GetDebugCurveOfCdtEdge(t){return t.CcwTriangle==null||t.CwTriangle==null?It.mkDebugCurveTWCI(255,.5,t.constrained?"Brown":"Black",D.mkPP(t.upperSite.point,t.lowerSite.point)):It.mkDebugCurveTWCI(200,t.constrained?.8:.2,t.constrained?"Pink":"Navy",D.mkPP(t.upperSite.point,t.lowerSite.point))}PointEvent(t){let e=this.ProjectToFront(t),i={rightSite:null},r=e.item.x+x.distanceEpsilon<t.point.x?this.MiddleCase(t,e,i):this.LeftCase(t,e,i),s=this.InsertSiteIntoFront(r,t,i.rightSite);this.TriangulateEmptySpaceToTheRight(s),s=ue.FindNodeInFrontBySite(this.front,r),this.TriangulateEmptySpaceToTheLeft(s)}LeftCase(t,e,i){let r=e.item;this.InsertAndLegalizeTriangle(t,r);let s=this.front.previous(e),o=s.item.LeftSite;i.rightSite=e.item.RightSite,this.InsertAndLegalizeTriangle(t,s.item),this.front.deleteNodeInternal(s);let a=this.front.remove(r);return o}MiddleCase(t,e,i){let r=e.item.LeftSite;return i.rightSite=e.item.RightSite,this.InsertAndLegalizeTriangle(t,e.item),this.front.deleteNodeInternal(e),r}TriangulateEmptySpaceToTheLeft(t){let e=t.item.RightSite,i=this.front.previous(t);for(;i!=null;){let r=i.item,s=r.LeftSite,o=r.RightSite;if(o.point.sub(e.point).dot(s.point.sub(o.point))<0)t=this.ShortcutTwoFrontElements(i,t),i=this.front.previous(t);else{this.TryTriangulateBasinToTheLeft(t);break}}}ShortcutTwoListElements(t){let e=t.Next,i=dr.mkSSSEE(t.Start,t.End,e.End,t.Edge,e.Edge,this.createEdgeDelegate);this.triangles.add(i);let r=i.Edges.getItem(2);this.LegalizeEdge(t.Start,i.OppositeEdge(t.Start)),i=r.CcwTriangle??r.CwTriangle,this.LegalizeEdge(e.End,i.OppositeEdge(e.End));let s=new Nh(r);return s.Start=t.Start,s.End=e.End,t.Prev.Next=s,s.Prev=t.Prev,s.Next=e.Next,e.Next.Prev=s,s}ShortcutTwoFrontElements(t,e){let i=t.item,r=e.item,s=dr.mkSSSEED(i.LeftSite,i.RightSite,r.RightSite,i.Edge,r.Edge,this.createEdgeDelegate);this.triangles.add(s),this.front.deleteNodeInternal(t),this.front.remove(r);let o=s.Edges.getItem(2);return this.LegalizeEdge(i.LeftSite,s.OppositeEdge(i.LeftSite)),s=o.CcwTriangle??o.CwTriangle,this.LegalizeEdge(r.RightSite,s.OppositeEdge(r.RightSite)),this.front.insert(new Mr(i.LeftSite,o))}TryTriangulateBasinToTheLeft(t){if(!ue.DropsSharpEnoughToTheLeft(t.item))return;let e=new Rh.Stack;for(e.push(t.item.LeftSite);;){let i=e.pop();t=ue.FindNodeInFrontBySite(this.front,i);let r=this.front.previous(t);if(r==null)return;if(g.getTriangleOrientation(r.item.LeftSite.point,t.item.LeftSite.point,t.item.RightSite.point)==1)e.push(r.item.LeftSite),this.ShortcutTwoFrontElements(r,t);else if(t.item.LeftSite.point.y>t.item.RightSite.point.y)e.push(r.item.LeftSite);else{if(r.item.LeftSite.point.y<=r.item.RightSite.point.y)return;e.push(r.item.LeftSite)}}}static DropsSharpEnoughToTheLeft(t){let e=t.Edge;if(t.RightSite!==e.upperSite)return!1;let i=e.lowerSite.point.sub(e.upperSite.point);return i.x>=.5*i.y}InsertSiteIntoFront(t,e,i){let r=null,s=null;for(let o of e.Edges)if(s==null&&o.lowerSite===t&&(s=o),r==null&&o.lowerSite===i&&(r=o),s!=null&&r!=null)break;return this.front.insert(new Mr(t,s)),this.front.insert(new Mr(e,r))}TriangulateEmptySpaceToTheRight(t){let e=t.item.LeftSite.point,i=this.front.next(t);for(;i!=null;){let r=i.item,s=r.LeftSite,o=r.RightSite;if(s.point.sub(e).dot(o.point.sub(s.point))<0)t=this.ShortcutTwoFrontElements(t,i),i=this.front.next(t);else{this.TryTriangulateBasinToTheRight(t);break}}}TryTriangulateBasinToTheRight(t){if(!ue.DropsSharpEnoughToTheRight(t.item))return;let e=new Rh.Stack;for(e.push(t.item.LeftSite);;){let i=e.pop();t=ue.FindNodeInFrontBySite(this.front,i);let r=this.front.next(t);if(r==null)return;if(g.getTriangleOrientation(t.item.LeftSite.point,t.item.RightSite.point,r.item.RightSite.point)==1)this.ShortcutTwoFrontElements(t,r),e.push(i);else if(t.item.LeftSite.point.y>t.item.RightSite.point.y)e.push(t.item.RightSite);else{if(r.item.LeftSite.point.y>=r.item.RightSite.point.y)return;e.push(t.item.RightSite)}}}static DropsSharpEnoughToTheRight(t){let e=t.Edge;if(t.LeftSite!==e.upperSite)return!1;let 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){if(g.getTriangleOrientation(t.point,e.LeftSite.point,e.RightSite.point)!==2){let i=dr.mkSED(t,e.Edge,this.createEdgeDelegate);this.triangles.add(i),this.LegalizeEdge(t,i.Edges.getItem(0))}else{let i=e.Edge;va(i.upperSite.Edges,i);let r=i.CcwTriangle??i.CwTriangle,s=r.OppositeSite(i);ue.RemoveTriangleButLeaveEdges(this.triangles,r),r=dr.mkSSSD(e.LeftSite,s,t,this.createEdgeDelegate);let o=dr.mkSSSD(e.RightSite,s,t,this.createEdgeDelegate);this.triangles.add(r),this.triangles.add(o),this.LegalizeEdge(t,r.OppositeEdge(t)),this.LegalizeEdge(t,o.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){let i=e.CwTriangle.Edges.index(e);if(Gh(t,e.upperSite,e.CwTriangle.Sites.getItem(i+2),e.lowerSite)){let r=Dh(t,e);this.LegalizeEdge(t,r.CwTriangle.OppositeEdge(t)),this.LegalizeEdge(t,r.CcwTriangle.OppositeEdge(t))}}LegalizeEdgeForOtherCcwTriangle(t,e){let i=e.CcwTriangle.Edges.index(e);if(Gh(t,e.lowerSite,e.CcwTriangle.Sites.getItem(i+2),e.upperSite)){let r=Dh(t,e);this.LegalizeEdge(t,r.CwTriangle.OppositeEdge(t)),this.LegalizeEdge(t,r.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(){let t=new Set;for(let e of this.addedTriangles)for(let 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(let e of t)this.AddEdgeToFront(e)}AddEdgeToFront(t){let e=t.upperSite.point.x<t.lowerSite.point.x?t.upperSite:t.lowerSite;this.front.insert(new Mr(e,t))}TriangulatePolygon0(t,e,i,r){t.length>0&&this.TriangulatePolygon1(0,t.length-1,t,e,i,r)}TriangulatePolygon1(t,e,i,r,s,o){let a=i[t],l=t;for(let d=t+1;d<=e;d++){let c=i[d];u(c)&&(l=d,a=c)}let h=dr.mkSSSD(r,s,a,this.createEdgeDelegate);this.triangles.add(h),this.addedTriangles.push(h),t<l&&this.TriangulatePolygon1(t,l-1,i,r,a,o),l<e&&this.TriangulatePolygon1(l+1,e,i,a,s,o);function u(d){return o?xa(d,r,a,s):xa(d,r,s,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(let 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(g.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){let e=t.item.Edge,i=e.CcwTriangle??e.CwTriangle,r=i.Edges.index(e);for(let s=1;s<=2;s++){let o=i.Edges.getItem(s+r),a=Zi.sign(g.signedDoubledTriangleArea(o.lowerSite.point,this.a.point,this.b.point));if(Zi.sign(g.signedDoubledTriangleArea(o.upperSite.point,this.a.point,this.b.point))*a<=0){this.piercedTriangle=i,this.piercedEdge=o;break}}}FindMoreRemovedFromFrontElements(){for(let t of this.removedTriangles)for(let e of t.Edges)if(e.CcwTriangle==null&&e.CwTriangle==null){let i=e.upperSite.point.x<e.lowerSite.point.x?e.upperSite:e.lowerSite,r=ue.FindNodeInFrontBySite(this.front,i);r.item.Edge===e&&this.elementsToBeRemovedFromFront.push(r.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(){let t=this.piercedEdge.CwTriangle??this.piercedEdge.CcwTriangle,e=t.Edges.index(this.piercedEdge);for(let i=1;i<=2;i++){let r=t.Edges.getItem(i+e),s=Zi.sign(g.signedDoubledTriangleArea(r.lowerSite.point,this.a.point,this.b.point));if(Zi.sign(g.signedDoubledTriangleArea(r.upperSite.point,this.a.point,this.b.point))*s<=0){if(r.CwTriangle!=null&&r.CcwTriangle!=null){this.piercedTriangle=t,this.piercedEdge=r;break}this.piercedTriangle=null,this.piercedEdge=null;let o=r.upperSite.point.x<r.lowerSite.point.x?r.upperSite:r.lowerSite,a=ue.FindNodeInFrontBySite(this.front,o);o.point.x<this.a.point.x?this.piercedToTheLeftFrontElemNode=a:this.piercedToTheRightFrontElemNode=a,this.removePiercedTriangle(r.CwTriangle??r.CcwTriangle);break}}}removePiercedTriangle(t){this.triangles.delete(t);for(let 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(g.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(){let t=this.piercedToTheLeftFrontElemNode??this.piercedToTheRightFrontElemNode;return t!=null?t.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=[];let t=ue.FindNodeInFrontBySite(this.front,this.a),e=this.front.previous(t);if(g.pointToTheLeftOfLine(this.b.point,e.item.LeftSite.point,e.item.RightSite.point))this.piercedToTheLeftFrontElemNode=e;else if(g.pointToTheRightOfLine(this.b.point,t.item.RightSite.point,t.item.LeftSite.point))this.piercedToTheRightFrontElemNode=t;else for(let i of this.a.Edges){let r=i.CcwTriangle;if(r==null||g.pointToTheLeftOfLine(this.b.point,i.lowerSite.point,i.upperSite.point))continue;let s=r.Edges.index(i),o=r.Sites.getItem(s+2);if(g.pointToTheLeftOfLineOrOnLine(this.b.point,o.point,i.upperSite.point)){this.piercedEdge=r.Edges.getItem(s+1),this.piercedTriangle=r;break}}}};function va(n,t){if(n.length===0)return;let e=n.findIndex(i=>t===i);e>=0&&(e!==n.length-1&&(n[e]=n[n.length-1]),n.pop())}function Gh(n,t,e,i){return Hm(n,t,e,i)&&xa(n,t,e,i)}function Hm(n,t,e,i){return g.getTriangleOrientation(t.point,n.point,e.point)===0&&g.getTriangleOrientation(e.point,n.point,i.point)===0}function xa(n,t,e,i){let r=t.point.x-n.point.x,s=t.point.y-n.point.y,o=e.point.x-n.point.x,a=e.point.y-n.point.y,l=i.point.x-n.point.x,h=i.point.y-n.point.y,u=r*r+s*s,d=o*o+a*a,c=l*l+h*h;return r*(a*c-h*d)-o*(s*c-h*u)+l*(s*d-a*u)>x.tolerance}function Dh(n,t){let e,i;t.CcwTriangle.Contains(n)?(e=t.CcwTriangle,i=t.CwTriangle):(e=t.CwTriangle,i=t.CcwTriangle);let r=e.Edges.index(t),s=i.Edges.index(t),o=i.Sites.getItem(s+2),a=e.Edges.getItem(r+1),l=i.Edges.getItem(s+1),h=Ae.GetOrCreateEdge(n,o);return e.Sites.setItem(r+1,o),e.Edges.setItem(r,l),e.Edges.setItem(r+1,h),i.Sites.setItem(s+1,n),i.Edges.setItem(s,a),i.Edges.setItem(s+1,h),l.lowerSite===o?l.CcwTriangle=e:l.CwTriangle=e,a.lowerSite===n?a.CcwTriangle=i:a.CwTriangle=i,h.upperSite===n?(h.CcwTriangle=i,h.CwTriangle=e):(h.CcwTriangle=e,h.CwTriangle=i),va(t.upperSite.Edges,t),h}var Ae=class qe extends Nt{constructor(t,e,i){super(null),this.isolatedSites=[],this.obstacles=[],this.PointsToSites=new _e,this.simplifyObstacles=!0,this.rectangleNodeOnTriangles=null,this.isolatedSites=t,this.obstacles=e,this.isolatedSegments=i}static constructor_(t){let e=new qe(null,null,null);return e.isolatedSitesWithObject=t,e}FillAllInputSites(){if(this.isolatedSitesWithObject!=null)for(let t of this.isolatedSitesWithObject)this.AddSite(t[0],t[1]);if(this.isolatedSites!=null)for(let t of this.isolatedSites)this.AddSite(t,null);if(this.obstacles!=null)for(let t of this.obstacles)this.AddPolylineToAllInputSites(t);if(this.isolatedSegments!=null)for(let 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=ea.mkSO(t,e),this.PointsToSites.set(t,i)),i}AddP1AndP2(){let t=it.mkEmpty();for(let r of this.PointsToSites.keys())t.add(r);let e=10,i=10;this.P1=new ea(t.leftBottom.add(new g(-e,-i))),this.P2=new ea(t.rightBottom.add(new g(e,-i)))}AddPolylineToAllInputSites(t){if(this.simplifyObstacles)for(let e=t.startPoint;e!=null;){let i=e.point;if(e=e.next,!e)break;for(;e.next&&g.getTriangleOrientation(i,e.point,e.next.point)===2;)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){let r=qe.AbovePP(t,e),s,o;r>0?(s=this.AddSite(t,i),o=this.AddSite(e,i)):(s=this.AddSite(e,i),o=this.AddSite(t,i));let a=qe.CreateEdgeOnOrderedCouple(s,o);a.constrained=!0}static GetOrCreateEdge(t,e){return qe.AboveCC(t,e)===1?t.EdgeBetweenUpperSiteAndLowerSite(e)??qe.CreateEdgeOnOrderedCouple(t,e):e.EdgeBetweenUpperSiteAndLowerSite(t)??qe.CreateEdgeOnOrderedCouple(e,t)}static CreateEdgeOnOrderedCouple(t,e){return new km(t,e)}GetTriangles(){return this.sweeper.triangles}run(){this.Initialization(),this.SweepAndFinalize()}SweepAndFinalize(){this.sweeper=new $m(this.allInputSites,this.P1,this.P2,qe.GetOrCreateEdge),this.sweeper.run(),this.cleanRemovedEdges()}cleanRemovedEdges(){for(let t of this.PointsToSites.values())t.cleanRemovedEdges()}Initialization(){this.FillAllInputSites(),this.allInputSites.sort(qe.OnComparison)}static OnComparison(t,e){return qe.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 qe.AbovePP(t.point,e.point)}RestoreEdgeCapacities(){for(let t of this.allInputSites)for(let e of t.Edges)e.constrained||(e.ResidualCapacity=e.Capacity)}SetInEdges(){for(let t of this.PointsToSites.values())for(let 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++){let r=e.Sites.getItem(i).point,s=e.Sites.getItem(i+1).point;if(g.signedDoubledTriangleArea(t,r,s)<x.distanceEpsilon*-1)return!1}return!0}getRectangleNodeOnTriangles(){return this.rectangleNodeOnTriangles==null&&(this.rectangleNodeOnTriangles=qt(Array.from(this.GetTriangles().values()).map(t=>ne(t,t.BoundingBox())))),this.rectangleNodeOnTriangles}};function Zu(n){let t=Array.from(n.GetAllLeaves()),e=n.irect,i=e.diagonal/4,r=e.clone();return r.pad(i),Wm(t.concat([r.perimeter()]))}function Wm(n){let t=new Ae(null,n,null);return t.run(),t}var Ji=class Ea{constructor(t){this.stamp=0,this.SetPivotAndAllocateHullPointsArray(t)}SetPivotAndAllocateHullPointsArray(t){this.pivot=new g(0,Number.MAX_SAFE_INTEGER);let e=-1,i=0;for(let r of t)r.y<this.pivot.y?(this.pivot=r,e=i):r.y===this.pivot.y&&r.x>this.pivot.x&&(this.pivot=r,e=i),i++;if(i>=1){this.hullPoints=new Array(i-1),i=0;for(let r of t)i!==e?this.hullPoints[i++]={point:r,deleted:!1,stamp:this.stamp++}:e=-1}}get StackTopPoint(){return this.stack.point}get StackSecondPoint(){return this.stack.next.point}static*CalculateConvexHull(t){let e=new Ea(t);for(let 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(let 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 g.getTriangleOrientation(this.StackSecondPoint,this.StackTopPoint,this.pivot)===1}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;let e=g.getTriangleOrientationWithIntersectionEpsilon(this.StackSecondPoint,this.StackTopPoint,this.hullPoints[t].point);return e===1?!0:e===0?!1:this.BackSwitchOverPivot(this.hullPoints[t].point)}BackSwitchOverPivot(t){return this.stack.next.next!=null?!1:this.StackTopPoint.x>this.pivot.x+x.distanceEpsilon&&t.x<this.pivot.x-x.distanceEpsilon}Push(t){this.stack={point:this.hullPoints[t].point,next:this.stack}}SortAllPointsWithoutPivot(){this.hullPoints.sort(zm(this.pivot))}static createConvexHullAsClosedPolyline(t){return et.mkClosedFromPoints(Array.from(Ea.CalculateConvexHull(t)))}};function zm(n){return(t,e)=>{if(t===e)return 0;if(t==null)return-1;if(e==null)return 1;switch(g.getTriangleOrientationWithIntersectionEpsilon(n,t.point,e.point)){case 1:return-1;case 0:return 1;case 2:let i=t.point.x-n.x,r=e.point.x-n.x;if(i>x.distanceEpsilon&&r<-x.distanceEpsilon)return-1;if(i<-x.distanceEpsilon&&r>x.distanceEpsilon)return 1;let s=t.point.sub(n),o=e.point.sub(n),a=s.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 xe(n,t,e){n.irect.intersects_rect(t.irect)&&(n.Left==null?t.Left==null?e(n.UserData,t.UserData):(xe(n,t.Left,e),xe(n,t.Right,e)):t.Left!=null?(xe(n.Left,t.Left,e),xe(n.Left,t.Right,e),xe(n.Right,t.Left,e),xe(n.Right,t.Right,e)):(xe(n.Left,t,e),xe(n.Right,t,e)))}function de(n,t,e){n.irect.intersects_rect(t.irect)&&(n===t?Um(n,e):n.Left==null?t.Left==null?e(n.UserData,t.UserData):(de(n,t.Left,e),de(n,t.Right,e)):t.Left!=null?(de(n.Left,t.Left,e),de(n.Left,t.Right,e),de(n.Right,t.Left,e),de(n.Right,t.Right,e)):(de(n.Left,t,e),de(n.Right,t,e)))}function Ve(n,t,e){if(!n.irect.intersects_rect(t.irect))return!1;if(n===t)return qm(n,e);if(n.Left==null){if(t.Left==null)return e(n.UserData,t.UserData);if(Ve(n,t.Left,e)||Ve(n,t.Right,e))return!0}else if(t.Left!=null){if(Ve(n.Left,t.Left,e)||Ve(n.Left,t.Right,e)||Ve(n.Right,t.Left,e)||Ve(n.Right,t.Right,e))return!0}else if(Ve(n.Left,t,e)||Ve(n.Right,t,e))return!0;return!1}function qm(n,t){return n.Left==null?!1:Ve(n.Left,n.Left,t)||Ve(n.Left,n.Right,t)||Ve(n.Right,n.Right,t)}function Um(n,t){n.Left!=null&&(de(n.Left,n.Left,t),de(n.Left,n.Right,t),de(n.Right,n.Right,t))}var jm=ct(bi(),1);function*tn(n){let t=new Array(n.nodeCount).fill(!1),e=new jm.Queue;for(let i=0;i<n.nodeCount;i++)if(!t[i]){let r=new Array;for(Mh(i,e,t);e.length>0;){let s=e.dequeue();r.push(s);for(let o of Qm(n,s))Mh(o,e,t)}yield r}}function*Qm(n,t){for(let e of n.outEdges[t])yield e.target;for(let e of n.inEdges[t])yield e.source}function Mh(n,t,e){e[n]===!1&&(t.enqueue(n),e[n]=!0)}var Vh=BigInt("6364136223846793005"),ia=(BigInt(1)<<BigInt(32))-BigInt(1),xi=(BigInt(1)<<BigInt(64))-BigInt(1),go=class{constructor(n,t){this._state=BigInt(0),this._inc=(BigInt(t)<<BigInt(1)|BigInt(1))&xi,this._random_b(),this._state=this._state+BigInt(n)&xi,this._random_b()}_random_b(){let n=this._state;this._state=n*Vh+this._incξlet t=(n>>BigInt(18)^n)>>BigInt(27),e=n>>BigInt(59),i=e^BigInt(31);return(t>>e|t<<i)&ia}_advance(n){n&=xi;let t=BigInt(1),e=Vh,i=BigInt(0),r=this._inc;for(;n>0;)n&BigInt(1)&&(t=t*e&xi,i=i*e+r&xi),r=(e+BigInt(1))*r&xi,e=e*e&xi,n>>=BigInt(1);this._state=t*this._state+i&xi}randint(n){if(n>ia)throw new TypeError(`Bound too large: ${n}`);if(n<=0)throw new TypeError(`Empty sample space for r: 0 \u2264 r < ${n}`);let t=BigInt(n),e=(ia^t)%t;for(;;){let i=this._random_b();if(i>=e)return Number(i%t)}}random(){return Number(this._random_b())/Math.pow(2,32)}},Er;function en(n){return Er==null&&(Er=new go(0,0)),Er.randint(n)}function po(n){Er=new go(n,0)}function Tr(){return Er==null&&(Er=new go(0,0)),Er.random()}var As=class{get Sequence(){return this.f}set Sequence(n){this.f=n}get Length(){return this.length}set Length(n){this.length=n}constructor(n,t){this.f=n,this.length=t}FindMinimum(){let n=0,t=this.length-1,e=n+Math.floor((t-n)/2),i=this.f(e);if(i>=this.f(0)&&i>=this.f(this.length-1))return this.f(0)<this.f(this.length-1)?0:this.length-1;for(;t-n>1;)switch(e=n+Math.floor((t-n)/2),this.BehaviourAtIndex(e)){case 1:n=e;break;case 0:t=e;break;case 2:return e}return n===t||this.f(n)<=this.f(t)?n:t}BehaviourAtIndex(n){let t=this.f(n);if(n===0){let r=this.f(1);return r===t?2:r>t?0:1}if(n===this.length-1){let r=this.f(this.length-2);return r===t?2:r>t?1:0}let e=t-this.f(n-1),i=this.f(n+1)-t;return e*i<=0?2:e>0?0:1}FindMaximum(){let n=0,t=this.length-1,e=n+Math.floor((t-n)/2),i=this.f(e);if(i<=this.f(0)&&i<=this.f(this.length-1))return this.f(0)>this.f(this.length-1)?0:this.length-1;for(;t-n>1;)switch(e=n+Math.floor((t-n)/2),this.BehaviourAtIndex(e)){case 1:t=e;break;case 0:n=e;break;case 2:return e}return n===t||this.f(n)>=this.f(t)?n:t}},Xm=class{toArray(){let n=[];for(let t=0;t<this.length;t++)n.push(this.f(t));return n}constructor(n,t){this.f=n,this.length=t}GetAdjustedSequenceForMinimum(){let n=this.f(0),t=(this.f(this.length-1)-n)/(this.length-1);return e=>Math.min(this.f(e),n+t*e)}GetAdjustedSequenceForMaximum(){let n=this.f(0),t=(this.f(this.length-1)-n)/(this.length-1);return e=>Math.max(this.f(e),n+t*e)}FindMinimum(){return this.f(0)===this.f(this.length-1)?new As(this.f,this.length).FindMinimum():new As(this.GetAdjustedSequenceForMinimum(),this.length).FindMinimum()}FindMaximum(){return this.f(0)===this.f(this.length-1)?new As(this.f,this.length).FindMaximum():new As(this.GetAdjustedSequenceForMaximum(),this.length).FindMaximum()}},Ku=class _u{constructor(t,e){this.P=t,this.Q=e}LeftFromLineOnP(t,e,i){let r=this.P.pnt(t);return this.upperBranchOnP?g.pointToTheLeftOfLineOrOnLine(i,r,e):g.pointToTheRightOfLineOrOnLine(i,r,e)}LeftFromLineOnQ(t,e,i){let r=this.Q.pnt(t);return this.lowerBranchOnQ?g.pointToTheLeftOfLineOrOnLine(i,r,e):g.pointToTheRightOfLineOrOnLine(i,r,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,r){for(;e!==t||r!==i;){let s=e!==t?this.MedianOnP(t,e):t,o=r!==i?this.MedianOnQ(i,r):i,a=this.P.pnt(s),l=this.Q.pnt(o),h=!0;this.ModuleP(t,e)>1?this.LeftFromLineOnP(this.NextOnP(s),a,l)?t=s:this.LeftFromLineOnP(this.PrevOnP(s),a,l)?e=s:h=!1:e!==t?this.LeftFromLineOnP(e,this.P.pnt(t),l)?t=e:this.LeftFromLineOnP(t,this.P.pnt(e),l)?e=t:h=!1:h=!1;let u=!0;this.ModuleQ(i,r)>1?this.LeftFromLineOnQ(this.NextOnQ(o),l,a)?i=o:this.LeftFromLineOnQ(this.PrevOnQ(o),l,a)?r=o:u=!1:r!==i?this.LeftFromLineOnQ(r,this.Q.pnt(i),a)?i=r:this.LeftFromLineOnQ(i,this.Q.pnt(r),a)?r=i:u=!1:u=!1,!h&&!u&&(t=s,e=s,i=o,r=o)}return[t,r]}FindDividingBisector(t){let e={pClosest:void 0,qClosest:void 0,p1:void 0,p2:void 0,q1:void 0,q2:void 0};this.FindClosestFeatures(e),t.bisectorPivot=g.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(){let 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){let 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=g.ClosestPointAtLineSegment(t.pClosest,this.Q.pp(t.q1).point,this.Q.pp(t.q2).point),g.closeDistEps(t.qClosest,this.Q.pnt(t.q1))?t.q2=t.q1:g.closeDistEps(t.qClosest,this.Q.pnt(t.q2))&&(t.q1=t.q2))):(t.qClosest=this.Q.pp(t.q1).point,t.pClosest=g.ClosestPointAtLineSegment(t.qClosest,this.P.pp(t.p1).point,this.P.pp(t.p2).point),g.closeDistEps(t.pClosest,this.P.pnt(t.p1))?t.p2=t.p1:g.closeDistEps(t.qClosest,this.P.pnt(t.p2))&&(t.p1=t.p2))}ChunksAreLong(t,e,i,r){let s=this.P.Module(t-e)+1;if(s>2)return!0;let o=this.Q.Module(r-i)+1;return o>2||s===2&&o===2}ShrinkChunks(t){let 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),r=this.P.pp(e).point,s=this.Q.pp(i).point,o={a1:void 0,a2:void 0,b1:void 0,b2:void 0};if(this.GetAnglesAtTheMedian(e,i,r,s,o),!this.InternalCut(t,e,i,o.a1,o.a2,o.b1,o.b2)&&!_u.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)){let a=D.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,r,s,o,a){let l=!1;if(r>=Math.PI&&s>=Math.PI){let h=this.P.pp(e).point,u=this.Q.pp(i).point,d=this.P.pp(this.P.Next(e)).point,c=g.getTriangleOrientation(h,u,this.Q.pp(0).point),f=g.getTriangleOrientation(h,u,d);c===f?t.p1=this.P.Next(e):t.p2=this.P.Prev(e),l=!0}if(o>=Math.PI&&a>=Math.PI){let h=this.P.pp(e).point,u=this.Q.pp(i).point,d=this.Q.pp(this.Q.Next(i)).point,c=g.getTriangleOrientation(h,u,this.P.pp(0).point),f=g.getTriangleOrientation(h,u,d);c===f?t.q2=this.Q.Next(i):t.q1=this.Q.Prev(i),l=!0}return l}GetAnglesAtTheMedian(t,e,i,r,s){s.a1=g.anglePCP(r,i,this.P.pnt(this.P.Prev(t))),s.a2=g.anglePCP(this.P.pnt(this.P.Next(t)),i,r),s.b1=g.anglePCP(this.Q.pnt(this.Q.Next(e)),r,i),s.b2=g.anglePCP(i,r,this.Q.pnt(this.Q.Prev(e)))}OnlyOneChunkContainsExactlyTwoVertices(t,e,i){let r=t.p2===this.P.Next(t.p1),s=t.q1===this.Q.Next(t.q2);return r&&!s?(this.ProcessShortSide(t,e.mp,e.mq,i.a1,i.b1,i.a2,i.b2),!0):s&&!r?(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 r=t.p2;t.p2=t.q1,t.q1=r,r=t.q2,t.q2=t.p1,t.p1=r,r=e.mq,e.mq=e.mp,e.mp=r,r=i.a2,i.a2=i.b1,i.b1=r,r=i.b2,i.b2=i.a1,i.a1=r}ProcessShortSide(t,e,i,r,s,o,a){e===t.p2?this.ProcessSide(t,i,r,s,a):o<=Math.PI?o+a>=Math.PI?o>=Math.PI/2?t.p2=t.p1:t.q2=i:s>=Math.PI/2?t.q1=i:o<a&&(g.canProject(this.Q.pnt(i),this.P.pp(t.p1).point,this.P.pp(t.p2).point)?t.q1=i:t.p1=t.p2):r+s<=Math.PI?t.p1=t.p2:t.p2=t.p1}SwapPq(){let t=this.P;this.P=this.Q,this.Q=t}ProcessSide(t,e,i,r,s){let o=this.Q.pnt(e);i<=Math.PI?i+r>=Math.PI?i>=Math.PI/2?t.p1=t.p2:t.q1=e:s>=Math.PI/2?t.q2=e:i<s&&(g.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,r>=Math.PI?t.q1=e:s>=Math.PI&&(t.q2=e))}static OneOfChunksContainsOnlyOneVertex(t,e,i,r,s){return t.p1===t.p2?(s>=Math.PI/2?t.q1=i:t.q2=i,!0):t.q1===t.q2?(r>=Math.PI/2?t.p1=e:t.p2=e,!0):!1}CalculateLeftTangents(){let t={bisectorPivot:null,bisectorRay:null,p1:0,p2:0,q1:0,q2:0};this.FindDividingBisector(t);let 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(){let t={bisectorPivot:null,bisectorRay:null,p1:0,p2:0,q1:0,q2:0};this.FindDividingBisector(t);let 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)}},Ze=class Aa{static mkFromPoints(t){return new Aa(et.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,r){let s=r.rotate(Math.PI/2);this.polyline.startPoint.point.sub(i).dot(s)<0&&(s=s.mul(-1)),t===e&&(e=this.Next(t));do{let o=this.Median(e,t),a=this.pnt(o);this.pnt(this.Next(o)).sub(a).dot(s)>=0?e=this.Next(o):this.pnt(this.Prev(o)).sub(a).dot(s)>=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 r=0;r<t.count;r++)for(let s=0;s<e.count;s++){let o=D.minDistBetweenLineSegments(t.pnt(r),t.pnt(r+1),e.pnt(s),e.pnt(s+1));i=Math.min(i,o.dist)}return i}static Distance(t,e){let i=new Ku(t,e).FindClosestPoints();return{p:i.pClosest,q:i.qClosest,dist:i.pClosest.sub(i.qClosest).length}}static DistanceOnly(t,e){return Aa.Distance(t,e).dist}static PolygonIsLegalDebug(t){let e=t.Polyline;for(let i=e.startPoint;i.next!=null&&i.next.next!=null;i=i.next)if(g.getTriangleOrientation(i.point,i.next.point,i.next.next.point)===2)return!1;return!0}static DistancePoint(t,e){let i=Number.MAX_VALUE;for(let r=0;r<t.count;r++){let s=g.distToLineSegment(e,t.points[r].point,t.points[(r+1)%t.count].point).dist;i=Math.min(i,s)}return i}GetTangentPoints(t,e){let i=new Xm(this.GetSequenceDelegate(e),this.count);t.leftTangentPoint=i.FindMaximum(),t.rightTangentPoint=i.FindMinimum()}GetSequenceDelegate(t){let e=this.pnt(0);return i=>{let r=g.anglePCP(e,t,this.pnt(i));return r<Math.PI?r:r-2*Math.PI}}},ye=class dt{constructor(t,e,i,r){this.randomizationShift=.01,this.TightObstacles=new Set,this.Obstacles=t,this.TightPadding=e,this.LoosePadding=i,this.IgnoreTightPadding=r}ObstaclesIntersectLine(t,e){return this.ObstaclesIntersectICurve(D.mkPP(t,e))}static PadCorner(t,e,i,r,s){let o=dt.GetPaddedCorner(e,i,r,s);return o.numberOfPoints===-1?!1:(t.addPoint(o.a),o.numberOfPoints===2&&t.addPoint(o.b),!0)}static CurveIsClockwise(t,e){return g.getTriangleOrientation(e,t.start,t.start.add(t.derivative(t.parStart)))==0}static PaddedPolylineBoundaryOfNode(t,e,i=!1){return dt.CreatePaddedPolyline(G.polylineAroundClosedCurve(t),e,i)}static LoosePolylineWithFewCorners(t,e,i){return e<x.distanceEpsilon?t:dt.CreateLoosePolylineOnBisectors(t,e,i)}static CreateLoosePolylineOnBisectors(t,e,i){let r=Array.from(dt.BisectorPoints(t,e));i&&o();let s=Ji.CalculateConvexHull(r);return et.mkClosedFromPoints(s);function o(){for(let a=0;a<r.length;a++){let l=r[a];r[a]=new g(l.x+(2*Tr()-1)*i,l.y+(2*Tr()-1)*i)}}}static CreateRectNodeOfPolyline(t){return ne(t,t.boundingBox)}CreateLooseObstacles(){this.tightPolylinesToLooseDistances=new Map,this.LooseObstacles=new Array;for(let t of this.TightObstacles){let e=dt.FindMaxPaddingForTightPolyline(this.RootOfTightHierarchy,t,this.LoosePadding);this.tightPolylinesToLooseDistances.set(t,e),this.LooseObstacles.push(dt.LoosePolylineWithFewCorners(t,e,this.randomizationShift))}this.RootOfLooseHierarchy=dt.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}ObstaclesIntersectICurve(t){let e=t.boundingBox;return dt.CurveIntersectsRectangleNode(t,e,this.RootOfTightHierarchy)}static CurveIntersectsRectangleNode(t,e,i){if(!i.irect.intersects(e))return!1;if(i.UserData!=null){let r=i.UserData;return G.intersectionOne(r,t,!1)!=null||dt.PointIsInside(r.start,t)}return dt.CurveIntersectsRectangleNode(t,e,i.Left)||dt.CurveIntersectsRectangleNode(t,e,i.Right)}static PointIsInside(t,e){return G.PointRelativeToCurveLocation(t,e)===2}CreateTightObstaclesIgnoringTightPadding(){let t=this.Obstacles.map(r=>G.polylineAroundClosedCurve(r)),e=dt.CalculateHierarchy(t),i=dt.GetOverlappedPairSet(e);if(this.TightObstacles=new Set,i.size===0){for(let r of t){let s=dt.FindMaxPaddingForTightPolyline(e,r,this.TightPadding);this.TightObstacles.add(dt.LoosePolylineWithFewCorners(r,s,this.randomizationShift))}this.RootOfTightHierarchy=dt.CalculateHierarchy(Array.from(this.TightObstacles))}else{for(let r of t)this.TightObstacles.add(dt.CreatePaddedPolyline(r,this.TightPadding));if(!this.IsEmpty())for(this.RootOfTightHierarchy=dt.CalculateHierarchy(Array.from(this.TightObstacles)),this.OverlapsDetected=!1;dt.GetOverlappedPairSet(this.RootOfTightHierarchy).size>0;)this.RootOfTightHierarchy=dt.ReplaceTightObstaclesWithConvexHulls(this.TightObstacles,Array.from(i)),this.OverlapsDetected=!0}}CreateTightObstacles_(){if(this.Obstacles.length===0)return null;for(let t of this.Obstacles)dt.CalculateTightPolyline(this.TightObstacles,this.TightPadding,t);return dt.RemovePossibleOverlapsInTightPolylinesAndCalculateHierarchy(this.TightObstacles)}static CalculateTightPolyline(t,e,i){let r=dt.PaddedPolylineBoundaryOfNode(i,e);t.add(r)}static CalculateHierarchy(t){let e=t.map(i=>dt.CreateRectNodeOfPolyline(i));return qt(e)}static RemovePossibleOverlapsInTightPolylinesAndCalculateHierarchy(t,e=null){let i=dt.CalculateHierarchy(Array.from(t)),r;for(;(r=dt.GetOverlappedPairSet(i)).size>0;)i=dt.ReplaceTightObstaclesWithConvexHulls(t,Array.from(r),e);return i}static MapToInt(t){let e=new Map;for(let i=0;i<t.length;i++)e.set(t[i],i);return e}static ReplaceTightObstaclesWithConvexHulls(t,e,i=null){let r=new Set;for(let h of e)r.add(h[0]),r.add(h[1]);let s=Array.from(r),o=dt.MapToInt(s),a=vu(Array.from(e).map(h=>new mt(o.get(h[0]),o.get(h[1])))),l=tn(a);for(let h of l){let u=h.map(m=>s[m]),d=Xn(u,m=>m),c=Ji.createConvexHullAsClosedPolyline(d),f=new Array;for(let m of u)t.delete(m),i!=null&&(f.push(...i.get(m)),i.delete(m));i?.set(c,f),t.add(c)}return dt.CalculateHierarchy(Array.from(t))}static OneCurveLiesInsideOfOther(t,e){return G.PointRelativeToCurveLocation(t.start,e)!==0||G.PointRelativeToCurveLocation(e.start,t)!==0}static PolylinesIntersect(t,e){return G.CurvesIntersect(t,e)||dt.OneCurveLiesInsideOfOther(t,e)}static GetOverlappedPairSet(t){let e=new Set;return de(t,t,(i,r)=>{dt.PolylinesIntersect(i,r)&&e.add([i,r])}),e}static*BisectorPoints(t,e){for(let i=t.startPoint;i!=null;i=i.next){let r={skip:!1},s=dt.GetStickingVertexOnBisector(i,e,r);r.skip||(yield s)}}static GetStickingVertexOnBisector(t,e,i){let r=t.polyline.prev(t).point,s=t.point,o=t.polyline.next(t).point,a=s.sub(r).normalize().add(s.sub(o).normalize()),l=a.length;return l<x.tolerance?i.skip=!0:(i.skip=!1,a=a.div(l)),a.mul(e).add(s)}static{this.LooseDistCoefficient=2.1}static FindMaxPaddingForTightPolyline(t,e,i){let r=i,s=new Ze(e),o=e.boundingBox.clone();o.pad(2*i);for(let a of Array.from(t.GetNodeItemsIntersectingRectangle(o)).filter(l=>l!==e)){let l=Ze.Distance(s,new Ze(a)).dist;r=Math.min(r,l/dt.LooseDistCoefficient)}return r}static GetPaddedCorner(t,e,i,r){let s=t.point,o=e.point,a=i.point;if(g.getTriangleOrientation(s,o,a)===1)return{a:void 0,b:void 0,numberOfPoints:-1};let l=o.sub(s).rotate(Math.PI/2).normalize();if(dt.CornerIsNotTooSharp(s,o,a)){l=l.mul(r);let m=a.sub(o).normalize().mul(r).rotate(Math.PI/2),P=g.lineLineIntersection(s.add(l),o.add(l),o.add(m),a.add(m));return{a:P,b:P,numberOfPoints:1}}let h=o.sub(s).normalize().add(o.sub(a).normalize());if(h.length<x.intersectionEpsilon){let m=o.add(l.mul(r));return{a:m,b:m,numberOfPoints:1}}let u=h.normalize().mul(r),d=u.rotate(Math.PI/2),c=(r-u.dot(l))/d.dot(l),f=d.mul(c);return{a:u.add(f).add(o),b:u.sub(f).add(o),numberOfPoints:2}}static CornerIsNotTooSharp(t,e,i){let r=t.sub(e).rotate(Math.PI/4).add(e);return g.getTriangleOrientation(e,r,i)===1}static CreatePaddedPolyline(t,e,i=!1){let r=new et,s=i?Ym(t):t;if(!dt.PadCorner(r,s.endPoint.prev,s.endPoint,s.startPoint,e)||!dt.PadCorner(r,s.endPoint,s.startPoint,s.startPoint.next,e))return dt.CreatePaddedPolyline(et.mkClosedFromPoints(Array.from(Ji.CalculateConvexHull(s))),e);for(let o=s.startPoint;o.next.next!=null;o=o.next)if(!dt.PadCorner(r,o,o.next,o.next.next,e))return dt.CreatePaddedPolyline(et.mkClosedFromPoints(Array.from(Ji.CalculateConvexHull(s))),e);return r.closed=!0,r}};function Ym(n){let t=new et,e=.01;for(let i=n.startPoint;i;i=i.next){let r=i.point.x+e*Tr(),s=i.point.y+e*Tr();t.addPointXY(r,s)}return t.closed=n.closed,t}var Jm=ct(bi(),1);function Zm(n){let t=new Map;for(let e of n.filter(i=>!t.has(i)))t.set(e,td(e,t));return t}function td(n,t){let e=new Set(n.Parents);for(let i of n.Parents){let r=t.get(i);r||t.set(i,r=td(i,t));for(let s of r)e.add(s)}return e}function Km(n,t,e,i){let r=new Set,s=t.get(n.sourcePort),o=t.get(n.targetPort);return kh(s,o,e)?(Li(r,o.Parents),r.add(s),r):kh(o,s,e)?(Li(r,s.Parents),r.add(o),r):(s!==i&&Li(r,s.Parents),o!==i&&Li(r,o.Parents),r)}function kh(n,t,e){let i;return t!=null&&(i=e.get(t))!=null&&i.has(n)}function _m(n,t,e,i){let r=new Array;for(let s of n){let o=Km(s,t,e,i),a=r.find(l=>qn(l.passport,o));a||(a={passport:o,edges:[]},r.push(a)),a.edges.push(s)}return r}function tP(n,t,e){if(n.size===0)return new Set(e.Children);let i=iP(n,t),r=eP(n,t),s=new Set;for(let l of n)for(let h of l.Children)r.has(h)||s.add(h);let o=ir(new Set(n),s),a=new Jm.Queue;for(let l of n)i.has(l)||a.enqueue(l);for(;a.length>0;){let l=a.dequeue();for(let h of l.Parents){for(let u of h.Children)r.has(u)||s.add(u);!i.has(h)&&!o.has(h)&&(a.enqueue(h),o.add(h))}}return s}function eP(n,t){if(n.size===0)return new Set;let e=new Set(n);for(let i of n)e=ir(e,t.get(i));return e}function iP(n,t){if(n.size===0)return new Set;let e=Array.from(n),i=t.get(e[0]);for(let r=1;r<e.length;r++){let s=e[r];i=Ri(i,t.get(s))}return i}function rP(n,t){let e=new Map;for(let i of n.Descendants())for(let r of i.Ports)e.set(r,i);for(let i of t)i.sourcePort&&!e.has(i.sourcePort)&&(n.Ports.add(i.sourcePort),e.set(i.sourcePort,n)),i.targetPort&&!e.has(i.targetPort)&&(n.Ports.add(i.targetPort),e.set(i.targetPort,n));return e}var ed=class{constructor(n){this._trianglesByOwner=null,this._portalsByPoly=null;let t=new Map,e=[];for(let r of n.GetTriangles())t.set(r,e.length),e.push(r);this.triToId=t,this.triangles=e,this.n=e.length;let i=this.n;this.nbId=new Int32Array(i*3).fill(-1),this.nbEdge=new Array(i*3).fill(null),this.midX=new Float64Array(i*3),this.midY=new Float64Array(i*3),this.centX=new Float64Array(i),this.centY=new Float64Array(i),this.obstacleOwner=new Array(i);for(let r=0;r<i;r++){let s=e[r],o=s.Sites.item0.point,a=s.Sites.item1.point,l=s.Sites.item2.point;this.centX[r]=(o.x+a.x+l.x)/3,this.centY[r]=(o.y+a.y+l.y)/3;let h=s.Sites.item0.Owner,u=s.Sites.item1.Owner,d=s.Sites.item2.Owner;this.obstacleOwner[r]=h!=null&&u!=null&&d!=null&&h===u&&h===d?h:null;let c=0;for(let f of s.Edges){if(c>=3)break;let m=f.GetOtherTriangle_T(s);if(m==null){c++;continue}let P=t.get(m);if(P===void 0){c++;continue}this.nbId[r*3+c]=P,this.nbEdge[r*3+c]=f;let v=(f.lowerSite.point.x+f.upperSite.point.x)*.5,b=(f.lowerSite.point.y+f.upperSite.point.y)*.5;this.midX[r*3+c]=v,this.midY[r*3+c]=b,c++}}}getId(n){return this.triToId.get(n)??-1}isInsideObstacle(n,t){let e=this.obstacleOwner[n];return e!=null&&!t.has(e)}getTrianglesByOwner(n){if(!this._trianglesByOwner){let t=new Map;for(let e=0;e<this.n;e++){let i=this.obstacleOwner[e];if(i==null)continue;let r=t.get(i);r||(r=[],t.set(i,r)),r.push(e)}this._trianglesByOwner=t}return this._trianglesByOwner.get(n)}getPortalsByPoly(n){if(!this._portalsByPoly){let t=new Map;for(let e=0;e<this.n;e++){if(this.obstacleOwner[e]!=null)continue;let i=this.triangles[e],r=i.Sites.item0.Owner,s=i.Sites.item1.Owner,o=i.Sites.item2.Owner;if(r!=null&&(r===s||r===o)){let a=t.get(r);a||(a=[],t.set(r,a)),a.push(e)}if(s!=null&&s!==r&&s===o){let a=t.get(s);a||(a=[],t.set(s,a)),a.push(e)}}this._portalsByPoly=t}return this._portalsByPoly.get(n)}},id=class{constructor(n){this.size=0,this.keys=new Float64Array(n),this.vals=new Int32Array(n)}clear(){this.size=0}push(n,t){let e=this.keys,i=this.vals,r=this.size++;for(e[r]=n,i[r]=t;r>0;){let s=r-1>>1;if(e[s]<=e[r])break;let o=e[r];e[r]=e[s],e[s]=o;let a=i[r];i[r]=i[s],i[s]=a,r=s}}topKey(){return this.keys[0]}topVal(){return this.vals[0]}pop(){let n=this.keys,t=this.vals,e=--this.size;if(e>0){n[0]=n[e],t[0]=t[e];let i=0;for(;;){let r=i,s=2*i+1,o=2*i+2;if(s<this.size&&n[s]<n[r]&&(r=s),o<this.size&&n[o]<n[r]&&(r=o),r===i)break;let a=n[i];n[i]=n[r],n[r]=a;let l=t[i];t[i]=t[r],t[r]=l,i=r}}}};function ro(n,t){let e=n.getRectangleNodeOnTriangles();if(e){let i=e.FirstHitNodeWithPredicate(t,(r,s)=>s.containsPoint(r)?1:0);if(i)return i.UserData}for(let i of n.GetTriangles())if(i.containsPoint(t))return i;return null}function rd(n,t,e,i,r,s,o,a){r[n]=0,s[n]=-1,o.push(n),a.clear(),a.push(0,n);let l=t.size,h=new Set;for(;a.size>0&&l>0;){let u=a.topKey(),d=a.topVal();if(a.pop(),u>r[d])continue;if(t.has(d)&&!h.has(d)&&(h.add(d),l--,l===0))break;let c=s[d],f,m;c>=0?(f=i.midX[c],m=i.midY[c]):(f=i.centX[d],m=i.centY[d]);let P=d*3;for(let v=0;v<3;v++){let b=i.nbId[P+v];if(b<0||c>=0&&i.nbEdge[P+v]===i.nbEdge[c])continue;if(i.isInsideObstacle(b,e)){if(t.has(b)&&!h.has(b)){let _=i.midX[P+v],T=i.midY[P+v],B=f-_,z=m-T,tt=u+Math.sqrt(B*B+z*z);if(tt<r[b]){r[b]=tt;let O=b*3;for(let L=0;L<3;L++)if(i.nbId[O+L]===d&&i.nbEdge[O+L]===i.nbEdge[P+v]){s[b]=O+L;break}o.push(b),h.add(b),l--}}continue}let C=i.midX[P+v],E=i.midY[P+v],w=f-C,F=m-E,V=u+Math.sqrt(w*w+F*F);if(V>=r[b])continue;r[b]=V;let q=b*3;for(let _=0;_<3;_++)if(i.nbId[q+_]===d&&i.nbEdge[q+_]===i.nbEdge[P+v]){s[b]=q+_;break}o.push(b),a.push(V,b)}}}function ol(n,t,e,i){let r=[],s=t;for(;s!==n;){let o=e[s];if(o<0)break;let a=i.nbEdge[o],l=i.nbId[o];r.push({source:i.triangles[l],edge:a}),s=l}return r.reverse()}function wa(n,t,e,i,r,s,o,a,l=null,h=-1){r[n]=0,s[n]=-1,o.push(n),a.clear();let u=t.x,d=t.y,c=i.centX[n]-u,f=i.centY[n]-d;for(a.push(Math.sqrt(c*c+f*f),n);a.size>0;){let m=a.topKey(),P=a.topVal();a.pop();let v=r[P],b=i.centX[P]-u,C=i.centY[P]-d,E=Math.sqrt(b*b+C*C);if(m>v+E+1e-10)continue;if(P===h||i.triangles[P].containsPoint(t))return ol(n,P,s,i);let w=s[P],F,V;w>=0?(F=i.midX[w],V=i.midY[w]):(F=i.centX[P],V=i.centY[P]);let q=P*3;for(let _=0;_<3;_++){let T=i.nbId[q+_];if(T<0||w>=0&&i.nbEdge[q+_]===i.nbEdge[w]||i.isInsideObstacle(T,e)&&!i.triangles[T].containsPoint(t)||l!==null&&l[T]===0&&!i.triangles[T].containsPoint(t))continue;let B=i.midX[q+_],z=i.midY[q+_],tt=F-B,O=V-z,L=v+Math.sqrt(tt*tt+O*O);if(L>=r[T])continue;r[T]=L;let U=T*3;for(let K=0;K<3;K++)if(i.nbId[U+K]===P&&i.nbEdge[U+K]===i.nbEdge[q+_]){s[T]=U+K;break}o.push(T);let st=i.centX[T]-u,W=i.centY[T]-d;a.push(L+Math.sqrt(st*st+W*W),T)}}return null}function ws(n,t,e){return(t.x-n.x)*(e.y-n.y)-(t.y-n.y)*(e.x-n.x)}function no(n,t,e){let i=[];for(let m of n){let P=m.edge,v=m.source.OppositeSite(P);g.getTriangleOrientation(v.point,P.lowerSite.point,P.upperSite.point)===1?i.push({left:P.upperSite.point,right:P.lowerSite.point,leftSite:P.upperSite,rightSite:P.lowerSite}):i.push({right:P.upperSite.point,left:P.lowerSite.point,leftSite:P.lowerSite,rightSite:P.upperSite})}if(i.length===0)return[];function r(m){let P=[];for(let v of m)P.length===0||ht(P[P.length-1].pt,v.pt)>1e-8?P.push({pt:v.pt,site:v.site,firstIdx:v.idx,lastIdx:v.idx}):P[P.length-1].lastIdx=v.idx;return P}let s=i.map((m,P)=>({pt:m.left,site:m.leftSite,idx:P})),o=i.map((m,P)=>({pt:m.right,site:m.rightSite,idx:P})),a=r(s),l=r(o),h=-1;if(t)for(let m=0;m<l.length-1;m++)l[m].site.Owner===t.poly&&ws(t.center,l[m].pt,l[m+1].pt)<-1e-10&&(h=l[m].lastIdx);let u=i.length;if(e)for(let m=l.length-1;m>=1;m--)l[m].site.Owner===e.poly&&ws(l[m-1].pt,l[m].pt,e.center)<-1e-10&&(u=l[m].firstIdx);let d=-1;if(t)for(let m=0;m<a.length-1;m++)a[m].site.Owner===t.poly&&ws(t.center,a[m].pt,a[m+1].pt)>1e-10&&(d=a[m].lastIdx);let c=i.length;if(e)for(let m=a.length-1;m>=1;m--)a[m].site.Owner===e.poly&&ws(a[m-1].pt,a[m].pt,e.center)>1e-10&&(c=a[m].firstIdx);let f=[];for(let m=0;m<i.length;m++){let P=i[m].left,v=i[m].right;t&&i[m].leftSite.Owner===t.poly&&m<=d&&(P=t.center),t&&i[m].rightSite.Owner===t.poly&&m<=h&&(v=t.center),e&&i[m].leftSite.Owner===e.poly&&m>=c&&(P=e.center),e&&i[m].rightSite.Owner===e.poly&&m>=u&&(v=e.center),!(ht(P,v)<1e-8)&&f.push({left:P,right:v})}return f}function so(n,t,e){if(e.length===0)return[n,t];let i=[],r=n,s={point:r},o={point:r},a={point:e[0].left,prev:s},l={point:e[0].right,prev:o};s.next=a,o.next=l;let h;for(let V=1;V<e.length;V++)c(V);let u=[...e,{right:t,left:a.point}];c(u.length-1);let d=[...i];for(let V=o;V!=null;V=V.next)d.push(V.point);return d;function c(V){let q=V<e.length?e:u;if(q[V-1].left!==q[V].left){h=q[V].left;let _=a;for(;!(E(_)||P(_));_=_.prev);E(_)?b():F(_)}else{h=q[V].right;let _=l;for(;!(E(_)||v(_));_=_.prev);E(_)?C():w(_)}}function f(V){return V.next==null||g.pointToTheLeftOfLineOrOnLine(h,V.point,V.next.point)}function m(V){return V.next==null||g.pointToTheRightOfLineOrOnLine(h,V.point,V.next.point)}function P(V){return g.pointToTheLeftOfLine(h,V.prev.point,V.point)}function v(V){return g.pointToTheRightOfLine(h,V.prev.point,V.point)}function b(){let V=o;for(;!f(V);)V=V.next;if(!E(V)){let q=o;for(;!q.point.equal(V.point);q=q.next)i.push(q.point);o.point=q.point,o.next=q.next,r=q.point,l.point.equal(o.point)&&(l.prev=l.next=null)}s.point=r,a.point=h,a.prev=s,s.next=a}function C(){let V=s;for(;!m(V);)V=V.next;if(!E(V)){let q=s;for(;!q.point.equal(V.point);q=q.next)i.push(q.point);s.point=q.point,s.next=q.next,r=q.point,a.point.equal(s.point)&&(a.prev=s.next=null)}o.point=r,l.point=h,l.prev=o,o.next=l}function E(V){return V.point===r}function w(V){V!==l?(l.point=h,l.prev=V,V.next=l):(l={point:h,prev:V},V.next=l)}function F(V){V!==a?(a.point=h,a.prev=V,V.next=a):(a={point:h,prev:V},V.next=a)}}function nP(n){for(let t of n.shallowNodes)if(t instanceof we)return!0;return!1}function sP(n,t,e,i=2,r,s,o,a=0,l,h=!1){if(!t||t.length===0)return;if(aP(t),nP(n)){lP(n,t,e,i,h);return}let u=new Map,d=[],c=it.mkEmpty(),f=0;for(let q of n.nodesBreadthFirst){if(e&&e.canceled)return;if(q.boundaryCurve==null||o&&!o.has(q))continue;f++;let _=q.boundaryCurve;if(s){let B=s(q);if(B&&B!==1){let z=Oe.scaleAroundCenterTransformation(B,B,q.center);_=_.transform(z)}}let T=ye.PaddedPolylineBoundaryOfNode(_,i+a);u.set(q,T),d.push(T),c.addRecSelf(T.boundingBox)}c.pad(Math.max(c.diagonal/4,100)),d.push(c.perimeter()),console.time("CorridorRouter CDT");let m=new Ae([],d,[]);m.run(),console.timeEnd("CorridorRouter CDT");let P=new ed(m),v=new Float64Array(P.n).fill(1/0),b=new Int32Array(P.n).fill(-1),C=[],E=new id(P.n*4),w=new Map,F=q=>{if(!s)return q.boundaryCurve;let _=w.get(q);if(_)return _;let T=s(q);if(!T||T===1)return w.set(q,q.boundaryCurve),q.boundaryCurve;let B=Oe.scaleAroundCenterTransformation(T,T,q.center),z=q.boundaryCurve.transform(B);return w.set(q,z),z};console.time("CorridorRouter routing");let V=new Map;for(let q of t){if(e&&e.canceled)return;if(q.sourcePort==null||q.targetPort==null)continue;let _=V.get(q.source);_||(_=[],V.set(q.source,_)),_.push(q)}for(let[q,_]of V){if(e&&e.canceled)return;let T=q.center,B=u.get(q),z=ro(m,T);if(!z){for(let W of _){let K=W.target.center,at=et.mkFromPoints([T,K]);W.curve=at.toCurve(),W.smoothedPolyline=Ot.mkFromPoints([T,K]),ge.trimSplineAndCalculateArrowheadsII(W,F(W.source),F(W.target),W.curve,!1)}continue}let tt=P.getId(z);if(tt<0)continue;let O=[],L=new Set;for(let W of _){let K=W.target.center,at=u.get(W.target),ut=ro(m,K);if(!ut){let Z=et.mkFromPoints([T,K]);W.curve=Z.toCurve(),W.smoothedPolyline=Ot.mkFromPoints([T,K]),ge.trimSplineAndCalculateArrowheadsII(W,F(W.source),F(W.target),W.curve,!1);continue}let $=P.getId(ut);$<0||(O.push({edge:W,target:K,targetPoly:at,targetId:$}),L.add($))}if(O.length===0)continue;let U=new Set;B&&U.add(B),rd(tt,L,U,P,v,b,C,E);let st=[];for(let{edge:W,target:K,targetPoly:at,targetId:ut}of O){if(v[ut]===1/0){st.push({edge:W,target:K,targetPoly:at});continue}let $=ol(tt,ut,b,P);if($.length===0){let Z=et.mkFromPoints([T,K]);W.curve=Z.toCurve(),W.smoothedPolyline=Ot.mkFromPoints([T,K])}else{let Z=no($,B?{poly:B,center:T}:void 0,at?{poly:at,center:K}:void 0);if(Z.length===0){let Q=et.mkFromPoints([T,K]);W.curve=Q.toCurve(),W.smoothedPolyline=Ot.mkFromPoints([T,K])}else{let Q=so(T,K,Z),ot=et.mkFromPoints(Q);W.smoothedPolyline=Ot.mkFromPoints(ot),h?(oo(W.smoothedPolyline,i),W.curve=W.smoothedPolyline.createCurve()):W.curve=ot.toCurve()}}ge.trimSplineAndCalculateArrowheadsII(W,F(W.source),F(W.target),W.curve,!1)}for(let W of C)v[W]=1/0,b[W]=-1;C.length=0;for(let{edge:W,target:K,targetPoly:at}of st){let ut=new Set;B&&ut.add(B),at&&ut.add(at);let $=wa(tt,K,ut,P,v,b,C,E);for(let Z of C)v[Z]=1/0,b[Z]=-1;if(C.length=0,!$||$.length===0){let Z=new Set(u.values());$=wa(tt,K,Z,P,v,b,C,E);for(let Q of C)v[Q]=1/0,b[Q]=-1;C.length=0}if($&&$.length>0){let Z=no($,B?{poly:B,center:T}:void 0,at?{poly:at,center:K}:void 0);if(Z.length>0){let Q=so(T,K,Z),ot=et.mkFromPoints(Q);W.smoothedPolyline=Ot.mkFromPoints(ot),h?(oo(W.smoothedPolyline,i),W.curve=W.smoothedPolyline.createCurve()):W.curve=ot.toCurve()}else{let Q=et.mkFromPoints([T,K]);W.curve=Q.toCurve(),W.smoothedPolyline=Ot.mkFromPoints([T,K])}}else if(!$||$.length===0){let Z=et.mkFromPoints([T,K]);W.curve=Z.toCurve(),W.smoothedPolyline=Ot.mkFromPoints([T,K])}ge.trimSplineAndCalculateArrowheadsII(W,F(W.source),F(W.target),W.curve,!1);for(let Z of C)v[Z]=1/0,b[Z]=-1;C.length=0}for(let W of C)v[W]=1/0,b[W]=-1;C.length=0}console.timeEnd("CorridorRouter routing")}function oo(n,t){let e=n.headSite,i;for(;i=G.findCorner(e);)e=oP(e,i.c,i.b,t)}function oP(n,t,e,i){let r=.5,s,o,a;n.prev==null?(a=2,o=1):t.next==null?(a=1,o=2):a=o=1;do s=G.createBezierSeg(r*a,r*o,n,e,t),e.previouisBezierCoefficient=r*a,e.nextBezierCoefficient=r*o,r/=1.5;while(l()>i&&r>.01);return r*=1.5,r<.5&&r>.01&&(r=.5*(r+r*1.5),s=G.createBezierSeg(r*a,r*o,n,e,t),l()>i&&(e.previouisBezierCoefficient=r*a,e.nextBezierCoefficient=r*o)),e;function l(){let h=s.closestParameter(e.point);return ht(e.point,s.value(h))}}function Vr(n,t,e){let i=et.mkFromPoints([t,e]);n.curve=i.toCurve(),n.smoothedPolyline=Ot.mkFromPoints([t,e])}function aP(n){for(let t of n){if(t.sourcePort==null){let e=t;e.sourcePort=Si.mk(()=>e.source.boundaryCurve,()=>e.source.center)}if(t.targetPort==null){let e=t;e.targetPort=Si.mk(()=>e.target.boundaryCurve,()=>e.target.center)}}}function lP(n,t,e,i,r){let s=_r.GetShapes(n,t).filter(d=>d.Parents==null||d.Parents.length===0),o,a=!1;if(s.length===1&&s[0].BoundaryCurve==null)o=s[0];else{a=!0,o=new Ir(null);for(let d of s)o.AddChild(d)}let l=Zm(Array.from(o.Descendants())),h=rP(o,t),u=_m(t,h,l,o);for(let d of u){if(e&&e.canceled)break;let c=tP(d.passport,l,o);hP(n,d.edges,c,e,i,r)}if(a)for(let d of s)d.RemoveParent(o)}function hP(n,t,e,i,r,s){let o=new Map,a=[],l=it.mkEmpty();for(let v of e){if(v.BoundaryCurve==null)continue;let b=v instanceof io?v.node:null,C=ye.PaddedPolylineBoundaryOfNode(v.BoundaryCurve,r);b&&o.set(b,C),a.push(C),l.addRecSelf(C.boundingBox)}for(let v of t)for(let b of[v.source,v.target])if(!o.has(b)&&b.boundaryCurve!=null){let C=ye.PaddedPolylineBoundaryOfNode(b.boundaryCurve,r);o.set(b,C)}if(a.length===0&&t.length>0)for(let v of t)v.source.boundaryCurve&&l.addRecSelf(v.source.boundingBox),v.target.boundaryCurve&&l.addRecSelf(v.target.boundingBox);l.pad(Math.max(l.diagonal/4,100)),a.push(l.perimeter());let h=new Ae([],a,[]);h.run();let u=new ed(h),d=new Float64Array(u.n).fill(1/0),c=new Int32Array(u.n).fill(-1),f=[],m=new id(u.n*4),P=new Map;for(let v of t){if(i&&i.canceled)return;if(v.sourcePort==null||v.targetPort==null)continue;let b=P.get(v.source);b||(b=[],P.set(v.source,b)),b.push(v)}for(let[v,b]of P){if(i&&i.canceled)return;let C=v.center,E=o.get(v),w=ro(h,C);if(!w){for(let B of b){let z=B.target.center;Vr(B,C,z),ge.trimSplineAndCalculateArrowheadsII(B,B.source.boundaryCurve,B.target.boundaryCurve,B.curve,!1)}continue}let F=u.getId(w);if(F<0)continue;let V=[],q=new Set;for(let B of b){let z=B.target.center,tt=o.get(B.target),O=ro(h,z);if(!O){Vr(B,C,z),ge.trimSplineAndCalculateArrowheadsII(B,B.source.boundaryCurve,B.target.boundaryCurve,B.curve,!1);continue}let L=u.getId(O);L<0||(V.push({edge:B,target:z,targetPoly:tt,targetId:L}),q.add(L))}if(V.length===0)continue;let _=new Set;E&&_.add(E),rd(F,q,_,u,d,c,f,m);let T=[];for(let{edge:B,target:z,targetPoly:tt,targetId:O}of V){if(d[O]===1/0){T.push({edge:B,target:z,targetPoly:tt});continue}let L=ol(F,O,c,u);if(L.length===0)Vr(B,C,z);else{let U=no(L,E?{poly:E,center:C}:void 0,tt?{poly:tt,center:z}:void 0);if(U.length===0)Vr(B,C,z);else{let st=so(C,z,U),W=et.mkFromPoints(st);B.smoothedPolyline=Ot.mkFromPoints(W),s?(oo(B.smoothedPolyline,r),B.curve=B.smoothedPolyline.createCurve()):B.curve=W.toCurve()}}ge.trimSplineAndCalculateArrowheadsII(B,B.source.boundaryCurve,B.target.boundaryCurve,B.curve,!1)}for(let B of f)d[B]=1/0,c[B]=-1;f.length=0;for(let{edge:B,target:z,targetPoly:tt}of T){let O=new Set;E&&O.add(E),tt&&O.add(tt);let L=wa(F,z,O,u,d,c,f,m);if(L&&L.length>0){let U=no(L,E?{poly:E,center:C}:void 0,tt?{poly:tt,center:z}:void 0);if(U.length>0){let st=so(C,z,U),W=et.mkFromPoints(st);B.smoothedPolyline=Ot.mkFromPoints(W),s?(oo(B.smoothedPolyline,r),B.curve=B.smoothedPolyline.createCurve()):B.curve=W.toCurve()}else Vr(B,C,z)}else Vr(B,C,z);ge.trimSplineAndCalculateArrowheadsII(B,B.source.boundaryCurve,B.target.boundaryCurve,B.curve,!1);for(let U of f)d[U]=1/0,c[U]=-1;f.length=0}for(let B of f)d[B]=1/0,c[B]=-1;f.length=0}}var al=(n=>(n[n.Spline=0]="Spline",n[n.SplineBundling=1]="SplineBundling",n[n.StraightLine=2]="StraightLine",n[n.SugiyamaSplines=3]="SugiyamaSplines",n[n.Rectilinear=4]="Rectilinear",n[n.RectilinearToCenter=5]="RectilinearToCenter",n[n.None=6]="None",n[n.Corridor=7]="Corridor",n))(al||{}),uP=ct(se(),1),Ki=class{constructor(n,t,e,i=1){this.Source=n,this.Target=t,this.CrossingWeight=e,this.Weight=i}toString(){return uP.String.format("{0}->{1}",this.Source,this.Target)}},dP=class Fn{static FindClosestPoints(t,e){let i=G.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 G){for(let i of t.segs)if((i.start.y-e)*(i.end.y-e)<=0)return i}return null}static ShiftLabel(t,e,i){let r=t.lineWidth/2,s=e.sub(i),o=s.length;o>r&&t.label.positionCenter(t.label.center.add(s.div(o*(o-r))))}static updateLabel(t,e){let i=null;e.labelIsToTheRightOfTheSpline?(t.label.positionCenter(new g(e.x+e.rightAnchor/2,e.y)),i=D.mkPP(t.label.boundingBox.leftTop,t.label.boundingBox.leftBottom)):e.labelIsToTheLeftOfTheSpline&&(t.label.positionCenter(new g(e.x-e.leftAnchor/2,e.y)),i=D.mkPP(t.label.boundingBox.rightTop,t.label.boundingBox.rightBottom));let r=Fn.GetSegmentInFrontOfLabel(t.curve,t.label.center.y);if(r!=null&&G.getAllIntersections(t.curve,G.polyFromBox(t.label.boundingBox),!1).length===0){let s=Fn.FindClosestPoints(r,i);if(s)Fn.ShiftLabel(t,s.curveClosestPoint,s.labelSideClosest);else{let o,a,l=r.closestParameter(i.start),h=r.closestParameter(i.end);r.value(l).sub(i.start).length<r.value(h).sub(i.end).length?(o=r.value(l),a=i.start):(o=r.value(h),a=i.end),Fn.ShiftLabel(t,o,a)}}}},Bi=class nd{constructor(t,e,i,r=1,s=1){this.reversed=!1,this.source=t,this.target=e,this.edge=i,this.weight=r,this.separation=s}get CrossingWeight(){return 1}get hasLabel(){return this.edge.label!=null}get labelWidth(){return this.edge.label.width}get labelHeight(){return this.edge.label.height}reverse(){let 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(){let t=new nd(this.target,this.source,this.edge);if(this.LayerEdges!=null){let e=this.LayerEdges.length;t.LayerEdges=new Array(e);for(let i=0;i<e;i++){let r=this.LayerEdges[e-1-i];t.LayerEdges[i]=new Ki(r.Target,r.Source,r.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){let e=this.LayerEdges.length/2,i=this.LayerEdges[e];dP.updateLabel(this.edge,t[i.Source])}}[Symbol.iterator](){return this.nodes()}*nodes(){yield this.LayerEdges[0].Source;for(let t of this.LayerEdges)yield t.Target}},Fi=class sd{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;let i=this.arrayOfSets[t];return i!==void 0&&i.has(e)}constructor(){this.arrayOfSets=new Array}static mk(t){let e=new sd;for(let i of t)e.add(i);return e}*values(){for(let t=0;t<this.arrayOfSets.length;t++){let e=this.arrayOfSets[t];if(e)for(let i of e.values())yield new mt(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(let t of this.arrayOfSets)t&&t.clear()}},cP=class{constructor(){this.maxLayerOfGeomGraph=new Set,this.minLayerOfGeomGraph=new Set,this.sameLayerConstraints=new Array,this.upDownConstraints=new Array,this.gluedUpDownIntConstraints=new Fi,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(n,t){throw new Error("Method not implemented.")}pinNodeToMaxLayer(n){this.maxLayerOfGeomGraph.add(n)}pinNodeToMinLayer(n){this.minLayerOfGeomGraph.add(n)}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(n,t){return this.nodeIdToIndex=t,this.intGraph=n,this.maxRepresentative=-1,this.minRepresentative=-1,this.createIntegerConstraints(),this.glueTogetherSameConstraintsMaxAndMin(),this.addMaxMinConstraintsToGluedConstraints(),this.removeCyclesFromGluedConstraints(),this.getFeedbackSet()}removeCyclesFromGluedConstraints(){let n=yi(Array.from(this.gluedUpDownIntConstraints.values()),this.intGraph.nodeCount),t=zn.getFeedbackSetWithConstraints(n,null);for(let e of t)this.gluedUpDownIntConstraints.remove(e)}addMaxMinConstraintsToGluedConstraints(){if(this.maxRepresentative!==-1)for(let n=0;n<this.intGraph.nodeCount;n++){let t=this.nodeToRepr(n);t!==this.maxRepresentative&&this.gluedUpDownIntConstraints.add(new mt(this.maxRepresentative,t))}if(this.minRepresentative!==-1)for(let n=0;n<this.intGraph.nodeCount;n++){let t=this.nodeToRepr(n);t!==this.minRepresentative&&this.gluedUpDownIntConstraints.add(new mt(t,this.minRepresentative))}}glueTogetherSameConstraintsMaxAndMin(){this.createDictionaryOfSameLayerRepresentatives();let n=this.upDownInts.map(this.gluedIntPairNN);this.gluedUpDownIntConstraints=new Fi}gluedIntPairNN(n){return new mt(this.nodeToRepr(n[0]),this.nodeToRepr(n[1]))}gluedIntPairI(n){return new mt(this.nodeToRepr(n.source),this.nodeToRepr(n.target))}gluedIntPair(n){return new mt(this.nodeToRepr(n.source),this.nodeToRepr(n.target))}gluedIntEdge(n){let t=this.nodeToRepr(n.source),e=this.nodeToRepr(n.target),i=new Bi(t,e,n.edge);return i.separation=n.separation,i.weight=0,i}nodeToRepr(n){return this.sameLayerDictionaryOfRepresentatives.get(n)||n}createDictionaryOfSameLayerRepresentatives(){let n=this.createGraphOfSameLayers();for(let t of tn(n))this.glueSameLayerNodesOfALayer(t)}createGraphOfSameLayers(){return yi(this.createEdgesOfSameLayers(),this.intGraph.nodeCount)}createEdgesOfSameLayers(){let n=new Array;return this.maxRepresentative!==-1&&this.maxLayerInt.filter(t=>t!==this.maxRepresentative).map(t=>new mt(this.maxRepresentative,t)).forEach(t=>n.push(t)),this.minRepresentative!==-1&&this.minLayerInt.filter(t=>t!==this.minRepresentative).map(t=>new mt(this.minRepresentative,t)).forEach(t=>n.push(t)),this.sameLayerInts.forEach(t=>n.push(new mt(t[0],t[1]))),n}glueSameLayerNodesOfALayer(n){if(n.length>1){let t=-1;if(this.componentsIsMaxLayer(n))for(let e of n)this.sameLayerDictionaryOfRepresentatives.set(e,t=this.maxRepresentative);else if(this.componentIsMinLayer(n))for(let e of n)this.sameLayerDictionaryOfRepresentatives.set(e,t=this.minRepresentative);else for(let e of n)t===-1&&(t=e),this.sameLayerDictionaryOfRepresentatives.set(e,t);this.representativeToItsLayer.set(t,n)}}componentIsMinLayer(n){return n.findIndex(t=>this.minRepresentative===t)>=0}componentsIsMaxLayer(n){return n.findIndex(t=>this.maxRepresentative===t)>=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(n){return n.map(t=>[this.nodeIndex(t[0]),this.nodeIndex(t[1])]).filter(t=>t[0]!==-1&&t[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(n){return Array.from(n).map(t=>this.nodeIndex(t)).filter(t=>t!==-1)}nodeIndex(n){return this.nodeIdToIndex.get(n.node.id)||-1}getFeedbackSet(){return this.gluedIntGraph=this.createGluedGraph(),Array.from(this.unglueIntPairs(zn.getFeedbackSetWithConstraints(this.gluedIntGraph,this.gluedUpDownIntConstraints)))}*unglueIntPairs(n){for(let t of n)for(let e of this.unglueEdge(t))yield e}*unglueEdge(n){for(let t of this.unglueNode(n.source))for(let e of this.intGraph.outEdges[t])this.nodeToRepr(e.target)===n.target&&(yield e)}createGluedGraph(){let n=new Fi;return this.intGraph.edges.forEach(t=>n.add(this.gluedIntPairI(t))),yi(Array.from(n.values()),this.intGraph.nodeCount)}unglueNode(n){return this.representativeToItsLayer.get(n)||[n]}getGluedNodeCounts(){let n=new Array(this.nodeIdToIndex.size).fill(0);for(let t=0;t<n.length;t++)n[this.nodeToRepr(t)]++;return n}};function gP(n,t){return[n,t]}var pP=class{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(n){for(let t=0;t<n.length-1;t++)this.AddSameLayerNeighborsPair(n[t],n[t+1])}AddSameLayerNeighborsPair(n,t){this.leftRightNeighbors.push([n,t])}NodeToBlockRootSoft(n){return this.nodeToBlockRoot.get(n)||n}CreateMappingOfNeibBlocks(){let n=this.BasicGraphFromLeftRightIntNeibs();for(let t=0;t<n.nodeCount;t++)if(n.inEdges[t].length===0&&!this.nodeToBlockRoot.has(t)){let e=new Array,i=t;for(let r=n.outEdges[i];r.length>0;r=n.outEdges[i])i=r[0].y,e.push(i),this.nodeToBlockRoot.set(i,t);e.length>0&&this.BlockRootToBlock.set(t,e)}}BasicGraphFromLeftRightIntNeibs(){return Ks(Array.from(this.LeftRightIntNeibs.values()).map(n=>new mt(n.x,n.y)))}NodeIndex(n){return this.nodeIdToIndex.get(n.id)||-1}PrepareForOrdering(n,t){this.nodeIdToIndex=n,this.MapNodesToToIntegers(t),this.CreateMappingOfNeibBlocks(),this.LiftLeftRightRelationsToNeibBlocks()}LiftLeftRightRelationsToNeibBlocks(){this.LeftRighInts=Fi.mk(this.leftRightConstraints.map(t=>gP(this.NodeIndex(t[0]),this.NodeIndex(t[1]))).filter(t=>t[0]!==-1&&t[1]!==-1).map(t=>new mt(this.NodeToBlockRootSoft(t[0]),this.NodeToBlockRootSoft(t[1]))).filter(t=>t.x!==t.x));let n=zn.getFeedbackSet(Ks(Array.from(this.LeftRighInts.values())));for(let t of n)this.LeftRighInts.remove(new mt(t.source,t.target))}MapNodesToToIntegers(n){this.LeftRightIntNeibs=Fi.mk(Array.from(this.leftRightNeighbors.values()).map(t=>[this.NodeIndex(t[0]),this.NodeIndex(t[1])]).filter(t=>t[0]!==-1&&t[1]!==-1).map(t=>new mt(t[0],t[1]))),this.VerticalInts=Fi.mk(this.upDownVerticalConstraints.map(t=>[this.NodeIndex(t[0]),this.NodeIndex(t[1])]).filter(t=>t[0]!==-1&&t[1]!==-1&&n[t[0]]>n[t[1]]).map(t=>new mt(t[0],t[1])))}},ll=(n=>(n[n.TB=0]="TB",n[n.LR=1]="LR",n[n.BT=2]="BT",n[n.RL=3]="RL",n[n.None=4]="None",n))(ll||{}),Ia=class li{constructor(){this.capacityOverflowCoefficient=li.DefaultCapacityOverflowCoefficientMultiplier,this.RotateBundles=!1,this.MaxHubRadius=50,this.MinHubRadius=.1,this.CreateUnderlyingPolyline=!1,this.pathLengthImportance=li.DefaultPathLengthImportance,this.inkImportance=li.DefaultInkImportance,this.edgeSeparation=li.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(){let t={};return this.capacityOverflowCoefficient!=li.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!=li.DefaultPathLengthImportance&&(t.pathLengthImportance=this.pathLengthImportance),this.inkImportance!=li.DefaultInkImportance&&(t.inkImportance=this.inkImportance),this.edgeSeparation!=li.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){let e=new li;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}static{this.DefaultCapacityOverflowCoefficientMultiplier=1e3}get CapacityOverflowCoefficient(){return this.capacityOverflowCoefficient}set CapacityOverflowCoefficient(t){this.capacityOverflowCoefficient=t}static{this.DefaultPathLengthImportance=500}get PathLengthImportance(){return this.pathLengthImportance}set PathLengthImportance(t){this.pathLengthImportance=t}static{this.DefaultInkImportance=.01}get InkImportance(){return this.inkImportance}set InkImportance(t){this.inkImportance=t}static{this.DefaultEdgeSeparation=.5}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}},Ta=class od{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.smoothCorners=!1,this.KeepOriginalSpline=!1,this.EdgeRoutingMode=0}toJSON(){let t={};return this.EdgeRoutingMode!=0&&(t.edgeRoutingMode=0),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){let e=new od;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=Ia.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}get EdgeRoutingMode(){return this.edgeRoutingMode}set EdgeRoutingMode(t){t===1&&this.bundlingSettings==null&&this.bundlingSettings==null&&(this.bundlingSettings=new Ia),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}},ao=class ad{constructor(){this.edgeRoutingSettings=new Ta,this.nodeSeparation=10,this.packingAspectRatio=1.5}static fromJSON(t){let e=new ad;return t.nodeSeparation!=10&&(e.nodeSeparation=t.nodeSeparation),t.packingAspectRatio&&(e.packingAspectRatio=t.packingAspectRatio),t.edgeRoutingSettings&&(e.edgeRoutingSettings=Ta.fromJSON(t.edgeRoutingSettings)),e}toJSON(){let t=!1,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}},Jn=class ld{constructor(){this.commonSettings=new ao,this.verticalConstraints=new cP,this.horizontalConstraints=new pP,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=0,this.yLayerSep=30,this.transform=Oe.getIdentity(),this.GridSizeByY=0,this.GridSizeByX=0,this.commonSettings.edgeRoutingSettings.EdgeRoutingMode=3}get NodeSeparation(){return this.commonSettings.NodeSeparation}get edgeRoutingSettings(){return this.commonSettings.edgeRoutingSettings}set edgeRoutingSettings(t){this.commonSettings.edgeRoutingSettings=t}toJSON(){let 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!=0&&(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){let e=new ld;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 Oe(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=ao.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}transformIsRotation(t){let e=Oe.rotation(t);for(let i=0;i<2;i++)for(let r=0;r<3;r++)if(!lt(e.elements[i][r],this.transform.elements[i][r]))return!1;return!0}get layerDirection(){if(this.transformIsRotation(0))return 0;if(this.transformIsRotation(Math.PI/2))return 1;if(this.transformIsRotation(-Math.PI/2))return 3;if(this.transformIsRotation(Math.PI))return 2;throw new Error("unexpected layout direction")}set layerDirection(t){switch(t){case 0:this.transform=Oe.getIdentity();break;case 1:this.transform=Oe.rotation(Math.PI/2);break;case 3:this.transform=Oe.rotation(-Math.PI/2);break;case 2:this.transform=Oe.rotation(Math.PI);break;default:throw new Error("unexpected layout direction")}}},hd=class extends Nt{constructor(n,t,e){super(null),this.graph=n,this.source=t,this.length=e}get Result(){return this.result}run(){let n=new nr((i,r)=>i-r),t=new Map;for(let i of this.graph.shallowNodes){let r=i===this.source?0:Number.POSITIVE_INFINITY;n.Enqueue(i,r),t.set(i,r)}for(;n.count>0;){let i={priority:0},r=n.DequeueAndGetPriority(i);t.set(r,i.priority);let s=t.get(r);for(let o of r.inEdges()){let a=o.source,l=s+this.length(o);t.get(a)>l&&(t.set(a,l),n.DecreasePriority(a,l))}for(let o of r.outEdges()){let a=o.target,l=s+this.length(o);t.get(a)>l&&(t.set(a,l),n.DecreasePriority(a,l))}}this.result=new Array(this.graph.shallowNodeCount);let e=0;for(let i of this.graph.shallowNodes){let r=t.get(i);r!==void 0?this.result[e++]=r:this.result[e++]=Number.POSITIVE_INFINITY}}},fP=class ud extends Nt{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(let e of this.graph.shallowNodes){let i=new hd(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;let r=new ud(t,e);r.run();let s=r.Result,o=0;for(let l of t.shallowEdges)o+=e(l);o/=t.edgeCount;let a=0;for(let l of t.shallowNodes){let h=l.center.x,u=l.center.y,d=0;for(let c of t.shallowNodes){if(d>=a)break;let f=h-c.center.x,m=u-c.center.y,P=Math.sqrt(f*f+m*m),v=o*s[a][d],b=v-P;i+=b*b/(v*v),d++}a++}return i*2}},mP=class extends Nt{get Result(){return this.result}constructor(n,t,e){super(null),this.graph=n,this.pivotArray=t,this.length=e}run(){this.result=new Array(this.pivotArray.length);let n=Array.from(this.graph.shallowNodes),t=new Array(this.graph.shallowNodeCount).fill(Number.POSITIVE_INFINITY),e=n[0];this.pivotArray[0]=0;for(let i=0;;i++){let r=new hd(this.graph,e,this.length);if(r.run(),this.Result[i]=r.Result,i+1<this.pivotArray.length){let s=0;for(let o=0;o<this.Result[i].length;o++)t[o]=Math.min(t[o],this.Result[i][o]),t[o]>t[s]&&(s=o);e=n[s],this.pivotArray[i+1]=s}else break}}},PP=class{static Rotate(n,t,e){let i=Math.sin(e*(Math.PI/180)),r=Math.cos(e*(Math.PI/180));for(let s=0;s<n.length;s++){let o=r*n[s]+i*t[s];t[s]=r*t[s]-i*n[s],n[s]=o}}},ra=class Rt{static DoubleCenter(t){let e=new Array(t.length).fill(0),i=new Array(t[0].length).fill(0),r=0;for(let s=0;s<t.length;s++)for(let o=0;o<t[0].length;o++)e[s]+=t[s][o],i[o]+=t[s][o],r+=t[s][o];for(let s=0;s<t.length;s++)e[s]/=t.length;for(let s=0;s<t[0].length;s++)i[s]/=t[0].length;r/=t.length,r/=t[0].length;for(let s=0;s<t.length;s++)for(let o=0;o<t[0].length;o++)t[s][o]-=e[s]+i[o]-r}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 r=0;r<t[0].length;r++)t[i][r]*=e}static MultiplyX(t,e){if(t[0].length!==e.length)return null;let i=new Array(e.length).fill(0);for(let r=0;r<t.length;r++)for(let s=0;s<t[0].length;s++)i[r]+=t[r][s]*e[s];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){let e=Rt.Norm(t);if(e<=0)return 0;for(let i=0;i<t.length;i++)t[i]/=e;return e}static RandomUnitLengthVector(t){let e=new Array(t);for(let i=0;i<t;i++)e[i]=Tr();return Rt.Normalize(e),e}static SpectralDecomposition(t,e){Rt.SpectralDecompositionIE(t,e,30,1e-6)}static SpectralDecompositionIE(t,e,i,r){let s=t[0].length;e.u1=Rt.RandomUnitLengthVector(s),e.lambda1=0,e.u2=Rt.RandomUnitLengthVector(s),e.lambda2=0;let o=0,a=1-r;for(let l=0;l<i&&o<a;l++){let h=Rt.MultiplyX(t,e.u1),u=Rt.MultiplyX(t,e.u2);e.lambda1=Rt.Normalize(h),e.lambda2=Rt.Normalize(u),Rt.MakeOrthogonal(u,h),Rt.Normalize(u),o=Math.min(Rt.DotProduct(e.u1,h),Rt.DotProduct(e.u2,u)),e.u1=h,e.u2=u}}static DotProduct(t,e){if(t.length!==e.length)return 0;let i=0;for(let r=0;r<t.length;r++)i+=t[r]*e[r];return i}static MakeOrthogonal(t,e){if(t.length!==e.length)return;let i=Rt.DotProduct(t,e)/Rt.DotProduct(e,e);for(let r=0;r<t.length;r++)t[r]-=i*e[r]}static ClassicalScaling(t,e){let i=new Array(t.length);for(let r=0;r<t.length;r++)i[r]=t[r].slice();Rt.SquareEntries(i),Rt.DoubleCenter(i),Rt.Multiply(i,-.5),Rt.SpectralDecomposition(i,e),e.lambda1=Math.sqrt(Math.abs(e.lambda1)),e.lambda2=Math.sqrt(Math.abs(e.lambda2));for(let r=0;r<e.u1.length;r++)e.u1[r]*=e.lambda1,e.u2[r]*=e.lambda2}static DistanceScalingSubset(t,e,i,r,s){let o=e.length,a=t.length,l=new Array(a);for(let u=0;u<a;u++)for(let d=0;d<o;d++)t[u][d]===0&&(l[u]=d);let h=new Array(a).fill(0);for(let u=0;u<a;u++)for(let d=0;d<o;d++)l[u]!==d&&(h[u]+=r[u][d]);for(let u=0;u<s;u++)for(let d=0;d<a;d++){let c=0,f=0;for(let m=0;m<o;m++)if(d!==m){let P=Math.sqrt(Math.pow(e[l[d]]-e[m],2)+Math.pow(i[l[d]]-i[m],2));P>0&&(P=1/P),c+=r[d][m]*(e[m]+t[d][m]*(e[l[d]]-e[m])*P),f+=r[d][m]*(i[m]+t[d][m]*(i[l[d]]-i[m])*P)}e[l[d]]=c/h[d],i[l[d]]=f/h[d]}}static DistanceScaling(t,e,i,r,s){let o=e.length,a=new Array(o).fill(0);for(let l=0;l<o;l++)for(let h=0;h<o;h++)l!==h&&(a[l]+=r[l][h]);for(let l=0;l<s;l++)for(let h=0;h<o;h++){let u=0,d=0;for(let c=0;c<o;c++)if(h!==c){let f=Math.sqrt(Math.pow(e[h]-e[c],2)+Math.pow(i[h]-i[c],2));f>0&&(f=1/f),u+=r[h][c]*(e[c]+t[h][c]*(e[h]-e[c])*f),d+=r[h][c]*(i[c]+t[h][c]*(i[h]-i[c])*f)}e[h]=u/a[h],i[h]=d/a[h]}}static ExponentialWeightMatrix(t,e){let i=new Array(t.length);for(let r=0;r<t.length;r++){i[r]=new Array(t[r].length).fill(0);for(let s=0;s<t[r].length;s++)t[r][s]>0&&(i[r][s]=Math.pow(t[r][s],e))}return i}static EuclideanDistanceMatrix(t,e){let i=new Array(t.length);for(let r=0;r<t.length;r++){i[r]=new Array(t.length);for(let s=0;s<t.length;s++)i[r][s]=Math.sqrt(Math.pow(t[r]-t[s],2)+Math.pow(e[r]-e[s],2))}return i}static LandmarkClassicalScaling(t,e,i){let r=new Array(t.length);for(let a=0;a<t.length;a++){r[a]=new Array(t.length);for(let l=0;l<t.length;l++)r[a][l]=t[a][i[l]]}Rt.SquareEntries(r);let s=new Array(t.length).fill(0);for(let a=0;a<t.length;a++){for(let l=0;l<t.length;l++)s[a]+=r[a][l];s[a]/=t.length}Rt.DoubleCenter(r),Rt.Multiply(r,-.5);let o={u1:new Array,u2:new Array,lambda1:0,lambda2:0};Rt.SpectralDecomposition(r,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 l=0;l<r.length;l++){let h=(Math.pow(t[l][a],2)-s[l])/2;e.x[a]-=o.u1[l]*h,e.y[a]-=o.u2[l]*h}}},yP=class Ms{constructor(t,e){this.start=t,this.end=e}add(t){this.add_d(t)}add_rect(t){let e=t,i=this.clone();return i.add_d(e.start),i.add_d(e.end),i}clone(){return new Ms(this.start,this.end)}contains_point(t){return this.contains_d(t)}contains_rect(t){let e=t;return this.contains_d(e.start)&&this.contains_d(e.end)}intersection_rect(t){let e=t;return new Ms(Math.max(this.start,e.start),Math.min(this.end,e.end))}intersects_rect(t){let 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){let i=new Ms(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+x.distanceEpsilon?!1:!(t.end<this.start-x.distanceEpsilon)}},dd=class{constructor(n){this.heapSize=0,this._priors=new Array(n),this._heap=new Array(n+1),this._reverse_heap=new Array(n)}get Count(){return this.heapSize}SwapWithParent(n){let t=this._heap[n>>1];this.PutAtI(n>>1,this._heap[n]),this.PutAtI(n,t)}Enqueue(n,t){this.heapSize++;let e=this.heapSize;for(this._priors[n]=t,this.PutAtI(e,n);e>1&&this._priors[this._heap[e>>1]]>t;)this.SwapWithParent(e),e>>=1}PutAtI(n,t){this._heap[n]=t,this._reverse_heap[t]=n}Dequeue(){if(this.heapSize===0)throw new Error;let n=this._heap[1];if(this.heapSize>1){this.PutAtI(1,this._heap[this.heapSize]);let t=1;for(;;){let e=t,i=t<<1;i<=this.heapSize&&this._priors[this._heap[i]]<this._priors[this._heap[t]]&&(e=i);let r=i+1;if(r<=this.heapSize&&this._priors[this._heap[r]]<this._priors[this._heap[e]]&&(e=r),e!==t)this.SwapWithParent(e);else break;t=e}}return this.heapSize--,n}IsEmpty(){return this.heapSize===0}DecreasePriority(n,t){this._priors[n]=t;let e=this._reverse_heap[n];for(;e>1&&this._priors[this._heap[e]]<this._priors[this._heap[e>>1]];)this.SwapWithParent(e),e>>=1}},SP=class{constructor(n,t,e,i){this._numberOfOverlaps=0,this._proximityEdges=n,this._nodeSizes=t,this._nodePositions=e,this._forLayers=i,this._q=new dd(t.length*2)}Run(){return this.InitQueue(),this.FindOverlaps(),this._numberOfOverlaps}FindOverlaps(){for(;this._q.Count>0;){let n=this._q.Dequeue();n<this._nodePositions.length?(this.FindOverlapsWithInterval(n),this.AddIntervalToTree(n)):(n-=this._nodePositions.length,this.RemoveIntervalFromTree(n))}}RemoveIntervalFromTree(n){this._intervalTree.Remove(this.GetInterval(n),n)}AddIntervalToTree(n){let t=this.GetInterval(n);this._intervalTree==null&&(this._intervalTree=Vn([])),this._intervalTree.Add(t,n)}FindOverlapsWithInterval(n){if(this._intervalTree==null)return;let t=this.GetInterval(n);for(let e of this._intervalTree.GetAllIntersecting(t)){let i=hl.GetIdealEdge(n,e,this._nodePositions[n],this._nodePositions[e],this._nodeSizes);if(i.overlapFactor<=1)return;this._proximityEdges.push(i),this._numberOfOverlaps++}}GetInterval(n){let t=this._nodeSizes[n].width/2,e=this._nodePositions[n].x;return new yP(e-t,e+t)}InitQueue(){for(let n=0;n<this._nodeSizes.length;n++){let t=this._nodeSizes[n].height/2,e=this._nodePositions[n].y;this._q.Enqueue(n,e-t),this._q.Enqueue(this._nodeSizes.length+n,e+t)}}},$h=class{constructor(n,t,e){this.treeNodes=new Set,this.hedgehog=new Map,this.graph=n,this.weight=t,this.root=e,this.q=new dd(this.graph.nodeCount)}NodeIsInTree(n){return this.treeNodes.has(n)}GetTreeEdges(){let n=new Array;for(this.Init();n.length<this.graph.nodeCount-1&&this.q.Count>0;)this.AddEdgeToTree(n);return n}AddEdgeToTree(n){let t=this.q.Dequeue(),e=this.hedgehog.get(t);this.treeNodes.add(t),n.push(e),this.UpdateOutEdgesOfV(t),this.UpdateInEdgesOfV(t)}UpdateOutEdgesOfV(n){for(let t of this.graph.outEdges[n]){let e=t.target;if(this.NodeIsInTree(e))continue;let i=this.hedgehog.get(e);if(i){let r=this.weight(i),s=this.weight(t);s<r&&(this.q.DecreasePriority(e,s),this.hedgehog.set(e,t))}else this.q.Enqueue(e,this.weight(t)),this.hedgehog.set(e,t)}}UpdateInEdgesOfV(n){for(let t of this.graph.inEdges[n]){let e=t.source;if(this.NodeIsInTree(e))continue;let i=this.hedgehog.get(e);if(i){let r=this.weight(i),s=this.weight(t);s<r&&(this.q.DecreasePriority(e,s),this.hedgehog.set(e,t))}else this.q.Enqueue(e,this.weight(t)),this.hedgehog.set(e,t)}}Init(){this.treeNodes.add(this.root);for(let n of this.graph.outEdges[this.root]){let t=this.weight(n);this.q.Enqueue(n.target,t),this.hedgehog.set(n.target,n)}for(let n of this.graph.inEdges[this.root]){let t=this.weight(n);this.q.Enqueue(n.source,t),this.hedgehog.set(n.source,n)}}},bP=class cd{static GetMst(t,e){if(t.length===0)return null;let i=t.map(o=>new mt(o.source,o.target)),r=new Jr;for(let o=0;o<t.length;o++)r.setPair(i[o],t[o]);let s=yi(i,e);return new $h(s,o=>r.get(o.source,o.target).weight,i[0].source).GetTreeEdges().map(o=>r.get(o.source,o.target))}static GetMstOnCdt(t,e){let i=Array.from(t.PointsToSites.values()),r=new Map;for(let a=0;a<i.length;a++)r.set(i[a],a);let s=cd.GetEdges(i,r),o=vu(Array.from(s.keys()));return new $h(o,a=>e(s.get(a.source,a.target)),0).GetTreeEdges().map(a=>s.get(a.source,a.target))}static GetEdges(t,e){let i=new Jr;for(let r=0;r<t.length;r++){let s=t[r],o=e.get(s);for(let a of s.Edges)i.set(o,e.get(a.lowerSite),a)}return i}},CP=class gd{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(){let t=new gd;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}},hl=class Ui{constructor(t,e){this._settings=t,this._nodes=e}static RemoveOverlaps(t,e){let i=new CP;i.RandomizationShift=1,i.NodeSeparation=e,new Ui(i,t).RemoveOverlaps()}RemoveOverlaps(){if(this._nodes.length<3){this.RemoveOverlapsOnTinyGraph();return}let t={nodePositions:new Array,nodeSizes:new Array};for(vP(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){let t=this._nodes[0],e=this._nodes[1];g.closeDistEps(t.center,e.center)&&(e.center=e.center.add(new g(.001,0)));let i=this.GetIdealDistanceBetweenTwoNodes(t,e),r=g.middle(t.center,e.center),s=t.center.sub(e.center),o=s.length;s=s.mul(.5*(i/o)),t.center=r.add(s),e.center=r.sub(s)}}GetIdealDistanceBetweenTwoNodes(t,e){let i=t.center.sub(e.center),r=Math.abs(i.x),s=Math.abs(i.y),o=(t.width+e.width)/2+this._settings.NodeSeparation,a=(t.height+e.height)/2+this._settings.NodeSeparation,l=Number.POSITIVE_INFINITY,h=Number.POSITIVE_INFINITY;return r>x.tolerance&&(l=o/r),s>x.tolerance&&(h=a/s),Math.min(l,h)*i.length}static AvgEdgeLength(t){let e=0,i=0;for(let r of t)for(let s of r.outEdges())i+=r.center.sub(s.target.center).length,e++;return e>0?i/e:1}OneIteration(t,e,i){let r=new Array;for(let u=0;u<t.length;u++)r.push([t[u],u]);let s=Ae.constructor_(r);s.run();let o=new Map;for(let u=0;u<t.length;u++)o.set(s.PointsToSites.get(t[u]),u);let a=0,l=new Array;for(let u of s.PointsToSites.values())for(let d of u.Edges){let c=d.upperSite.point,f=d.lowerSite.point,m=o.get(d.upperSite),P=o.get(d.lowerSite),v=Ui.GetIdealEdge(m,P,c,f,e);l.push(v),v.overlapFactor>1&&a++}if(a===0||i){let u=this.FindProximityEdgesWithSweepLine(l,e,t);if(a===0&&u===0||a===0&&!i)return!1}let h=bP.GetMst(l,t.length);return Ui.MoveNodePositions(h,t,h[0].source),!0}FindProximityEdgesWithSweepLine(t,e,i){return new SP(t,e,i,this._overlapForLayers).Run()}static GetIdealEdge(t,e,i,r,s){let o={overlapFactor:0},a=Ui.GetIdealEdgeLength(t,e,i,r,s,o),l=i.sub(r).length,h=it.mkSizeCenter(s[t],i),u=it.mkSizeCenter(s[e],r),d=o.overlapFactor>1?l-a:Ui.GetDistanceRects(h,u);return{source:Math.min(t,e),target:Math.max(t,e),overlapFactor:o.overlapFactor,idealDistance:a,weight:d}}static GetIdealEdgeLength(t,e,i,r,s,o){let a=i.sub(r),l=a.length,h=Math.abs(a.x),u=Math.abs(a.y),d=(s[t].width+s[e].width)/2,c=(s[t].height+s[e].height)/2;if(h>=d||u>=c)return o.overlapFactor=1,a.length;let f,m=1e-10;if(h>m)u>m?f=Math.min(d/h,c/u):f=d/h;else if(u>m)f=c/u;else return o.overlapFactor=2,Math.sqrt(d*d+c*c)/4;return f=Math.max(f,1.001),o.overlapFactor=f,f*l}static GetDistanceRects(t,e){if(t.intersects(e))return 0;let i=0,r=0;return(t.right<e.left||e.right<t.left)&&(r=t.left-e.right),t.top<e.bottom?i=e.bottom-t.top:e.top<t.bottom&&(i=t.bottom-e.top),Math.sqrt(r*r+i*i)}static MoveNodePositions(t,e,i){let r=e.map(o=>o.clone()),s=new Set;s.add(i);for(let o=0;o<t.length;o++){let a=t[o];s.has(a.source)?Ui.MoveNode(a.source,a.target,r,e,s,a.idealDistance):Ui.MoveNode(a.target,a.source,r,e,s,a.idealDistance)}}static MoveNode(t,e,i,r,s,o){let a=i[e].sub(i[t]);a=a.mul(o/a.length+.01),r[e]=r[t].add(a),s.add(e)}GetLastRunIterations(){return this.lastRunNumberIterations}};function vP(n,t,e,i){e.nodePositions=t.map(r=>r.center),i&&xP(e.nodePositions,new go(0,0),i),e.nodeSizes=t.map(r=>{let s=r.boundingBox.size;return s.width+=n.NodeSeparation,s.height+=n.NodeSeparation,s})}function xP(n,t,e){let i=new Zt;for(let r=0;r<n.length;r++){let s=n[r];if(e||i.has(s))do{let o=s.x+(2*t.random()-1)*e,a=s.y+(2*t.random()-1)*e;s=new g(o,a)}while(i.has(s));n[r]=s,i.add(s)}}var pd=class Oa extends Nt{constructor(t,e,i,r){super(i),this.settings=t,this.graph=e,this.length=r}run(){this.LayoutConnectedGraphWithMds(),this.graph.pumpTheBoxToTheGraphWithMargins()}static ScaleToAverageEdgeLength(t,e,i,r){let s=new Map,o=0;for(let h of t.shallowNodes)s.set(h,o),o++;let a=0,l=0;for(let h of t.shallowEdges){let u=s.get(h.source),d=s.get(h.target);l+=Math.sqrt(Math.pow(e[u]-e[d],2)+Math.pow(i[u]-i[d],2)),a+=r(h)}if(a>0&&(l/=a),l>0)for(let h=0;h<e.length;h++)e[h]/=l,i[h]/=l}static LayoutGraphWithMds(t,e,i,r){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}let s=Math.min(e.PivotNumber,t.shallowNodeCount),o=e.GetNumberOfIterationsWithMajorization(t.shallowNodeCount),a=e.Exponent,l=new Array(s),h=new mP(t,l,r);h.run();let u=h.Result;if(ra.LandmarkClassicalScaling(u,i,l),Oa.ScaleToAverageEdgeLength(t,i.x,i.y,r),o>0){let d=new fP(t,r);d.run();let c=d.Result,f=ra.ExponentialWeightMatrix(c,a);ra.DistanceScalingSubset(c,i.x,i.y,f,o)}}LayoutConnectedGraphWithMds(){let t={x:[],y:[]};Oa.LayoutGraphWithMds(this.graph,this.settings,t,this.length),this.settings.RotationAngle!==0&&PP.Rotate(t.x,t.y,this.settings.RotationAngle);let e=0;for(let i of this.graph.shallowNodes)i.boundingBox&&(i.center=new g(t.x[e]*this.settings.ScaleX,t.y[e]*this.settings.ScaleY)),e++;this.settings.removeOverlaps&&hl.RemoveOverlaps(Array.from(this.graph.shallowNodes),this.settings.NodeSeparation),this.graph.pumpTheBoxToTheGraphWithMargins()}ScaleNodes(t,e){for(let i of t)i.center=i.center.mul(e)}static PackGraphs(t,e){if(t.length===0)return it.mkEmpty();if(t.length===1)return t[0].boundingBox;let i=t.map(o=>o.boundingBox),r=new Array;for(let o of t)r.push({g:o,lb:o.boundingBox.leftBottom.clone()});let s=new qu(i,e.PackingAspectRatio);s.run();for(let{g:o,lb:a}of r){let l=o.boundingBox.leftBottom.sub(a);o.translate(l)}return new it({left:0,bottom:0,right:s.PackedWidth,top:s.PackedHeight})}},La=class fd{constructor(){this.commonSettings=new ao,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){let e=new fd;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(){let 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}},md=class extends Nt{get scaleX(){return this.settings.ScaleX}set scaleX(n){this.settings.ScaleX=n}get scaleY(){return this.settings.ScaleY}set scaleY(n){this.settings.ScaleY=n}constructor(n,t,e,i){super(t),this.graph=n,this.length=e,this.settings=i,this.settings.ScaleX=this.settings.ScaleY=200}run(){new pd(this.settings,this.graph,this.cancelToken,this.length).run()}};function Pd(n,t,e){if(t)for(let i of t){if(e&&e.canceled)return;na.RouteEdge(i)}else for(let i of n.nodesBreadthFirst){if(e&&e.canceled)return;for(let r of i.outEdges())r.curve==null&&na.RouteEdge(r);for(let r of i.selfEdges())r.curve==null&&na.RouteEdge(r)}}var na=class hi extends Nt{constructor(t,e){super(null),this.edges=t,this.padding=e}run(){Or.CreatePortsIfNeeded(this.edges);for(let t of this.edges)hi.RouteEdge(t)}static RouteEdge(t){let e=t;e.sourcePort==null&&(e.sourcePort=Si.mk(()=>t.source.boundaryCurve,()=>t.source.center)),e.targetPort==null&&(e.targetPort=Si.mk(()=>t.target.boundaryCurve,()=>t.target.center)),hi.ContainmentLoop(e)||(e.curve=hi.GetEdgeLine(t)),ge.trimSplineAndCalculateArrowheadsII(e,e.sourcePort.Curve,e.targetPort.Curve,t.curve,!1)}static ContainmentLoop(t){let e=t.sourcePort.Curve,i=t.targetPort.Curve;if(e==null||i==null)return!1;let r=e.boundingBox,s=i.boundingBox,o=r.containsRect(s),a=!o&&s.containsRect(r);return o||a?(t.curve=hi.CreateLoop(r,s,a),!0):!1}static CreateLoop(t,e,i){return i?hi.CreateLoop_(t,e,!1):hi.CreateLoop_(e,t,!0)}static CreateLoop_(t,e,i){let r=t.center,s=hi.FindClosestPointOnBoxBoundary(t.center,e),o=s.sub(r),a=(Math.abs(o.x)<x.distanceEpsilon?Math.min(r.y-e.bottom,e.top-r.y):Math.min(r.x-e.left,e.right-r.x))/2,l=1,h=Math.min(l,a);o.length<=x.distanceEpsilon&&(o=new g(1,0));let u=o.normalize(),d=u.rotate(Math.PI/2),c=s.add(u.mul(l)),f=c.add(d.mul(h)),m=s.add(d.mul(h)),P=r.add(d.mul(h));return(i?Ot.mkFromPoints([P,m,f,c,s,r]):Ot.mkFromPoints([r,s,c,f,m,P])).createCurve()}static FindClosestPointOnBoxBoundary(t,e){let i=t.x-e.left<e.right-t.x?e.left:e.right,r=t.y-e.bottom<e.top-t.y?e.bottom:e.top;return Math.abs(i-t.x)<Math.abs(r-t.y)?new g(i,t.y):new g(t.x,r)}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 r,s;t.targetPort==null?(r=t.target.center,s=t.target.boundaryCurve):(r=t.targetPort.Location,s=t.targetPort.Curve);let o=D.mkPP(e,r),a=G.getAllIntersections(i,o,!1);if(a.length>0){let l=o.trim(a[0].par1,1);l instanceof D&&(o=l,a=G.getAllIntersections(s,o,!1),a.length>0&&(l=o.trim(0,a[0].par1),l instanceof D&&(o=l)))}return o}static CreateSimpleEdgeCurveWithUnderlyingPolyline(t){let e=t.sourcePort?t.sourcePort.Location:t.source.center,i=t.targetPort?t.targetPort.Location:t.target.center;if(t.source===t.target){let r=2/(3*t.source.boundaryCurve.boundingBox.width),s=t.source.boundingBox.height/4;t.smoothedPolyline=hi.CreateUnderlyingPolylineForSelfEdge(e,r,s),t.curve=t.smoothedPolyline.createCurve()}else t.smoothedPolyline=Ot.mkFromPoints([e,i]),t.curve=t.smoothedPolyline.createCurve();ge.trimSplineAndCalculateArrowheadsII(t,t.source.boundaryCurve,t.target.boundaryCurve,t.curve,!1)}static CreateUnderlyingPolylineForSelfEdge(t,e,i){let r=t.add(new g(0,i)),s=t.add(new g(e,i)),o=t.add(new g(e,i*-1)),a=t.add(new g(0,i*-1)),l=re.mkSiteP(t),h=new Ot(l);return l=re.mkSiteSP(l,r),l=re.mkSiteSP(l,s),l=re.mkSiteSP(l,o),l=re.mkSiteSP(l,a),re.mkSiteSP(l,t),h}static SetStraightLineEdgesWithUnderlyingPolylines(t){Or.CreatePortsIfNeeded(Array.from(t.deepEdges));for(let e of t.deepEdges)hi.CreateSimpleEdgeCurveWithUnderlyingPolyline(e)}},yd=(n=>(n[n.OverlapsOtherLabels=0]="OverlapsOtherLabels",n[n.OverlapsNodes=1]="OverlapsNodes",n[n.OverlapsEdges=2]="OverlapsEdges",n[n.OverlapsNothing=Number.MAX_VALUE]="OverlapsNothing",n))(yd||{}),EP=class{},AP=class{constructor(){this.points=[],this.coveredLength=0}AddFirst(n){if(this.points.length!==0){let t=this.points[0];this.coveredLength=this.coveredLength+n.Center.sub(t.Center).length}return this.points.unshift(n),this.coveredLength}AddLast(n){if(this.points.length!==0){let t=this.points[this.points.length-1];this.coveredLength=this.coveredLength+n.Center.sub(t.Center).length}return this.points.push(n),this.coveredLength}},Hh=class{constructor(n){this.location=n,this.boundingBox=it.rectangleOnPoint(n)}},xn=class{constructor(n,t){this.data=t,this.boundingBox=n}},wP=class{constructor(n){this.innerPoints=[],this.outerPoints=[],this.placementSide=0,this.placementOffset=.5,this.edgePoints=n,this.placementSide}},fo=class xt extends Nt{constructor(t,e){super(null),this.placementStrategy=[1,0],this.obstacleMaps=[],this.edgeInfos=new Map,this.granularity=xt.MinGranularity,this.ScaleCollisionGranularity=!0,this.granularity=this.ScaleCollisionGranularity?this.interpolateGranularity(e.length):xt.MinGranularity,this.InitializeObstacles(t,e),this.edges=e}static{this.MinGranularity=5}static{this.MaxGranularity=50}static{this.LowerEdgeBound=500}static{this.UpperEdgeBound=3e3}get CollisionGranularity(){return this.granularity}set CollisionGranularity(t){this.granularity=t}static constructorG(t){return new xt(Array.from(t.nodesBreadthFirst),Array.from(t.deepEdges).filter(e=>e.label))}static constructorGA(t,e){return new xt(Array.from(t.nodesBreadthFirst),e.filter(i=>i.label))}interpolateGranularity(t){if(t<=xt.LowerEdgeBound)return xt.MaxGranularity;if(t>=xt.UpperEdgeBound)return xt.MinGranularity;let e=(xt.UpperEdgeBound-xt.LowerEdgeBound)/(t-xt.LowerEdgeBound);return Math.ceil(xt.MinGranularity+e)}InitializeObstacles(t,e){let i=this.GetEdgeObstacles(e);this.obstacleMaps[1]=Vn(t.map(r=>[r.boundingBox,new xn(r.boundingBox,r)])),this.obstacleMaps[2]=Vn(i.map(r=>[r.boundingBox,new xn(r.boundingBox,r)]))}static CurvePoints(t,e){let i=[],r=t.end.sub(t.start).lengthSquared/(e*e);return xt.SubdivideCurveSegment(i,t,r,t.parStart,t.parEnd),i.sort(xt.compareByArgument),i}static compareByArgument(t,e){return t[0]<e[0]?-1:t[0]>e[0]?1:0}static SubdivideCurveSegment(t,e,i,r,s){if(t.length>64)return;let o=e.value(r),a=e.value(s);if(o.sub(a).lengthSquared>i){let l=(r+s)/2;xt.SubdivideCurveSegment(t,e,i,r,l),xt.SubdivideCurveSegment(t,e,i,l,s)}else t.push([r,o])}static PlaceLabelsAtDefaultPositions(t,e){for(let i of e)i.label&&new xt([i.source,i.target],[i]).run()}GetEdgeObstacles(t){let e=[];for(let i of t){if(i.curve==null)continue;let r=xt.CurvePoints(i.curve,this.CollisionGranularity);this.edgeInfos.set(i,new wP(r));for(let s of r)e.push(new Hh(s[1]))}return e}AddLabelObstacle(t){this.labelObstacleMap==null?(this.labelObstacleMap=Vn([[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(let t of this.edges)this.PlaceLabel(t)}PlaceLabel(t){let e=!1;for(let i of this.placementStrategy){switch(i){case 0:e=this.PlaceEdgeLabelOnCurve(t.label);break;case 1: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){let e=t.parent;return this.edgeInfos.get(e)}PlaceLabelAtFirstPosition(t){let e=t.parent,i=e.curve,r=this.edgeInfos.get(e).edgePoints,s=this.StartIndex(t,r.map(c=>c[1])),o=r[s][1],a=i.derivative(r[s][0]);a.length<x.distanceEpsilon&&(a=new g(1,1)),a=a.normalize();let l=new fi(t.width,t.height),h=this.getLabelInfo(t),u=xt.GetPossibleSides(h.placementSide,a)[0],d=xt.GetLabelBounds(o,a,l,u);this.SetLabelBounds(this.getLabelInfo(t),d)}StartIndex(t,e){let i=this.getLabelInfo(t);return Math.min(e.length-1,Math.max(0,Math.floor(e.length*i.placementOffset)))}CalculateCenterLabelInfoCenter(t){let e=this.getLabelInfo(t),i=new g(0,0);for(let r of e.innerPoints)i=i.add(r);for(let r of e.outerPoints)i=i.add(r);t.positionCenter(i.div(e.innerPoints.length+e.outerPoints.length))}PlaceEdgeLabelHorizontally(t){let e=t.label,i=this.getLabelInfo(e).edgePoints,r=new fi(e.width,e.height),s=-1,o=it.mkEmpty(),a=t.curve;for(let l of xt.ExpandingSearch(this.StartIndex(e,i.map(h=>h[1])),0,i.length)){let h=i[l],u=a.derivative(h[0]);if(!lt(u.lengthSquared,0)){u=u.normalize();for(let d of xt.GetPossibleSides(this.getLabelInfo(e).placementSide,u)){let c=xt.GetLabelBounds(h[1],u,r,d),f=this.ConflictIndexRL(c,e);if(f>s&&(s=f,o=c,s===Number.MAX_VALUE))break}if(s===Number.MAX_VALUE)break}}if(s>=0){this.SetLabelBounds(this.getLabelInfo(e),o);let l=new xn(o,null);this.AddLabelObstacle(l);let h=this.getLabelInfo(e);return s===0?h.placementResult=0:s===1?h.placementResult=1:s===2?h.placementResult=2:h.placementResult=yd.OverlapsNothing,!0}return!1}static GetLabelBounds(t,e,i,r){let s=e.rotate(Math.PI/2).mul(r),o=t.add(s),a=1,l=s.x>0?o.x:o.x-i.width,h=s.y>0?o.y:o.y-i.height;if(Math.abs(s.x)<.75){let u=Math.acos(Math.abs(s.y)/a),d=a/Math.sin(u),c=a/Math.cos(u);l+=(s.x>0?-1:1)*Math.min(d,i.width/2),h+=(s.y>0?1:-1)*c}else if(Math.abs(s.y)<.75){let u=Math.acos(Math.abs(s.x)/a),d=a/Math.sin(u),c=a/Math.cos(u);l+=(s.x>0?1:-1)*c,h+=(s.y>0?-1:1)*Math.min(d,i.height/2)}return it.mkLeftBottomSize(l,h,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=0),t){case 1:return[-1];case 2:return[1];case 3:return lt(e.x,0)?xt.GetPossibleSides(5,e):[1];case 4:return lt(e.x,0)?xt.GetPossibleSides(6,e):[e.x<0?-1:1];case 5:return lt(e.y,0)?xt.GetPossibleSides(3,e):[e.y<0?-1:1];case 6:return lt(e.y,0)?xt.GetPossibleSides(4,e):[e.y<0?1:-1];default:return[-1,1]}}static*ExpandingSearch(t,e,i){let r=t+1,s=r;for(;s>e;)yield--s;for(;r<i;)yield r++}static PointSetLength(t){let e=0,i=null;for(let r of t)i!=null&&(e+=i.sub(r.Center).length),i=r.Center;return e}PlaceEdgeLabelOnCurve(t){let e=t.parent,i=this.getLabelInfo(t);i.innerPoints=null;let r=i.edgePoints,s=3,o=t.height/2,a=new fi(o,o),l=t.width;for(let h of xt.ExpandingSearch(this.StartIndex(t,r),0,r.length)){let u=this.GetSidesAndEdgeCurve(t,e,r,h);for(let d of u){let c=new AP,f={coveredLength:0};if(this.ProcessExpandingSearchOnSide(h,r,e.curve,d,o,s,a,f,c,l),f.coveredLength>=l)return this.CaseOfCoveredLengthGreaterThanLabelLength(t,c,f.coveredLength,l,a),!0}}return!1}CaseOfCoveredLengthGreaterThanLabelLength(t,e,i,r,s){let o=new Array,a=new Array,l=Array.from(e.points),h=i-r;if(h>0){let d=l[l.length-1],c=l[l.length-2],f=d.Center.sub(c.Center),m=f.length;h>m&&(d=l[0],c=l[1],f=d.Center.sub(c.Center),m=f.length);let P=f.mul((m-h)/m);d.Center=c.Center.add(P),d.Inner=c.Inner.add(P),d.Outer=c.Outer.add(P)}this.GoOverOrderedPointsAndAddLabelObstacels(l,o,a,s);let u=this.getLabelInfo(t);u.innerPoints=o,u.outerPoints=a}GoOverOrderedPointsAndAddLabelObstacels(t,e,i,r){for(let s of t){let o=s.Center;e.push(s.Inner),i.push(s.Outer);let a=new xn(it.mkSizeCenter(new fi(r.width*2,r.height*2),o),null);this.AddLabelObstacle(a)}}ProcessExpandingSearchOnSide(t,e,i,r,s,o,a,l,h,u){for(let d of xt.ExpandingSearch(t,0,e.length)){let[c,f]=e[d],m=i.derivative(c);if(lt(m.lengthSquared,0))continue;let P=m.rotate(Math.PI/2).normalize().mul(r),v=f.add(P.mul(s+o));if(this.Conflict(v,s,a))break;{let b=new EP;if(b.Center=v,b.Inner=f.add(P.mul(o)),b.Outer=f.add(P.mul(2*s+o)),l.coveredLength=d<=t?h.AddFirst(b):h.AddLast(b),l.coveredLength>=u)break}}}GetSidesAndEdgeCurve(t,e,i,r){let s=e.curve.derivative(i[r][0]);return xt.GetPossibleSides(this.getLabelInfo(t).placementSide,s)}Conflict(t,e,i){return this.ConflictIndex(t,e,i)!==Number.MAX_VALUE}ConflictIndexRL(t,e){let i=e.parent,r=i.source,s=i.target;for(let o=0;o<this.obstacleMaps.length;o++)if(this.obstacleMaps[o]!=null){for(let a of this.obstacleMaps[o].GetAllIntersecting(t))if(!(o===1&&a instanceof xn&&a.data instanceof we&&(r.node.isDescendantOf(a.data.graph)||s.node.isDescendantOf(a.data))))return o}return Number.MAX_VALUE}ConflictIndex(t,e,i){let r=it.creatRectangleWithSize(new fi(i.width*2,i.height*2),t),s=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(let l of this.obstacleMaps[a].GetAllIntersecting(r))if(l instanceof Hh){if(t.sub(l.location).lengthSquared<s)return a}else return a;return Number.MAX_VALUE}}},Ti=class extends Mu{clone(){throw new Error("Method not implemented.")}rebind(n){this.entity=n,this.bind(tr.AlgorithmDataIndex)}constructor(n,t=null){super(n,tr.AlgorithmDataIndex),this.data=t}static getAlgData(n){return n.getAttr(tr.AlgorithmDataIndex)}};function Ba(n){let t=Ti.getAlgData(n.node);return t==null?null:t.data}var IP=class{constructor(n,t){this.force=new g(0,0),this.stayWeight=1,this.index=n,this.geomNode=t,this.ResetBounds()}get Center(){return this.center}set Center(n){this.geomNode.center=n,this.center=n}ResetBounds(){this.previousCenter=this.geomNode.center,this.center=this.geomNode.center,this.Width=this.geomNode.width,this.Height=this.geomNode.height}ToString(){return"FINode("+(this.index+("):"+this.geomNode))}},TP=class{constructor(n){this._length=1,this.mEdge=n,this.sourceFiNode=Ba(this.mEdge.source),this.targetFiNode=Ba(this.mEdge.target)}get source(){return this.sourceFiNode.index}get target(){return this.targetFiNode.index}get length(){return this._length}set length(n){this._length=n}vector(){return this.sourceFiNode.geomNode.center.sub(this.targetFiNode.geomNode.center)}},OP=ct(bi(),1),Is=class Ue{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){let 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(r=>r==i)==-1&&!this.Contains(t[i]))return!1;return!0}static constructorP(t){let e=new Ue;return e.c=t,e.r=0,e.r2=0,e}static midPoint(t,e){return new g((e.x+t.x)/2,(e.y+t.y)/2)}static constructorPP(t,e){let i=new Ue;return i.c=Ue.midPoint(t,e),i.r2=i.Distance2(t),i.r=Math.sqrt(i.r2),Wt.assert(i.OnBoundary(t)),Wt.assert(i.OnBoundary(e)),i}OnBoundary(t){let e=this.Distance2(t);return Math.abs(e-this.r2)/(e+this.r2)<1e-5}static centre(t,e,i){Wt.assert(e.x!=t.x),Wt.assert(i.x!=e.x);let r=(e.y-t.y)/(e.x-t.x),s=(i.y-e.y)/(i.x-e.x);Wt.assert(s!=r);let o,a=(r*s*(t.y-i.y)+s*(t.x+e.x)-r*(e.x+i.x))/(2*(s-r));return Math.abs(r)>Math.abs(s)?o=(t.y+e.y)/2-(a-(t.x+e.x)/2)/r:o=(e.y+i.y)/2-(a-(e.x+i.x)/2)/s,new g(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{this.count=0}static constructorPPP(t,e,i){Ue.count++;let r=new Ue;if(Ue.Collinear(t,e,i)){let s=new g(Math.min(t.x,Math.min(e.x,i.x)),Math.min(t.y,Math.max(e.y,i.y))),o=new g(Math.max(t.x,Math.max(e.x,i.x)),Math.max(t.y,Math.max(e.y,i.y)));r.c=Ue.midPoint(s,o),r.r2=r.Distance2(o),r.r=Math.sqrt(r.r2)}else{let s=e.x-t.x,o=i.x-e.x,a=i.x-t.x;s!=0?o!=0?r.c=Ue.centre(t,e,i):(Wt.assert(a!=0),r.c=Ue.centre(e,t,i)):(Wt.assert(o!=0),r.c=Ue.centre(e,i,t)),r.r2=r.Distance2(t),r.r=Math.sqrt(r.r2),Wt.assert(r.OnBoundary(t)),Wt.assert(r.OnBoundary(e)),Wt.assert(r.OnBoundary(i))}return r}};function LP(n){let t=n.slice();BP(t);let e=t.length;if(e===0)return{x:0,y:0,r:0};if(e===1)return{x:t[0].x,y:t[0].y,r:0};let i=sa(t[0],t[1]);for(let r=2;r<e;r++)if(!oa(t[r],i)){i=sa(t[0],t[r]);for(let s=1;s<r;s++)if(!oa(t[s],i)){i=sa(t[r],t[s]);for(let o=0;o<s;o++)oa(t[o],i)||(i=RP(t[r],t[s],t[o]))}}return i}function BP(n){let t,e,i;for(i=n.length-1;i>0;i--)t=en(i+1),e=n[i],n[i]=n[t],n[t]=e;return n}function RP(n,t,e){let i=n.x,r=n.y,s=t.x,o=t.y,a=e.x,l=e.y,h=s-i,u=o-r,d=a-i,c=l-r,f=h*(s+i)*.5+u*(o+r)*.5,m=d*(a+i)*.5+c*(l+r)*.5,P=h*c-u*d,v=(c*f-u*m)/P,b=(-d*f+h*m)/P;return{x:v,y:b,r:Math.sqrt((i-v)*(i-v)+(r-b)*(r-b))}}function sa(n,t){let e=n.x,i=n.y,r=t.x,s=t.y,o=.5*(e+r),a=.5*(i+s);return{x:o,y:a,r:Math.sqrt((e-o)*(e-o)+(i-a)*(i-a))}}function oa(n,t){return(t.x-n.x)*(t.x-n.x)+(t.y-n.y)*(t.y-n.y)<=t.r*t.r}var FP=class{static LinearComputation(n){let t=LP(n),e=new Is;return e.Center=new g(t.x,t.y),e.Radius=t.r,e}static SlowComputation(n){let t=n.length,e=null,i=null;for(let r=0;r<t;r++)for(let s=0;s<t;s++){if(r!=s){let o=Is.constructorPP(n[r],n[s]);o.ContainsPN(n,[r,s])&&(e==null||e.Radius>o.Radius)&&(e=o,i=[r,s])}for(let o=0;o<t;o++)if(o!=r&&o!=s&&!Is.Collinear(n[r],n[s],n[o])){let a=Is.constructorPPP(n[r],n[s],n[o]);a.ContainsPN(n,[r,s,o])&&(e==null||e.Radius>a.Radius)&&(e=a,i=[r,s,o])}}return Wt.assert(i!=null),e}},Un=class mr{static constructorNPA(t,e,i){let r=new mr;r.p=t,r.z0=new ee(e.x,e.y),r.a=new Array(t);for(let s=0;s<t;s++)r.a[s]=r.compute(s,i);return r}static constructorPMM(t,e,i){let r=new mr;Wt.assert(e.p==i.p),r.p=e.p,r.z0=new ee(t.x,t.y);let s=i.shift(r.z0),o=e.shift(r.z0);r.a=new Array(r.p);for(let a=0;a<r.p;a++)r.a[a]=aa(o[a],s[a]);return r}static factorial(t){let e=1;for(let i=2;i<=t;i++)e*=i;return e}static binomial(t,e){return mr.factorial(t)/(mr.factorial(e)*mr.factorial(t-e))}sum(t,e){let i=ee.constructorN(0);for(let r=1;r<=t;r++){let s=ee.constructorN(mr.binomial(t-1,r-1));i=aa(i,_i(this.a[r],_i(ee.Pow(e,t-r),s)))}return i}shift(t){let e=new Array(this.p),i=e[0]=this.a[0],r=En(this.z0,t);for(let s=1;s<this.p;s++){let o=ee.constructorN(s);e[s]=aa(_i(GP(i),la(ee.Pow(r,s),o)),this.sum(s,r))}return e}compute(t,e){let i=e.length,r=ee.constructorN(0);if(t==0)r.re=i;else{for(let s=0;s<i;s++){let o=e[s],a=new ee(o.x,o.y);r=En(r,ee.Pow(En(a,this.z0),t))}r.divideBy(t)}return r}ApproximateForce(t){let e=new ee(t.x,t.y),i=En(e,this.z0),r=la(this.a[0],i),s=i,o=0;for(;r=En(r,la(NP(this.a[o],o),s)),o++,o!=this.p;)s=_i(s,i);return new g(r.re,-r.im)}static Force(t,e){let i=e.sub(t),r=i.lengthSquared;return r<.1?r!=0?i.div(.1):new g(1,0):i.div(r)}},ee=class Nn{constructor(t,e){this.re=t,this.im=e}static constructorN(t){return new Nn(t,0)}divideBy(t){this.re/=t,this.im/=t}static Pow(t,e){switch(Wt.assert(e>=0),e){case 0:return Nn.constructorN(1);case 1:return t;case 2:return _i(t,t);case 3:return _i(t,_i(t,t));default:return _i(Nn.Pow(t,e/2),Nn.Pow(t,e/2+e%2))}}};function aa(n,t){return new ee(n.re+t.re,n.im+t.im)}function _i(n,t){return new ee(n.re*t.re-n.im*t.im,n.re*t.im+t.re*n.im)}function NP(n,t){return new ee(n.re*t,n.im*t)}function En(n,t){return new ee(n.re-t.re,n.im-t.im)}function GP(n){return new ee(-n.re,-n.im)}function la(n,t){let e=t.re*t.re+t.im*t.im;if(e==0)return ee.constructorN(0);let i=n.re*t.re+n.im*t.im,r=n.im*t.re-n.re*t.im;return new ee(i/e,r/e)}var Sd=class{intersects(n){return n.med.Center.sub(this.med.Center).length<n.med.Radius+this.med.Radius}},DP=class extends Sd{constructor(n,t,e){super(),this.med=n,this.parent=t.parent,this.parent!=null&&(this.parent.leftChild==t?this.parent.leftChild=this:this.parent.rightChild=this),this.leftChild=t,this.rightChild=e,t.parent=this,e.parent=this}computeMultipoleCoefficients(n){this.leftChild.computeMultipoleCoefficients(n),this.rightChild.computeMultipoleCoefficients(n),this.multipoleCoefficients=Un.constructorPMM(this.med.Center,this.leftChild.multipoleCoefficients,this.rightChild.multipoleCoefficients)}},Wh=class bd extends Sd{constructor(t){super(),this.particles=t,this.ComputeMinimumEnclosingDisc()}computeMultipoleCoefficients(t){this.multipoleCoefficients=Un.constructorNPA(t,this.med.Center,this.ps)}ComputeMinimumEnclosingDisc(){let 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=FP.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){let e=this.Dimension(0)>this.Dimension(1)?0:1,i=e==0?1:0,r=this.Size(),s=r>>1,o=r-s,a=[new Array(s),new Array(s)],l=[new Array(o),new Array(o)],h=0,u=0;for(let c=0;c<r;c++){let f=this.particles[e][c];c<s?(a[e][c]=f,f.splitLeft=!0):(l[e][c-s]=f,f.splitLeft=!1)}for(let c=0;c<r;c++){let f=this.particles[i][c];f.splitLeft?a[i][u++]=f:l[i][h++]=f}let d=this.med;return this.particles=a,this.ComputeMinimumEnclosingDisc(),t.rightSibling=new bd(l),new DP(d,this,t.rightSibling)}ComputeForces(){for(let t of this.particles[0])for(let e of this.particles[0])t!=e&&(t.force=t.force.add(Un.Force(t.point,e.point)))}},MP=class{pos(n){return n==0?this.point.x:this.point.y}constructor(n){this.point=n,this.force=new g(0,0)}},VP=class{particlesBy(n){return this.particles.map(t=>t).sort((t,e)=>t.pos(n)-e.pos(n))}constructor(n,t){this.particles=n;let e=new Array;e.push(this.particlesBy(0)),e.push(this.particlesBy(1)),this.leaves=new Array;let i=new Wh(e);this.leaves.push(i);let r={rightSibling:null};this.root=i.Split(r),this.leaves.push(r.rightSibling);let s=new kP(t);for(s.EnqueueLL(i,r.rightSibling);s.length>0;)i=s.dequeue(),i.Split(r),this.leaves.push(r.rightSibling),s.EnqueueLL(i,r.rightSibling)}ComputeForces(n){this.root.computeMultipoleCoefficients(n);for(let t of this.leaves){t.ComputeForces();let e=new Array;for(e.push(this.root);e.length>0;){let i=e.pop();if(t.intersects(i))if(i instanceof Wh)for(let r of t.particles[0])for(let s of i.particles[0])r!=s&&(r.force=r.force.add(Un.Force(r.point,s.point)));else{let r=i;e.push(r.leftChild),e.push(r.rightChild)}else for(let r of t.particles[0])r.force=r.force.sub(i.multipoleCoefficients.ApproximateForce(r.point))}}}},kP=class extends OP.Queue{constructor(n){super(),this.B=n}EnqueueLL(n,t){n.Size()>this.B&&this.enqueue(n),t.Size()>this.B&&this.enqueue(t)}},Cd=class Ra extends Nt{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(r=>Ti.getAlgData(r.edge).data),this.nodes=Array.from(this.graph.shallowNodes).map(r=>Ti.getAlgData(r.node).data),this.components=new Array,this.settings.InterComponentForces)this.components.push(this.nodes);else{this.basicGraph=yi(this.edges,this.nodes.length);for(let r of tn(this.basicGraph)){let s=new Array(r.length),o=0;for(let a of r)s[o++]=this.nodes[a];this.components.push(s)}}this.computeWeight(t),this.setCurrentConstraintLevel(i)}initFiNodesEdges(){let t=0;for(let e of this.graph.shallowNodes){let i=new IP(t++,e);new Ti(e.node,i)}for(let e of this.graph.shallowEdges){let i=new TP(e);new Ti(e.edge,i)}}getCurrentConstraintLevel(){return this.currentConstraintLevel}setCurrentConstraintLevel(t){this.currentConstraintLevel=t,this.settings.Unconverge()}ResetNodePositions(){for(let t of this.nodes)t.ResetBounds()}AddRepulsiveForce(t,e){t.force=e.mul(10*this.settings.RepulsiveForceConstant)}AddLogSpringForces(t,e,i){let r=e.length,s=7e-4*this.settings.AttractiveForceConstant*r*Math.log((r+.1)/(i+.1));t.sourceFiNode.force=t.sourceFiNode.force.add(e.mul(s)),t.targetFiNode.force=t.targetFiNode.force.sub(e.mul(s))}AddSquaredSpringForces(t,e,i){let r=e.length,s=i*i+.1,o=this.settings.AttractiveForceConstant*(r-i)/s;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,r=t.targetFiNode.Center,s=t.mEdge.sourcePort;s instanceof ve&&(i=s.Location);let o=t.mEdge.targetPort;o instanceof ve&&(r=o.Location),e=i.sub(r)}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){let e=t.length;if(e>16&&this.settings.ApproximateRepulsion){let i=new Array(t.length),r=2*(Math.PI/e),s=0;for(let o=0;o<e;o++)i[o]=new MP(t[o].Center.add(new g(Math.cos(s),Math.sin(s)).mul(1e-5))),s+=r;new VP(i,8).ComputeForces(5);for(let o=0;o<t.length;o++)this.AddRepulsiveForce(t[o],i[o].force)}else for(let i of t){let r=new g(0,0);for(let s of t)i!=s&&(r=r.add(Un.Force(i.Center,s.Center)));this.AddRepulsiveForce(i,r)}}SetBarycenter(t){let e=this.clustersInfo.get(t);if(e!=null)return e.barycenter;let i=new g(0,0);if(t.shallowNodeCount||$P(t)){let r=this.clustersInfo.get(t);if((r==null||r.weight==null)&&this.computeWeight(t),r.weight!=null){for(let s of t.shallowNodes)s instanceof ke?i=i.add(s.center):i=i.add(this.SetBarycenter(s).mul(this.clustersInfo.get(s).weight));this.clustersInfo.get(t).barycenter=i=i.div(r.weight)}}else this.clustersInfo.get(t).barycenter=i;return i}computeWeight(t){let e=0;for(let r of t.shallowNodes)r.entity instanceof Be?e+=this.computeWeight(r):e++;let i=this.clustersInfo.get(t);return i==null&&this.clustersInfo.set(t,i={barycenter:new g(0,0)}),i.weight=e,e}AddClusterForces(t){if(t!=null){this.SetBarycenter(t);for(let e of this.clusterEdges){let i=Tt.getGeom(e.source),r=Tt.getGeom(e.target),s=Ti.getAlgData(e.source).data,o=Ti.getAlgData(e.target).data,a=i.hasOwnProperty("shallowNodes"),l=a?this.clustersInfo.get(i).barycenter:i.center,h=r.hasOwnProperty("shallowNodes"),u=h?this.clustersInfo.get(r).barycenter:r.center,d=l.sub(u),c=d.length,f=1e-8*(this.settings.AttractiveInterClusterForceConstant*(c*Math.log(c+.1)));if(d=d.mul(f),a){let m=i;for(let P of m.shallowNodes){let v=Ti.getAlgData(P.node).data;v.force=v.force.add(d)}}else s.force=s.force.add(d);if(h){let m=r;for(let P of m.shallowNodes){let v=Ti.getAlgData(P.node).data;v.force=v.force.sub(d)}}else o.force=o.force.sub(d)}for(let e of t.subgraphsDepthFirst){let i=this.clustersInfo.get(e).barycenter;for(let r of e.shallowNodes)Ra.AddGravityForce(i,this.settings.ClusterGravity,Ba(r))}}}ComputeForces(){if(this.components!=null)for(let t of this.components)this.ComputeRepulsiveForces(t);else this.ComputeRepulsiveForces(this.nodes);this.edges.forEach(t=>this.AddSpringForces(t));for(let t of this.components){let e=new g(0,0);for(let r=0;r<t.length;r++)e=e.add(t[r].Center);e=e.div(t.length);let i=Number.NEGATIVE_INFINITY;for(let r=0;r<t.length;r++){let s=t[r];Ra.AddGravityForce(e,this.settings.GravityConstant,s),s.force.length>i&&(i=s.force.length)}if(i>100)for(let r=0;r<t.length;r++)t[r].force=t[r].force.mul(100/i)}this.AddClusterForces(this.graph)}VerletIntegration(){let t=this.energy;this.energy=this.ComputeDescentDirection(1),this.UpdateStepSize(t);let e=0;for(let i=0;i<this.nodes.length;i++){let r=this.nodes[i];e+=r.Center.sub(r.previousCenter).lengthSquared}return e}ComputeDescentDirection(t){this.ResetForceVectors(),this.settings.ApplyForces&&this.ComputeForces();let e=0;for(let i of this.nodes){e=e+i.force.lengthSquared;let r=i.Center.sub(i.previousCenter).mul(this.settings.Friction),s=i.force.mul(-this.stepSize*t);i.previousCenter=i.Center,Wt.assert(!Number.isNaN(s.x),"!double.IsNaN(a.X)"),Wt.assert(!Number.isNaN(s.y),"!double.IsNaN(a.Y)"),Wt.assert(Number.isFinite(s.x),"!double.IsInfinity(a.X)"),Wt.assert(Number.isFinite(s.y),"!double.IsInfinity(a.Y)"),r=r.add(s),r=r.div(i.stayWeight),i.Center=i.Center.add(r)}return e}ResetForceVectors(){for(let t of this.nodes)t.force=new g(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(){let t=new Array(this.nodes.length),e=new Array(this.nodes.length),i=new Array(this.nodes.length),r=new Array(this.nodes.length),s=new Array(this.nodes.length),o=this.energy;for(let l=0;l<this.nodes.length;l++)this.nodes[l].previousCenter=this.nodes[l].Center,t[l]=this.nodes[l].Center;let a=3;this.ComputeDescentDirection(a);for(let l=0;l<this.nodes.length;l++)e[l]=this.nodes[l].Center.sub(this.nodes[l].previousCenter),this.nodes[l].Center=t[l].add(e[l].mul(.5));this.ComputeDescentDirection(a);for(let l=0;l<this.nodes.length;l++)i[l]=this.nodes[l].Center.sub(this.nodes[l].previousCenter),this.nodes[l].previousCenter=t[l],this.nodes[l].Center=t[l].add(i[l].mul(.5));this.ComputeDescentDirection(a);for(let l=0;l<this.nodes.length;l++)r[l]=this.nodes[l].Center.sub(this.nodes[l].previousCenter),this.nodes[l].previousCenter=t[l],this.nodes[l].Center=t[l].add(r[l]);this.energy=this.ComputeDescentDirection(a);for(let l=0;l<this.nodes.length;l++){s[l]=this.nodes[l].Center.sub(this.nodes[l].previousCenter),this.nodes[l].previousCenter=t[l];let h=e[l].add(i[l].mul(2).add(r[l].mul(2)).add(s[l])).div(6);this.nodes[l].Center=t[l].add(h)}return this.UpdateStepSize(o),this.nodes.reduce((l,h)=>h.Center.sub(h.previousCenter).lengthSquared+l,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 $P(n){for(let t of n.Clusters)return!0;return!1}var lo=class Vs{constructor(){this.commonSettings=new ao,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}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}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 Cd(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 Vs.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){let e=new Vs;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(){let t=new Vs;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}},HP=class{constructor(n){this.topNodes=n}get nodesBreadthFirst(){return this.nodesBreadthFirst_()}*nodesBreadthFirst_(){for(let n of this.topNodes)if(yield ke.getGeom(n),n instanceof Be)for(let t of n.nodesBreadthFirst)yield ke.getGeom(t)}get Clusters(){return this.clusters()}*clusters(){for(let n of this.topNodes)n instanceof Be&&(yield we.getGeom(n))}get subgraphsDepthFirst(){return this.subgraphsDepthFirst_()}*subgraphsDepthFirst_(){for(let n of this.topNodes)if(n instanceof Be){let t=we.getGeom(n);yield*t.subgraphsDepthFirst,yield t}}get shallowEdges(){return this.edges_()}*edges_(){for(let n of this.topNodes){for(let t of n.outEdges)yield Fe.getGeom(t);for(let t of n.selfEdges)yield Fe.getGeom(t)}}get shallowNodes(){return this.shallowNodes_()}*shallowNodes_(){for(let n of this.topNodes)yield ke.getGeom(n)}pumpTheBoxToTheGraphWithMargins(){let n={b:it.mkEmpty()};return nl(this,n),this.boundingBox=n.b}get shallowNodeCount(){return this.topNodes.length}translate(n){this.boundingBox&&(this.boundingBox.center=this.boundingBox.center.add(n));for(let t of this.topNodes)ke.getGeom(t).translate(n)}},zh=class{static LinearInterpolation(n,t,e,i,r){if(n<t)return i;if(n>e)return r;let s=(n-t)/(e-t);return i+s*(r-i)}static NegativeLinearInterpolation(n,t,e,i,r){if(n<t)return r;if(n>e)return i;let s=(n-t)/(e-t);return i+(1-s)*(r-i)}},WP=class extends Nt{constructor(n,t){super(null),this.SingleComponent=!1,this.graph=n,this.settings=lo.ctorClone(t),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{let n=Array.from(this.graph.graph.getClusteredConnectedComponents()).map(t=>new HP(t));this.componentCount=n.length;for(let t of n)this.LayoutComponent(t);this.graph.boundingBox=pd.PackGraphs(n,this.settings.commonSettings)}}LayoutComponent(n){if(n.shallowNodeCount>1){if(this.settings.MaxIterations=zh.NegativeLinearInterpolation(n.shallowNodeCount,50,500,5,10),this.settings.MinorIterations=zh.NegativeLinearInterpolation(n.shallowNodeCount,50,500,3,20),this.settings.MinConstraintLevel==0){let e=new La;e.removeOverlaps=!1,e.IterationsWithMajorization=0,new md(n,null,()=>1,new La).run()}let t=new Cd(n,this.settings,this.settings.MinConstraintLevel);for(let e of this.GetConstraintLevels(n)){if(e>this.settings.MaxConstraintLevel)break;e>this.settings.MinConstraintLevel&&t.setCurrentConstraintLevel(e);do t.run();while(!this.settings.IsDone)}this.settings.AvoidOverlaps&&hl.RemoveOverlaps(Array.from(this.graph.shallowNodes),this.settings.NodeSeparation)}n.pumpTheBoxToTheGraphWithMargins(),n.uniformMargins=this.settings.NodeSeparation,n.translate(n.boundingBox.leftBottom.mul(-1))}GetConstraintLevels(n){let t=new Set;return t.add(0),this.settings.AvoidOverlaps&&n.shallowNodeCount<2e3&&t.add(2),t}};function vd(n){n.layoutSettings||(n.layoutSettings=xd(n))}function zP(n){let t=n.parent;for(;t;){if(t.layoutSettings)return t.layoutSettings;t=t.parent}return null}function xd(n){let t=zP(n);if(t)return t;if(n.graph.shallowNodeCount>2e3||n.graph.deepEdgesCount>4e3)return new lo;let e=!1;for(let i of n.deepEdges)if(i.sourceArrowhead!=null||i.targetArrowhead!=null){e=!0;break}return e?new Jn:new lo}function qP(n,t,e=()=>1){if(vd(n),n.layoutSettings instanceof Jn)new Ud(n,n.layoutSettings,t).run();else if(n.layoutSettings instanceof La)new md(n,t,e,n.layoutSettings).run();else if(n.layoutSettings instanceof lo){let i=new WP(n,n.layoutSettings);i.SingleComponent=!0,i.run()}else throw new Error("not implemented")}function Ed(n,t=null){vd(n),Id(n,t,qP,wd,Mm),YP(n)}function Ad(n){do{if(n.layoutSettings&&n.layoutSettings.commonSettings.edgeRoutingSettings)return n.layoutSettings.commonSettings.edgeRoutingSettings;let e=n.graph.parent;if(e)n=Tt.getGeom(e);else break}while(!0);let t=new Ta;return t.EdgeRoutingMode=0,t}function wd(n,t,e){let i=Ad(n);i.EdgeRoutingMode===4?QP(n,t,e):i.EdgeRoutingMode===0||i.EdgeRoutingMode===1?bS(n,t,e):i.EdgeRoutingMode===2?Pd(n,t,e):i.EdgeRoutingMode===7?sP(n,t,e,i.Padding,void 0,void 0,void 0,0,void 0,i.smoothCorners):i.EdgeRoutingMode!==6&&new Or(n,t).run(),Td(n,t)}function Id(n,t,e,i,r,s=1,o=()=>1){if(n.graph.isEmpty())return;let a=n.shallowNodes.next();n.parent==null&&(po(s),XP(n));let l=f();c(n);let h=UP(n.graph),u=jP(n);if(m(),h.forEach(P=>{P[0].edge.remove(),P[1].add()}),u.forEach(P=>{for(let v of P.graph.shallowNodes)v.parent=n.graph}),l.forEach(P=>P.add()),n.graph.parent==null){let P=d(n);i(n,P,t),Td(n,P),n.pumpTheBoxToTheGraphWithMargins()}function d(P){let v=[];for(let b of P.nodesBreadthFirst){for(let C of b.outEdges())C.curve==null&&v.push(C);for(let C of b.selfEdges())C.curve==null&&v.push(C)}return v}function c(P){for(let v of P.shallowNodes)v instanceof we&&Id(v,t,e,i,r)}function f(){let P=new Set,v=n.graph;if(v.parent==null)return P;for(let b of v.shallowNodes){for(let C of b.outEdges){let E=v.liftNode(C.target);(E==null||E===b)&&P.add(C)}for(let C of b.inEdges){let E=v.liftNode(C.source);(E==null||E===b)&&P.add(C)}}for(let b of P)b.remove();return P}function m(){if(u.length===1)e(n,t,o);else{for(let P of u)e(P,t,o),P.boundingBox=P.pumpTheBoxToTheGraphWithMargins();r(n,u)}}}function UP(n){let t=new Array;for(let e of n.nodesBreadthFirst){let i=n.liftNode(e);if(i!=null)for(let r of e.outEdges.values()){let s=r.target,o=n.liftNode(s);if(o==null||i===e&&o===s||i===o)continue;r.remove();let a=new Yn(i,o),l=new Fe(a);t.push([l,r])}}return t}function jP(n){let t=n.graph,e=Rm(t),i=[],r=0;for(let s of e){let o=new Be(t.id+r++);o.parent=t;let a=new we(o);a.layoutSettings=n.layoutSettings??xd(n);for(let l of s)l.parent=o,o.addNode(l);i.push(a)}return i}function QP(n,t,e,i=1,r=3,s=3){let o=cl.constructorGNAN(n,t,i,r);o.edgeSeparatian=s,o.run()}function Td(n,t){t.length!==0&&fo.constructorGA(n,t).run()}function XP(n){for(let t of n.deepEdges)t.label&&(t.label.isPositioned=!1)}function YP(n){let t=n.boundingBox.leftBottom;if(t.x<0||t.y<0){let e=new g(-t.x,-t.y);n.translate(e)}}var Od=class extends rl{toString(){return"label of "+(this.parent?this.parent.toString():"null")}constructor(n){super(),this.parent=n}},gi=class Ld extends sl{get Location(){return this.curve.value(this.parameter)}set Location(t){throw new Error("Method should not be called.")}static mk(t,e){let i=new Ld;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}},rr=class Bd extends Kr{static constructorVV(t,e){return new Bd(t,e,0)}constructor(t,e,i=0){super(t,e,i)}},Rd=class Fa{constructor(t,e,i){this.upperBound=Number.POSITIVE_INFINITY,this._visGraph=i,this._visGraph.ClearPrevEdgesTable();for(let r of i.Vertices())r.Distance=Number.POSITIVE_INFINITY;this.source=t,this.targets=new Set(e),this.source.Distance=0}GetPath(){let t=new nr(Mt);for(this.source.Distance=0,t.Enqueue(this.source,0);!t.IsEmpty()&&(this.current=t.Dequeue(),!this.targets.has(this.current));){for(let e of this.current.OutEdges)this.PassableOutEdge(e)&&this.ProcessNeighbor(t,e,e.Target);for(let 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)||!Fa.IsForbidden(t)}PassableInEdge(t){return this.targets.has(t.Source)||t.Target===this.source||!Fa.IsForbidden(t)}static IsForbidden(t){return t.IsPassable!=null&&!t.IsPassable()||t instanceof rr}ProcessNeighbor(t,e,i){let r=e.Length,s=this.current.Distance+r;s>=this.upperBound||(this.targets.has(i)&&(this.upperBound=s,this.closestTarget=i),i!==this.source&&this._visGraph.PreviosVertex(i)==null?(i.Distance=s,this._visGraph.SetPreviousEdge(i,e),t.Enqueue(i,s)):s<i.Distance&&(i.Distance=s,this._visGraph.SetPreviousEdge(i,e),t.DecreasePriority(i,s)))}CalculatePath(){if(this.closestTarget==null)return null;let t=new Array,e=this.closestTarget;do t.push(e),e=this._visGraph.PreviosVertex(e);while(e!==this.source);return t.push(this.source),t.reverse()}},JP=class Na{constructor(t,e,i){this._visGraph=t,this._source=e,this._target=i,this._source.Distance=0}GetPath(){let t=new nr(Mt);for(this._source.Distance=0,this._target.Distance=Number.POSITIVE_INFINITY,t.Enqueue(this._source,this.H(this._source));!t.IsEmpty();){let e={priority:0},i=t.DequeueAndGetPriority(e);if(e.priority>=this._target.Distance)break;for(let r of i.OutEdges)if(this.PassableOutEdge(r)){let s=r.Target;this.ProcessNeighbor(t,i,r,s)}for(let r of i.InEdges)if(this.PassableInEdge(r)){let s=r.Source;this.ProcessNeighbor(t,i,r,s)}}return this._visGraph.PreviosVertex(this._target)==null?null:this.CalculatePath()}PassableOutEdge(t){return t.Source===this._source||t.Target===this._target||!Na.IsForbidden(t)}PassableInEdge(t){return t.Source===this._target||t.Target===this._source||!Na.IsForbidden(t)}static IsForbidden(t){return t.IsPassable!=null&&!t.IsPassable()||t instanceof rr}ProcessNeighborN(t,e,i,r,s){let o=i.Length+s,a=e.Distance+o;r!==this._source&&this._visGraph.PreviosVertex(r)==null?(r.Distance=a,this._visGraph.SetPreviousEdge(r,i),r!==this._target&&t.Enqueue(r,this.H(r))):r!==this._source&&a<r.Distance&&(r.Distance=a,this._visGraph.SetPreviousEdge(r,i),r!==this._target&&t.DecreasePriority(r,this.H(r)))}ProcessNeighbor(t,e,i,r){let s=i.Length,o=e.Distance+s;r!==this._source&&this._visGraph.PreviosVertex(r)==null?(r.Distance=o,this._visGraph.SetPreviousEdge(r,i),r!==this._target&&t.Enqueue(r,this.H(r))):r!==this._source&&o<r.Distance&&(r.Distance=o,this._visGraph.SetPreviousEdge(r,i),r!==this._target&&t.DecreasePriority(r,this.H(r)))}H(t){return t.Distance+t.point.sub(this._target.point).length}CalculatePath(){let t=new Array,e=this._target;do t.push(e),e=this._visGraph.PreviosVertex(e);while(e!==this._source);return t.push(this._source),t.reverse()}},ho=class Fd extends Nt{constructor(t,e){super(null),this.coneAngle=Math.PI/6,this.ports=new Zt,this._obstacles=Array.from(zt.OrientHolesClockwise(t)),this._visibilityGraph=e}static mk(t,e,i,r,s){let o=new Fd(t,e);return o.Ports=r,o.BorderPolyline=s,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(){let 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 g(Math.cos(e),Math.sin(e)),this.BorderPolyline,this._visibilityGraph)}}HandleBideractionalCase(){let t=Math.PI/this.coneAngle;for(let e=0;e<t;e++){let i=e*this.coneAngle,r=new zt;this.AddDirection(new g(Math.cos(i),Math.sin(i)),this.BorderPolyline,r);let s=new zt;this.AddDirection(new g(Math.cos(i)*-1,Math.sin(i)*-1),this.BorderPolyline,s),this.AddIntersectionOfBothDirectionSweepsToTheResult(r,s)}}AddIntersectionOfBothDirectionSweepsToTheResult(t,e){for(let i of t.Edges)e.FindEdgePP(i.SourcePoint,i.TargetPoint)!=null&&this._visibilityGraph.AddEdgePP(i.SourcePoint,i.TargetPoint)}AddDirection(t,e,i){Qd.Sweep(this._obstacles,t,this.coneAngle,i,this.Ports,e)}},ZP=ct(se(),1),qh=class{toString(){return ZP.String.format("{0},{1}",this.Start,this.End)}get Start(){return this.leftTangent.End.point}get End(){return this.rightTangent.End.point}constructor(n,t){this.LeftTangent=n,this.RightTangent=t}get LeftTangent(){return this.leftTangent}set LeftTangent(n){this.leftTangent=n}get RightTangent(){return this.rightTangent}set RightTangent(n){this.rightTangent=n}get RbNode(){return this.rbNode}set RbNode(n){this.rbNode=n}},KP=ct(se(),1),Uh=class{get Comp(){return this.comp}set Comp(n){this.comp=n}get IsHigh(){return!this.IsLow}get IsLow(){return this.lowTangent}set IsLow(n){this.lowTangent=n}get SeparatingPolygons(){return this.separatingPolygons}set SeparatingPolygons(n){this.separatingPolygons=n}get Diagonal(){return this.diagonal}set Diagonal(n){this.diagonal=n}get Start(){return this.start}set Start(n){this.start=n}get End(){return this.end}set End(n){this.end=n}constructor(n,t){this.start=n,this.End=t}toString(){return KP.String.format("{0},{1}",this.Start,this.End)}},jh=class{get PointOnTangentAndInsertedDiagonal(){return this.pointOnTheRay}set PointOnTangentAndInsertedDiagonal(n){this.pointOnTheRay=n}Compare(n,t){return n.Start.equal(t.Start)?0:g.getTriangleOrientation(this.PointOnTangentAndInsertedDiagonal,t.Start,t.End)===1?-1:1}static BelongsToTheDiagonal(n,t,e){return g.closeDistEps(n,g.ClosestPointAtLineSegment(n,t,e))}static IntersectDiagonalWithRay(n,t,e){let i=t.sub(n),r=e.Start,s=e.End,o=Wn.solve(s.x-r.x,i.x*-1,n.x-r.x,s.y-r.y,i.y*-1,n.y-r.y);return n.add(i.mul(o.y))}},Nd=class ks{constructor(t){this.pivot=t}IComparer(t,e){if(t===e)return 0;if(t==null)return-1;if(e==null)return 1;let i=t.Start.point.sub(this.pivot),r=e.Start.point.sub(this.pivot);return ks.CompareVectorsByAngleToXAxis(i,r)}static CompareVectorsByAngleToXAxis(t,e){return t.y>=0?e.y<0?-1:ks.CompareVectorsPointingToTheSameYHalfPlane(t,e):e.y>=0?1:ks.CompareVectorsPointingToTheSameYHalfPlane(t,e)}static CompareVectorsPointingToTheSameYHalfPlane(t,e){let i=t.x*e.y-t.y*e.x;if(i>x.tolerance)return-1;if(i<-x.tolerance)return 1;if(t.x>=0){if(e.x<0)return-1}else if(e.x>=0)return 1;let r=Math.abs(t.x)-Math.abs(e.x);return r<0?-1:r>0?1:(r=Math.abs(t.y)-Math.abs(e.y),r<0?-1:r>0?1:0)}},Ts=class $s extends Nt{constructor(t,e,i){super(null),this.polygons=[],this.activeDiagonalComparer=new jh,this.polygons=t,this.visibilityGraph=i,this.addedPolygons=e}run(){this.useLeftPTangents=!0,this.CalculateAndAddEdges(),this.useLeftPTangents=!1,this.CalculateAndAddEdges()}CalculateAndAddEdges(){for(let 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 Re(this.activeDiagonalComparer.Compare.bind(this.activeDiagonalComparer))}Sweep(){if(!(this.tangents.length<2))for(let t=1;t<this.tangents.length;t++){let 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 qh(e,e.Comp)),e.Diagonal.RbNode===this.activeDiagonalTree.treeMinimum()&&this.AddVisibleEdge(e))}}AddVisibleEdge(t){zt.AddEdgeVV(Qh(this.visibilityGraph,t.start),Qh(this.visibilityGraph,t.End))}InitActiveDiagonals(){if(this.tangents.length===0)return;let t=this.tangents[0],e=t.start.point,i=t.End.point;for(let r of this.diagonals)$s.RayIntersectDiagonal(e,i,r)&&(this.activeDiagonalComparer.PointOnTangentAndInsertedDiagonal=jh.IntersectDiagonalWithRay(e,i,r),this.InsertActiveDiagonal(r));if(t.Diagonal.RbNode===this.activeDiagonalTree.treeMinimum()&&this.AddVisibleEdge(t),t.IsLow===!1){let r=t.Diagonal;this.RemoveDiagonalFromActiveNodes(r)}}RemoveDiagonalFromActiveNodes(t){let 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),$s.MarkDiagonalAsActiveInTangents(t)}static MarkDiagonalAsActiveInTangents(t){t.LeftTangent.Diagonal=t,t.RightTangent.Diagonal=t}static RayIntersectDiagonal(t,e,i){let r=i.Start,s=i.End;return g.getTriangleOrientation(t,r,s)===1&&g.getTriangleOrientation(t,e,r)!==1&&g.getTriangleOrientation(t,e,s)!==0}static TangentComparison(t,e){return Nd.CompareVectorsByAngleToXAxis(t.End.point.sub(t.start.point),e.End.point.sub(e.start.point))}*AllObstacles(){for(let t of this.addedPolygons)yield t;if(this.polygons)for(let t of this.polygons)yield t}OrganizeTangents(){for(let t of this.AllObstacles())t!==this.currentPolygon&&this.ProcessPolygonQ(t);this.tangents.sort($s.TangentComparison)}ProcessPolygonQ(t){let e=new Ku(this.currentPolygon,t);this.useLeftPTangents?e.CalculateLeftTangents():e.CalculateRightTangents();let i=this.useLeftPTangents?e.leftPLeftQ:e.rightPLeftQ,r=new Uh(this.currentPolygon.pp(i[0]),t.pp(i[1]));r.IsLow=!0,r.SeparatingPolygons=!this.useLeftPTangents,i=this.useLeftPTangents?e.leftPRightQ:e.rightPRightQ;let s=new Uh(this.currentPolygon.pp(i[0]),t.pp(i[1]));s.IsLow=!1,s.SeparatingPolygons=this.useLeftPTangents,r.Comp=s,s.Comp=r,this.tangents.push(r),this.tangents.push(s),this.diagonals.push(new qh(r,s))}};function Qh(n,t){return n.FindVertex(t.point)}var _P=class Gd{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){return g.getTriangleOrientation(this.IntersectionOfTheRayAndInsertedEdge,e.point,e.nextOnPolyline.point)===1?-1:1}IntersectionPointBelongsToTheInsertedEdge(t){let e=t.point.sub(this.IntersectionOfTheRayAndInsertedEdge),i=t.nextOnPolyline.point.sub(this.IntersectionOfTheRayAndInsertedEdge);return Math.abs(e.x*i.y-i.x*e.y)<x.distanceEpsilon}IntersectEdgeWithRayPPP(t,e,i){let r=Wn.solve(e.x-t.x,-i.x,this.Pivot.x-t.x,e.y-t.y,-i.y,this.Pivot.y-t.y);if(!(-x.tolerance<=r.x&&r.x<=1+x.tolerance))throw new Error;if(!r)throw new Error;return this.Pivot.add(i.mul(r.y))}IntersectEdgeWithRay(t,e){return this.IntersectEdgeWithRayPPP(t.point,t.nextOnPolyline.point,e)}static constructorPP(t,e){let i=new Gd;return i.pivot=t,i.pointOnTheRay=e,i}},ty=ct(se(),1),An=class{get Start(){return this.start}set Start(n){this.start=n}get End(){return this.end}set End(n){this.end=n}constructor(n,t){this.start=n,this.end=t}*Sides(){let n=this.start;for(;n!==this.end;){let t=n;yield t,n=t.nextOnPolyline}}MoveStartClockwise(){return this.Start!==this.End?(this.Start=this.Start.nextOnPolyline,!0):!1}toString(){return ty.String.format("Stem({0},{1})",this.Start,this.End)}},wn=class Hs{constructor(t,e,i,r){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=Ni.mkFromPoint(this.q),this.QVertex=this.visibilityGraph.AddVertexP(this.qPolylinePoint.point),this.visibilityKind=r;let s=new Nd(this.q);this.heapForSorting=new tl(s.IComparer.bind(s))}get QVertex(){return this.qV}set QVertex(t){this.qV=t}static CalculatePointVisibilityGraph(t,e,i,r){let s=e.FindVertex(i);if(s!=null)return s;let o=new Hs(t,e,i,r);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(let t of this.GetInitialVisibleBoundaryStemsAndInsertActiveSides())this.heapForSorting.Enqueue(t)}*GetInitialVisibleBoundaryStemsAndInsertActiveSides(){for(let[t,e]of this.visibleBoundaries){let i=!1;for(let r of e.Sides()){let s=r;if(s.point.y<this.q.y){if(r.nextOnPolyline.point.y>=this.q.y){let o=g.getTriangleOrientation(this.q,s.point,r.nextOnPolyline.point);if(o===1||o===2){i=!0,yield new An(e.Start,r),yield new An(r.nextOnPolyline,e.End),this.RegisterActiveSide(r);break}}}else{if(s.point.y>this.q.y)break;if(r.point.x>=this.q.x){i=!0,yield new An(r,e.End),r!==e.Start&&(yield new An(e.Start,t.prev(s))),this.RegisterActiveSide(r);break}}}i||(yield e)}}RegisterActiveSide(t){this.activeEdgeComparer.IntersectionOfTheRayAndInsertedEdge=this.activeEdgeComparer.IntersectEdgeWithRay(t,new g(1,0)),this.sideNodes.set(t,this.activeSidesTree.insert(t))}Sweep(){for(let t of this.sortedListOfPolypoints)this.SweepPolylinePoint(t)}SweepPolylinePoint(t){let e=Hs.GetIncomingSide(t),i=this.GetOutgoingSide(t);this.activeEdgeComparer.IntersectionOfTheRayAndInsertedEdge=t.point;let r;if(r=this.sideNodes.get(e)){if(r===this.activeSidesTree.treeMinimum()&&this.AddEdge(t),i!=null)r.item=i,this.sideNodes.set(i,r);else{let s=this.activeSidesTree.deleteSubTree(r);s!=null&&s.item!=null&&this.sideNodes.set(s.item,s)}this.sideNodes.delete(e)}else if(i!=null){let s;(s=this.sideNodes.get(i))||(s=this.activeSidesTree.insert(i),this.sideNodes.set(i,s),s===this.activeSidesTree.treeMinimum()&&this.AddEdge(t))}else throw new Error}AddEdge(t){(this.visibilityKind===0||this.visibilityKind===1&&Hs.LineTouchesPolygon(this.QVertex.point,t))&&this.visibilityGraph.AddEdgeF(this.QVertex.point,t.point,(e,i)=>new rr(e,i))}static LineTouchesPolygon(t,e){let i=e.polyline.prev(e).point,r=e.polyline.next(e).point,s=e.point;return g.signedDoubledTriangleArea(t,s,i)*g.signedDoubledTriangleArea(t,s,r)>=0}GetOutgoingSide(t){let e=this.visibleBoundaries.get(t.polyline);return t===e.End?null:t}static GetIncomingSide(t){return t.prevOnPolyline}ComputeHoleBoundariesPossiblyVisibleFromQ(){this.InitActiveEdgesAndActiveEdgesComparer();for(let t of this.holes)this.ComputeVisiblePartOfTheHole(t)}InitActiveEdgesAndActiveEdgesComparer(){this.activeEdgeComparer=new _P,this.activeEdgeComparer.pivot=this.q,this.activeSidesTree=new Re(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 r=t.next(e);if(i)for(;this.HoleSideIsVisibleFromQ(t,t.prev(e));)e=t.prev(e);for(;this.HoleSideIsVisibleFromQ(t,r);r=t.next(r));this.visibleBoundaries.set(t,new An(e,r))}HoleSideIsVisibleFromQ(t,e){return g.signedDoubledTriangleArea(this.q,e.point,t.next(e).point)>=-x.squareOfDistanceEpsilon}},Ga=class Ft extends Nt{constructor(){super(...arguments),this.IgnoreTightPadding=!0,this.activeRectangle=it.mkEmpty(),this.activePolygons=new Array,this.alreadyAddedOrExcludedPolylines=new Set,this.UseInnerPolylingShortcutting=!0,this.UsePolylineEndShortcutting=!0,this.AllowedShootingStraightLines=!0,this.LookForRoundedVertices=!1}rerouteEdge(t){let e=t.smoothedPolyline?et.mkFromPoints(t.smoothedPolyline):et.mkFromPoints(t.getSmoothPolyPoints());this.pathOptimizer.run(e),t.curve=this.pathOptimizer.poly.toCurve()}static constructorANNN(t,e,i,r){return Ft.constructorANNNB(t,e,i,r,!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=Ft.GetFirstHitPolyline(this.sourcePort.Location,this.ObstacleCalculator.RootOfTightHierarchy),this.sourcePort instanceof ve)this.alreadyAddedOrExcludedPolylines.add(this.SourceLoosePolyline),this.StartPointOfEdgeRouting=this.SourcePort.Location;else{let 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 zt);let e=null;if(!this.activeRectangle.contains(t)){this.activeRectangle.isEmpty?this.activeRectangle=it.mkPP(this.SourcePort.Location,t):this.activeRectangle.add(t),e=this.GetAddedPolygonesAndMaybeExtendActiveRectangle();for(let 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 Ts(e,this.activePolygons,this.VisibilityGraph).run(),Yi(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=wn.CalculatePointVisibilityGraph(this.GetActivePolylines(),this.VisibilityGraph,t,1)}CalculateSourcePortVisibilityGraph(){this.sourceVV=wn.CalculatePointVisibilityGraph(this.GetActivePolylines(),this.VisibilityGraph,this.StartPointOfEdgeRouting,1)}TakeBoundaryPortOutsideOfItsLoosePolyline(t,e,i){let r=t.value(e),s=t.leftDerivative(e).normalize().add(t.rightDerivative(e).normalize()).normalize();g.getTriangleOrientation(Ft.PointInsideOfConvexCurve(t),r,r.add(s))==1&&(s=s.mul(-1)),s=s.rotate(Math.PI/2);let o=i.boundingBox.diagonal,a=D.mkPP(r,r.add(s.mul(o))),l=G.intersectionOne(a,i,!1).x,h=s.mul(l.sub(r).length/2);for(;;){a=D.mkPP(r,l.add(h));let u=!1;for(let d of Ft.IntersectionsOfLineAndRectangleNodeOverPolylineLR(a,this.ObstacleCalculator.RootOfLooseHierarchy))if(d.seg1!==i){h=h.div(1.5),u=!0;break}if(!u)break}return a.end}static PointInsideOfConvexCurve(t){return t.value(0).add(t.value(1.5)).div(2)}*GetActivePolylines(){for(let t of this.activePolygons)yield t.Polyline}GetAddedPolygonesAndMaybeExtendActiveRectangle(){let t=this.activeRectangle,e=new Array,i;do{i=!1;for(let r of this.ObstacleCalculator.RootOfLooseHierarchy.GetNodeItemsIntersectingRectangle(this.activeRectangle))this.alreadyAddedOrExcludedPolylines.has(r)||(t.addRec(r.boundingBox),e.push(new Ze(r)),this.alreadyAddedOrExcludedPolylines.add(r),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(D.mkPP(t,e),i)}PolylineIntersectsPolyRectangleNodeOfTightHierarchy(t,e){if(!t.boundingBox.intersects(e.irect))return!1;if(e.UserData!=null){for(let i of G.getAllIntersections(t,e.UserData,!1))if(i.seg1!==this.SourceTightPolyline&&i.seg1!==this.TargetTightPolyline||(i.seg1===this.SourceTightPolyline&&this.SourcePort)instanceof gi||(i.seg1===this.TargetTightPolyline&&this.TargetPort)instanceof gi)return!0;return!1}return this.PolylineIntersectsPolyRectangleNodeOfTightHierarchy(t,e.Left)||this.PolylineIntersectsPolyRectangleNodeOfTightHierarchy(t,e.Right)}static IntersectionsOfLineAndRectangleNodeOverPolylineLR(t,e){let i=new Array;return Ft.IntersectionsOfLineAndRectangleNodeOverPolyline(t,e,i),i}static IntersectionsOfLineAndRectangleNodeOverPolyline(t,e,i){if(e!=null&&t.boundingBox.intersects(e.irect)){if(e.UserData!=null){Yi(i,G.getAllIntersections(t,e.UserData,!0));return}Ft.IntersectionsOfLineAndRectangleNodeOverPolyline(t,e.Left,i),Ft.IntersectionsOfLineAndRectangleNodeOverPolyline(t,e.Right,i)}}LineCanBeAcceptedForRouting(t){let e=this.SourcePort instanceof ve,i=this.TargetPort instanceof ve;if(!e&&!this.targetIsInsideOfSourceTightPolyline&&!this.InsideOfTheAllowedConeOfBoundaryPort(t.end,this.SourcePort)||!i&&this.TargetPort!=null&&!this.sourceIsInsideOfTargetTightPolyline&&!this.InsideOfTheAllowedConeOfBoundaryPort(t.start,this.TargetPort))return!1;let r=Ft.IntersectionsOfLineAndRectangleNodeOverPolylineLR(t,this.ObstacleCalculator.RootOfTightHierarchy);for(let s of r)if(s.seg1!==this.SourceTightPolyline&&s.seg1!==this.targetTightPolyline)return!1;return!0}InsideOfTheAllowedConeOfBoundaryPort(t,e){let i=e.Curve,r=ye.CurveIsClockwise(i,Ft.PointInsideOfConvexCurve(i)),s=e.Location,o=this.GetPointOnTheRightBoundaryPortConeSide(s,i,r,e.Parameter),a=this.GetPointOnTheLeftBoundaryPortConeSide(s,i,r,e.Parameter);return g.getTriangleOrientation(s,o,t)!==0&&g.getTriangleOrientation(s,t,a)!==0}GetPointOnTheRightBoundaryPortConeSide(t,e,i,r){let s=i?e.rightDerivative(r):e.leftDerivative(r).neg();return t.add(s.rotate(this.EnteringAngleBound))}GetPointOnTheLeftBoundaryPortConeSide(t,e,i,r){let s=i?e.leftDerivative(r).neg():e.rightDerivative(r);return t.add(s.rotate(-this.EnteringAngleBound))}SmoothenCorners(t){let e=t.headSite,i={b:null,c:null};for(;i=G.findCorner(e);)e=this.SmoothOneCorner(e,i.c,i.b)}SmoothOneCorner(t,e,i){let r=.5,s,o,a;t.prev==null?(a=2,o=1):e.next==null?(a=1,o=2):a=o=1;do s=G.createBezierSeg(r*a,r*o,t,i,e),i.previouisBezierCoefficient=r*a,i.nextBezierCoefficient=r*o,r/=1.5;while(l()>this.loosePadding&&r>.01);return r*=1.5,r<.5&&r>.01&&(r=.5*(r+r*1.5),s=G.createBezierSeg(r*a,r*o,t,i,e),l()>this.loosePadding&&(i.previouisBezierCoefficient=r*a,i.nextBezierCoefficient=r*o)),i;function l(){let h=s.closestParameter(i.point);return i.point.sub(s.value(h)).length}}TryToRemoveInflectionsAndCollinearSegments(t){let e=!0,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)){let 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)){let 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)){let e=t.s.next.next;return t.s.next=e,e.prev=t.s,!0}return!1}GetShortestPolyline(t,e){this.CleanTheGraphForShortestPath();let i=new JP(this.visibilityGraph,t,e).GetPath();if(i==null)return null;let r=et.mkFromPoints(Array.from(i).map(s=>s.point)).RemoveCollinearVertices();return this.pathOptimizer&&(this.pathOptimizer.run(r),r=this.pathOptimizer.poly),r}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 ye(this.Obstacles,this.TightPadding,this.LoosePadding,this.IgnoreTightPadding),this.ObstacleCalculator.Calculate()}static constructorANNNB(t,e,i,r,s){let o=new Ft(null);return o.IgnoreTightPadding=s,o.EnteringAngleBound=80*(Math.PI/180),o.TightPadding=e,o.LoosePadding=i,r>0?(Wt.assert(r>Math.PI/180),Wt.assert(r<=90*(Math.PI/180)),o.UseSpanner=!0,o.ExpectedProgressSteps=ho.GetTotalSteps(r)):o.ExpectedProgressSteps=t.length,o.ConeSpannerAngle=r,o.Obstacles=t,o.CalculateObstacles(),o}RouteEdgeToLocation(t){this.TargetPort=new ve(null,t),this.TargetTightPolyline=null,this.TargetLoosePolyline=null;let e=new Fe(null),i=D.mkPP(this.SourcePort.Location,t);if(this.LineCanBeAcceptedForRouting(i)){this._polyline=new et,this._polyline.addPoint(i.start),this._polyline.addPoint(i.end);let r=Ot.mkFromPoints(this._polyline);return e.curve=r.createCurve(),e}return this.SourcePort instanceof gi&&(i=D.mkPP(this.StartPointOfEdgeRouting,t),Ft.IntersectionsOfLineAndRectangleNodeOverPolylineLR(i,this.ObstacleCalculator.RootOfTightHierarchy).length==0)?(this._polyline=new et,this._polyline.addPoint(this.SourcePort.Location),this._polyline.addPoint(i.start),this._polyline.addPoint(i.end),e.curve=Ot.mkFromPoints(this._polyline).createCurve(),e):(this.ExtendVisibilityGraphToLocation(t),this._polyline=this.GetShortestPolyline(this.sourceVV,this.targetVV),this.SourcePort instanceof gi&&this._polyline.PrependPoint(this.SourcePort.Location),e.curve=Ot.mkFromPoints(this._polyline).createCurve(),e)}RouteEdgeToPort(t,e,i,r){return this.ObstacleCalculator.IsEmpty()?this.sourcePort!=null&&this.targetPort!=null?(r.smoothedPolyline=this.SmoothedPolylineFromTwoPoints(this.sourcePort.Location,this.targetPort.Location),D.mkPP(this.sourcePort.Location,this.targetPort.Location)):null:(this.TargetPort=t,this.TargetTightPolyline=Ft.GetFirstHitPolyline(t.Location,this.ObstacleCalculator.RootOfTightHierarchy),t instanceof gi?this.RouteEdgeToBoundaryPort(e,i,r):this.RouteEdgeToFloatingPortOfNode(e,i,r))}SmoothedPolylineFromTwoPoints(t,e){return this._polyline=new et,this._polyline.addPoint(t),this._polyline.addPoint(e),Ot.mkFromPoints(this._polyline)}RouteEdgeToFloatingPortOfNode(t,e,i){return this.sourcePort instanceof ve?this.RouteFromFloatingPortToFloatingPort(t,e,i):this.RouteFromBoundaryPortToFloatingPort(t,e,i)}RouteFromBoundaryPortToFloatingPort(t,e,i){let r=this.SourcePort.Location,s=this.targetPort.Location,o=D.mkPP(r,s);if(this.LineCanBeAcceptedForRouting(o))return i.smoothedPolyline=this.SmoothedPolylineFromTwoPoints(o.start,o.end),o;if(!this.targetIsInsideOfSourceTightPolyline){let l=this.TakeBoundaryPortOutsideOfItsLoosePolyline(this.SourcePort.Curve,this.SourcePort.Parameter,this.SourceLoosePolyline);if(o=D.mkPP(l,s),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);let a=this.SourceTightPolyline;return this.targetIsInsideOfSourceTightPolyline||(this.SourceTightPolyline=null),this.SourceTightPolyline=a,this._polyline.PrependPoint(r),this.SmoothCornersAndReturnCurve(e,i)}SmoothCornersAndReturnCurve(t,e){return e.smoothedPolyline=Ot.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=Ot.mkFromPoints(this._polyline),this.SmoothCornersAndReturnCurve(e,i))}TryShortcutPolyPoint(t){return this.LineAvoidsTightHierarchyLPP(D.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 zt);let e=null,i=this.targetPort.Location;if(!this.activeRectangle.contains(i)){this.activeRectangle.isEmpty?this.activeRectangle=it.mkPP(this.SourcePort.Location,i):this.activeRectangle.add(i),e=this.GetAddedPolygonesAndMaybeExtendActiveRectangle();for(let r of e)this.VisibilityGraph.AddHole(r.Polyline)}e==null?(this.targetVV!=null&&this.VisibilityGraph.RemoveVertex(this.targetVV),this.CalculateEdgeTargetVisibilityGraphForFloatingPort(i,t),this.sourceVV==null&&this.CalculateSourcePortVisibilityGraph()):(this.RemovePointVisibilityGraphs(),new Ts(e,this.activePolygons,this.VisibilityGraph).run(),Yi(this.activePolygons,e),this.CalculateEdgeTargetVisibilityGraphForFloatingPort(i,t),this.CalculateSourcePortVisibilityGraph())}CalculateEdgeTargetVisibilityGraphForFloatingPort(t,e){this.UseSpanner?this.targetVV=this.AddTransientVisibilityEdgesForPort(t,e):this.targetVV=wn.CalculatePointVisibilityGraph(this.GetActivePolylinesWithException(e),this.VisibilityGraph,t,1)}AddTransientVisibilityEdgesForPort(t,e){let i=this.GetVertex(t);if(i!=null)return i;if(i=this.visibilityGraph.AddVertexP(t),e!=null)for(let r of e)this.visibilityGraph.AddEdgeF(t,r,(s,o)=>new rr(s,o));else i=wn.CalculatePointVisibilityGraph(this.GetActivePolylines(),this.VisibilityGraph,t,1);return i}GetVertex(t){let e=this.visibilityGraph.FindVertex(t);return e==null&&this.LookForRoundedVertices&&(e=this.visibilityGraph.FindVertex(g.RoundPoint(t))),e}*GetActivePolylinesWithException(t){for(let e of this.activePolygons)e.Polyline!==t&&(yield e.Polyline)}RouteEdgeToBoundaryPort(t,e,i){return this.TargetLoosePolyline=t,this.sourcePort instanceof ve?this.RouteFromFloatingPortToBoundaryPort(e,i):this.RouteFromBoundaryPortToBoundaryPort(e,i)}RouteFromBoundaryPortToBoundaryPort(t,e){let i=this.SourcePort.Location,r,s=this.targetPort.Location,o=D.mkPP(i,s);if(this.LineCanBeAcceptedForRouting(o))this._polyline=new et,this._polyline.addPoint(o.start),this._polyline.addPoint(o.end),e.smoothedPolyline=this.SmoothedPolylineFromTwoPoints(o.start,o.end),r=Ot.mkFromPoints(this._polyline).createCurve();else{let a=this.TakeBoundaryPortOutsideOfItsLoosePolyline(this.targetPort.Curve,this.targetPort.Parameter,this.TargetLoosePolyline);if(o=D.mkPP(i,a),this.InsideOfTheAllowedConeOfBoundaryPort(a,this.SourcePort)&&this.LineAvoidsTightHierarchyLP(o,this._sourceTightPolyline))this._polyline=new et,this._polyline.addPoint(o.start),this._polyline.addPoint(o.end),this._polyline.addPoint(s),r=this.SmoothCornersAndReturnCurve(t,e);else if(o=D.mkPP(this.StartPointOfEdgeRouting,s),this.InsideOfTheAllowedConeOfBoundaryPort(this.StartPointOfEdgeRouting,this.TargetPort)&&this.LineAvoidsTightHierarchy(o))this._polyline=new et,this._polyline.addPoint(i),this._polyline.addPoint(o.start),this._polyline.addPoint(o.end),r=this.SmoothCornersAndReturnCurve(t,e);else{let l;if(l=D.IntersectPPPP(i,this.StartPointOfEdgeRouting,s,a))this._polyline=new et,this._polyline.addPoint(i),this._polyline.addPoint(l),this._polyline.addPoint(s),r=this.SmoothCornersAndReturnCurve(t,e);else if(g.closeDistEps(this.StartPointOfEdgeRouting,a))this._polyline=new et,this._polyline.addPoint(i),this._polyline.addPoint(a),this._polyline.addPoint(s),r=this.SmoothCornersAndReturnCurve(t,e);else if(this.LineAvoidsTightHierarchy(D.mkPP(this.StartPointOfEdgeRouting,a)))this._polyline=new et,this._polyline.addPoint(i),this._polyline.addPoint(this.StartPointOfEdgeRouting),this._polyline.addPoint(a),this._polyline.addPoint(s),r=this.SmoothCornersAndReturnCurve(t,e);else{this.ExtendVisibilityGraphToTargetBoundaryPort(a),this._polyline=this.GetShortestPolyline(this.sourceVV,this.targetVV);let h={tmpTargetTight:null},u=this.HideSourceTargetTightsIfNeeded(h);this.RecoverSourceTargetTights(u,h.tmpTargetTight),this._polyline.PrependPoint(i),this._polyline.addPoint(s),r=this.SmoothCornersAndReturnCurve(t,e)}}}return r}RecoverSourceTargetTights(t,e){this.SourceTightPolyline=t,this.TargetTightPolyline=e}HideSourceTargetTightsIfNeeded(t){let e=this.SourceTightPolyline;return t.tmpTargetTight=this.TargetTightPolyline,this.TargetTightPolyline=null,this.SourceTightPolyline=null,e}LineAvoidsTightHierarchy(t){return Ft.IntersectionsOfLineAndRectangleNodeOverPolylineLR(t,this.ObstacleCalculator.RootOfTightHierarchy).length===0}RouteFromFloatingPortToBoundaryPort(t,e){let i=this.targetPort.Location,r;if(this.InsideOfTheAllowedConeOfBoundaryPort(this.sourcePort.Location,this.targetPort)&&(r=D.mkPP(this.SourcePort.Location,i),this.LineCanBeAcceptedForRouting(r)))return e.smoothedPolyline=this.SmoothedPolylineFromTwoPoints(r.start,r.end),r;let s=this.TakeBoundaryPortOutsideOfItsLoosePolyline(this.TargetPort.Curve,this.TargetPort.Parameter,this.TargetLoosePolyline);if(r=D.mkPP(this.SourcePort.Location,s),this.LineAvoidsTightHierarchyLP(r,this._sourceTightPolyline))return this._polyline=et.mkFromPoints([r.start,r.end,i]),e.smoothedPolyline=Ot.mkFromPoints(this._polyline),e.smoothedPolyline.createCurve();this.ExtendVisibilityGraphToTargetBoundaryPort(s),this._polyline=this.GetShortestPolyline(this.sourceVV,this.targetVV),this._polyline.addPoint(i);let o={smoothedPolyline:null};return this.SmoothCornersAndReturnCurve(t,o)}LineAvoidsTightHierarchyLP(t,e){let i=!0;for(let r of Ft.IntersectionsOfLineAndRectangleNodeOverPolylineLR(t,this.ObstacleCalculator.RootOfTightHierarchy))if(r.seg1!==e){i=!1;break}return i}LineAvoidsTightHierarchyLPP(t,e,i){let r=!0;for(let s of Ft.IntersectionsOfLineAndRectangleNodeOverPolylineLR(t,this.ObstacleCalculator.RootOfTightHierarchy))if(!(s.seg1===e||s.seg1===i)){r=!1;break}return r}LineAvoidsTightHierarchyPPPP(t,e,i,r){return this.LineAvoidsTightHierarchyLPP(D.mkPP(t,e),i,r)}ExtendVisibilityGraphToTargetBoundaryPort(t){let e=null;if(this.VisibilityGraph==null&&(this.VisibilityGraph=new zt),!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(let i of e)this.VisibilityGraph.AddHole(i.Polyline)}e==null?(this.targetVV!=null&&this.VisibilityGraph.RemoveVertex(this.targetVV),this.CalculateEdgeTargetVisibilityGraph(t)):(this.RemovePointVisibilityGraphs(),new Ts(e,this.activePolygons,this.VisibilityGraph).run(),Yi(this.activePolygons,e),this.CalculateEdgeTargetVisibilityGraph(t),this.CalculateSourcePortVisibilityGraph())}GetHitLoosePolyline(t){return this.ObstacleCalculator.IsEmpty()||this.ObstacleCalculator.RootOfLooseHierarchy==null?null:Ft.GetFirstHitPolyline(t,this.ObstacleCalculator.RootOfLooseHierarchy)}static GetFirstHitPolyline(t,e){let i=Ft.GetFirstHitRectangleNode(t,e);return i?i.UserData:null}static GetFirstHitRectangleNode(t,e){return e==null?null:e.FirstHitNodeWithPredicate(t,(i,r)=>G.PointRelativeToCurveLocation(i,r)!==0?1:0)}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=Ft.GetFirstHitPolyline(this.sourcePort.Location,this.ObstacleCalculator.RootOfTightHierarchy),this.sourcePort instanceof ve?(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 zt,this.CalculateWholeVisibilityGraphOnExistingGraph()}CalculateWholeVisibilityGraphOnExistingGraph(){this.activePolygons=Array.from(this.AllPolygons());for(let e of this.ObstacleCalculator.LooseObstacles)this.VisibilityGraph.AddHole(e);let t;this.UseSpanner?t=new ho(this.ObstacleCalculator.LooseObstacles,this.VisibilityGraph):t=new Ts(new Array,this.activePolygons,this.visibilityGraph),t.run()}RouteSplineFromPortToPortWhenTheWholeGraphIsReady(t,e,i,r){let s=t instanceof ve&&e instanceof gi||t instanceof Le;if(s){let a=t;t=e,e=a}this.sourcePort=t,this.targetPort=e,this.FigureOutSourceTargetPolylinesAndActiveRectangle();let o=this.GetEdgeGeomByRouting(i,r);return o==null?null:(this.targetVV=null,this.sourceVV=null,s&&(o=o.reverse()),o)}GetEdgeGeomByRouting(t,e){this.sourceIsInsideOfTargetTightPolyline=this.TargetTightPolyline==null||G.PointRelativeToCurveLocation(this.sourcePort.Location,this.TargetTightPolyline)===2;let i;if(this.sourcePort instanceof gi){let r=this.sourcePort;this.StartPointOfEdgeRouting=this.targetIsInsideOfSourceTightPolyline?r.Location:this.TakeBoundaryPortOutsideOfItsLoosePolyline(r.Curve,r.Parameter,this.SourceLoosePolyline),this.CalculateSourcePortVisibilityGraph();let s={smoothedPolyline:null};this.targetPort instanceof gi?i=this.RouteFromBoundaryPortToBoundaryPort(t,s):i=this.RouteFromBoundaryPortToFloatingPort(this.targetLoosePolyline,t,s)}else this.targetPort instanceof ve?(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,r){return r.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(r),r.HookSize>0&&this.BuildHook(r),this.SmoothCornersAndReturnCurve(e,i))):(i.smoothedPolyline=null,null)}BuildHook(t){let e=t.Curve,i=Dt.mkFullEllipseNNP(t.HookSize,t.HookSize,this._polyline.end),r=G.getAllIntersections(e,i,!0);g.getTriangleOrientation(r[0].x,this._polyline.end,this._polyline.endPoint.prev.point)==1&&r.reverse();let s=this._polyline.end.sub(this._polyline.endPoint.prev.point).normalize(),o=e.derivative(r[0].par0).normalize(),a=o.dot(s);if(Math.abs(a)<.2)this.ExtendPolyline(o,r[0],s,t);else{let l=e.derivative(r[1].par0).normalize();l.dot(s)<a?this.ExtendPolyline(l,r[1],s,t):this.ExtendPolyline(o,r[0],s,t)}}ExtendPolyline(t,e,i,r){let s=t.rotate(Math.PI/2);s.dot(i)<0&&(s=s.neg());let o=e.x.add(s.mul(r.HookSize)),a;(a=g.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(;;){let 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);let r=i.rotate(t.AdjustmentAngle*-1),s=i.rotate(t.AdjustmentAngle),o=G.intersectionOne(t.Curve,D.mkPP(e.point,e.point.add(r)),!0),a=G.intersectionOne(t.Curve,D.mkPP(e.point,e.point.add(s)),!0);if(o==null||a==null)return;let l=Ft.GetTrimmedCurveForHookingUpAnywhere(t.Curve,e,o,a),h=l.value(l.closestParameter(e.point));if(!this.LineAvoidsTightHierarchyLPP(D.mkPP(e.point,h),this.SourceTightPolyline,null)){let u=G.intersectionOne(t.Curve,D.mkPP(e.point,e.next.point),!1);if(u==null)return;this._polyline.endPoint.point=u.x;break}if(this._polyline.endPoint.point=h,e.prev==null||!this.TryShortcutPolyPoint(e.prev))break}}static GetTrimmedCurveForHookingUpAnywhere(t,e,i,r){let s=g.getTriangleOrientation(r.x,i.x,e.point)===0,o=i.par0,a=r.par0,l,h,u;return s?o<a?t.trim(o,a):(h=t.trim(o,t.parEnd),l=t.trim(t.parStart,a),u=new G,u.addSegs([h,l])):a<o?t.trim(a,o):(h=t.trim(a,t.parEnd),l=t.trim(t.parStart,o),u=new G,u.addSegs([h,l]))}GetLastPointInsideOfCurveOnPolyline(t){for(let e=this._polyline.endPoint.prev;e!=null;e=e.prev)if(e.prev==null||G.PointRelativeToCurveLocation(e.point,t)===2)return e;throw new Error}GetShortestPolylineToMulitpleTargets(t,e){this.CleanTheGraphForShortestPath();let i=new Rd(t,e,this.VisibilityGraph).GetPath();if(i==null)return null;let r=new et;for(let s of i)r.addPoint(s.point);return r.RemoveCollinearVertices()}Targets(t){return Array.from(t).map(e=>this.visibilityGraph.FindVertex(e))}ExtendVisibilityGraphFromFloatingSourcePort(){let t=this.sourcePort;this.StartPointOfEdgeRouting=t.Location,this.UseSpanner?this.sourceVV=this.AddTransientVisibilityEdgesForPort(this.sourcePort.Location,this.SourceLoosePolyline):this.sourceVV=wn.CalculatePointVisibilityGraph(this.GetActivePolylinesWithException(this.SourceLoosePolyline),this.VisibilityGraph,this.StartPointOfEdgeRouting,1)}FigureOutSourceTargetPolylinesAndActiveRectangle(){let t=this.sourcePort.Curve.value(this.sourcePort.Curve.parStart);this._sourceTightPolyline=Ft.GetFirstHitPolyline(t,this.ObstacleCalculator.RootOfTightHierarchy),this.SourceLoosePolyline=Ft.GetFirstHitPolyline(t,this.ObstacleCalculator.RootOfLooseHierarchy),t=this.targetPort.Curve.value(this.targetPort.Curve.parStart),this.targetTightPolyline=Ft.GetFirstHitPolyline(t,this.ObstacleCalculator.RootOfTightHierarchy),this.targetLoosePolyline=Ft.GetFirstHitPolyline(t,this.ObstacleCalculator.RootOfLooseHierarchy),this.activeRectangle=it.mkPP(new g(Number.NEGATIVE_INFINITY,Number.POSITIVE_INFINITY),new g(Number.POSITIVE_INFINITY,Number.NEGATIVE_INFINITY))}*AllPolygons(){for(let t of this.ObstacleCalculator.LooseObstacles)yield new Ze(t)}GetVisibilityGraph(){return this.VisibilityGraph}AddActivePolygons(t){Yi(this.activePolygons,t)}ClearActivePolygons(){this.activePolygons=[]}},kn=class extends Ar{constructor(n,t){super(),this.SetEdges(n,t)}},ey=class{constructor(n){this.MultipleMiddles=new Set,this.Multiedges=new Jr}*RegularMultiedges(){for(let[n,t]of this.Multiedges.keyValues())n.x!==n.y&&(yield t)}*AllIntEdges(){for(let n of this.Multiedges.values())for(let t of n)yield t}addFeedbackSet(n){for(let t of n){let e=new mt(t.source,t.target),i=new mt(t.target,t.source),r=this.Multiedges.get(e.x,e.y);for(let s of r)s.reverse();if(this.Multiedges.has(i.x,i.y)){let s=this.Multiedges.get(i.x,i.y);for(let o of r)s.push(o)}else this.Multiedges.set(i.x,i.y,r);this.Multiedges.delete(e.x,e.y)}}registerOriginalEdgeInMultiedges(n){let t=this.Multiedges.get(n.source,n.target);t==null&&this.Multiedges.set(n.source,n.target,t=[]),t.push(n)}*SkeletonEdges(){for(let[n,t]of this.Multiedges.keyValues())n.x!==n.y&&(yield t[0])}GetMultiedge(n,t){return this.GetMultiedgeI(new mt(n,t))}GetMultiedgeI(n){return this.Multiedges.has(n.x,n.y)?this.Multiedges.get(n.x,n.y):new Array}};function Da(n,t){for(let e=0;e<n.length;e++)t[e]=n[e]}var rn=class Ma{constructor(t){this.initialize(t)}initialize(t){this.y=t,this.verticesToX=null,this.layers=null}DropEmptyLayers(){let t=new Array(this.Layers.length),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;let i=new Array(this.y.length);for(let o=0;o<i.length;o++)i[o]=this.y[o]-t[this.y[o]];let r=new Array(this.layers.length-e);for(let o=0;o<this.layers.length;o++)this.layers[o].length>0&&(r[o-t[o]]=Array.from(this.layers[o]));let s=new Ma(i);return s.layers=r,s}updateLayers(t){this.layers==null&&this.InitLayers();for(let e=0;e<this.layers.length;e++)Da(t[e],this.layers[e]);this.UpdateXFromLayers()}UpdateXFromLayers(){this.layers==null&&this.InitLayers(),this.verticesToX==null&&(this.verticesToX=new Array(this.y.length));for(let t of this.layers){let e=0;for(let 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(){let 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 Ma(t)}get Layers(){return this.layers!=null?this.layers:(this.InitLayers(),this.layers)}set Layers(t){this.layers=t}InitLayers(){let t=0;for(let i of this.y)i+1>t&&(t=i+1);let e=new Array(t).fill(0);for(let 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++){let r=this.y[i];this.layers[r][e[r]++]=i}}},iy=class Dd extends Nt{constructor(t,e,i,r){super(r),this.jumpers=new Set,this.possibleJumperFeasibleIntervals=new Map,this.nodeCount=i,this.dag=t,this.layering=e,this.Init()}static Balance(t,e,i,r){new Dd(t,e,i,r).run()}run(){for(;this.jumpers.size>0;)this.Jump(this.ChooseJumper())}Init(){this.CalculateLayerCounts(),this.InitJumpers()}Jump(t){this.jumpers.delete(t);let e=this.possibleJumperFeasibleIntervals.get(t),i=this.CalcJumpInfo(e.x,e.y,t);if(i==null)return;this.layering[t]=i.layerToJumpTo;let r=this.nodeCount[t];this.vertsCounts[i.jumperLayer]-=r,this.vertsCounts[i.layerToJumpTo]+=r,this.UpdateRegionsForPossibleJumpersAndInsertJumpers(i.jumperLayer,t)}IsJumper(t){return this.possibleJumperFeasibleIntervals.has(t)}UpdateRegionsForPossibleJumpersAndInsertJumpers(t,e){let i=new Set;for(let s of this.dag.pred(e))this.IsJumper(s)&&(this.CalculateRegionAndInsertJumper(s),i.add(s));for(let s of this.dag.succ(e))this.IsJumper(s)&&(this.CalculateRegionAndInsertJumper(s),i.add(s));let r=new Array;for(let s of this.possibleJumperFeasibleIntervals)i.has(s[0])||s[1].x>t&&s[1].y<t&&r.push(s[0]);for(let s of r)this.CalculateRegionAndInsertJumper(s)}InitJumpers(){let t=new Array(this.dag.nodeCount).fill(0);for(let 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){let e=new mt(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){let r=this.layering[i],s=-1,o=this.vertsCounts[r]-2*this.nodeCount[i];for(let a=t-1;a>r;a--)this.vertsCounts[a]<o&&(o=this.vertsCounts[a],s=a);for(let a=r-1;a>e;a--)this.vertsCounts[a]<o&&(o=this.vertsCounts[a],s=a);if(s!==-1)return{jumperLayer:r,layerToJumpTo:s}}Up(t){let e=Number.MAX_SAFE_INTEGER;for(let i of this.dag.inEdges[t]){let r=this.layering[i.source]-i.separation+1;r<e&&(e=r)}return e===Number.MAX_SAFE_INTEGER&&(e=this.layering[t]+1),e}Down(t){let e=Number.NEGATIVE_INFINITY;for(let i of this.dag.outEdges[t]){let r=this.layering[i.target]+i.separation-1;r>e&&(e=r)}return e===Number.NEGATIVE_INFINITY&&(e=this.layering[t]-1),e}CalculateLayerCounts(){this.vertsCounts=new Array(Math.max(...this.layering)+1).fill(0);for(let t of this.layering)this.vertsCounts[t]+=this.nodeCount[t]}ChooseJumper(){for(let t of this.jumpers)return t;throw new Error("there are no jumpers to choose")}},ul=class Ws{constructor(t){this.Initialize(t)}Initialize(t){this.BaseGraph=t,this.totalNumberOfNodes=t.nodeCount;for(let e of this.BaseGraph.edges)if(e.LayerEdges!=null)for(let i of e.LayerEdges){let r=Math.max(i.Source,i.Target)+1;r>this.totalNumberOfNodes&&(this.totalNumberOfNodes=r)}this.firstVirtualNode=Number.POSITIVE_INFINITY;for(let e of this.BaseGraph.edges)if(e.LayerEdges!=null)for(let i=1;i<e.LayerEdges.length;i++){let r=e.LayerEdges[i];this.firstVirtualNode=Math.min(this.firstVirtualNode,r.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(let e of this.BaseGraph.edges)if(e.LayerSpan>0)for(let 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(let t of this.BaseGraph.edges)if(t.LayerSpan>0)for(let e of t.LayerEdges)yield e}get Edges(){return this.edges_()}*InEdges(t){if(t<this.BaseGraph.nodeCount)for(let e of this.BaseGraph.inEdges[t])e.source!==e.target&&e.LayerEdges!=null&&(yield Ws.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(let e of this.BaseGraph.outEdges[t])e.source!==e.target&&e.LayerEdges!=null&&(yield Ws.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){if(t>=this.BaseGraph.nodeCount)return 1;let e=0;for(let i of this.BaseGraph.inEdges[t])i.LayerEdges!=null&&e++;return e}OutEdgesCount(t){return this.RealOutEdgesCount(t)}RealOutEdgesCount(t){if(t>=this.BaseGraph.nodeCount)return 1;let e=0;for(let i of this.BaseGraph.outEdges[t])i.LayerEdges!=null&&e++;return e}get NodeCount(){return this.totalNumberOfNodes}IsRealNode(t){return t<this.BaseGraph.nodeCount}IsVirtualNode(t){return!this.IsRealNode(t)}ReversedClone(){let t=this.CreateReversedEdges();return new Ws(new kn(t,this.BaseGraph.nodeCount))}CreateReversedEdges(){let t=new Array;for(let e of this.BaseGraph.edges)e.isSelfEdge()||t.push(e.reversedClone());return t}*Succ(t){for(let e of this.OutEdges(t))yield e.Target}*Pred(t){for(let e of this.InEdges(t))yield e.Source}},Md=class Va{constructor(t,e,i,r){this.la=e,this.database=i,this.layeredGraph=t,this.intGraph=r}static InsertLayers(t,e,i,r){let s=new Va(t,e,i,r);return s.InsertLayers(),{layeredGraph:s.nLayeredGraph,la:s.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(let e of this.database.RegularMultiedges()){let i=0,r=e[0];if(i=r.LayerSpan*2,i>0){for(let s of r.LayerEdges)s.Target!==r.target&&(t++,this.UpdateOldLayer(t++,s.Target));t+=(i-1)*(e.length-1)+1}}}UpdateOldLayer(t,e){let i=this.la.x[e],r=this.la.y[e],s=this.la.Layers[r];s[i]=t}WidenOriginalLayers(){for(let t=0;t<this.la.Layers.length;t++){let e=this.Nla.Layers[t*2],i=0;for(let r of this.la.Layers[t]){let s=this.virtNodesToIntEdges[r];if(s!=null){let o=this.NLayering[s.source]-this.NLayering[r],a=this.database.Multiedges.get(s.source,s.target);for(let l of a)if(l!==s){let h=l.LayerEdges[o].Source;e[i]=h,this.Nla.x[h]=i++}else e[i]=r,this.Nla.x[r]=i++}else e[i]=r,this.Nla.x[r]=i++}}}FillUnsortedNewOddLayers(){let t=new Array(this.Nla.Layers.length).fill(0);for(let e=this.intGraph.nodeCount;e<this.nLayeredGraph.NodeCount;e++){let i=this.NLayering[e];i%2===1&&(this.Nla.Layers[i][t[i]++]=e)}}MapVirtualNodesToEdges(){this.virtNodesToIntEdges=new Array(this.NLayering.length);for(let t of this.database.AllIntEdges())if(t.source!==t.target&&t.LayerEdges!=null)for(let e of t.LayerEdges)e.Target!==t.target&&(this.virtNodesToIntEdges[e.Target]=t)}CreateFullLayeredGraph(){this.totalNodes=this.intGraph.nodeCount;for(let t of this.database.RegularMultiedges()){let e=0,i=!0;for(let r of t)if(i&&(i=!1,e=r.LayerSpan*2),e>0){r.LayerEdges=new Array(e);for(let s=0;s<e;s++){let o={currentVV:this.totalNodes},a=ka.GetSource(o,r,s);this.totalNodes=o.currentVV;let l=ka.GetTarget(this.totalNodes,r,s,e);r.LayerEdges[s]=new Ki(a,l,r.CrossingWeight)}Va.RegisterDontStepOnVertex(this.database,r)}}this.nLayeredGraph=new ul(this.intGraph)}SortNewOddLayers(){for(let t=1;t<this.Nla.Layers.length;t+=2){let e=new Map,i=this.Nla.Layers[t];for(let o of i){let a=-1;for(let u of this.nLayeredGraph.InEdges(o))a=u.Source;let l=-1;for(let u of this.nLayeredGraph.OutEdges(o))l=u.Target;let h=this.Nla.x[a]+this.Nla.x[l];if(e.has(h)){let u=e.get(h);if(typeof u=="number"){let d=new Array;d.push(u),d.push(o),e.set(h,d)}else u.push(o)}else e.set(h,o)}let r=Array.from(e.entries()).sort((o,a)=>o[0]-a[0]),s=0;for(let o of r.map(a=>a[1]))if(typeof o=="number")i[s++]=o;else for(let a of o)i[s++]=a;for(let o=0;o<i.length;o++)this.Nla.x[i[o]]=o}}InitNewLayering(){this.Nla=new rn(new Array(this.totalNodes));for(let i=0;i<this.layeredGraph.NodeCount;i++)this.NLayering[i]=this.la.y[i]*2;for(let[i,r]of this.database.Multiedges.keyValues())if(i.x!==i.y&&this.la.y[i.x]!==this.la.y[i.y]){let s=this.la.y[i.x]*2;for(let o of r){let a=s-1;for(let l of o.LayerEdges)l.Target!==o.target&&(this.NLayering[l.Target]=a--)}}let t=new Array(2*this.la.Layers.length-1),e=new Array(t.length).fill(0);for(let i of this.NLayering)e[i]++;for(let i=0;i<e.length;i++)t[i]=new Array(e[i]);this.Nla=new rn(this.NLayering),this.Nla.Layers=t}static RegisterDontStepOnVertex(t,e){if(t.Multiedges.get(e.source,e.target).length>1){let i=e.LayerEdges[Math.floor(e.LayerEdges.length/2)];t.MultipleMiddles.add(i.Source)}}},ka=class zs{constructor(t,e,i,r){this.virtNodesToIntEdges=new Map,this.la=e,this.database=i,this.layeredGraph=t,this.intGraph=r}get NLayering(){return this.Nla.y}static InsertPaths(t,e,i,r){let s=new zs(t,e,i,r);return s.InsertPaths(),{layeredGraph:s.NLayeredGraph,la:s.Nla}}InsertPaths(){this.CreateFullLayeredGraph(),this.InitNewLayering(),this.MapVirtualNodesToEdges(),this.WidenOriginalLayers()}WidenOriginalLayers(){for(let t=0;t<this.la.Layers.length;t++){let e=this.Nla.Layers[t],i=0;for(let r of this.la.Layers[t]){let s=this.virtNodesToIntEdges.get(r);if(s!=null){let o=this.NLayering[s.source]-this.NLayering[r],a=this.database.Multiedges.get(s.source,s.target);for(let l of a)if(!this.EdgeIsFlat(l))if(l!==s){let h=l.LayerEdges[o].Source;e[i]=h,this.Nla.x[h]=i++}else e[i]=r,this.Nla.x[r]=i++}else e[i]=r,this.Nla.x[r]=i++}}}EdgeIsFlat(t){return this.la.y[t.source]===this.la.y[t.target]}MapVirtualNodesToEdges(){for(let t of this.database.RegularMultiedges())for(let e of t)if(!this.EdgeIsFlat(e))for(let i of e.LayerEdges)i.Target!==e.target&&this.virtNodesToIntEdges.set(i.Target,e)}CreateFullLayeredGraph(){let t=this.layeredGraph.NodeCount;for(let[e,i]of this.database.Multiedges.keyValues())if(e.x!==e.y){let r=!0,s=0;for(let o of i){if(r)r=!1,s=o.LayerSpan;else if(o.LayerEdges=new Array(s),s===1)o.LayerEdges[0]=new Ki(o.source,o.target,o.CrossingWeight);else for(let a=0;a<s;a++){let l={currentVV:t},h=zs.GetSource(l,o,a);t=l.currentVV;let u=zs.GetTarget(t,o,a,s);o.LayerEdges[a]=new Ki(h,u,o.CrossingWeight)}Md.RegisterDontStepOnVertex(this.database,o)}}this.NLayeredGraph=new ul(this.intGraph)}static GetTarget(t,e,i,r){return i<r-1?t:e.target}static GetSource(t,e,i){return i===0?e.source:t.currentVV++}InitNewLayering(){this.Nla=new rn(new Array(this.NLayeredGraph.NodeCount));for(let i=0;i<this.layeredGraph.NodeCount;i++)this.NLayering[i]=this.la.y[i];for(let[i,r]of this.database.Multiedges.keyValues())if(i.x!==i.y&&this.la.y[i.x]!==this.la.y[i.y]){let s=0,o=!0;for(let a of r){o&&(o=!1,s=this.la.y[a.source]);let l=s-1;for(let h of a.LayerEdges)this.NLayering[h.Target]=l--}}let t=new Array(this.la.Layers.length),e=new Array(t.length).fill(0);for(let i of this.NLayering)e[i]++;for(let i=0;i<e.length;i++)t[i]=new Array(e[i]);this.Nla=new rn(this.NLayering),this.Nla.Layers=t}},In=class{constructor(n,t,e){this.numberOfCrossings=t,this.la=n,this.virtVertexStart=e}LayerGroupDisbalance(n,t,e){return t===1?this.LayerGroupDisbalanceWithOrigSeparators(n,e):this.LayerGroupDisbalanceWithVirtSeparators(n,t)}LayerGroupDisbalanceWithVirtSeparators(n,t){let e=0;for(let i=0;i<n.length;){let r=this.CurrentOrigGroupDelta(i,n,t);i=r.i,e+=r.ret}return e}CurrentOrigGroupDelta(n,t,e){let i=0,r=n;for(;r<t.length&&t[r]<this.virtVertexStart;r++)i++;return n=r+1,{ret:Math.abs(e-i),i:n}}LayerGroupDisbalanceWithOrigSeparators(n,t){let e=0;for(let i=0;i<n.length;){let r=this.CurrentVirtGroupDelta(i,n,t);e+=r.ret,i=r.i}return e}CurrentVirtGroupDelta(n,t,e){let i=0,r=n;for(;r<t.length&&t[r]>=this.virtVertexStart;r++)i++;return n=r+1,{ret:Math.abs(e-i),i:n}}static less(n,t){return n.numberOfCrossings<t.numberOfCrossings}static greater(n,t){return n.numberOfCrossings>t.numberOfCrossings}IsPerfect(){return this.numberOfCrossings===0}},ry=ct(ti(),1),ny=class{constructor(n){this.x=n}Compare(n,t){let e=this.x[n.Source]-this.x[t.Source];return e!==0?e:this.x[n.Target]-this.x[t.Target]}},sy=class{constructor(n){this.x=n}Compare(n,t){let e=this.x[n.Target]-this.x[t.Target];return e!==0?e:this.x[n.Source]-this.x[t.Source]}};function Os(){return en(2)===0}function oy(n,t,e){let i=e.Layers[n+1],r=e.Layers[n];return r.length<=i.length?ly(r,t,e):ay(i,r,t,e)}function ay(n,t,e,i){let r=Vd(t,e),s=new sy(i.x);r.sort((h,u)=>s.Compare(h,u));let o=1;for(;o<n.length;)o*=2;let a=new Array(2*o-1).fill(0);o--;let l=0;for(let h of r){let u=o+i.x[h.Source],d=h.CrossingWeight;for(a[u]+=d;u>0;)u%2!==0&&(l+=d*a[u+1]),u=Math.floor((u-1)/2),a[u]+=d}return l}function ly(n,t,e){let i=Vd(n,t),r=new ny(e.x);i.sort((l,h)=>r.Compare(l,h));let s=1;for(;s<n.length;)s*=2;let o=new Array(2*s-1).fill(0);s--;let a=0;for(let l of i){let h=s+e.x[l.Target],u=l.CrossingWeight;for(o[h]+=u;h>0;)h%2!==0&&(a+=u*o[h+1]),h=Math.floor((h-1)/2),o[h]+=u}return a}function Vd(n,t){return Xn(n,e=>t.InEdges(e))}function Xh(n,t){let e=0;for(let i=0;i<t.Layers.length-1;i++)e+=oy(i,n,t);return e}var hy=class Gn extends Nt{constructor(t,e,i,r,s,o,a){super(a),this.tryReverse=!0,this.MaxNumberOfAdjacentExchanges=50,this.cancelToken=a,this.tryReverse=e,this.startOfVirtNodes=r,this.layerArrays=i,this.layering=i.y,this.nOfLayers=i.Layers.length,this.layers=i.Layers,this.properLayeredGraph=t,this.hasCrossWeights=s,this.SugSettings=o}get NoGainStepsBound(){return this.SugSettings.NoGainAdjacentSwapStepsBound*this.SugSettings.NoGainStepsForOrderingMultiplier}get SeedOfRandom(){return en(100)}get MaxOfIterations(){return this.SugSettings.MaxNumberOfPassesInOrdering*this.SugSettings.NoGainStepsForOrderingMultiplier}static OrderLayers(t,e,i,r,s){let o=!1;for(let a of t.Edges)if(a.CrossingWeight!==1){o=!0;break}new Gn(t,!0,e,i,o,r,s).run()}run(){if(this.Calculate(),this.tryReverse){let t=this.layerArrays.ReversedClone(),e=new Gn(this.properLayeredGraph.ReversedClone(),!1,t,this.startOfVirtNodes,this.hasCrossWeights,this.SugSettings,this.cancelToken);if(e.run(),In.less(e.measure,this.measure)){for(let i=0;i<this.nOfLayers;i++)Da(t.Layers[i],this.layerArrays.Layers[this.nOfLayers-1-i]);this.layerArrays.UpdateXFromLayers()}}}Calculate(){this.Init(),this.layerArraysCopy=Gn.CloneLayers(this.layers,this.layerArraysCopy);let t=0;this.measure=new In(this.layerArraysCopy,Xh(this.properLayeredGraph,this.layerArrays),this.startOfVirtNodes);for(let e=0;e<this.MaxOfIterations&&t<this.NoGainStepsBound&&!this.measure.IsPerfect();e++){let i=e%2===0;this.LayerByLayerSweep(i),this.AdjacentExchange();let r=new In(this.layerArrays.Layers,Xh(this.properLayeredGraph,this.layerArrays),this.startOfVirtNodes);In.less(this.measure,r)?(this.Restore(),t++):(In.less(r,this.measure)||Os())&&(t=0,this.layerArraysCopy=Gn.CloneLayers(this.layers,this.layerArraysCopy),this.measure=r)}}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(r=>r)}else for(let i=0;i<t.length;i++)Da(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){let i=this.layers[t],r=new Array(i.length);for(let o=0;o<r.length;o++)r[o]=this.WMedian(i[o],e);this.Sort(t,r);let s=this.layerArrays.Layers[t];for(let o=0;o<s.length;o++)this.layerArrays.x[s[o]]=o}Sort(t,e){let i=new Map,r=this.layers[t],s=0;for(let l of e){let h=r[s++];if(l!==-1)if(!i.has(l))i.set(l,h);else{let u=i.get(l);if(typeof u!="number"){let d=u;if(Os())d.push(h);else{let c=en(d.length),f=d[c];d[c]=h,d.push(f)}}else{let d=u,c=new Array;i.set(l,c),Os()?(c.push(d),c.push(h)):(c.push(h),c.push(d))}}}let o=Array.from(i).sort((l,h)=>l[0]-h[0]).map(l=>l[1]),a=0;for(s=0;s<r.length;)if(e[s]!==-1){let l=o[a++];if(typeof l=="number")r[s++]=l;else{let h=l;for(let u of h){for(;e[s]===-1;)s++;r[s++]=u}}}else s++}WMedian(t,e){let i,r;if(e?(i=this.properLayeredGraph.OutEdges(t),r=this.properLayeredGraph.OutEdgesCount(t)):(i=this.properLayeredGraph.InEdges(t),r=this.properLayeredGraph.InEdgesCount(t)),r===0)return-1;let s=new Array(r),o=0;if(e)for(let u of i)s[o++]=this.X[u.Target];else for(let u of i)s[o++]=this.X[u.Source];s.sort((u,d)=>u-d);let a=Math.floor(r/2);if(r%2===1)return s[a];if(r===2)return .5*(s[0]+s[1]);let l=s[a-1]-s[0],h=s[r-1]-s[a];return Math.floor((s[a-1]*l+s[a]*h)/(l+h))}Init(){let t=new Array(this.nOfLayers).fill(0),e=new ry.Stack;for(let r=0;r<this.properLayeredGraph.NodeCount;r++)this.properLayeredGraph.InEdgesCount(r)===0&&e.push(r);let i=new Array(this.properLayeredGraph.NodeCount).fill(!1);for(;e.size>0;){let r=e.pop(),s=this.layerArrays.y[r];this.layerArrays.Layers[s][t[s]]=r,this.layerArrays.x[r]=t[s],t[s]++;for(let o of this.properLayeredGraph.Succ(r))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(){let 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){let r=this.inCrossingCount[e]=new Map;for(let s of this.properLayeredGraph.InEdges(e))r.set(s.Source,s.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){let r=this.outCrossingCount[e]=new Map;for(let s of this.properLayeredGraph.OutEdges(e))r.set(s.Target,s.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(let t of this.layers)this.InitPsArraysForLayer(t)}CalcPair(t,e){let i=this.successors[t],r=this.successors[e],s=this.predecessors[t],o=this.predecessors[e];if(this.hasCrossWeights){let a=this.outCrossingCount[t],l=this.outCrossingCount[e],h=this.inCrossingCount[t],u=this.inCrossingCount[e];return{cuv:this.CountOnArraysUV(i,r,a,l)+this.CountOnArraysUV(s,o,h,u),cvu:this.CountOnArraysUV(r,i,l,a)+this.CountOnArraysUV(o,s,u,h)}}else return{cuv:this.CountOnArrays(i,r)+this.CountOnArrays(s,o),cvu:this.CountOnArrays(r,i)+this.CountOnArrays(o,s)}}InitPsArraysForLayer(t){for(let e of t){for(let i of this.properLayeredGraph.Pred(e)){let r=this.sOrder[i],s=r.size;this.successors[i][s]=e,r.set(e,s)}for(let i of this.properLayeredGraph.Succ(e)){let r=this.pOrder[i],s=r.size;this.predecessors[i][s]=e,r.set(e,s)}}}CountOnArrays(t,e){let i=0,r=e.length-1,s=-1,o=0;for(let a of t){let l=this.X[a];for(;s<r&&this.X[e[s+1]]<l;s++)o++;i+=o}return i}CountOnArraysUV(t,e,i,r){let s=0,o=e.length-1,a=-1,l=0;for(let h of t){let u=this.X[h],d;for(;a<o&&this.X[d=e[a+1]]<u;a++)l+=r.get(d);s+=l*i.get(h)}return s}AdjExchangeLayer(t){let e=this.layers[t];return this.ExchangeWithGainWithNoDisturbance(e)?!0:(this.DisturbLayer(e),this.ExchangeWithGainWithNoDisturbance(e))}Swap(t,e){let i=this.X[t],r=this.X[e],s=this.layering[t],o=this.layers[s];o[i]=e,o[r]=t,this.X[t]=r,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(let i of this.successors[t]){let r=this.pOrder[i];if(r.has(e)){let s=r.get(e),o=this.predecessors[i];o[s-1]=e,o[s]=t,r.set(e,s-1),r.set(t,s)}}else for(let i of this.successors[e]){let r=this.pOrder[i];if(r.has(t)){let s=r.get(e),o=this.predecessors[i];o[s-1]=e,o[s]=t,r.set(e,s-1),r.set(t,s)}}}UpdateSsContainingUv(t,e){if(this.predecessors[t].length<=this.predecessors[e].length)for(let i of this.predecessors[t]){let r=this.sOrder[i];if(r.has(e)){let s=r.get(e),o=this.successors[i];o[s-1]=e,o[s]=t,r.set(e,s-1),r.set(t,s)}}else for(let i of this.predecessors[e]){let r=this.sOrder[i];if(r.has(t)){let s=r.get(e),o=this.successors[i];o[s-1]=e,o[s]=t,r.set(e,s-1),r.set(t,s)}}}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){let i=t[e],r=t[e+1],s=this.SwapGain(i,r);(s>0||s===0&&Os())&&this.Swap(i,r)}SwapGain(t,e){let 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,r;return(i=this.properLayeredGraph.OutEdgesCount(t))===0||(r=this.properLayeredGraph.OutEdgesCount(e))===0?!1:this.X[this.successors[t][i>>1]]<this.X[this.successors[e][r>>1]]}UpperNeighborsForbidTheSwap(t,e){let i=this.properLayeredGraph.InEdgesCount(t),r=this.properLayeredGraph.InEdgesCount(e);return i===0||r===0?!1:this.X[this.predecessors[t][i>>1]]<this.X[this.predecessors[e][r>>1]]}CalcDeltaBetweenGroupsToTheLeftAndToTheRightOfTheSeparator(t,e,i){let r=this.GetKindDelegate(i),s=0;for(let a=e-1;a>=0&&!r(t[a]);a--)s++;let o=0;for(let a=e+1;a<t.length&&!r(t[a]);a++)o++;return s-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}},uy=class $a{constructor(t,e,i){this.properLayeredGraph=t,this.layerArrays=e,this.nodePositions=i}static UpdateLayerArrays0(t,e,i){new $a(t,e,i).UpdateLayerArrays()}static UpdateLayerArrays1(t,e){let i=$a.BuildInitialNodePositions(t,e);this.UpdateLayerArrays0(t,e,i)}static BuildInitialNodePositions(t,e){let i=new Map;for(let r=0;r<e.Layers.length;r++){let s=0,o=0;for(;s<e.Layers[r].length;){for(;s<e.Layers[r].length&&t.IsVirtualNode(e.Layers[r][s]);)s++;for(let a=o;a<s;a++)i.set(e.Layers[r][a],new g(r,o));s<e.Layers[r].length&&i.set(e.Layers[r][s],new g(r,s)),s++,o=s}}return i}UpdateLayerArrays(){let t=this.CreateInitialOrdering();t=this.BuildOrdering(t),this.RestoreLayerArrays(t)}CreateInitialOrdering(){let t=new _e;for(let e of this.layerArrays.Layers)for(let i of e){let r=this.nodePositions.get(i);t.hasxy(r.x,r.y)||t.setxy(r.x,r.y,[]),t.getxy(r.x,r.y).push(i)}return t}BuildOrdering(t){let e=new _e,i=new Map;for(let r of this.layerArrays.Layers)for(let s of r){let o=this.nodePositions.get(s);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(let e of this.properLayeredGraph.Succ(t))return e}firstPred(t){for(let e of this.properLayeredGraph.Pred(t))return e}Comparison(t){return(e,i)=>{let r=this.firstSucc(e),s=this.firstSucc(i),o=this.firstPred(e),a=this.firstPred(i),l=this.nodePositions.get(r),h=this.nodePositions.get(s),u=this.nodePositions.get(o),d=this.nodePositions.get(a);if(!l.equal(h))return u.equal(d)?l.compareTo(h):u.compareTo(d);if(this.properLayeredGraph.IsVirtualNode(r)){if(!u.equal(d))return u.compareTo(d);let c=t.get(r),f=t.get(s);return Mt(c,f)}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))?Mt(e,i):this.nodePositions.get(o).compareTo(this.nodePositions.get(a))}}RestoreLayerArrays(t){for(let e of this.layerArrays.Layers){let i=0,r=0;for(;i<e.length;){for(;i<e.length&&this.nodePositions.get(e[r]).equal(this.nodePositions.get(e[i]));)i++;let s=t.get(this.nodePositions.get(e[r]));for(let o=r;o<i;o++)e[o]=s[o-r];r=i}}this.layerArrays.UpdateXFromLayers()}},dy=ct(se(),1),cy=ct(ti(),1),kd=class $d{static getOrder(t,e){let i=yi(e.map(([r,s])=>new mt(r,s)),t);return $d.getOrderOnGraph(i)}static getOrderOnGraph(t){let e=new Array(t.nodeCount).fill(!1),i=new cy.Stack,r=[],s;for(let o=0;o<t.nodeCount;o++){if(e[o])continue;let a=o;e[a]=!0;let l=0;s=t.outEdges[o];do{for(;l<s.length;l++){let h=s[l].target;e[h]||(e[h]=!0,i.push({edges:s,index:l+1,current_u:a}),a=h,s=t.outEdges[a],l=-1)}if(r.push(a),i.length>0){let h=i.pop();s=h.edges,l=h.index,a=h.current_u}else break}while(!0)}return r.reverse()}},gy=class{GetLayers(){let n=kd.getOrderOnGraph(this.graph),t=new Array(this.graph.nodeCount).fill(0),e=this.graph.nodeCount;for(;e-- >0;){let i=n[e];for(let r of this.graph.inEdges[i]){let s=r.source,o=t[i]+r.separation;t[s]<o&&(t[s]=o)}}return t}checkTopoOrder(n){for(let t of this.graph.edges)if(py(t,n))return!1;return!0}constructor(n){this.graph=n}};function py(n,t){let e=t.findIndex(r=>r===n.source),i=t.findIndex(r=>r===n.target);return e===-1||i===-1||e>=i}var je=class Hd{constructor(t){this.inTree=!1,this.cut=Hd.infinity,this.iedge=t}static{this.infinity=Number.MAX_SAFE_INTEGER}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}},cr=ct(ti(),1);function fy(n){let t=new Array;for(let e of n.edges)t.push(new je(e));return yi(t,n.nodeCount)}var ha=class{constructor(n,t,e,i,r){this.v=n,this.outEnum=t,this.i=e,this.inEnum=i,this.j=r}},Wd=class{constructor(n,t){this.layers=null,this.treeVertices=[],this.vertices=[],this.leaves=[],this.graph=fy(n),this.networkCancelToken=t;for(let e=0;e<this.graph.nodeCount;e++)this.vertices.push({inTree:!1,lim:-1,low:-1,parent:null})}get weight(){return this.graph.edges.map(n=>n.weight*(this.layers[n.source]-this.layers[n.target])).reduce((n,t)=>n+t,0)}get nodeCount(){return this.vertices.length}setLow(n,t){this.vertices[n].low=t}setLim(n,t){this.vertices[n].lim=t}setParent(n,t){this.vertices[n].parent=t}GetLayers(){return this.layers==null&&this.run(),this.layers}shiftLayerToZero(){let n=Math.min(...this.layers);for(let t=0;t<this.layers.length;t++)this.layers[t]-=n}addVertexToTree(n){this.vertices[n].inTree=!0}vertexInTree(n){return this.vertices[n].inTree}lim(n){return this.vertices[n].lim}low(n){return this.vertices[n].low}parent(n){return this.vertices[n].parent}feasibleTree(){for(this.initLayers();this.tightTree()<this.nodeCount;){let n=this.getNonTreeEdgeIncidentToTheTreeWithMinimalAmountOfSlack();if(n==null)break;let t=this.slack(n);this.vertexInTree(n.source)&&(t=-t);for(let e of this.treeVertices)this.layers[e]+=t}this.initCutValues()}vertexSourceTargetVal(n,t){let e=t.source,i=t.target;return this.lim(e)>this.lim(i)?this.lim(n)<=this.lim(i)&&this.low(i)<=this.lim(n)?0:1:this.lim(n)<=this.lim(e)&&this.low(e)<=this.lim(n)?1:0}incidentEdges(n){return this.graph.incidentEdges(n)}allLowCutsHaveBeenDone(n){for(let t of this.incidentEdges(n))if(t.inTree&&t.cut===je.infinity&&t!==this.parent(n))return!1;return!0}edgeSourceTargetVal(n,t){return this.vertexSourceTargetVal(n.source,t)-this.vertexSourceTargetVal(n.target,t)}initCutValues(){this.initLimLowAndParent();let n=new cr.Stack;for(let e of this.leaves)n.push(e);let t=new cr.Stack;for(;n.length>0;){for(;n.length>0;){let i=n.pop(),r=this.parent(i);if(r==null)continue;let s=0;for(let a of this.incidentEdges(i))if(a.inTree===!1){let l=this.edgeSourceTargetVal(a,r);l!==0&&(s+=l*a.weight)}else if(a===r)s+=a.weight;else{let l=r.source===a.target||r.target===a.source?1:-1,h=this.edgeContribution(a,i);s+=h*l}r.cut=s;let o=r.source===i?r.target:r.source;this.allLowCutsHaveBeenDone(o)&&t.push(o)}let e=n;n=t,t=e}}edgeContribution(n,t){let e=n.cut-n.weight;for(let i of this.incidentEdges(t))if(i.inTree===!1){let r=this.edgeSourceTargetVal(i,n);r===-1?e+=i.weight:r===1&&(e-=i.weight)}return e}initLimLowAndParent(){this.initLowLimParentAndLeavesOnSubtree(1,0)}initLowLimParentAndLeavesOnSubtree(n,t){let e=new cr.Stack,i=this.graph.outEdges[t],r=-1,s=this.graph.inEdges[t],o=-1;for(e.push(new ha(t,i,r,s,o)),this.vertices[t].low=n;e.length>0;){let a=e.pop();t=a.v,i=a.outEnum,r=a.i,s=a.inEnum,o=a.j;let l;do{for(l=!0;++r<i.length;){let h=i[r];!h.inTree||this.vertices[h.target].low>0||(e.push(new ha(t,i,r,s,o)),t=h.target,this.setParent(t,h),this.setLow(t,n),i=this.graph.outEdges[t],r=-1,s=this.graph.inEdges[t],o=-1)}for(;++o<s.length;){let h=s[o];if(!(!h.inTree||this.vertices[h.source].low>0)){e.push(new ha(t,i,r,s,o)),t=h.source,this.setLow(t,n),this.setParent(t,h),i=this.graph.outEdges[t],r=-1,s=this.graph.inEdges[t],o=-1,l=!1;break}}}while(!l);this.setLim(t,n++),this.lim(t)===this.low(t)&&this.leaves.push(t)}}updateLimLowLeavesAndParentsUnderNode(n){let t=this.vertices[n].low,e=this.vertices[n].lim;this.leaves=[];for(let i=0;i<this.nodeCount;i++)t<=this.vertices[i].lim&&this.vertices[i].lim<=e?this.setLow(i,0):this.low(i)===this.lim(i)&&this.leaves.push(i);this.initLowLimParentAndLeavesOnSubtree(t,n)}slack(n){return this.layers[n.source]-this.layers[n.target]-n.separation}getNonTreeEdgeIncidentToTheTreeWithMinimalAmountOfSlack(){let n=null,t=je.infinity;for(let e of this.treeVertices){for(let i of this.graph.outEdges[e]){if(this.vertexInTree(i.source)&&this.vertexInTree(i.target))continue;let r=this.slack(i);if(r<t&&(n=i,t=r,r===1))return i}for(let i of this.graph.inEdges[e]){if(this.vertexInTree(i.source)&&this.vertexInTree(i.target))continue;let r=this.slack(i);if(r<t&&(n=i,t=r,r===1))return i}}return n}tightTree(){this.treeVertices=[];for(let t of this.graph.edges)t.inTree=!1;for(let t=1;t<this.nodeCount;t++)this.vertices[t].inTree=!1;this.vertices[0].inTree=!0,this.treeVertices.push(0);let n=new cr.Stack;for(n.push(0);n.length>0;){let t=n.pop();for(let e of this.graph.outEdges[t])this.vertexInTree(e.target)||this.layers[e.source]-this.layers[e.target]===e.separation&&(n.push(e.target),this.addVertexToTree(e.target),this.treeVertices.push(e.target),e.inTree=!0);for(let e of this.graph.inEdges[t])this.vertexInTree(e.source)||this.layers[e.source]-this.layers[e.target]===e.separation&&(n.push(e.source),this.addVertexToTree(e.source),this.treeVertices.push(e.source),e.inTree=!0)}return this.treeVertices.length}leaveEnterEdge(){let n,t,e=0;for(let s of this.graph.edges)s.inTree&&s.cut<e&&(e=s.cut,n=s);if(n==null)return null;let i=!1,r=je.infinity;for(let s of this.graph.edges){let o=this.slack(s);if(s.inTree===!1&&this.edgeSourceTargetVal(s,n)===-1&&(o<r||o===r&&(i=en(2)===1))){if(r=o,t=s,r===0&&!i)break;i=!1}}if(t==null)throw new Error;return{leaving:n,entering:t}}exchange(n,t){let e=this.commonPredecessorOfSourceAndTargetOfF(t);this.createPathForCutUpdates(n,t,e),this.updateLimLowLeavesAndParentsUnderNode(e),this.updateCuts(n),this.updateLayersUnderNode(e)}updateLayersUnderNode(n){let t=new cr.Stack;t.push(n);for(let e=0;e<this.nodeCount;e++)this.low(n)<=this.lim(e)&&this.lim(e)<=this.lim(n)&&e!==n&&(this.layers[e]=je.infinity);for(;t.length>0;){let e=t.pop();for(let i of this.graph.outEdges[e])i.inTree&&this.layers[i.target]===je.infinity&&(this.layers[i.target]=this.layers[e]-i.separation,t.push(i.target));for(let i of this.graph.inEdges[e])i.inTree&&this.layers[i.source]===je.infinity&&(this.layers[i.source]=this.layers[e]+i.separation,t.push(i.source))}}updateCuts(n){let t=new cr.Stack,e=new cr.Stack;for(t.push(n.source),t.push(n.target);t.length>0;){for(;t.length>0;){let r=t.pop(),s=this.parent(r);if(s==null||s.cut!==je.infinity)continue;let o=0;for(let l of this.incidentEdges(r))if(l.inTree===!1)o+=this.edgeSourceTargetVal(l,s)*l.weight;else if(l===s)o+=l.weight;else{let h=s.source===l.target||s.target===l.source?1:-1,u=this.edgeContribution(l,r);o+=u*h}s.cut=o;let a=s.source===r?s.target:s.source;this.allLowCutsHaveBeenDone(a)&&e.push(a)}let i=t;t=e,e=i}}createPathForCutUpdates(n,t,e){let i=t.target;for(;i!==e;){let r=this.parent(i);r.cut=je.infinity,i=r.source===i?r.target:r.source}t.cut=je.infinity,n.inTree=!1,t.inTree=!0}commonPredecessorOfSourceAndTargetOfF(n){let t,e;this.lim(n.source)<this.lim(n.target)?(t=this.lim(n.source),e=this.lim(n.target)):(t=this.lim(n.target),e=this.lim(n.source));let i=n.source;for(;!(this.low(i)<=t&&e<=this.lim(i));){let r=this.parent(i);r.cut=je.infinity,i=r.source===i?r.target:r.source}return i}checkCutValues(){for(let n of this.graph.edges)if(n.inTree){let t=0;for(let e of this.graph.edges)t+=this.edgeSourceTargetVal(e,n)*e.weight;n.cut!==t&&console.log(dy.String.format("cuts are wrong for {0}; should be {1} but is {2}",n,t,n.cut))}}initLayers(){let n=new gy(this.graph);return this.layers=n.GetLayers()}run(){if(this.graph.edges.length===0&&this.graph.nodeCount===0)this.layers=[];else{this.feasibleTree();let n;for(;(n=this.leaveEnterEdge())!=null;)this.exchange(n.leaving,n.entering);this.shiftLayerToZero()}}},my=class{GetLayers(){return new Wd(this.graph,this.Cancel).GetLayers()}ShrunkComponent(n){let t=[];for(let e of n){let i=e[0],r=e[1];for(let s of this.graph.outEdges[i]){let o=new Bi(r,n.get(s.target),s.edge);o.separation=s.separation,o.weight=s.weight,t.push(o)}}return new kn(t,n.size)}constructor(n,t){this.graph=n,this.Cancel=t}},zd=class Qe{constructor(t){this.padding=0,this.alreadySitsOnASpline=!1,this.labelIsToTheLeftOfTheSpline=!1,this.labelIsToTheRightOfTheSpline=!1,this.labelCornersPreserveCoefficient=t}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 g(this.left,this.top)}get leftBottom(){return new g(this.left,this.bottom)}get rightBottom(){return new g(this.right,this.bottom)}get node(){return this.node_}set node(t){this.node_=t,this.polygonalBoundary_=null}get rightTop(){return new g(this.right,this.top)}static mkAnchor(t,e,i,r,s,o){let a=new Qe(o);return a.la=t,a.ra=e,a.ta=i,a.ba=r,a.node=s,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 g(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_=Qe.pad(this.creatPolygonalBoundaryWithoutPadding(),this.padding)}static pad(t,e){return e===0?t:Qe.curveIsConvex(t)?Qe.padConvexCurve(t,e):Qe.padConvexCurve(t.boundingBox.perimeter(),e)}static padCorner(t,e,i,r,s){let o=Qe.getPaddedCorner(e,i,r,s);t.addPoint(o.a),o.numberOfPoints===2&&t.addPoint(o.b)}static padConvexCurve(t,e){let i=new et;Qe.padCorner(i,t.endPoint.prev,t.endPoint,t.startPoint,e),Qe.padCorner(i,t.endPoint,t.startPoint,t.startPoint.next,e);for(let r=t.startPoint;r.next.next!=null;r=r.next)Qe.padCorner(i,r,r.next,r.next.next,e);return i.closed=!0,i}static getPaddedCorner(t,e,i,r){let s=t.point,o=e.point,a=i.point,l=g.getTriangleOrientation(s,o,a)===1,h=o.sub(s),u=h.rotate((l?-Math.PI:Math.PI)/2).normalize(),d=h.normalize().add(o.sub(a).normalize());if(d.length<x.intersectionEpsilon)return{a:o.add(u.mul(r)),b:null,numberOfPoints:1};let c=d.normalize().mul(r),f=c.rotate(Math.PI/2),m=(r-c.dot(u))/f.dot(u);return{a:c.add(f.mul(m)).add(o),b:c.sub(f.mul(m)).add(o),numberOfPoints:2}}static*orientations(t){yield g.getTriangleOrientation(t.endPoint.point,t.startPoint.point,t.startPoint.next.point),yield g.getTriangleOrientation(t.endPoint.prev.point,t.endPoint.point,t.startPoint.point);let e=t.startPoint;for(;e.next.next!=null;)yield g.getTriangleOrientation(e.point,e.next.point,e.next.next.point),e=e.next}static curveIsConvex(t){let e=2;for(let i of Qe.orientations(t))if(i!==2){if(e===2)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():G.polylineAroundClosedCurve(this.nodeBoundary)}get nodeBoundary(){return this.node==null?null:this.node.boundaryCurve}standardRectBoundary(){let t=new et;return t.addPoint(this.leftTop),t.addPoint(this.rightTop),t.addPoint(this.rightBottom),t.addPoint(this.leftBottom),t.closed=!0,t}polygonOnLeftLabel(){let t=this.left+(1-this.labelCornersPreserveCoefficient)*this.LabelWidth;return et.mkClosedFromPoints([new g(t,this.top),this.rightTop,this.rightBottom,new g(t,this.bottom),new g(this.left,this.y)])}polygonOnRightLabel(){let t=this.right-(1-this.labelCornersPreserveCoefficient)*this.LabelWidth;return et.mkClosedFromPoints([new g(t,this.top),new g(this.right,this.y),new g(t,this.bottom),this.leftBottom,this.leftTop])}move(t){this.x+=t.x,this.y+=t.y}},Py=class Dn{constructor(t,e,i,r,s){this.xCoords=new Array(4),this.la=t,this.graph=e,this.nOfOriginalVertices=i,this.nOfVertices=this.graph.NodeCount,this.markedEdges=new Fi,this.h=this.la.Layers.length,this.root=new Array(this.nOfVertices),this.align=new Array(this.nOfVertices),this.anchors=r,this.nodeSep=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,r,s){new Dn(t,e,i,r,s).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){let i=new Array(e);e=0;for(let s of this.graph.InEdges(t))i[e++]=s.Source;i.sort((s,o)=>this.CompareByX(s,o));let r=Math.floor(e/2);r*2===e?this.upperMedians[t]=new mt(i[r-1],i[r]):this.upperMedians[t]=i[r]}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){let i=new Array(e);e=0;for(let s of this.graph.OutEdges(t))i[e++]=s.Target;i.sort((s,o)=>this.CompareByX(s,o));let r=Math.floor(e/2);r*2===e?this.lowMedians[t]=new mt(i[r-1],i[r]):this.lowMedians[t]=i[r]}else this.lowMedians[t]=-1}HorizontalBalancing(){let t=-1,e=new Array(4),i=new Array(4),r=Number.MAX_VALUE;for(let o=0;o<4;o++){let a={a:0,b:0};this.AssignmentBounds(o,a),e[o]=a.a,i[o]=a.b;let l=i[o]-e[o];l<r&&(t=o,r=l)}for(let o=0;o<4;o++){let a;if(Dn.IsLeftMostAssignment(o)?a=e[t]-e[o]:a=i[t]-i[o],this.x=this.xCoords[o],a!==0)for(let l=0;l<this.nOfVertices;l++)this.x[l]=this.x[l]+a}let s=new Array(4);for(let o=0;o<this.nOfVertices;o++)s[0]=this.xCoords[0][o],s[1]=this.xCoords[1][o],s[2]=this.xCoords[2][o],s[3]=this.xCoords[3][o],s.sort((a,l)=>a-l),this.anchors[o].x=(s[1]+s[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++){let r=this.x[i];r<e.a?e.a=r:r>e.b&&(e.b=r)}}}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){let e=this.BT?this.upperMedians[t]:this.lowMedians[t];if(typeof e!="number"){let i=e;this.LR?(yield i.x,yield i.y):(yield i.y,yield i.x)}else{let i=e;i>=0&&(yield i)}}MarkConflictingEdges(){let t=this.LowerOf(0,this.h-1),e=t,i=this.UpperOf(0,this.h-1),r=this.NextLower(i);for(;this.IsBelow(t,i);t=this.NextUpper(t))this.IsBelow(e,t)&&this.IsBelow(t,r)&&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){let e=this.la.Layers[t],i=null,r=this.LeftMost(0,e.length-1),s=this.RightMost(0,e.length-1);for(;this.IsNotRightFrom(r,s)&&i==null;r=this.NextRight(r))i=this.InnerEdgeByTarget(e[r]);if(i!=null){let o=this.Pos(this.Source(i));for(let l=this.LeftMost(0,e.length-1);this.IsLeftFrom(l,r);l=this.NextRight(l))for(let h of this.InEdges(e[l]))this.IsLeftFrom(o,this.Pos(this.Source(h)))&&this.MarkEdge(h);let a=this.Pos(this.Source(i));for(;this.IsNotRightFrom(r,s);){let l=this.AlignmentToTheRightOfInner(e,r,o);if(r=this.NextRight(r),l!=null){let h=this.Pos(this.Source(l));this.MarkEdgesBetweenInnerAndNewInnerEdges(e,i,l,a,h),i=l,a=h}}for(let l=this.NextRight(this.Pos(this.Target(i)));this.IsNotRightFrom(l,s);l=this.NextRight(l))for(let h of this.InEdges(e[l]))this.IsLeftFrom(this.Pos(this.Source(h)),this.Pos(this.Source(i)))&&this.MarkEdge(h)}}}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,r,s){let o=this.NextRight(this.Pos(this.Target(e)));for(;this.IsLeftFrom(o,this.Pos(this.Target(i)));o=this.NextRight(o))for(let a of this.InEdges(t[o])){let l=this.Pos(this.Source(a));this.IsLeftFrom(l,r)?this.MarkEdge(a):this.IsLeftFrom(s,l)&&this.MarkEdge(a)}}AlignmentToTheRightOfInner(t,e,i){if(this.NumberOfInEdges(t[e])===1){let r=null;for(let s of this.InEdges(t[e]))r=s;return this.IsInnerEdge(r)&&this.IsLeftFrom(i,this.Pos(r.Source))?r: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)){let 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()}Align(){this.CreateBlocks(),this.AssignCoordinatesByLongestPath()}AssignCoordinatesByLongestPath(){this.x=this.xCoords[this.CurrentEnumRightUp]=new Array(this.nOfVertices);let t=new Array;for(let r=0;r<this.nOfVertices;r++)if(r===this.root[r]){let s=r;do{let o={neighbor:0};this.TryToGetRightNeighbor(s,o)&&t.push(new Bi(r,this.root[o.neighbor],null)),s=this.align[s]}while(s!==r)}let e=yi(t,this.nOfVertices),i=kd.getOrderOnGraph(e);for(let r of i)if(r===this.root[r]){let s=0,o=!0,a=r;do{let l={neighbor:0};this.TryToGetLeftNeighbor(a,l)&&(o?(s=this.x[this.root[l.neighbor]]+this.DeltaBetweenVertices(l.neighbor,a),o=!1):s=this.RightMost(s,this.x[this.root[l.neighbor]]+this.DeltaBetweenVertices(l.neighbor,a))),a=this.align[a]}while(a!==r);this.x[r]=s}for(let r of i)if(r===this.root[r]&&e.inEdges[r].length===0){let s=r,o=this.RightMost(-Dn.infinity,Dn.infinity),a=o;do{let l={neighbor:0};this.TryToGetRightNeighbor(s,l)&&(o=this.LeftMost(o,this.x[this.root[l.neighbor]]-this.DeltaBetweenVertices(s,l.neighbor))),s=this.align[s]}while(s!==r);a!==o&&(this.x[r]=o)}for(let r=0;r<this.nOfVertices;r++)r!==this.root[r]&&(this.x[r]=this.x[this.root[r]])}TryToGetRightNeighbor(t,e){let i=this.NextRight(this.Pos(t)),r=this.la.Layers[this.la.y[t]];return i>=0&&i<r.length?(e.neighbor=r[i],!0):!1}TryToGetLeftNeighbor(t,e){let i=this.NextLeft(this.Pos(t)),r=this.la.Layers[this.la.y[t]];return i>=0&&i<r.length?(e.neighbor=r[i],!0):!1}CreateBlocks(){for(let e=0;e<this.nOfVertices;e++)this.root[e]=this.align[e]=e;let 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)){let i=this.la.Layers[e],r=this.LeftMost(-1,this.la.Layers[this.NextUpper(e)].length),s=this.RightMost(0,i.length-1);for(let o=this.LeftMost(0,i.length-1);this.IsNotRightFrom(o,s);o=this.NextRight(o)){let a=i[o];for(let l of this.UpperEdgeMedians(a))if(!this.IsMarked(a,l)&&this.IsLeftFrom(r,this.Pos(l))){this.align[l]=a,this.root[a]=this.root[l],this.align[a]=this.root[l],r=this.Pos(l);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)}static{this.infinity=1e7}DeltaBetweenVertices(t,e){let i;if(this.Pos(t)>this.Pos(e)){let r=t;t=e,e=r,i=-1}else i=1;return(this.anchors[t].rightAnchor+this.anchors[e].leftAnchor+this.nodeSep)*i}},yy=class extends Ar{constructor(n,t,e,i,r){super(),this.weightMultiplierOfOriginalOriginal=1,this.weightMultOfOneVirtual=3,this.weightMultiplierOfTwoVirtual=8,this.SetEdges(i,r),this.virtualVerticesStart=n.nodeCount,this.virtualVerticesEnd=t.NodeCount-1,this.layeredGraph=t,this.layerArrays=e}EdgeWeightMultiplier(n){let t=n.source,e=n.target;if(t<this.layeredGraph.NodeCount&&this.layerArrays.y[t]===this.layerArrays.y[e]&&this.layerArrays.x[t]===this.layerArrays.x[e]+1)return 0;let i=0,r=-1,s=-1;for(let o of this.outEdges[t])s===-1?s=o.target:r=o.target;return s>=this.virtualVerticesStart&&s<=this.virtualVerticesEnd&&i++,r>=this.virtualVerticesStart&&r<=this.virtualVerticesEnd&&i++,i===0?this.weightMultiplierOfOriginalOriginal:i===1?this.weightMultOfOneVirtual:this.weightMultiplierOfTwoVirtual}SetEdgeWeights(){for(let n of this.edges)n.weight=n.weight*this.EdgeWeightMultiplier(n)}},Ls=class qd{constructor(t,e){this.groupSplitThreshold=2,this.initialNodes=t,this.groupSplitThreshold=e}static Calculate(t,e=0){return new qd(t,e).Calculate()}Calculate(){return this.Calc(this.initialNodes)}Calc(t){if(t.length===0)return null;if(t.length===1)return t[0];let e=t[0].parallelogram,i=1,r=ie.parallelogramOfTwo(e,t[i].parallelogram).area;for(let u=2;u<t.length;u++){let d=ie.parallelogramOfTwo(e,t[u].parallelogram).area;d>r&&(i=u,r=d)}let s;for(let u=0;u<t.length;u++)if(u!==i){s=u;break}r=ie.parallelogramOfTwo(t[i].parallelogram,t[s].parallelogram).area;for(let u=0;u<t.length;u++){if(u===i)continue;let d=ie.parallelogramOfTwo(t[i].parallelogram,t[u].parallelogram).area;d>r&&(s=u,r=d)}let o=new Array,a=new Array;o.push(t[i]),a.push(t[s]);let l=t[i].parallelogram,h=t[s].parallelogram;for(let u=0;u<t.length;u++){if(u===i||u===s)continue;let d=ie.parallelogramOfTwo(l,t[u].parallelogram),c=d.area-l.area,f=ie.parallelogramOfTwo(h,t[u].parallelogram),m=f.area-h.area;o.length*this.groupSplitThreshold<a.length?(o.push(t[u]),l=d):a.length*this.groupSplitThreshold<o.length?(a.push(t[u]),h=f):c<m?(o.push(t[u]),l=d):(a.push(t[u]),h=f)}return{parallelogram:ie.parallelogramOfTwo(l,h),node:{children:[this.Calc(o),this.Calc(a)]},seg:void 0,leafBoxesOffset:void 0}}},Sy=class Me{constructor(t,e,i,r,s,o,a,l){this.topNode=t,this.bottomNode=e,this.topSite=i,this.bottomSite=i.next,this.currentTopSite=i,this.currentBottomSite=i.next,this.layerArrays=r,this.layeredGraph=s,this.originalGraph=o,this.anchors=a,this.layerSeparation=l}static Refine(t,e,i,r,s,o,a,l){new Me(t,e,i,s,o,a,r,l).Refine()}Refine(){for(this.Init();this.InsertSites(););}FixCorner(t,e,i){if(t.equal(e))return e;let r=g.ClosestPointAtLineSegment(e,t,i),s=e.sub(r),o=Math.abs(s.y),a=this.layerSeparation/2;return o>a&&(s=s.mul(a/(o*2))),s.add(e)}InsertSites(){return en(2)===0?this.CalculateNewTopSite()||this.CalculateNewBottomSite():this.CalculateNewBottomSite()||this.CalculateNewTopSite()}CalculateNewBottomSite(){let t=this.currentBottomSite.point.sub(this.currentTopSite.point),e=Me.absCotan(t),i,r=!1;for(let s of this.bottomCorners()){let o=Me.absCotan(s.sub(this.currentBottomSite.point));o<e&&(e=o,i=s,r=!0)}return r?lt(e,Me.absCotan(t))?!1:(this.currentBottomSite=re.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(){let t=this.currentBottomSite.point.sub(this.currentTopSite.point),e=Me.absCotan(t),i,r=!1;for(let s of this.topCorners()){let o=Me.absCotan(s.sub(this.currentTopSite.point));o<e&&(e=o,i=s,r=!0)}return r?lt(e,Me.absCotan(t))?!1:(this.currentTopSite=re.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(let e of this.anchors[t].polygonalBoundary.polylinePoints())yield e.point}*CornersToTheLeftOfBottom(){let t=this.layerArrays.x[this.bottomNode],e=this.currentTopSite.point.x,i=this.currentBottomSite.point.x;for(let r of this.LeftFromTheNode(this.NodeLayer(this.bottomNode),t,2,e,i))for(let s of this.NodeCorners(r))s.y>this.currentBottomSite.point.y&&Me.PossibleCorner(e,i,s)&&(yield s)}*CornersToTheLeftOfTop(){let t=this.layerArrays.x[this.topNode],e=this.currentBottomSite.point.x,i=this.currentTopSite.point.x;for(let r of this.LeftFromTheNode(this.NodeLayer(this.topNode),t,0,e,i))for(let s of this.NodeCorners(r))s.y<this.currentTopSite.point.y&&Me.PossibleCorner(e,i,s)&&(yield s)}*CornersToTheRightOfBottom(){let t=this.layerArrays.x[this.bottomNode],e=this.currentBottomSite.point.x,i=this.currentTopSite.point.x;for(let r of this.RightFromTheNode(this.NodeLayer(this.bottomNode),t,2,e,i))for(let s of this.NodeCorners(r))s.y>this.currentBottomSite.point.y&&Me.PossibleCorner(e,i,s)&&(yield s)}*CornersToTheRightOfTop(){let t=this.layerArrays.x[this.topNode],e=this.currentTopSite.point.x,i=this.currentBottomSite.point.x;for(let r of this.RightFromTheNode(this.NodeLayer(this.topNode),t,0,e,i))for(let s of this.NodeCorners(r))s.y<this.currentTopSite.point.y&&Me.PossibleCorner(e,i,s)&&(yield s)}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(let e of this.layeredGraph.InEdges(t))return e;throw new Error}OutcomingEdge(t){for(let e of this.layeredGraph.OutEdges(t))return e;throw new Error}IsVirtualVertex(t){return t>=this.originalGraph.shallowNodeCount}*RightFromTheNode(t,e,i,r,s){let o=0,a=0;i===2&&(o=Number.MAX_VALUE),i===0&&(a=Number.MAX_VALUE);let l=t[e];for(let h=e+1;h<t.length;h++){let u=t[h];if(this.NodeUCanBeCrossedByNodeV(u,l))continue;let d=this.anchors[u];if(d.left>=s)break;d.right>r&&(d.topAnchor>a+x.distanceEpsilon?(a=d.topAnchor,yield u):d.bottomAnchor>o+x.distanceEpsilon&&(o=d.bottomAnchor,yield u))}}*LeftFromTheNode(t,e,i,r,s){let o=0,a=0;i===2&&(o=Number.MAX_VALUE),i===0&&(a=Number.MAX_VALUE);let l=t[e];for(let h=e-1;h>-1;h--){let u=t[h];if(this.NodeUCanBeCrossedByNodeV(u,l))continue;let d=this.anchors[u];if(d.right<=r)break;d.left<s&&(d.topAnchor>a+x.distanceEpsilon?(a=d.topAnchor,yield u):d.bottomAnchor>o+x.distanceEpsilon&&(o=d.bottomAnchor,yield u))}}},by=class me{constructor(t,e,i,r,s,o,a){this.thinRightNodes=new Array,this.thinWestNodes=new Array,this.database=a,this.edgePath=t,this.anchors=e,this.layerArrays=s,this.originalGraph=i,this.settings=r,this.layeredGraph=o,this.eastHierarchy=this.BuildEastHierarchy(),this.westHierarchy=this.BuildWestHierarchy()}BuildEastHierarchy(){let t=this.FindEastBoundaryAnchorCurves(),e=new Array;for(let i of t)e.push(i.pNodeOverICurve());return this.thinEastHierarchy=Ls.Calculate(this.thinRightNodes),Ls.Calculate(e)}BuildWestHierarchy(){let t=this.FindWestBoundaryAnchorCurves(),e=new Array;for(let i of t)e.push(i.pNodeOverICurve());return this.thinWestHierarchy=Ls.Calculate(this.thinWestNodes),Ls.Calculate(e)}FindEastBoundaryAnchorCurves(){let t=new Array,e=0;for(let i of this.edgePath){let r=null;for(let s of this.EastBoundaryNodesOfANode(i,Ha.GetNodeKind(e,this.edgePath))){let o=this.anchors[s];(r==null||r.origin.x>o.origin.x)&&(r=o),t.push(o.polygonalBoundary)}r!=null&&this.thinRightNodes.push(D.mkLinePXY(r.origin,this.originalGraph.right,r.y).pNodeOverICurve()),e++}return t}FindWestBoundaryAnchorCurves(){let t=[],e=0;for(let i of this.edgePath.nodes()){let r=-1;for(let s of this.LeftBoundaryNodesOfANode(i,Ha.GetNodeKind(e,this.edgePath)))(r===-1||this.layerArrays.x[s]>this.layerArrays.x[r])&&(r=s),t.push(this.anchors[s].polygonalBoundary);if(r!==-1){let s=this.anchors[r];this.thinWestNodes.push(D.mkLinePXY(s.origin,this.originalGraph.left,s.origin.y).pNodeOverICurve())}e++}return t}*FillRightTopAndBottomVerts(t,e,i){let r=0,s=0;i===2?r=Number.MAX_VALUE:i===0&&(s=Number.MAX_VALUE);let o=t[e];for(let a=e+1;a<t.length;a++){let l=t[a],h=this.anchors[l];h.topAnchor>s?this.NodeUCanBeCrossedByNodeV(l,o)||(s=h.topAnchor,h.bottomAnchor>r&&(r=h.bottomAnchor),yield l):h.bottomAnchor>r&&(this.NodeUCanBeCrossedByNodeV(l,o)||(r=h.bottomAnchor,h.topAnchor>s&&(s=h.topAnchor),yield l))}}*FillLeftTopAndBottomVerts(t,e,i){let r=0,s=0;i===0?s=Number.MAX_VALUE:i===2&&(r=Number.MAX_VALUE);let o=t[e];for(let a=e-1;a>=0;a--){let l=t[a],h=this.anchors[l];h.topAnchor>s+x.distanceEpsilon?this.NodeUCanBeCrossedByNodeV(l,o)||(s=h.topAnchor,r=Math.max(r,h.bottomAnchor),yield l):h.bottomAnchor>r+x.distanceEpsilon&&(this.NodeUCanBeCrossedByNodeV(l,o)||(s=Math.max(s,h.topAnchor),r=h.bottomAnchor,yield l))}}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{let i=this.OutcomingEdge(t),r=this.OutcomingEdge(e);if(this.Intersect(i,r))return!0;t=i.Target,e=r.Target}while(this.IsVirtualVertex(t)&&this.IsVirtualVertex(e));return t===e}IntersectAbove(t,e){do{let i=this.IncomingEdge(t),r=this.IncomingEdge(e);if(this.Intersect(i,r))return!0;t=i.Source,e=r.Source}while(this.IsVirtualVertex(t)&&this.IsVirtualVertex(e));return t===e}Intersect(t,e){let i=this.layerArrays.x[t.Source]-this.layerArrays.x[e.Source],r=this.layerArrays.x[t.Target]-this.layerArrays.x[e.Target];return i>0&&r<0||i<0&&r>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 Ot(this.headSite)}LineSegIntersectBound(t,e){let i=D.mkPP(t,e);return me.CurveIntersectsHierarchy(i,this.westHierarchy)||me.CurveIntersectsHierarchy(i,this.thinWestHierarchy)||me.CurveIntersectsHierarchy(i,this.eastHierarchy)||me.CurveIntersectsHierarchy(i,this.thinEastHierarchy)}SegIntersectWestBound(t,e){return me.SegIntersectsBound(t,e,this.westHierarchy)||me.SegIntersectsBound(t,e,this.thinWestHierarchy)}SegIntersectEastBound(t,e){return me.SegIntersectsBound(t,e,this.eastHierarchy)||me.SegIntersectsBound(t,e,this.thinEastHierarchy)}TryToRemoveInflectionCorner(t){if(!t.s.next||!t.s.prev||t.s.turn===1&&this.SegIntersectEastBound(t.s.prev,t.s.next)||t.s.turn===0&&this.SegIntersectWestBound(t.s.prev,t.s.next)){t.cut=!1,t.s=t.s.next;return}let 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 me.CurveIntersectsHierarchy(D.mkPP(t.point,e.point),i)}static CurveIntersectsHierarchy(t,e){if(e==null||!ie.intersect(t.pNodeOverICurve().parallelogram,e.parallelogram))return!1;if(e.node.hasOwnProperty("children")){let i=e.node;return me.CurveIntersectsHierarchy(t,i.children[0])||me.CurveIntersectsHierarchy(t,i.children[1])}return G.intersectionOne(t,e.seg,!1)!=null}static Flat(t){return g.getTriangleOrientation(t.prev.point,t.point,t.next.point)===2}Reverse(){let t=new me(this.edgePath,this.anchors,this.originalGraph,this.settings,this.layerArrays,this.layeredGraph,this.database),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 r=0;r<this.edgePath.count;r++)i=e.next,this.RefineBeetweenNeighborLayers(e,this.EdgePathNode(r),this.EdgePathNode(r+1)),e=i;this.TryToRemoveInflections(),t&&this.OptimizeShortPath()}RefineBeetweenNeighborLayers(t,e,i){Sy.Refine(e,i,t,this.anchors,this.layerArrays,this.layeredGraph,this.originalGraph,this.settings.LayerSeparation)}CreateInitialListOfSites(){let t=this.headSite=re.mkSiteP(this.EdgePathPoint(0));for(let e=1;e<=this.edgePath.count;e++)t=re.mkSiteSP(t,this.EdgePathPoint(e))}get TailSite(){let t=this.headSite;for(;t.next!=null;)t=t.next;return t}OptimizeForThreeSites(){let t=this.EdgePathNode(0),e=this.EdgePathNode(2),i=this.anchors[t],r=this.anchors[e];if(lt(i.x,r.x))return;let s={ax:i.x,bx:r.x,sign:0};if(!this.FindLegalPositions(i,r,s))return;let o=(i.y-r.y)/(i.bottom-r.top),a=.5*(s.ax+s.bx),l=s.sign*((s.ax-s.bx)*.5);s.ax=a+o*(l*s.sign),s.bx=a-o*(l*s.sign),this.headSite.point=new g(s.ax,i.y);let h=this.headSite.next,u=h.point.y;h.point=new g(this.MiddlePos(s.ax,s.bx,i,r,u),u),h.next.point=new g(s.bx,r.y);let d=this.anchors[this.EdgePathNode(1)];d.x=h.point.x}OptimizeForTwoSites(){let t=this.EdgePathNode(0),e=this.EdgePathNode(1),i=this.anchors[t],r=this.anchors[e];if(lt(i.x,r.x))return;let s={ax:i.x,bx:r.x,sign:0};if(!this.FindPositions(i,r,s))return;let o=(i.y-r.y)/(i.bottom-r.top),a=.5*(s.ax+s.bx),l=s.sign*((s.ax-s.bx)*.5);s.ax=a+o*(l*s.sign),s.bx=a-o*(l*s.sign),this.headSite.point=new g(s.ax,i.y),this.headSite.next.point=new g(s.bx,r.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 r,s;if(i.ax<i.bx?(i.sign=1,s=Math.max(i.ax,e.left),r=Math.min(t.right,i.bx)):(i.sign=-1,s=Math.max(t.left,i.bx),r=Math.min(e.right,i.ax)),s<=r)i.bx=.5*(s+r),i.ax=.5*(s+r);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){let i=D.mkPP(t.origin,e.origin);return t.x<e.x&&G.CurvesIntersect(i,D.mkPP(t.rightBottom,t.rightTop))||G.CurvesIntersect(i,D.mkPP(e.leftBottom,t.leftTop))||t.x>e.x&&G.CurvesIntersect(i,D.mkPP(t.leftBottom,t.leftTop))||G.CurvesIntersect(i,D.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,r,s,o){if(!lt(t,e)&&(t-e)*i>0)return!1;let a=this.anchors[o],l=this.MiddlePos(t,e,r,s,a.y);return this.MiddleAnchorLegal(l,o,a)?!this.LineSegIntersectBound(new g(t,r.bottom),new g(e,s.top)):!1}MiddleAnchorLegal(t,e,i){let r=this.NodeLayer(e),s=this.layerArrays.x[e],o=t-i.x;return!(s>0&&this.anchors[r[s-1]].right>o+i.left||s<r.length-1&&this.anchors[r[s+1]].left<o+i.right)}MiddlePos(t,e,i,r,s){let o=i.y-s,a=s-r.y;return(t*o+e*a)/(o+a)}TryToRemoveInflections(){if(this.TurningAlwaySameDirection())return;let t=!0;for(;t;){t=!1;for(let 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){let 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 G,e=this.headSite,i=G.findCorner(e);return i!==void 0?(this.createFilletCurve(t,{a:e,b:i.b,c:i.c}),t=this.ExtendCurveToEndpoints(t)):t.addSegment(D.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)me.Flat(e.next)&&(t=!0,e.next=e.next.next,e.next.prev=e);return t}ExtendCurveToEndpoints(t){let e=this.headSite.point;if(!g.closeDistEps(e,t.start)){let i=new G;i.addSegs([D.mkPP(e,t.start),t]),t=i}return e=this.TailSite.point,g.closeDistEps(e,t.end)||t.addSegment(D.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,r){let s=.5,o;do o=G.createBezierSeg(s,s,t,e,i),e.previouisBezierCoefficient=s,s/=2;while(this.BezierSegIntersectsBoundary(o));if(s*=2,s<.5){s=.5*(s+s*2);let a=G.createBezierSeg(s,s,t,e,i);this.BezierSegIntersectsBoundary(a)||(e.nextBezierCoefficient=s,e.previouisBezierCoefficient=s,o=a)}r.segs.length>0&&!g.closeDistEps(r.end,o.start)&&r.addSegment(D.mkPP(r.end,o.start)),r.addSegment(o)}BezierSegIntersectsBoundary(t){return g.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(ie.intersect(t.pNodeOverICurve().parallelogram,e.parallelogram))if(e.node.hasOwnProperty("children")){let i=e.node;return this.BezierSegIntersectsTree(t,i.children[0])||this.BezierSegIntersectsTree(t,i.children[1])}else return me.BezierSegIntersectsBoundary(t,e.seg);else return!1}static BezierSegIntersectsBoundary(t,e){for(let i of G.getAllIntersections(t,e,!1))if(e instanceof G){let r=e;if(G.realCutWithClosedCurve(i,r,!1))return!0}else return!0;return!1}},Ha=class Mn extends Nt{constructor(t,e,i,r,s,o){super(null),this.settings=t,this.OriginalGraph=e,this.Database=i,this.ProperLayeredGraph=s,this.LayerArrays=r,this.IntGraph=o}run(){this.createSplines()}createSplines(){this.createRegularSplines(),this.createSelfSplines(),this.IntGraph!=null&&this.RouteFlatEdges(),this.OriginalGraph.graph.parent==null&&this.RouteUnroutedEdges()}RouteUnroutedEdges(){let t=[];for(let i of this.OriginalGraph.deepEdges)i.curve||t.push(i);if(t.length==0)return;let e=(this.OriginalGraph.layoutSettings?this.OriginalGraph.layoutSettings:new Jn).commonSettings.edgeRoutingSettings;new Or(this.OriginalGraph,t,e.padding,e.polylinePadding,e.coneAngle,e.bundlingSettings,this.cancelToken).run(),fo.constructorGA(this.OriginalGraph,t).run()}RouteFlatEdges(){}createRegularSplines(){for(let t of this.Database.RegularMultiedges()){if(Cy(t))continue;let e=t.length,i=e===1&&this.MayOptimizeEdge(t[0]);for(let r=Math.floor(e/2);r<e;r++)this.createSplineForNonSelfEdge(t[r],i);for(let r=Math.floor(e/2)-1;r>=0;r--)this.createSplineForNonSelfEdge(t[r],i)}}MayOptimizeEdge(t){return!(this.ProperLayeredGraph.OutDegreeIsMoreThanOne(t.source)||this.ProperLayeredGraph.InDegreeIsMoreThanOne(t.target)||Yh(t.edge.source)||Yh(t.edge.target))}createSelfSplines(){for(let[t,e]of this.Database.Multiedges.keyValues()){let i=t;if(i.x===i.y){let r=this.Database.Anchors[i.x],s=r.leftAnchor;for(let o of e){let a=this.settings.NodeSeparation+(this.settings.MinNodeWidth+s),l=r.bottomAnchor/2,h=r.origin,u=h.add(new g(0,l)),d=h.add(new g(a,l)),c=h.add(new g(a,-l)),f=h.add(new g(0,-l)),m=re.mkSiteP(h),P=new Ot(m);m=re.mkSiteSP(m,u),m=re.mkSiteSP(m,d),m=re.mkSiteSP(m,c),m=re.mkSiteSP(m,f),re.mkSiteSP(m,h);let v=P.createCurve();if(o.curve=v,s=a,o.edge.label!=null){s+=o.edge.label.width;let b=v.value((v.parStart+v.parEnd)/2),C=new g(b.x+o.labelWidth/2,r.y),E=new g(o.edge.label.width/2,o.edge.label.height/2),w=it.mkPP(C.add(E),C.sub(E));o.edge.label.width=w.width,o.edge.label.height=w.height,o.edge.label.positionCenter(C)}ge.trimSplineAndCalculateArrowheadsII(o.edge,o.edge.source.boundaryCurve,o.edge.target.boundaryCurve,v,!1)}}}}createSplineForNonSelfEdge(t,e){t.LayerEdges!=null&&(this.drawSplineBySmothingThePolyline(t,e),t.IsVirtualEdge||(t.updateEdgeLabelPosition(this.Database.Anchors),ge.trimSplineAndCalculateArrowheadsII(t.edge,t.edge.source.boundaryCurve,t.edge.target.boundaryCurve,t.curve,!0)))}drawSplineBySmothingThePolyline(t,e){let i=new by(t,this.Database.Anchors,this.OriginalGraph,this.settings,this.LayerArrays,this.ProperLayeredGraph,this.Database).getSpline(e);t.reversed?t.curve=i.reverse():t.curve=i}static UpdateLabel(t,e){let i=null;e.labelIsToTheRightOfTheSpline?(t.label.positionCenter(new g(e.x+e.rightAnchor/2,e.y)),i=D.mkPP(t.label.boundingBox.leftTop,t.label.boundingBox.leftBottom)):e.labelIsToTheLeftOfTheSpline&&(t.label.positionCenter(new g(e.x-e.leftAnchor/2,e.y)),i=D.mkPP(t.label.boundingBox.rightTop,t.label.boundingBox.rightBottom));let r=Mn.GetSegmentInFrontOfLabel(t.curve,t.label.center.y);if(r!=null&&G.getAllIntersections(t.curve,G.polyFromBox(t.label.boundingBox),!1).length===0){let s={curveClosestPoint:void 0,labelSideClosest:void 0};if(Mn.FindClosestPoints(s,r,i))Mn.ShiftLabel(t,s);else{let o=r.closestParameter(i.start),a=r.closestParameter(i.end);r.value(o).sub(i.start).length<r.value(a).sub(i.end).length?(s.curveClosestPoint=r.value(o),s.labelSideClosest=i.start):(s.curveClosestPoint=r.value(a),s.labelSideClosest=i.end),Mn.ShiftLabel(t,s)}}}static ShiftLabel(t,e){let i=t.lineWidth/2,r=e.curveClosestPoint.sub(e.labelSideClosest),s=r.length;s>i&&t.label.positionCenter(t.label.center.add(r.div(s*(s-i))))}static FindClosestPoints(t,e,i){let r=G.minDistWithinIntervals(e,i,e.parStart,e.parEnd,i.parStart,i.parEnd,(e.parStart+e.parEnd)/2,(i.parStart+i.parEnd)/2);return r?(t.curveClosestPoint=r.aX,t.labelSideClosest=r.bX,!0):!1}static GetSegmentInFrontOfLabel(t,e){if(t instanceof G){let i=t;for(let r of i.segs)if((r.start.y-e)*(r.end.y-e)<=0)return r}return null}static GetNodeKind(t,e){return t===0?0:t<e.count?1:2}};function Cy(n){if(n.length<4)return!1;for(let t of n)if(t.edge.label)return!1;return!0}function Yh(n){return n.node.selfEdges.size>0}var Ud=class extends Nt{constructor(n,t,e){if(super(e),this.LayersAreDoubled=!1,n==null)return;this.originalGraph=n,this.sugiyamaSettings=t;let i=Array.from(n.shallowNodes);this.nodeIdToIndex=new Map;let r=0;for(let o of i)this.nodeIdToIndex.set(o.id,r++);let s=[];for(let o of this.originalGraph.shallowEdges){let a=this.nodeIdToIndex.get(o.source.id);if(a==null)continue;let l=this.nodeIdToIndex.get(o.target.id);if(l==null)continue;let h=new Bi(a,l,o);s.push(h)}this.IntGraph=new kn(s,n.shallowNodeCount),this.IntGraph.nodes=i,this.database=new ey(i.length);for(let o of this.IntGraph.edges)this.database.registerOriginalEdgeInMultiedges(o);this.cycleRemoval()}get extremeAspectRatio(){let n=this.originalGraph.boundingBox,t=n.width/n.height;return t<1/50||t>50}get verticalConstraints(){return this.sugiyamaSettings.verticalConstraints}get HorizontalConstraints(){return this.sugiyamaSettings.horizontalConstraints}run(){if(this.originalGraph.shallowNodeCount===0){this.originalGraph.boundingBox=it.mkEmpty();return}Dy(this.originalGraph,this.sugiyamaSettings.transform),this.engineLayerArrays=this.calculateLayers(),this.sugiyamaSettings.edgeRoutingSettings.EdgeRoutingMode===3&&this.runPostLayering(),My(this.originalGraph,this.sugiyamaSettings.transform)}runPostLayering(){let n=this.sugiyamaSettings.commonSettings.edgeRoutingSettings,t=this.constrainedOrdering!=null?0:n.EdgeRoutingMode;this.extremeAspectRatio?Pd(this.originalGraph,Array.from(this.originalGraph.deepEdges),this.cancelToken):t===3?this.calculateEdgeSplines():wd(this.originalGraph,Array.from(this.originalGraph.deepEdges),this.cancelToken)}SetLabels(){throw new Error("not implementedt")}cycleRemoval(){let n=this.sugiyamaSettings.verticalConstraints,t=n.isEmpty?zn.getFeedbackSet(this.IntGraph):n.getFeedbackSetExternal(this.IntGraph,this.nodeIdToIndex);this.database.addFeedbackSet(t)}calculateLayers(){this.CreateGluedDagSkeletonForLayering();let n=this.CalculateLayerArrays();return this.UpdateNodePositionData(),n}UpdateNodePositionData(){for(let n=0;n<this.IntGraph.nodeCount&&n<this.database.Anchors.length;n++)this.IntGraph.nodes[n].center=this.database.Anchors[n].origin;if(this.sugiyamaSettings.GridSizeByX>0)for(let n=0;n<this.originalGraph.shallowNodeCount;n++)this.SnapLeftSidesOfTheNodeToGrid(n,this.sugiyamaSettings.GridSizeByX)}SnapLeftSidesOfTheNodeToGrid(n,t){let e=this.IntGraph.nodes[n],i=this.database.Anchors[n];i.leftAnchor-=t/2,i.rightAnchor-=t/2;let r=e.boundingBox.left,s=Math.floor(r/t),o=r-s*t;Math.abs(o)<.001||(Math.abs(o)<=t/2?e.center=e.center.add(new g(-o,0)):e.center=e.center.add(new g(t-o,0)),i.x=e.center.x)}GetCurrentHeight(){let n=new Zi;for(let t of this.NodeAnchors())n.AddValue(t.top),n.AddValue(t.bottom);return n.length}*NodeAnchors(){let n=Math.min(this.IntGraph.nodeCount,this.anchors.length);for(let t=0;t<n;t++)yield this.anchors[t]}GetCurrentWidth(){let n=new Zi;for(let t of this.NodeAnchors())n.AddValue(t.left),n.AddValue(t.right);return n.length}ExtendLayeringToUngluedSameLayerVertices(n){let t=this.verticalConstraints;for(let e=0;e<n.length;e++)n[e]=n[t.nodeToRepr(e)];return n}calculateEdgeSplines(){new Ha(this.sugiyamaSettings,this.originalGraph,this.database,this.engineLayerArrays,this.properLayeredGraph,this.IntGraph).run()}YLayeringAndOrdering(n){let t=n.GetLayers();iy.Balance(this.gluedDagSkeletonForLayering,t,this.GetNodeCountsOfGluedDag(),null),t=this.ExtendLayeringToUngluedSameLayerVertices(t);let e=new rn(t);if(this.HorizontalConstraints==null||this.HorizontalConstraints.IsEmpty)return e=this.YLayeringAndOrderingWithoutHorizontalConstraints(e),e;throw new Error("not implemented")}CreateProperLayeredGraph(n){let t=n.length,e=0;for(let r of this.database.SkeletonEdges()){let s=wy(n,r);s>0&&(r.LayerEdges=new Array(s));let o=0;if(s>1){let a=t+e++,l=new Ki(r.source,a,r.CrossingWeight,r.weight);r.LayerEdges[o++]=l;for(let h=0;h<s-2;h++)a++,e++,l=new Ki(a-1,a,r.CrossingWeight,r.weight),r.LayerEdges[o++]=l;l=new Ki(a,r.target,r.CrossingWeight,r.weight),r.LayerEdges[o]=l}else if(s===1){let a=new Ki(r.source,r.target,r.CrossingWeight,r.weight);r.LayerEdges[o]=a}}let i=new Array(this.originalGraph.shallowNodeCount+e).fill(0);for(let r of this.database.SkeletonEdges())if(r.LayerEdges!=null){let s=n[r.source];i[r.source]=s--;for(let o of r.LayerEdges)i[o.Target]=s--}else i[r.source]=n[r.source],i[r.target]=n[r.target];return this.properLayeredGraph=new ul(new kn(Array.from(this.database.SkeletonEdges()),n.length)),this.properLayeredGraph.BaseGraph.nodes=this.IntGraph.nodes,new rn(i)}YLayeringAndOrderingWithoutHorizontalConstraints(n){let t=this.CreateProperLayeredGraph(n.y);return hy.OrderLayers(this.properLayeredGraph,t,this.originalGraph.shallowNodeCount,this.sugiyamaSettings,this.cancelToken),uy.UpdateLayerArrays1(this.properLayeredGraph,t),t}CalculateYLayers(){let n=this.YLayeringAndOrdering(new my(this.gluedDagSkeletonForLayering,this.cancelToken));return this.constrainedOrdering!=null?n:this.InsertLayersIfNeeded(n)}InsertLayersIfNeeded(n){this.InsertVirtualEdgesIfNeeded(n);let t=this.AnalyzeNeedToInsertLayersAndHasMultiedges(n);if(t.needToInsertLayers){let e=Md.InsertLayers(this.properLayeredGraph,n,this.database,this.IntGraph);this.properLayeredGraph=e.layeredGraph,n=e.la,this.LayersAreDoubled=!0}else if(t.multipleEdges){let e=ka.InsertPaths(this.properLayeredGraph,n,this.database,this.IntGraph);this.properLayeredGraph=e.layeredGraph,n=e.la}return this.RecreateIntGraphFromDataBase(),n}RecreateIntGraphFromDataBase(){let n=new Array;for(let t of this.database.Multiedges.values())n=n.concat(t);this.IntGraph.SetEdges(n,this.IntGraph.nodeCount)}InsertVirtualEdgesIfNeeded(n){if(this.constrainedOrdering==null){for(let[t,e]of this.database.Multiedges.keyValues())if(e.length%2===0&&n.y[t.x]-1===n.y[t.y]){let i=new Fe(null),r=new Bi(t.x,t.y,i);r.IsVirtualEdge=!0,e.splice(e.length/2,0,r),this.IntGraph.addEdge(r)}}}AnalyzeNeedToInsertLayersAndHasMultiedges(n){let t=!1,e=!1;for(let i of this.IntGraph.edges)if(i.hasLabel&&n.y[i.source]!==n.y[i.target]){t=!0;break}if(t===!1&&this.constrainedOrdering==null){for(let[i,r]of this.database.Multiedges.keyValues())if(r.length>1&&(e=!0,n.y[i.x]-n.y[i.y]===1)){t=!0;break}}return{needToInsertLayers:t,multipleEdges:e}}UseBrandesXCalculations(n){return n.x.length>=this.sugiyamaSettings.BrandesThreshold}CalculateAnchorsAndYPositions(n){this.anchors=xy(this.database,this.properLayeredGraph,this.originalGraph,this.IntGraph,this.sugiyamaSettings),Ey(n,500,this.originalGraph,this.database,this.IntGraph,this.sugiyamaSettings,this.LayersAreDoubled)}OptimizeEdgeLabelsLocations(){for(let n=0;n<this.anchors.length;n++){let t=this.anchors[n];if(t.labelIsToTheRightOfTheSpline){let e=this.GetSuccessorAndPredecessor(n);if(!Ly(t,e.predecessor,e.successor)){let i=e.predecessor.origin.sub(t.origin).length+e.successor.origin.sub(t.origin).length,r=t.right-t.leftAnchor,s=new g(r,t.y);e.predecessor.origin.sub(s).length+e.successor.origin.sub(s).length<i&&jd(t)}}}}GetSuccessorAndPredecessor(n){let t;for(let i of this.properLayeredGraph.InEdges(n))t=i.Source;let e;for(let i of this.properLayeredGraph.OutEdges(n))e=i.Target;return{predecessor:this.anchors[t],successor:this.anchors[e]}}CalculateLayerArrays(){let n=this.CalculateYLayers();return this.constrainedOrdering==null?(this.CalculateAnchorsAndYPositions(n),this.UseBrandesXCalculations(n)?this.CalculateXPositionsByBrandes(n):this.CalculateXLayersByGansnerNorth(n)):this.anchors=this.database.Anchors,this.OptimizeEdgeLabelsLocations(),this.engineLayerArrays=n,this.StraightensShortEdges(),this.CalculateOriginalGraphBox(),n}StretchToDesiredAspectRatio(n,t){n>t?this.StretchInYDirection(n/t):n<t&&this.StretchInXDirection(t/n)}StretchInYDirection(n){let t=(this.originalGraph.boundingBox.top+this.originalGraph.boundingBox.bottom)/2;for(let i of this.database.Anchors)i.bottomAnchor=i.bottomAnchor*n,i.topAnchor=i.topAnchor*n,i.y=t+n*(i.y-t);let e=this.originalGraph.height*n;this.originalGraph.boundingBox=new it({left:this.originalGraph.boundingBox.left,top:t+e/2,right:this.originalGraph.boundingBox.right,bottom:t-e/2})}StretchInXDirection(n){let t=(this.originalGraph.boundingBox.left+this.originalGraph.boundingBox.right)/2;for(let i of this.database.Anchors)i.leftAnchor=i.leftAnchor*n,i.rightAnchor=i.rightAnchor*n,i.x=t+n*(i.x-t);let e=this.originalGraph.width*n;this.originalGraph.boundingBox=new it({left:t-e/2,top:this.originalGraph.boundingBox.top,right:t+e/2,bottom:this.originalGraph.boundingBox.bottom})}CalculateOriginalGraphBox(){if(this.anchors.length===0)return;let n=new it({left:this.anchors[0].left,top:this.anchors[0].top,right:this.anchors[0].right,bottom:this.anchors[0].bottom});for(let t=1;t<this.anchors.length;t++){let e=this.anchors[t];n.add(e.leftTop),n.add(e.rightBottom)}this.originalGraph.labelSize&&this.originalGraph.addLabelToGraphBB(n),n.padEverywhere(this.originalGraph.margins),this.originalGraph.boundingBox=n}StraightensShortEdges(){if(!(this.anchors.length<20))for(;this.StraightenEdgePaths(););}StraightenEdgePaths(){let n=!1;for(let t of this.database.AllIntEdges())t.LayerSpan===2&&(n=this.ShiftVertexWithNeighbors(t.LayerEdges[0].Source,t.LayerEdges[0].Target,t.LayerEdges[1].Target)||n);return n}ShiftVertexWithNeighbors(n,t,e){let i=this.database.Anchors[n],r=this.database.Anchors[e],s=this.database.Anchors[t],o=(s.y-i.y)*((r.x-i.x)/(r.y-i.y))+i.x,a=1e-4;return o>s.x+a?this.TryShiftToTheRight(o,t):o<s.x-a?this.TryShiftToTheLeft(o,t):!1}TryShiftToTheLeft(n,t){let e=this.engineLayerArrays.Layers[this.engineLayerArrays.y[t]],i=this.engineLayerArrays.x[t];if(i>0){let r=this.database.Anchors[e[i-1]],s=Math.max(r.right+(this.sugiyamaSettings.NodeSeparation+this.database.Anchors[t].leftAnchor),n);return s<this.database.Anchors[t].x-1?(this.database.Anchors[t].x=s,!0):!1}return this.database.Anchors[t].x=n,!0}TryShiftToTheRight(n,t){let e=this.engineLayerArrays.Layers[this.engineLayerArrays.y[t]],i=this.engineLayerArrays.x[t];if(i<e.length-1){let r=this.database.Anchors[e[i+1]],s=Math.min(r.left-(this.sugiyamaSettings.NodeSeparation-this.database.Anchors[t].rightAnchor),n);return s>this.database.Anchors[t].x+1?(this.database.Anchors[t].x=s,!0):!1}return this.database.Anchors[t].x=n,!0}CalculateXLayersByGansnerNorth(n){this.xLayoutGraph=this.CreateXLayoutGraph(n),this.CalculateXLayersByGansnerNorthOnProperLayeredGraph()}CalculateXLayersByGansnerNorthOnProperLayeredGraph(){let n=new Wd(this.xLayoutGraph,null).GetLayers();for(let t=0;t<this.database.Anchors.length;t++)this.anchors[t].x=n[t]}CreateXLayoutGraph(n){let t=this.properLayeredGraph.NodeCount,e=new Array;for(let r of this.properLayeredGraph.Edges){let s=new Bi(t,r.Source,null),o=new Bi(t,r.Target,null);o.weight=r.Weight,s.weight=r.Weight,s.separation=0,o.separation=0,t++,e.push(s),e.push(o)}for(let r of n.Layers)for(let s=r.length-1;s>0;s--){let o=r[s],a=r[s-1],l=new Bi(o,a,null),h=this.database.Anchors[o],u=this.database.Anchors[a],d=h.leftAnchor+(u.rightAnchor+this.sugiyamaSettings.NodeSeparation);l.separation=Math.ceil(d+.5),e.push(l)}let i=new yy(this.IntGraph,this.properLayeredGraph,n,e,t);return i.SetEdgeWeights(),i}CalculateXPositionsByBrandes(n){Py.CalculateXCoordinates(n,this.properLayeredGraph,this.originalGraph.shallowNodeCount,this.database.Anchors,this.sugiyamaSettings.NodeSeparation)}GluedDagSkeletonEdges(){let n=new Jr;for(let[e,i]of this.database.Multiedges.keyValues()){if(e.isDiagonal())continue;let r=this.verticalConstraints.gluedIntEdge(i[0]);r.source!==r.target&&n.set(r.source,r.target,r)}let t=Array.from(this.verticalConstraints.gluedUpDownIntConstraints.values()).map(e=>Ay(e,null));for(let e of t)n.set(e.source,e.target,e);return Array.from(n.values())}static CalcAnchorsForOriginalNode(n,t,e,i,r){let s={leftAnchor:0,rightAnchor:0,topAnchor:0,bottomAnchor:0};if(t.nodes!=null){let l=t.nodes[n];Fy(s,l,r)}Ny(n,s,i,r);let o=r.MinNodeWidth/2;s.leftAnchor<o&&(s.leftAnchor=o),s.rightAnchor<o&&(s.rightAnchor=o);let a=r.MinNodeHeight/2;s.topAnchor<a&&(s.topAnchor=a),s.bottomAnchor<a&&(s.bottomAnchor=a),e[n]=zd.mkAnchor(s.leftAnchor,s.rightAnchor,s.topAnchor,s.bottomAnchor,t.nodes[n],r.LabelCornersPreserveCoefficient),e[n].padding=1}CreateGluedDagSkeletonForLayering(){this.gluedDagSkeletonForLayering=new kn(this.GluedDagSkeletonEdges(),this.originalGraph.shallowNodeCount),this.SetGluedEdgesWeights()}SetGluedEdgesWeights(){let n=new Jr;for(let t of this.gluedDagSkeletonForLayering.edges)n.set(t.source,t.target,t);for(let[t,e]of this.database.Multiedges.keyValues())if(t.x!==t.y){let i=this.verticalConstraints.gluedIntPair(t);if(i.x===i.y)continue;let r=n.get(i.x,i.y);for(let s of e)r.weight+=s.weight}}GetNodeCountsOfGluedDag(){return this.verticalConstraints.isEmpty?new Array(this.IntGraph.nodeCount).fill(1):this.verticalConstraints.getGluedNodeCounts()}};function Jh(n,t){if(t===0)return 0;let e=Math.floor(n/t),i=n-e*t;return Math.abs(i)<1e-4?0:t-i}function vy(n,t){for(let e of n)if(e<t)return!0;return!1}function xy(n,t,e,i,r){let s=n.Anchors=new Array(t.NodeCount);for(let o=0;o<s.length;o++)s[o]=new zd(r.LabelCornersPreserveCoefficient);for(let o=0;o<e.shallowNodeCount;o++)Ud.CalcAnchorsForOriginalNode(o,i,s,n,r);for(let o of n.AllIntEdges())if(o.LayerEdges!=null){for(let a of o.LayerEdges){let l=a.Target;if(l!==o.target){let h=s[l];n.MultipleMiddles.has(l)?(h.leftAnchor=h.rightAnchor=ua()*4,h.topAnchor=h.bottomAnchor=Zh(r)/2):(h.leftAnchor=h.rightAnchor=ua()/2,h.topAnchor=h.bottomAnchor=Zh(r)/2)}}if(o.hasLabel){let a=o.LayerEdges[o.LayerEdges.length/2].Source,l=s[a],h=o.labelWidth,u=o.labelHeight;l.rightAnchor=h,l.leftAnchor=ua()*8,l.topAnchor<u/2&&(l.topAnchor=l.bottomAnchor=u/2),l.labelIsToTheRightOfTheSpline=!0}}return s}function ua(){return 1}function Zh(n){return n.MinNodeHeight*1.5/8}function Kh(n,t,e,i,r,s){let o=0;if(e>0){let a=By(t.Layers[e-1],t.y,i);if(a.length){let l=r.LayerSeparation/3,h=s;o=Math.max(...a.map(u=>Ry(u,h,l,n)))}}return o}function Ey(n,t,e,i,r,s,o){let a=i.Anchors,l=e.margins.top+t,h=0;for(let u of n.Layers){let d=0,c=0;for(let b of u){let C=a[b];C.bottomAnchor>d&&(d=C.bottomAnchor),C.topAnchor>c&&(c=C.topAnchor)}Iy(u,d,c,e.shallowNodeCount,i.Anchors);let f=Kh(i,n,h,r,s,l),m=l+d+f,P=m+c;if(Ty(s)){P+=Jh(P,s.GridSizeByY);for(let b of u)a[b].top=P}else if(Oy(s)){let b=m-d;b+=Jh(b,b);for(let C of u)a[C].bottom=b,P=Math.max(a[C].top,P)}else for(let b of u)a[b].y=m;let v=s.ActualLayerSeparation(o);l=P+v,h++}Kh(i,n,h,r,s,l)}function Ay(n,t){let e=new Bi(n.x,n.y,t);return e.weight=0,e.separation=1,e}function wy(n,t){return n[t.source]-n[t.target]}function Iy(n,t,e,i,r){if(vy(n,i)){for(let s of n)if(s>=i){let o=r[s];o.bottomAnchor=t,o.topAnchor=e}}}function Ty(n){return n.SnapToGridByY===1}function Oy(n){return n.SnapToGridByY===2}function Ly(n,t,e){if(n.labelIsToTheRightOfTheSpline){if(g.getTriangleOrientation(t.origin,n.origin,e.origin)===0)return!0;let i=n.leftAnchor,r=n.rightAnchor,s=n.x;return jd(n),g.getTriangleOrientation(t.origin,n.origin,e.origin)===1?!0:(n.x=s,n.leftAnchor=i,n.rightAnchor=r,n.labelIsToTheRightOfTheSpline=!0,n.labelIsToTheLeftOfTheSpline=!1,!1)}return!1}function jd(n){let t=n.right,e=n.leftAnchor;n.leftAnchor=n.rightAnchor,n.rightAnchor=e,n.x=t-n.rightAnchor,n.labelIsToTheLeftOfTheSpline=!0,n.labelIsToTheRightOfTheSpline=!1}function By(n,t,e){let i=new Fi;for(let r of n)if(!(r>=e.nodeCount))for(let s of e.outEdges[r])t[s.source]===t[s.target]&&i.addNN(s.source,s.target);return Array.from(i.values())}function Ry(n,t,e,i){let r=0,s=i.GetMultiedgeI(n);for(let o of s){r+=e;let a=o.edge.label;a!=null&&(a.positionCenter(new g(a.center.x,t+r+a.height/2)),r+=a.height)}return r}function Fy(n,t,e){n.rightAnchor=n.leftAnchor=(t.width+e.GridSizeByX)/2,n.topAnchor=n.bottomAnchor=t.height/2}function Ny(n,t,e,i){let r=Gy(e,n,t,i);t.rightAnchor+=r}function Gy(n,t,e,i){let r=0,s=n.GetMultiedge(t,t);if(s.length>0){for(let o of s)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));r+=(i.NodeSeparation+i.MinNodeWidth)*s.length}return r}function Dy(n,t){if(t.isIdentity())return;let e=t.inverse();for(let i of n.shallowNodes)i.transform(e);for(let i of n.shallowEdges)if(i.label!=null){let r=it.mkPP(e.multiplyPoint(new g(0,0)),e.multiplyPoint(new g(i.label.width,i.label.height)));i.label.width=r.width,i.label.height=r.height}}function My(n,t){if(!t.isIdentity()){for(let e of n.shallowNodes)e.transform(t);for(let e of n.shallowEdges)if(e.label!=null){let i=it.mkPP(t.multiplyPoint(new g(0,0)),t.multiplyPoint(new g(e.label.width,e.label.height)));e.label.width=i.width,e.label.height=i.height}Vy(n,t),n.graph.parent==null&&(n.boundingBox=null)}}function Vy(n,t){for(let e of n.shallowEdges)e.label&&e.label.transform(t),ky(t,e)}function ky(n,t){if(t.curve!=null){t.curve=t.curve.transform(n);let e=t;e.sourceArrowhead!=null&&(e.sourceArrowhead.tipPosition=n.multiplyPoint(e.sourceArrowhead.tipPosition)),e.targetArrowhead!=null&&(e.targetArrowhead.tipPosition=n.multiplyPoint(e.targetArrowhead.tipPosition)),$y(t,n)}}function $y(n,t){if(n.smoothedPolyline!=null)for(let e=n.smoothedPolyline.headSite;e!=null;e=e.next)e.point=t.multiplyPoint(e.point)}var dl=class{constructor(){this.Removed=!1}},Yr=class extends dl{get Start(){return this.start}get End(){return this.EndVertex.point}constructor(n,t,e){super(),this.start=n,this.EndVertex=t,this.ConeSide=e}get Direction(){return this.End.sub(this.Start)}toString(){return"BrokenConeSide: "+(this.Start+(","+this.End))}},da=class{get Removed(){return this.removed}set Removed(n){this.removed=n}constructor(n,t){this.apex=n,this.coneSweeper=t}get Apex(){return this.apex}set Apex(n){this.apex=n}get RightSideDirection(){return this.coneSweeper.ConeRightSideDirection}get LeftSideDirection(){return this.coneSweeper.ConeLeftSideDirection}get RightSide(){return this.rightSide}set RightSide(n){this.rightSide=n,this.rightSide.Cone=this}get LeftSide(){return this.leftSide}set LeftSide(n){this.leftSide=n,this.leftSide.Cone=this}},_h=class extends Gi{get ConeToClose(){return this.coneToClose}get Site(){return this.site}constructor(n,t){super(),this.site=n,this.coneToClose=t}toString(){return"ConeClosureEvent "+this.site}},pi=class extends dl{constructor(n){super(),this.Cone=n}get Start(){return this.Cone.Apex}get Direction(){return this.Cone.LeftSideDirection}toString(){return"ConeLeftSide "+this.Start+(" "+this.Direction)}},Wi=class extends dl{constructor(n){super(),this.Cone=n}get Start(){return this.Cone.Apex}get Direction(){return this.Cone.RightSideDirection}toString(){return"ConeRightSide "+this.Start+" "+this.Direction}},Hy=class Wa{SetOperand(t){this.x=this.IntersectionOfSegmentAndSweepLine(t)}constructor(t){this.coneSweeper=t}Compare(t,e){let i=t instanceof Yr,r=e instanceof Yr;return i?r?this.CompareBrokenSides(t,e):this.CompareObstacleSideAndConeSide(e):r?this.CompareConeSideAndObstacleSide(t,e):Wa.CompareNotIntersectingSegs(t,e)}static CompareNotIntersectingSegs(t,e){switch(g.getTriangleOrientation(t.Start,e.Start,e.Start.add(e.Direction))){case 1:return-1;case 0:return 1;default:return 0}}CompareObstacleSideAndConeSide(t){let e=g.getTriangleOrientation(this.x,t.Start,t.Start.add(t.Direction));return e===1?-1:e===0?1:t instanceof pi?-1:1}CompareConeSideAndObstacleSide(t,e){let i=g.getTriangleOrientation(this.x,e.start,e.End);return i===1?-1:i===0||t instanceof pi?1:-1}IntersectionOfSegmentAndSweepLine(t){let 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?Wa.CompareNotIntersectingSegs(t.ConeSide,e.ConeSide):g.getTriangleOrientation(this.x,e.start,e.EndVertex.point)===1?-1:1}},Tn=class extends Gi{get EndVertex(){return this.endVertex}constructor(n,t,e){super(),this.coneLeftSide=n,this.intersectionPoint=t,this.endVertex=e}get Site(){return this.intersectionPoint}toString(){return"LeftIntersectionEvent "+this.intersectionPoint}},tu=class extends Gi{get EndVertex(){return this.endVertex}set EndVertex(n){this.endVertex=n}constructor(n,t,e){super(),this.coneRightSide=n,this.intersectionPoint=t,this.endVertex=e}get Site(){return this.intersectionPoint}toString(){return"RightIntersectionEvent "+this.intersectionPoint}},Qd=class Ce extends Nu{constructor(t,e,i,r,s,o,a){super(t,e),this.visibilityGraph=s,this.ConeRightSideDirection=i,this.ConeLeftSideDirection=r,this.coneSideComparer=new Hy(this),this.leftConeSides=new Re((l,h)=>this.coneSideComparer.Compare(l,h)),this.rightConeSides=new Re((l,h)=>this.coneSideComparer.Compare(l,h)),this.Ports=o,this.BorderPolyline=a,this.PortEdgesCreator=(l,h)=>new rr(l,h,0)}static Sweep(t,e,i,r,s,o){new Ce(t,e,e.rotate(-i/2),e.rotate(i/2),r,s,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(let 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{let 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){let i=t.nextOnPolyline,r=Ce.FindInsidePoint(t.point,i.point,e);return g.closeDistEps(r,t.point)?(this.AddEdgeAndRemoveCone(e,t.point),this.AddEdgesAndRemoveRemainingConesByPoint(t.point)):g.closeDistEps(r,i.point)?(this.AddEdgeAndRemoveCone(e,i.point),this.AddEdgesAndRemoveRemainingConesByPoint(i.point),t=i):(t=Ce.InsertPointIntoPolylineAfter(this.BorderPolyline,t,r),this.AddEdgeAndRemoveCone(e,t.point),this.AddEdgesAndRemoveRemainingConesByPoint(t.point)),t}static FindInsidePoint(t,e,i){return Ce.FindInsidePointBool(t,e,i.Apex,i.Apex.add(i.LeftSideDirection),i.Apex.add(i.RightSideDirection))}static FindInsidePointBool(t,e,i,r,s){if(g.closeDistEps(t,e)||g.PointIsInsideCone(t,i,r,s))return t;if(g.PointIsInsideCone(e,i,r,s))return e;let o=g.middle(t,e);return g.pointToTheLeftOfLine(o,i,r)?Ce.FindInsidePointBool(o,e,i,r,s):Ce.FindInsidePointBool(t,o,i,r,s)}AddEdgesAndRemoveRemainingConesByPoint(t){let e=new Array;for(let i of this.leftConeSides)if(g.PointToTheRightOfLineOrOnLine(t,i.Start,i.Start.add(i.Direction)))e.push(i.Cone);else break;for(let i of e)this.AddEdgeAndRemoveCone(i,t)}FindPolylineSideIntersectingConeRightSide(t,e){let i=t,r=e.Apex,s=e.Apex.add(this.ConeRightSideDirection),o=Ce.GetSign(t,r,s);for(;;){let a=t.nextOnPolyline,l=Ce.GetSign(a,r,s);if(l-o>0)return t;if(t=a,o=l,t===i)throw new Error("cannod decide if the polyline intersects the cone!")}}static GetSign(t,e,i){let r=g.signedDoubledTriangleArea(e,i,t.point);return r<0?1:r>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 zt);let i=this.portEdgesGraph.FindVertex(t.Apex),r=i!=null?Array.from(i.InEdges).concat(Array.from(i.OutEdges.allNodes())):null;if(r)for(let s of r){let o=(s.Target===i?s.Source:s.Target).point;zt.RemoveEdge(s),this.portEdgesGraph.AddEdgePP(o,e)}this.portEdgesGraph.AddEdgePP(t.Apex,e)}static InsertPointIntoPolylineAfter(t,e,i){let r;return e.next!=null?(r=Ni.mkFromPoint(i),r.prev=e,r.next=e.next,e.next.prev=r,e.next=r):(r=Ni.mkFromPoint(i),r.prev=e,e.next=r,t.endPoint=r),r.polyline=t,t.setInitIsRequired(),r}ProcessEvent(t){t instanceof nn?this.ProcessVertexEvent(t):t instanceof tu?this.ProcessRightIntersectionEvent(t):t instanceof Tn?this.ProcessLeftIntersectionEvent(t):(t instanceof _h?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))<x.distanceEpsilon)this.RemoveCone(t.coneLeftSide.Cone);else{this.RemoveSegFromLeftTree(t.coneLeftSide),this.Z=this.GetZP(t.Site);let e=new Yr(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 Wi){let e=t.Cone.RightSide;g.getTriangleOrientation(e.Start,e.Start.add(e.Direction),t.EndVertex.point)==0&&this.CreateConeClosureEvent(t,e)}}CreateConeClosureEvent(t,e){let i=g.RayIntersectsRayInteriors(t.start,t.Direction,e.Start,e.Direction);if(i){let r=new _h(i,t.Cone);this.EnqueueEvent(r)}}ProcessRightIntersectionEvent(t){if(t.coneRightSide.Removed)this.Z=this.GetZP(t.Site);else{this.RemoveSegFromRightTree(t.coneRightSide),this.Z=this.GetZP(t.Site);let e=new Yr(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 pi){let e=t.Cone.LeftSide;g.getTriangleOrientation(e.Start,e.Start.add(e.Direction),t.EndVertex.point)==1&&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 r=i.findFirst(o=>g.getTriangleOrientation(o.Start,o.Start.add(o.Direction),t)===1);if(r==null||!g.IntervalIntersectsRay(t,e,r.item.Start,r.item.Direction))return;let s=new Array;do s.push(r.item.Cone),r=i.next(r);while(r!=null&&g.IntervalIntersectsRay(t,e,r.item.Start,r.item.Direction)!==void 0);for(let o of s)this.RemoveCone(o)}ProcessVertexEvent(t){this.Z=this.GetZS(t),this.GoOverConesSeeingVertexEvent(t),this.AddConeAndEnqueueEvents(t)}static Diamond(t){return ce.mkDiamond(2,2,t)}AddConeAndEnqueueEvents(t){if(t instanceof Cr){let e=t.Vertex.nextOnPolyline;this.CloseConesAddConeAtLeftVertex(t,e)}else if(t instanceof vr){let e=t.Vertex.prevOnPolyline;this.CloseConesAddConeAtRightVertex(t,e)}else this.CloseConesAddConeAtLeftVertex(t,t.Vertex.nextOnPolyline),this.CloseConesAddConeAtRightVertex(t,t.Vertex.prevOnPolyline)}CloseConesAddConeAtRightVertex(t,e){let i=t.Vertex.nextOnPolyline.point;this.directionPerp.dot(t.Site.sub(i))>x.distanceEpsilon&&this.RemoveConesClosedBySegment(i,t.Vertex.point),this.directionPerp.dot(e.point.sub(t.Site))>x.distanceEpsilon&&this.RemoveConesClosedBySegment(t.Site,e.point);let r=t.Site,s=r.add(this.ConeLeftSideDirection),o=r.add(this.ConeRightSideDirection),a=e.point;this.GetZP(r.sub(i))>x.distanceEpsilon&&this.RemoveRightSide(new Xr(t.Vertex.nextOnPolyline)),this.GetZP(r.sub(e.point))>x.distanceEpsilon&&this.RemoveLeftSide(new Qr(e)),this.GetZP(a)+x.distanceEpsilon<this.GetZS(t)&&this.CreateConeOnVertex(t),g.PointToTheRightOfLineOrOnLine(a,r,s)?g.PointToTheLeftOfLineOrOnLine(a,r,o)?this.CaseToTheLeftOfLineOrOnLineConeRp(t,e):(this.GetZP(a.sub(r))>x.distanceEpsilon&&(this.LookForIntersectionOfObstacleSideAndLeftConeSide(t.Site,e),this.InsertRightSide(new Xr(t.Vertex))),this.EnqueueRightVertexEvent(new vr(e))):(this.CreateConeOnVertex(t),g.PointToTheLeftOfLineOrOnLine(a.add(this.DirectionPerp),a,r)&&this.EnqueueRightVertexEvent(new vr(e)))}CaseToTheLeftOfLineOrOnLineConeRp(t,e){this.EnqueueRightVertexEvent(new vr(e));let i=new da(t.Vertex.point,this),r=new Yr(i.Apex,e,new pi(i));i.LeftSide=r,i.RightSide=new Wi(i);let s=this.InsertToTree(this.rightConeSides,i.RightSide);this.LookForIntersectionWithConeRightSide(s);let o=this.InsertToTree(this.leftConeSides,i.LeftSide);this.FixConeLeftSideIntersections(r,o),this.GetZP(e.point.sub(t.Site))>x.distanceEpsilon&&this.InsertRightSide(new Xr(t.Vertex))}LookForIntersectionOfObstacleSideAndRightConeSide(t,e){let i=this.GetLastNodeToTheLeftOfPointInRightSegmentTree(t);if(i!=null&&i.item instanceof Wi){let r=g.IntervalIntersectsRay(t,e.point,i.item.Start,this.ConeRightSideDirection);r&&this.SegmentIsNotHorizontal(r,e.point)&&this.EnqueueEvent(this.CreateRightIntersectionEvent(i.item,r,e))}}CreateRightIntersectionEvent(t,e,i){return new tu(t,e,i)}GetLastNodeToTheLeftOfPointInRightSegmentTree(t){return this.rightConeSides.findLast(e=>Ce.PointIsToTheRightOfSegment(t,e))}LookForIntersectionOfObstacleSideAndLeftConeSide(t,e){let i=this.GetFirstNodeToTheRightOfPoint(t);if(i==null||!(i.item instanceof pi))return;let r=i.item,s=g.IntervalIntersectsRay(t,e.point,r.Start,this.ConeLeftSideDirection);s&&this.EnqueueEvent(new Tn(r,s,e))}GetFirstNodeToTheRightOfPoint(t){return this.leftConeSides.findFirst(e=>Ce.PointIsToTheLeftOfSegment(t,e))}static PointIsToTheLeftOfSegment(t,e){return g.getTriangleOrientation(e.Start,e.Start.add(e.Direction),t)===1}static PointIsToTheRightOfSegment(t,e){return g.getTriangleOrientation(e.Start,e.Start.add(e.Direction),t)===0}FixConeLeftSideIntersections(t,e){do e=this.leftConeSides.next(e);while(e!=null&&g.PointToTheRightOfLineOrOnLine(t.Start,e.item.Start,e.item.Start.add(e.item.Direction)));if(e!=null&&e.item instanceof pi){let i=e.item,r=g.IntervalIntersectsRay(t.start,t.End,i.Start,i.Direction);r&&this.EnqueueEvent(new Tn(i,r,t.EndVertex))}}InsertToTree(t,e){return this.coneSideComparer.SetOperand(e),t.insert(e)}CloseConesAddConeAtLeftVertex(t,e){let i=t.Vertex.prevOnPolyline.point;t.Site.sub(i).dot(this.directionPerp)<-x.distanceEpsilon&&this.RemoveConesClosedBySegment(t.Site,i),e.point.sub(t.Site).dot(this.directionPerp)<-x.distanceEpsilon&&this.RemoveConesClosedBySegment(e.point,t.Site);let r=t.Site,s=r.add(this.ConeLeftSideDirection),o=r.add(this.ConeRightSideDirection),a=e.point;this.GetZP(r.sub(i))>x.distanceEpsilon&&this.RemoveLeftSide(new Qr(t.Vertex.prevOnPolyline));let l=this.GetZP(a)-this.Z;l<-x.distanceEpsilon&&this.RemoveRightSide(new Xr(e));let h=a.sub(t.Site);if(l<-x.distanceEpsilon||lt(l,0)&&this.GetZP(h)>0&&h.dot(this.directionPerp)>-x.distanceEpsilon)this.CreateConeOnVertex(t);else if(!g.PointToTheLeftOfLineOrOnLine(a,r,o))this.CreateConeOnVertex(t),this.EnqueueEvent(new Cr(e));else if(g.PointToTheLeftOfLineOrOnLine(a,r,s))this.EnqueueEvent(new Cr(e)),this.GetZP(h)>x.distanceEpsilon&&(this.LookForIntersectionOfObstacleSideAndRightConeSide(t.Site,e),this.InsertLeftSide(new Qr(t.Vertex)));else{this.EnqueueEvent(new Cr(e));let u=new da(t.Vertex.point,this),d=new Yr(t.Vertex.point,e,new Wi(u));u.RightSide=d,u.LeftSide=new pi(u),this.LookForIntersectionWithConeLeftSide(this.InsertToTree(this.leftConeSides,u.LeftSide));let c=this.InsertToTree(this.rightConeSides,d);this.FixConeRightSideIntersections(d,c),this.GetZP(h)>x.distanceEpsilon&&this.InsertLeftSide(new Qr(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){let 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){let e=this.Z;this.Z=Math.max(this.GetZP(t.Start),this.Z-.01),this.coneSideComparer.SetOperand(t),this.leftConeSides.remove(t),this.Z=e}}FixConeRightSideIntersections(t,e){do e=this.rightConeSides.previous(e);while(e!=null&&g.PointToTheLeftOfLineOrOnLine(t.start,e.item.Start,e.item.Start.add(e.item.Direction)));if(e!=null){let i;if(e.item instanceof Wi){let r=e.item;(i=g.IntervalIntersectsRay(t.start,t.End,r.Start,r.Direction))&&this.EnqueueEvent(this.CreateRightIntersectionEvent(r,i,t.EndVertex))}}}CreateConeOnVertex(t){let e=new da(t.Site,this);e.LeftSide=new pi(e),e.RightSide=new Wi(e);let i=this.InsertToTree(this.leftConeSides,e.LeftSide),r=this.InsertToTree(this.rightConeSides,e.RightSide);this.LookForIntersectionWithConeRightSide(r),this.LookForIntersectionWithConeLeftSide(i)}LookForIntersectionWithConeLeftSide(t){if(t.item instanceof pi){let e=t.item,i=this.FindFirstObstacleSideToTheLeftOfPoint(e.Start);i!=null&&this.TryIntersectionOfConeLeftSideAndObstacleSide(e,i)}else{let e=t.item;t=this.leftConeSides.next(t),t!=null&&t.item instanceof pi&&this.TryIntersectionOfConeLeftSideAndObstacleConeSide(t.item,e)}}LookForIntersectionWithConeRightSide(t){if(t.item instanceof Wi){let e=t.item,i=this.FindFirstObstacleSideToToTheRightOfPoint(e.Start);i!=null&&this.TryIntersectionOfConeRightSideAndObstacleSide(e,i)}else{let e=t.item;t=this.rightConeSides.previous(t),t!=null&&t.item instanceof Wi&&this.TryIntersectionOfConeRightSideAndObstacleConeSide(t.item,e)}}TryIntersectionOfConeRightSideAndObstacleConeSide(t,e){let i=g.IntervalIntersectsRay(e.start,e.End,t.Start,t.Direction);i&&this.EnqueueEvent(this.CreateRightIntersectionEvent(t,i,e.EndVertex))}TryIntersectionOfConeRightSideAndObstacleSide(t,e){let i=g.IntervalIntersectsRay(e.Start,e.End,t.Start,t.Direction);i&&this.EnqueueEvent(this.CreateRightIntersectionEvent(t,i,e.EndVertex))}TryIntersectionOfConeLeftSideAndObstacleConeSide(t,e){let i=g.IntervalIntersectsRay(e.start,e.End,t.Start,t.Direction);i&&this.EnqueueEvent(new Tn(t,i,e.EndVertex))}TryIntersectionOfConeLeftSideAndObstacleSide(t,e){let i=g.IntervalIntersectsRay(e.Start,e.End,t.Start,t.Direction);i&&this.EnqueueEvent(new Tn(t,i,e.EndVertex))}ExtendSegmentToZ(t){let e=t.Direction.dot(this.SweepDirection),i=(this.Z+40-t.Start.dot(this.SweepDirection))/e;return D.mkPP(t.Start,t.Start.add(t.Direction.mul(i)))}GoOverConesSeeingVertexEvent(t){let e=this.FindFirstSegmentInTheRightTreeNotToTheLeftOfVertex(t);if(e==null)return;let i=e.item.Cone,r=i.LeftSide;if(Ce.VertexIsToTheLeftOfSegment(t,r))return;let s=[i];if(this.coneSideComparer.SetOperand(r),e=this.leftConeSides.find(r),e==null){let o=this.Z;this.Z=Math.max(this.GetZP(r.Start),this.PreviousZ),this.coneSideComparer.SetOperand(r),e=this.leftConeSides.find(r),this.Z=o}if(!(e==null&&(e=this.GetRbNodeEmergency(r),e==null))){for(e=this.leftConeSides.next(e);e!=null&&!Ce.VertexIsToTheLeftOfSegment(t,e.item);)s.push(e.item.Cone),e=this.leftConeSides.next(e);for(let o of s)this.AddEdgeAndRemoveCone(o,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 g.getTriangleOrientation(e.Start,e.Start.add(e.Direction),t.Site)===1}static VertexIsToTheRightOfSegment(t,e){return g.getTriangleOrientation(e.Start,e.Start.add(e.Direction),t.Site)===0}FindFirstSegmentInTheRightTreeNotToTheLeftOfVertex(t){return this.rightConeSides.findFirst(e=>!Ce.VertexIsToTheRightOfSegment(t,e))}EnqueueRightVertexEvent(t){this.GetZP(t.Site.sub(t.Vertex.prevOnPolyline.point))>x.tolerance||this.EnqueueEvent(t)}invariant(){for(let t of this.leftConeSides)if(t.Removed)return!1;for(let t of this.rightConeSides)if(t.Removed)return!1;return!0}},Wy=class ui{static GetShapes(t,e){let i=new Map;for(let r of t)ui.ProcessAncestorDescendantCouple(r.target,r.source,i),ui.InsertEdgePortsToShapes(i,r);for(let r of e)ui.ProcessAncestorDescendantCouple(r.source,r.target,i),ui.InsertEdgePortsToShapes(i,r);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(let[e,i]of t){if(!(e instanceof we))continue;let r=e;for(let s of ca(r)){let o=t.get(s);o&&i.AddChild(o)}}}static ProcessAncestorDescendantCouple(t,e,i){let r=Bs(e);do{for(let s of ca(r))ui.CreateShapeIfNeeeded(s,i);if(r===t)break;r=Bs(r)}while(!0);ui.CreateShapeIfNeeeded(r,i)}static CreateShapeIfNeeeded(t,e){e.has(t)||e.set(t,new io(t))}static NumberOfActiveNodesIsUnderThreshold(t,e,i){let r=new Set;for(let s of t)if(ui.SetOfActiveNodesIsLargerThanThreshold(s.target,s.source,r,i))return!1;for(let s of e)if(ui.SetOfActiveNodesIsLargerThanThreshold(s.source,s.target,r,i))return!1;return!0}static SetOfActiveNodesIsLargerThanThreshold(t,e,i,r){let s=Bs(e);for(;;){for(let o of ca(s))if(i.add(o),i.size>r)return!0;if(s===t)break;s=Bs(s)}return i.add(s),i.size>r}};function Bs(n){let t=n.node.parent;return Tt.getGeom(t)}function*ca(n){for(let t of n.graph.shallowNodes)yield Tt.getGeom(t)}var zy=class Xd{get TightPolyline(){return this.tightPoly}set TightPolyline(t){this.tightPoly=t}static mk(t,e,i){let r=new Xd;return r.TightPolyline=t,r.LooseShape=e,r.Distance=i,r}toString(){return(this.TightPolyline==null?"null":this.TightPolyline.toString().substring(0,5))+","+(this.LooseShape==null?"null":this.LooseShape.toString().substring(0,5))}},qy=class Yd{constructor(t,e,i,r){this.loosePolylinesToNodes=new Map,this.MainShape=t,this.TightPadding=e,this.LoosePadding=i,this.ShapesToTightLooseCouples=r}Calculate(t){po(3),this.MainShape.Children.length!==0&&(this.CreateTightObstacles(),this.CreateTigthLooseCouples(t),this.OverlapsDetected&&this.FillTheMapOfShapeToTightLooseCouples())}FillTheMapOfShapeToTightLooseCouples(){let t=qt(this.MainShape.Children.map(e=>ne(e,e.BoundingBox)));xe(t,this.coupleHierarchy,this.TryMapShapeToTightLooseCouple.bind(this))}TryMapShapeToTightLooseCouple(t,e){Yd.ShapeIsInsideOfPoly(t,e.TightPolyline)&&this.ShapesToTightLooseCouples.set(t,e)}static ShapeIsInsideOfPoly(t,e){return G.PointRelativeToCurveLocation(t.BoundaryCurve.start,e)===2}CreateTigthLooseCouples(t){let e=new Array;for(let i of this.tightHierarchy.GetAllLeaves()){let r=ye.FindMaxPaddingForTightPolyline(this.tightHierarchy,i,this.LoosePadding),s=ye.LoosePolylineWithFewCorners(i,r,t),o=new Ir(s),a=zy.mk(i,o,r),l=this.tightToShapes.get(i);for(let h of l)this.ShapesToTightLooseCouples.set(h,a);e.push(a)}this.coupleHierarchy=qt(e.map(i=>ne(i,i.TightPolyline.boundingBox)))}CreateTightObstacles(){this.tightToShapes=new Map;let t=new Set(this.MainShape.Children.map(this.InitialTightPolyline.bind(this))),e=t.size;this.tightHierarchy=ye.RemovePossibleOverlapsInTightPolylinesAndCalculateHierarchy(t,this.tightToShapes),this.OverlapsDetected=e>t.size}InitialTightPolyline(t){let e=ye.PaddedPolylineBoundaryOfNode(t.BoundaryCurve,this.TightPadding),i=Xn(this.LoosePolylinesUnderShape(t),s=>s).filter(s=>G.PointRelativeToCurveLocation(s,e)===0);if(i.length==0)return this.tightToShapes&&this.tightToShapes.set(e,[t]),e;let r=Array.from(e).concat(i);return e=et.mkClosedFromPoints(Ji.CalculateConvexHull(r)),this.tightToShapes&&this.tightToShapes.set(e,[t]),e}LoosePolylinesUnderShape(t){return t.Children.map(e=>this.ShapesToTightLooseCouples.get(e).LooseShape.BoundaryCurve)}},Uy=ct(bi(),1),jn=class{constructor(){this.m=new Map}clear(){this.m.clear()}get size(){return this.m.size}set(n,t){this.m.set(Rs(n),t)}delete(n){this.m.delete(Rs(n))}has(n){return this.m.has(Rs(n))}getPP(n,t){return this.get(new Pe(n,t))}get(n){return this.m.get(Rs(n))}*keys(){for(let n of this.m.keys())yield eu(n)}*[Symbol.iterator](){for(let[n,t]of this.m)yield[eu(n),t]}*values(){yield*this.m.values()}};function eu(n){let t=n.split(" "),e=t[0],i=t[1],r=e.split(","),s=new g(Number(r[0]),Number(r[1]));r=i.split(",");let o=new g(Number(r[0]),Number(r[1]));return new Pe(s,o)}function jy(n,t){return[iu(n),iu(t)].sort().join(" ")}function Rs(n){return jy(n.first,n.second)}function iu(n){return n.x.toString()+","+n.y.toString()}var Qy=class Jd{static constructorStatic(t,e){let i=new Jd;i.edges=t,i.nodeBoundaries=e,i.boundingBox=it.mkEmpty();for(let r of i.nodeBoundaries)i.boundingBox=i.boundingBox.addRec(r.boundingBox);return i}AddGraph(t){for(let e of t.edges)this.edges.push(e);this.nodeBoundaries=ir(this.nodeBoundaries,t.nodeBoundaries),this.boundingBox.addRec(t.boundingBox)}AddNodeBoundary(t){this.nodeBoundaries.add(t),this.boundingBox.addRec(t.boundingBox)}},Xy=ct(ti(),1),qs=class{get CurrentPiercedEdge(){return this.currentPiercedEdge}get CurrentTriangle(){return this.currentTriangle}constructor(n,t,e){this.currentTriangle=n,this.start=t,this.end=e}FindFirstPiercedEdge(){let n=this.GetHyperplaneSign(this.currentTriangle.Sites.item0),t=this.GetHyperplaneSign(this.currentTriangle.Sites.item1);if(n!==t&&g.getTriangleOrientation(this.end,this.currentTriangle.Sites.item0.point,this.currentTriangle.Sites.item1.point)==0)return this.positiveSign=n,this.negativeSign=t,this.currentTriangle.Edges.item0;let e=this.GetHyperplaneSign(this.currentTriangle.Sites.item2);return t!==e&&g.getTriangleOrientation(this.end,this.currentTriangle.Sites.item1.point,this.currentTriangle.Sites.item2.point)==0?(this.positiveSign=t,this.negativeSign=e,this.currentTriangle.Edges.item1):(this.positiveSign=e,this.negativeSign=n,this.currentTriangle.Edges.item2)}FindNextPierced(){if(this.currentTriangle=this.currentPiercedEdge.GetOtherTriangle_T(this.currentTriangle),this.currentTriangle==null){this.currentPiercedEdge=null;return}let n=this.currentTriangle.Edges.index(this.currentPiercedEdge),t,e=this.currentTriangle.Sites.getItem(n+2),i=this.GetHyperplaneSign(e);this.negativeSign===0?i===-1||i===0?(this.negativeSign=i,t=n+1):t=n+2:this.positiveSign===0?i===1||i===0?(this.positiveSign=i,t=n+2):t=n+1:i!==this.positiveSign?(this.negativeSign=i,t=n+1):(this.positiveSign=i,t=n+2),this.currentPiercedEdge=g.signedDoubledTriangleArea(this.end,this.currentTriangle.Sites.getItem(t).point,this.currentTriangle.Sites.getItem(t+1).point)<-x.distanceEpsilon?this.currentTriangle.Edges.getItem(t):null}GetHyperplaneSign(n){let t=g.signedDoubledTriangleArea(this.start,n.point,this.end);return t>x.distanceEpsilon?1:t<-x.distanceEpsilon?-1:0}MoveNext(){return this.currentPiercedEdge==null?this.currentPiercedEdge=this.FindFirstPiercedEdge():this.FindNextPierced(),this.currentPiercedEdge!=null}},Yy=class Zd{constructor(t,e){this.ComputeForcesForBundles=!1,this.metroGraphData=t,this.bundlingSettings=e}EdgeIsLegal_(t,e,i,r){if(Ae.PointIsInsideOfTriangle(e,i))return!0;let s=new qs(i,t,e);for(;s.MoveNext();){let o=s.CurrentPiercedEdge;if(o.constrained){let a=o.lowerSite.Owner;if(!r.has(a))return!1}}return!0}BundleAvoidsObstacles(t,e,i,r,s,o){o.closestDist=new Array;let a=this.metroGraphData.looseIntersections.ObstaclesToIgnoreForBundle(t,e),l=this.FindCloseObstaclesForBundle(e.cdtTriangle,r,i,a,s);if(l==null)return!1;for(let h of l){let u=h[1];o.closestDist.push(u)}return!0}FindCloseObstaclesForBundle(t,e,i,r,s){let o=new Map,a=[];if(!this.ThreadLineSegmentThroughTriangles(t,e,i,r,a))return null;if(!this.ComputeForcesForBundles&&!this.bundlingSettings.HighestQuality)return o;let l=new Set;for(let h of a)for(let u of h.Sites){if(l.has(u))continue;l.add(u);let d=u.Owner;if(r.has(d))continue;let c=Zd.FindPolylinePoint(d,u.point),f=D.minDistBetweenLineSegments(c.point,c.nextOnPolyline.point,e,i),m=f.dist,P=f.parab,v=f.parcd,b=D.minDistBetweenLineSegments(c.point,c.prevOnPolyline.point,e,i),C=b.dist,E=b.parab,w=b.parcd,F,V,q;if(m<C){if(q=m,q>s)continue;F=c.point.add(c.nextOnPolyline.point.sub(c.point).mul(P)),V=e.add(i.sub(e).mul(v))}else{if(q=C,q>s)continue;F=c.point.add(c.prevOnPolyline.point.sub(c.point).mul(E)),V=e.add(i.sub(e).mul(w))}o.get(d)||o.set(d,[F,V])}return o}ThreadLineSegmentThroughTriangles(t,e,i,r,s){if(Ae.PointIsInsideOfTriangle(i,t))return s.push(t),!0;let o=new qs(t,e,i);for(s.push(t);o.MoveNext();){s.push(o.CurrentTriangle);let a=o.CurrentPiercedEdge;if(a.constrained){let l=a.lowerSite.Owner;if(!r.has(l))return!1}}return o.CurrentTriangle!=null&&s.push(o.CurrentTriangle),!0}static PointLocationInsideTriangle(t,e){let i=!1;for(let r=0;r<3;r++){let s=g.signedDoubledTriangleArea(t,e.Sites.getItem(r).point,e.Sites.getItem(r+1).point);if(s<x.distanceEpsilon*-1)return 0;s<x.distanceEpsilon&&(i=!0)}return i?1:2}static FindPolylinePoint(t,e){for(let i of t.polylinePoints())if(i.point.equal(e))return i;throw new Error("polyline point "+e+" not found")}EdgeIsLegal(t,e,i,r){let s=[],o=this.metroGraphData.looseIntersections.ObstaclesToIgnoreForBundle(t,e);return this.ThreadLineSegmentThroughTriangles(t.cdtTriangle,i,r,o,s)}EdgeIsLegalSSPPS(t,e,i){let r=t.Position,s=t.cdtTriangle,o=e.Position;if(Ae.PointIsInsideOfTriangle(o,s))return!0;let a=new qs(s,r,o);for(;a.MoveNext();){let l=a.CurrentPiercedEdge;if(l.constrained){let h=l.lowerSite.Owner;if(!i.has(h))return!1}}return!0}},uo=class Pr{constructor(t,e,i,r){this.metroGraphData=t,this.obstaclesToIgnoreLambda=r,this.bundlingSettings=e,this.obstacleTree=i}ObstaclesToIgnoreForBundle(t,e){return t!=null&&e!=null?ir(this.obstaclesToIgnoreLambda(t),this.obstaclesToIgnoreLambda(e)):t==null&&e==null?new Set:t!=null?this.obstaclesToIgnoreLambda(t):this.obstaclesToIgnoreLambda(e)}HubAvoidsObstaclesSPNBA(t,e,i,r){let s={minimalDistance:i};return Pr.IntersectCircleWithTree(this.obstacleTree,e,i,this.obstaclesToIgnoreLambda(t),r.touchedObstacles,s)}HubAvoidsObstaclesPNS__(t,e,i){let r={touchedObstacles:Array()},s={minimalDistance:0};return this.HubAvoidsObstaclesPNSTT(t,e,i,r,s)}GetMinimalDistanceToObstacles(t,e,i){let r=new Array,s={minimalDistance:i};return Pr.IntersectCircleWithTree(this.obstacleTree,e,i,this.obstaclesToIgnoreLambda(t),r,s)?s.minimalDistance:0}HubAvoidsObstaclesPNSTT(t,e,i,r,s){return r.touchedObstacles=new Array,s.minimalDistance=e,Pr.IntersectCircleWithTree(this.obstacleTree,t,e,i,r.touchedObstacles,s)}static IntersectCircleWithTree(t,e,i,r,s,o){if(!t.irect.contains_point_radius(e,i))return!0;if(t.UserData==null){let a=Pr.IntersectCircleWithTree(t.Left,e,i,r,s,o);if(!a||(a=Pr.IntersectCircleWithTree(t.Right,e,i,r,s,o),!a))return!1}else{let a=t.UserData;if(r.has(a))return!0;if(G.PointRelativeToCurveLocation(e,a)!==0)return Pr.containingPoly=a,!1;let l=a.value(a.closestParameter(e)),h=l.sub(e).length;h<=i&&s.push([a,l]),o.minimalDistance=Math.min(h,o.minimalDistance)}return!0}static Create4gon(t,e,i,r){let s=e.sub(t).normalize();return s=new g(s.y,s.x*-1),et.mkFromPoints([t.add(s.mul(i/2)),t.sub(s.mul(i/2)),e.sub(s.mul(r/2)),e.add(s.mul(r/2))])}},Jy=class{constructor(n,t,e,i){this.Width=t,this.Polyline=n,this.sourceAndTargetLoosePolylines=e,this.Index=i}UpdateLengths(){let n=0;for(let t=this.Polyline.startPoint;t.next!=null;t=t.next)n+=t.next.point.sub(t.point).length;this.Length=n,this.IdealLength=this.Polyline.end.sub(this.Polyline.start).length}},Zy=class{constructor(n,t,e){this.metroline=n,this.station=t,this.polyPoint=e}get Metroline(){return this.metroline}get PolyPoint(){return this.polyPoint}},Ky=class{constructor(n,t,e){this.Radius=0,this.BundleBases=new Map,this.MetroNodeInfos=new Array,this._cachedIdealRadius=0,this.SerialNumber=n,this.IsReal=t,this.Position=e}debStop(){return this.SerialNumber===28&&this.Position.sub(new g(841.2662778763244,303.3817005853006)).length<.001}get Position(){return this._Position}set Position(n){this._Position=n}getELP(){return this.EnterableLoosePolylines}setELP(n){this.EnterableLoosePolylines=n}addEL(n){this.EnterableLoosePolylines.add(n)}get cachedIdealRadius(){return this._cachedIdealRadius}set cachedIdealRadius(n){this._cachedIdealRadius=n}AddEnterableLoosePolyline(n){this.EnterableLoosePolylines==null&&(this.EnterableLoosePolylines=new Set),this.EnterableLoosePolylines.add(n)}AddEnterableTightPolyline(n){this.EnterableTightPolylines==null&&(this.EnterableTightPolylines=new Set),this.EnterableTightPolylines.add(n)}},_y=class{constructor(){this.Width=0,this.Metrolines=new Array,this.cachedBundleCost=0}get Count(){return this.Metrolines.length}},er=class ji{constructor(t,e){this.metroGraphData=t,this.bundlingSettings=e}CreateNodeRadii(){for(let t of this.metroGraphData.VirtualStations())t.Radius=0,t.cachedIdealRadius=ji.CalculateIdealHubRadiusWithNeighborsMBS(this.metroGraphData,this.bundlingSettings,t);this.GrowHubs(!1),this.GrowHubs(!0);for(let t of this.metroGraphData.VirtualStations())t.Radius=Math.max(t.Radius,this.bundlingSettings.MinHubRadius)}GrowHubs(t){let e=new nr(Mt);for(let r of this.metroGraphData.VirtualStations())e.Enqueue(r,-this.CalculatePotential(r,t));let i=!1;for(;!e.IsEmpty();){let r={priority:0},s=e.DequeueAndGetPriority(r);if(r.priority>=0)break;this.TryGrowHub(s,t)&&(e.Enqueue(s,-this.CalculatePotential(s,t)),i=!0)}return i}TryGrowHub(t,e){let i=this.CalculateAllowedHubRadius(t);if(t.Radius>=i)return!1;let r=e?ji.CalculateIdealHubRadiusWithAdjacentEdges(this.bundlingSettings,t):t.cachedIdealRadius;if(t.Radius>=r)return!1;let s=.05*(r-t.Radius);s<1&&(s=1);let o=Math.min(t.Radius+s,i);return o<=t.Radius?!1:(t.Radius=o,!0)}CalculatePotential(t,e){let i=e?ji.CalculateIdealHubRadiusWithAdjacentEdges(this.bundlingSettings,t):t.cachedIdealRadius;return i<=t.Radius?0:(i-t.Radius)/i}CalculateAllowedHubRadius(t){let e=this.bundlingSettings.MaxHubRadius;for(let r of t.Neighbors){let s=r.Position.sub(t.Position).length;e=Math.min(e,s/1.05-r.Radius)}let 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 r=1;for(let s of i.Neighbors){let o=t.GetWidthSSN(s,i,e.EdgeSeparation)/2+e.EdgeSeparation;r=Math.max(r,o)}return r=Math.min(r,2*e.MaxHubRadius),r}static CalculateIdealHubRadiusWithNeighborsMBS(t,e,i){return ji.CalculateIdealHubRadiusWithNeighborsMBNP(t,e,i,i.Position)}static CalculateIdealHubRadiusWithNeighborsMBNP(t,e,i,r){let s=ji.CalculateIdealHubRadius(t,e,i);if(i.Neighbors.length>1){let o=i.Neighbors;for(let a=0;a<o.length;a++){let l=o[a],h=o[(a+1)%o.length];s=Math.max(s,ji.GetMinRadiusForTwoAdjacentBundles(s,i,r,l,h,t,e))}}return s=Math.min(s,2*e.MaxHubRadius),s}static CalculateIdealHubRadiusWithAdjacentEdges(t,e){let i=t.MaxHubRadius;for(let r of e.Neighbors)i=Math.min(i,e.Position.sub(r.Position).length/2);return i}static GetMinRadiusForTwoAdjacentBundles(t,e,i,r,s,o,a){let l=o.GetWidthSSN(e,r,a.EdgeSeparation),h=o.GetWidthSSN(e,s,a.EdgeSeparation);return ji.GetMinRadiusForTwoAdjacentBundlesNPPPNNB(t,i,r.Position,s.Position,l,h,a)}static GetMinRadiusForTwoAdjacentBundlesNPPPNNB(t,e,i,r,s,o,a){if(s<x.distanceEpsilon||o<x.distanceEpsilon)return t;let l=g.anglePCP(i,e,r);if(l=Math.min(l,Math.PI*2-l),l<x.distanceEpsilon)return 2*a.MaxHubRadius;if(l>=Math.PI/2)return t*1.05;let h=Math.sin(l),u=Math.cos(l),d=s/(4*h),c=o/(4*h),f=2*Math.sqrt(d*d+(c*c+2*(d*(c*u))));return f=Math.min(f,2*a.MaxHubRadius),f=Math.max(f,t),f}},Kd=class _d{constructor(t,e,i,r){this.metroGraphData=t,this.bundlingSettings=e,this.costCalculator=i,this.cdt=r}InitializeCostCache(){for(let t of this.metroGraphData.VirtualStations())t.cachedIdealRadius=er.CalculateIdealHubRadiusWithNeighborsMBS(this.metroGraphData,this.bundlingSettings,t),t.cachedRadiusCost=this.costCalculator.RadiusCost(t,t.Position),t.cachedBundleCost=0;for(let t of this.metroGraphData.VirtualEdges()){let e=t[0],i=t[1],r=this.metroGraphData.GetIjInfo(e,i);r.cachedBundleCost=this.costCalculator.BundleCost(e,i,e.Position),e.cachedBundleCost+=r.cachedBundleCost,i.cachedBundleCost+=r.cachedBundleCost}}UpdateCostCache(t){let e=this.cdt.getRectangleNodeOnTriangles();t.cdtTriangle=e.FirstHitNodeWithPredicate(t.Position,_d.testPointInside).UserData,t.cachedIdealRadius=er.CalculateIdealHubRadiusWithNeighborsMBS(this.metroGraphData,this.bundlingSettings,t),t.cachedRadiusCost=this.costCalculator.RadiusCost(t,t.Position),t.cachedBundleCost=0;for(let i of t.Neighbors){i.IsReal||(i.cachedIdealRadius=er.CalculateIdealHubRadiusWithNeighborsMBS(this.metroGraphData,this.bundlingSettings,i),i.cachedRadiusCost=this.costCalculator.RadiusCost(i,i.Position));let r=this.metroGraphData.GetIjInfo(t,i);i.cachedBundleCost-=r.cachedBundleCost,r.cachedBundleCost=this.costCalculator.BundleCost(t,i,t.Position),t.cachedBundleCost+=r.cachedBundleCost,i.cachedBundleCost+=r.cachedBundleCost}}static testPointInside(t,e){return Ae.PointIsInsideOfTriangle(t,e)?1:0}},tc=class{constructor(){this.mainMap=new Map}get isEmpty(){return this.mainMap.size===0||this.everyMapIsEmpty()}everyMapIsEmpty(){for(let n of this.mainMap.values())if(n.size)return!1;return!0}get(n,t){let e=this.mainMap.get(n);if(e)return e.get(t)}has(n,t){let e=this.mainMap.get(n);return e?e.has(t):!1}set(n,t,e){let i=this.mainMap.get(n);i||(i=new Map,this.mainMap.set(n,i)),i.set(t,e)}*[Symbol.iterator](){for(let[n,t]of this.mainMap)for(let[e,i]of t)yield[n,e,i]}*keys(){for(let[n,t]of this.mainMap)for(let[e]of t)yield[n,e]}},tS=class{constructor(n,t,e,i,r,s,o,a){this.cachedEnterableLooseForEnd=new _e,this.bundlingSettings=i,this.regularEdges=n,r!=null?this.cdt=r:this.cdt=Zu(t),this.EdgeLooseEnterable=s,this.EdgeTightEnterable=o,this.LoosePolylineOfPort=a,this.looseIntersections=new uo(this,i,t,l=>l.getELP()),this.tightIntersections=new uo(this,i,e,l=>l.EnterableTightPolylines),this.cdtIntersections=new Yy(this,i),this.Initialize(!1)}get Ink(){return this.ink}get Edges(){return this.regularEdges}VirtualStations(){return Array.from(this.Stations).filter(n=>!n.IsReal)}get Metrolines(){return this.metrolines}get LooseTree(){return this.looseIntersections.obstacleTree}get TightTree(){return this.tightIntersections.obstacleTree}*VirtualEdges(){for(let n of this.edgeInfoDictionary.keys())yield n}RealEdgeCount(n,t){let e=n.SerialNumber<t.SerialNumber?[n,t]:[t,n],i=this.edgeInfoDictionary.get(e[0],e[1]);return i?i.Count:0}MetroNodeInfosOfNode(n){return n.MetroNodeInfos}GetIjInfo(n,t){let e=n.SerialNumber<t.SerialNumber?[n,t]:[t,n];return this.edgeInfoDictionary.get(e[0],e[1])}MoveNode(n,t){let e=n.Position;this.PointToStations.deleteP(e),this.PointToStations.set(t,n),n.Position=t;for(let i of this.MetroNodeInfosOfNode(n))i.PolyPoint.point=t;for(let i of this.MetroNodeInfosOfNode(n)){let r=i.Metroline,s=i.PolyPoint.prev.point,o=i.PolyPoint.next.point;r.Length+=o.sub(t).length+s.sub(t).length-o.sub(e).length-s.sub(e).length}for(let i of n.Neighbors)this.ink+=t.sub(i.Position).length-e.sub(i.Position).length;this.SortNeighbors(n);for(let i of n.Neighbors)this.SortNeighbors(i)}GetWidthSSN(n,t,e){let i=n.SerialNumber<t.SerialNumber?[n,t]:[t,n],r=this.edgeInfoDictionary.get(i[0],i[1]);return r?r.Width+(r.Count-1)*e:0}GetWidthAN(n,t){let e=0;for(let r of n)e+=r.Width;let i=n.length;return e+=i>0?(i-1)*t:0,e}Initialize(n){this.SimplifyRegularEdges(),this.InitializeStationData(),this.InitializeEdgeData(),this.InitializeVirtualGraph(),this.InitializeEdgeNodeInfo(n),this.InitializeCdtInfo()}SimplifyRegularEdges(){for(let n of this.regularEdges)this.SimplifyRegularEdge(n)}SimplifyRegularEdge(n){let t=n.curve,e=new Xy.Stack,i=new Zt;for(let r=t.endPoint;r!=null;r=r.prev){let s=r.point;if(i.has(r.point)){let o=r.next;do{let a=e.top;if(!a.equal(s))i.delete(a),e.pop(),o=o.next;else break}while(!0);o.prev=r.prev,o.prev.next=o}else e.push(s),i.add(s)}}InitializeStationData(){this.Stations=[],this.PointToStations=new _e;for(let n of this.regularEdges){let t=n.curve;this.ProcessPolylinePoints(t)}}ProcessPolylinePoints(n){let t=n.startPoint;for(this.RegisterStation(t,!0),t=t.next;t!==n.endPoint;t=t.next)this.RegisterStation(t,!1);this.RegisterStation(t,!0)}RegisterStation(n,t){if(!this.PointToStations.has(n.point)){let e=new Ky(this.Stations.length,t,n.point);this.PointToStations.set(n.point,e),this.Stations.push(e)}}InitializeEdgeData(){this.metrolines=new Array;for(let n=0;n<this.regularEdges.length;n++){let t=this.regularEdges[n];this.InitEdgeData(t,n)}}InitEdgeData(n,t){let e=new Jy(n.curve,this.bundlingSettings.ActualEdgeWidth(n),this.EdgeSourceAndTargetFunc(n),t);this.metrolines.push(e),this.PointToStations.get(e.Polyline.start).BoundaryCurve=n.sourcePort.Curve,this.PointToStations.get(e.Polyline.end).BoundaryCurve=n.targetPort.Curve}EdgeSourceAndTargetFunc(n){return()=>[this.LoosePolylineOfPort(n.sourcePort),this.LoosePolylineOfPort(n.targetPort)]}InitializeVirtualGraph(){let n=new Map;for(let t of this.metrolines){let e=this.PointToStations.get(t.Polyline.start),i;for(let r=t.Polyline.startPoint;r.next!=null;r=r.next,e=i)i=this.PointToStations.get(r.next.point),_s(n,e,i),_s(n,i,e)}for(let t of this.Stations)t.Neighbors=Array.from(n.get(t))}GetUnorderedIjInfo(n,t){return n.SerialNumber<t.SerialNumber?this.GetCreateOrderedIjInfo(n,t):this.GetCreateOrderedIjInfo(t,n)}static closedeb(n,t){return n.Position.sub(new g(360.561,428.416)).length<.1&&t.Position.sub(new g(414.281,440.732)).length<.1}GetCreateOrderedIjInfo(n,t){let e=this.edgeInfoDictionary.get(n,t);return e||(e=new _y,this.edgeInfoDictionary.set(n,t,e),e)}InitializeEdgeNodeInfo(n){this.edgeInfoDictionary=new tc,this.InitAllMetroNodeInfos(n),this.SortAllNeighbors(),this.InitEdgeIjInfos(),this.ink=0;for(let t of this.VirtualEdges())this.ink+=t[0].Position.sub(t[1].Position).length}InitAllMetroNodeInfos(n){for(let t=0;t<this.metrolines.length;t++){let e=this.metrolines[t];this.InitMetroNodeInfos(e),this.InitNodeEnterableLoosePolylines(e,this.regularEdges[t]),n&&this.InitNodeEnterableTightPolylines(e,this.regularEdges[t]),e.UpdateLengths()}}InitMetroNodeInfos(n){for(let t=n.Polyline.startPoint;t!=null;t=t.next){let e=this.PointToStations.get(t.point);e.MetroNodeInfos.push(new Zy(n,e,t))}}InitNodeEnterableLoosePolylines(n,t){let e=this.EdgeLooseEnterable!=null?this.EdgeLooseEnterable.get(t):new Set;for(let i=n.Polyline.startPoint.next;i!=null&&i.next!=null;i=i.next){let r=this.PointToStations.get(i.point);r.getELP()!=null?r.setELP(Ri(r.getELP(),e)):r.setELP(new Set(e))}this.AddLooseEnterableForMetrolineStartEndPoints(n)}AddLooseEnterableForMetrolineStartEndPoints(n){this.AddLooseEnterableForEnd(n.Polyline.start),this.AddLooseEnterableForEnd(n.Polyline.end)}AddTightEnterableForMetrolineStartEndPoints(n){this.AddTightEnterableForEnd(n.Polyline.start),this.AddTightEnterableForEnd(n.Polyline.end)}AddLooseEnterableForEnd(n){let t=this.PointToStations.get(n);if(this.cachedEnterableLooseForEnd.has(n))t.setELP(this.cachedEnterableLooseForEnd.get(n));else{for(let e of this.LooseTree.AllHitItems_(n))G.PointRelativeToCurveLocation(n,e)===2&&t.AddEnterableLoosePolyline(e);this.cachedEnterableLooseForEnd.set(n,t.getELP())}}AddTightEnterableForEnd(n){let t=this.PointToStations.get(n);for(let e of this.TightTree.AllHitItems_(n))G.PointRelativeToCurveLocation(n,e)===2&&t.AddEnterableTightPolyline(e)}InitNodeEnterableTightPolylines(n,t){let e=this.EdgeTightEnterable!=null?this.EdgeTightEnterable.get(t):new Set;for(let i=n.Polyline.startPoint.next;i!=null&&i.next!=null;i=i.next){let r=this.PointToStations.get(i.point),s=r.EnterableTightPolylines;s!=null?r.EnterableTightPolylines=Ri(s,e):r.EnterableTightPolylines=new Set(e)}this.AddTightEnterableForMetrolineStartEndPoints(n)}SortAllNeighbors(){for(let n of this.Stations)this.SortNeighbors(n)}SortNeighbors(n){if(n.Neighbors.length<=2)return;let t=n.Neighbors[0].Position,e=n.Position;n.Neighbors.sort((i,r)=>xr(t.sub(e),i.Position.sub(e),r.Position.sub(e)))}InitEdgeIjInfos(){for(let n of this.metrolines){let t=n.Polyline,e=this.PointToStations.get(t.start),i;for(let r=n.Polyline.startPoint;r.next!=null;r=r.next,e=i){i=this.PointToStations.get(r.next.point);let s=this.GetUnorderedIjInfo(e,i);s.Width+=n.Width,s.Metrolines.push(n)}}}InitializeCdtInfo(){let n=this.cdt.getRectangleNodeOnTriangles();for(let t of this.Stations)t.cdtTriangle=n.FirstHitNodeWithPredicate(t.Position,Kd.testPointInside).UserData}PointIsAcceptableForEdge(n,t){if(this.LoosePolylineOfPort==null)return!0;let e=n.sourceAndTargetLoosePolylines();return G.PointRelativeToCurveLocation(t,e[0])===0&&G.PointRelativeToCurveLocation(t,e[1])===0}};function xr(n,t,e){let i=g.crossProduct(n,e),r=n.dot(e),s=g.crossProduct(n,t),o=n.dot(t);return lt(s,0)&&Us(o,0)?lt(i,0)&&Us(r,0)?0:1:lt(i,0)&&Us(r,0)?-1:lt(s,0)||lt(i,0)||s*i>0?Js(g.crossProduct(e,t),0):-Js(Math.sign(s),0)}function Us(n,t){return Js(n,t)>=0}var eS=ct(ti(),1),Te=class Oi{static{this.Inf=1e9}constructor(t,e){this.metroGraphData=t,this.bundlingSettings=e}static InkError(t,e,i){return(t-e)*i.InkImportance}static PathLengthsError(t,e,i,r){return(t-e)*(r.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(let r of t.Metrolines)i+=e.PathLengthImportance*r.Length/r.IdealLength;return i+=this.CostOfForces(t),i}static CostOfForces(t){let e=0;for(let i of t.VirtualStations())e=e+i.cachedRadiusCost;for(let i of t.VirtualEdges()){let r=i[0],s=i[1];e+=t.GetIjInfo(r,s).cachedBundleCost}return e}InkGain(t,e){let i=this.metroGraphData.Ink,r=this.metroGraphData.Ink;for(let s of t.Neighbors){let o=s.Position;r-=ht(o,t.Position),r+=ht(o,e)}return Oi.InkError(i,r,this.bundlingSettings)}PathLengthsGain(t,e){let i=0;for(let r of this.metroGraphData.MetroNodeInfosOfNode(t)){let s=r.Metroline.Length,o=r.PolyPoint.prev.point,a=r.PolyPoint.next.point,l=r.Metroline.Length+ht(a,e)+ht(o,e)-ht(a,t.Position)-ht(o,t.Position);i+=Oi.PathLengthsError(s,l,r.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;g.closeDistEps(t.Position,e)?i=t.cachedIdealRadius:i=er.CalculateIdealHubRadiusWithNeighborsMBNP(this.metroGraphData,this.bundlingSettings,t,e);let r={touchedObstacles:[]};if(!this.metroGraphData.looseIntersections.HubAvoidsObstaclesSPNBA(t,e,i,r))return Oi.Inf;let s=0;for(let o of r.touchedObstacles){let a=ht(o[1],e);s+=Oi.RError(i,a,this.bundlingSettings)}return s}BundleGain(t,e){let i=t.cachedBundleCost;for(let r of t.Neighbors){let s=this.BundleCost(t,r,e);if(Us(s,Oi.Inf))return-Oi.Inf;i-=s}return i}BundleCost(t,e,i){let r=this.metroGraphData.GetWidthSSN(t,e,this.bundlingSettings.EdgeSeparation),s={closestDist:[]};if(!this.metroGraphData.cdtIntersections.BundleAvoidsObstacles(t,e,i,e.Position,r,s))return Oi.Inf;let o=0;for(let a of s.closestDist){let l=ht(a[0],a[1]);o+=Oi.BundleError(r/2,l,this.bundlingSettings)}return o}},iS=ct(bi(),1),rS=class{constructor(n){this.polylineToEdgeGeom=new Map,this.pathsThroughPoints=new _e,this.interestingPoints=new Zt,this.metroGraphData=n}get Polylines(){return Array.from(this.polylineToEdgeGeom.keys())}Run(){this.Init(),this.SwitchFlips()}Init(){for(let n of this.metroGraphData.Edges)this.polylineToEdgeGeom.set(n.curve,n);for(let n of this.Polylines)this.RegisterPolylinePointInPathsThrough(n.polylinePoints())}RegisterPolylinePointInPathsThrough(n){for(let t of n)this.RegisterPolylinePointInPathsThroughP(t)}RegisterPolylinePointInPathsThroughP(n){nS(this.pathsThroughPoints,n.point,n)}UnregisterPolylinePointsInPathsThrough(n){for(let t of n)this.UnregisterPolylinePointInPathsThrough(t)}UnregisterPolylinePointInPathsThrough(n){sS(this.pathsThroughPoints,n.point,n)}SwitchFlips(){let n=new Set(this.Polylines),t=new iS.Queue;for(let e of this.Polylines)t.enqueue(e);for(;t.length>0;){let e=t.dequeue();n.delete(e);let i=this.ProcessPolyline(e);i!=null&&(n.has(e)||(n.add(e),t.enqueue(e)),n.has(i)||(n.add(i),t.enqueue(i)))}}ProcessPolyline(n){let t=new Map;for(let e=n.startPoint.next;e!=null;e=e.next){this.FillDepartedPolylinePoints(e,t);for(let i of this.pathsThroughPoints.get(e.point)){let r=t.get(i.polyline);if(r){if(this.ProcessFlip(e,r))return i.polyline;t.delete(i.polyline)}}}return null}FillDepartedPolylinePoints(n,t){let e=n.prev.point;for(let i of this.pathsThroughPoints.get(e))this.IsNeighborOnTheSamePolyline(i,n)||t.has(i.polyline)||t.set(i.polyline,i)}ProcessFlip(n,t){let e=n.polyline,i=t.polyline,r=n.point,s=t.point,o=this.polylineToEdgeGeom.get(e),a=this.polylineToEdgeGeom.get(i);if(o.lineWidth!==a.lineWidth||this.metroGraphData.EdgeLooseEnterable==null||!qn(this.metroGraphData.EdgeLooseEnterable.get(o),this.metroGraphData.EdgeLooseEnterable.get(a)))return!1;let l=this.FindPointsOnPolyline(e,r,s),h=l[0],u=l[1],d=l[2];l=this.FindPointsOnPolyline(i,r,s);let c=l[0],f=l[1],m=l[2],P=this.FindRelationOnFirstPoint(h,c,d,m),v=this.FindRelationOnLastPoint(u,f,d,m);return P!==2&&v!==2||P===1||v===1?!1:(this.UnregisterPolylinePointsInPathsThrough(e.polylinePoints()),this.UnregisterPolylinePointsInPathsThrough(i.polylinePoints()),this.Swap(h,c,u,f,d,m),this.RegisterPolylinePointInPathsThrough(e.polylinePoints()),this.RegisterPolylinePointInPathsThrough(i.polylinePoints()),this.RegisterInterestingPoint(h.point),this.RegisterInterestingPoint(u.point),this.numberOfReducedCrossings++,!0)}FindPointsOnPolyline(n,t,e){let i,r;for(let s=n.startPoint;s!=null;s=s.next)if(i==null)if(s.point.equal(t)){if(r!=null)return[s,r,!1];i=s}else r==null&&s.point.equal(e)&&(r=s);else if(s.point.equal(e))return[i,s,!0]}PolylinePointsAreInForwardOrder(n,t){for(let e=n;e!=null;e=e.next)if(e===t)return!0;return!1}Next(n,t){return t?n.next:n.prev}Prev(n,t){return t?n.prev:n.next}FindRelationOnFirstPoint(n,t,e,i){let r=n,s=t;for(;;){let o=this.Prev(n,e),a=this.Prev(t,i);if(o==null||a==null)return 0;if(!o.point.equal(a.point))break;n=o,t=a}return this.PolylinesIntersect(r,s,n,t,e,i)}FindRelationOnLastPoint(n,t,e,i){let r=n,s=t;for(;;){let o=this.Next(n,e),a=this.Next(t,i);if(o==null||a==null)return 0;if(!o.point.equal(a.point))break;n=o,t=a}for(;this.Next(n,e).point.equal(this.Prev(t,i).point);)n=this.Next(n,e),t=this.Prev(t,i);return this.PolylinesIntersect(n,t,r,s,e,i)}PolylinesIntersect(n,t,e,i,r,s){let o=this.Prev(n,r),a=this.Next(n,r),l=this.Next(e,r),h=this.Prev(e,r),u=this.Next(t,s),d=this.Prev(i,s);if(n.point.equal(e.point)){let c=n.point,f=xr(h.point.sub(c),d.point.sub(c),a.point.sub(c)),m=xr(h.point.sub(c),u.point.sub(c),a.point.sub(c));return f===m?1:2}else{let c=xr(o.point.sub(n.point),a.point.sub(n.point),u.point.sub(n.point)),f=xr(l.point.sub(e.point),d.point.sub(e.point),h.point.sub(e.point));return c===f?1:2}}Swap(n,t,e,i,r,s){let o=this.GetRangeOnPolyline(this.Next(n,r),e,r),a=this.GetRangeOnPolyline(this.Next(t,s),i,s);this.ChangePolylineSegment(n,e,r,a),this.ChangePolylineSegment(t,i,s,o),za.RemoveSelfCyclesFromPolyline(n.polyline),za.RemoveSelfCyclesFromPolyline(t.polyline)}ChangePolylineSegment(n,t,e,i){let r=n;for(let s of i){let o=Ni.mkFromPoint(s.point);o.polyline=r.polyline,e?(o.prev=r,r.next=o):(o.next=r,r.prev=o),r=o}e?(r.next=t,t.prev=r):(r.prev=t,t.next=r)}GetRangeOnPolyline(n,t,e){let i=new Array;for(let r=n;r!==t;r=this.Next(r,e))i.push(r);return i}IsNeighborOnTheSamePolyline(n,t){return n.prev!=null&&n.prev.point.equal(t.point)||n.next!=null&&n.next.point.equal(t.point)}RegisterInterestingPoint(n){this.interestingPoints.has(n)||this.interestingPoints.add(n)}GetChangedHubs(){return this.interestingPoints}NumberOfReducedCrossings(){return this.numberOfReducedCrossings}PolylineIsOK(n){let t=new Zt;for(let e=n.startPoint;e!=null;e=e.next){if(e===n.startPoint){if(e.prev!=null)return!1}else if(e.prev.next!==e)return!1;if(e===n.endPoint){if(e.next!=null)return!1}else if(e.next.prev!==e)return!1;if(t.has(e.point))return!1;t.add(e.point)}return!(n.startPoint.prev!=null||n.endPoint.next!=null)}};function nS(n,t,e){let i=n.get(t);i||(i=new Set,n.set(t,i)),i.add(e)}function sS(n,t,e){let i=n.get(t);i&&(i.delete(e),i.size===0&&n.deleteP(t))}var za=class ec{constructor(t,e){this.foundCrossings=new Zt,this.crossingsThatShouldBecomeHubs=new Zt,this.metroGraphData=t,this.polylineAcceptsPoint=e}*Vertices(){for(let t of this.Polylines)for(let e of t.polylinePoints())yield e}get Polylines(){return this.metroGraphData.Edges.map(t=>t.curve)}Edges(){let t=new jn;for(let e of this.Vertices())e.next&&t.set(new Pe(e.point,e.next.point),0);return Array.from(t.keys())}run(){if(this.metroGraphData.Edges.length===0)return!1;let t=new jn,e=new eo(null);for(let a of this.Vertices()){let l=it.mkOnPoints([a.point]);l.pad(x.intersectionEpsilon),e.Add(l,a.point)}let i=to(this.Edges(),a=>it.mkPP(a.first,a.second));de(i,i,(a,l)=>this.IntersectTwoEdges.bind(a,l,t,e)),this.SortInsertedPoints(t);let r=this.InsertPointsIntoPolylines(t),s=this.FixPaths(),o=this.RemoveUnimportantCrossings();return s||r||o}FixPaths(){let t=!1;return this.RemoveSelfCycles()&&(t=!0),this.ReduceEdgeCrossings()&&(t=!0),t}SortInsertedPoints(t){for(let e of t)this.SortInsideSegment(e[0],e[1])}SortInsideSegment(t,e){e.sort((i,r)=>Mt(ht(i,t.first),ht(r,t.first)))}InsertPointsIntoPolylines(t){let e=!1;for(let i of this.metroGraphData.Metrolines)return this.InsertPointsIntoPolyline(i,t)&&(e=!0),e}InsertPointsIntoPolyline(t,e){let i=!1;for(let r=t.Polyline.startPoint;r.next!=null;r=r.next)this.InsertPointsOnPolypoint(r,e,t)&&(i=!0);return i}InsertPointsOnPolypoint(t,e,i){let r=new Pe(t.point,t.next.point),s=t.point!==r.first,o=e.get(r);if(!o)return!1;let a=t.next,l=t.polyline;if(s)for(let h=o.length-1;h>=0;h--){if(this.polylineAcceptsPoint!=null&&!this.polylineAcceptsPoint(i,o[h]))continue;let u=Ni.mkFromPoint(o[h]);u.prev=t,u.polyline=l,t.next=u,t=u}else for(let h=0;h<o.length;h++){if(this.polylineAcceptsPoint!=null&&!this.polylineAcceptsPoint(i,o[h]))continue;let u=Ni.mkFromPoint(o[h]);u.prev=t,u.polyline=l,t.next=u,t=u}return t.next=a,a.prev=t,!0}RemoveSelfCycles(){let t=!1;for(let e of this.Polylines)ec.RemoveSelfCyclesFromPolyline(e)&&(t=!0);return t}static RemoveSelfCyclesFromPolyline(t){let e=!1,i=new _e;for(let r=t.startPoint;r!=null;r=r.next){let s=r.point,o=i.get(s);if(o){for(let a=o.next;a!==r.next;a=a.next)i.deleteP(a.point);o.next=r.next,r.next.prev=o,e=!0}else i.set(r.point,r)}return e}ReduceEdgeCrossings(){let t=new rS(this.metroGraphData);t.Run();for(let e of t.GetChangedHubs())this.crossingsThatShouldBecomeHubs.add(e);return t.NumberOfReducedCrossings()>0}RemoveUnimportantCrossings(){let t=!1;this.pointsToDelete=Gf(this.foundCrossings,this.crossingsThatShouldBecomeHubs);for(let 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)&&g.getTriangleOrientation(i.prev.point,i.point,i.next.point)===2){let r=i.prev,s=i.next;r.next=s,s.prev=r,i=r,e=!0}return e}IntersectTwoEdges(t,e,i,r){let s=D.IntersectPPPP(t.first,t.second,e.first,e.second);if(s){let o=this.FindExistingVertexOrCreateNew(r,s);(this.AddVertexToSplittingList(t,i,o)||this.AddVertexToSplittingList(e,i,o))&&this.foundCrossings.add(o)}}FindExistingVertexOrCreateNew(t,e){let i=t.RootNode.FirstHitNode(e);if(i!=null)return i.UserData;let r=it.mkOnPoints([e]);return r.pad(x.intersectionEpsilon),t.Add(r,e),e}AddVertexToSplittingList(t,e,i){if(!G.closeIntersectionPoints(i,t.first)&&!G.closeIntersectionPoints(i,t.second)){let r=e.get(t);if(r||(r=new Array,e.set(t,r)),!r.find(s=>s.equal(i)))return r.push(i),!0}return!1}},ru=class{isCorrectlyOrienected(){return g.getTriangleOrientation(this.Curve.boundingBox.center,this.Curve.value(this.parEnd),this.Curve.value(this.parStart))!==1}get Count(){return this.points.length}constructor(n,t,e,i){this.BelongsToRealNode=i,this.Curve=t,this.Position=e,this.points=new Array(n),this.tangents=new Array(n),this.OrientedHubSegments=new Array(n)}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(n){this.initialMidParameter=n,this.InitialMidPoint=this.Curve.value(n)}get ParStart(){return this.parStart}set ParStart(n){this.parStart=n,this.StartPoint=this.Curve.value(this.parStart)}get ParEnd(){return this.parEnd}set ParEnd(n){this.parEnd=n,this.EndPoint=this.Curve.value(this.parEnd)}get ParMid(){return(this.parStart+this.parEnd)/2}get MidPoint(){return g.middle(this.StartPoint,this.EndPoint)}get Span(){return this.SpanBetweenTwoParameters(this.parStart,this.parEnd)}SpanBetweenTwoParameters(n,t){return n<=t?t-n:t-n+Xi(this.Curve)}RotateLeftPoint(n,t){return n===0?this.EndPoint:this.RotatePoint(n,this.parEnd,t)}RotateRigthPoint(n,t){return n===0?this.StartPoint:this.RotatePoint(n,this.parStart,t)}RotatePoint(n,t,e){let i=Xi(this.Curve)*e;return t+=n*i,t=this.AdjustParam(t),this.Curve.value(t)}AdjustParam(n){return n>this.Curve.parEnd?n=this.Curve.parStart+(n-this.Curve.parEnd):n<this.Curve.parStart&&(n=this.Curve.parEnd-(this.Curve.parStart-n)),n}RotateBy(n,t,e){let i=Xi(this.Curve)*e;n!==0&&(this.ParStart=this.AdjustParam(this.ParStart+n*i)),t!==0&&(this.ParEnd=this.AdjustParam(this.ParEnd+t*i))}RelativeOrderOfBasesIsPreserved(n,t,e){let i=Xi(this.Curve)*e,r=this.parStart+n*i,s=this.parStart<this.parEnd?this.parEnd+t*i:this.parEnd+Xi(this.Curve)+t*i;if(r>s||this.SpanBetweenTwoParameters(r,s)>Xi(this.Curve)/2)return!1;if(this.Prev==null||this.SpanBetweenTwoParameters(this.Prev.ParMid,this.ParMid)>i&&this.SpanBetweenTwoParameters(this.ParMid,this.Next.ParMid)>i)return!0;let o=this.RotateLeftPoint(t,e),a=this.RotateRigthPoint(n,e),l=g.middle(o,a),h=this.MidPoint;return!(g.getTriangleOrientation(this.CurveCenter,this.Prev.MidPoint,h)!=g.getTriangleOrientation(this.CurveCenter,this.Prev.MidPoint,l)||g.getTriangleOrientation(this.CurveCenter,this.Next.MidPoint,h)!=g.getTriangleOrientation(this.CurveCenter,this.Next.MidPoint,l))}},oS=class zr{static{this.FeasibleWidthEpsilon=.1}constructor(t,e,i,r){this.SourceBase=t,this.TargetBase=e,this.obstaclesToIgnore=i,this.HalfWidthArray=r,this.TotalRequiredWidth=this.HalfWidthArray.reduce((o,a)=>o+a,0)*2,this.longEnoughSideLength=t.Curve.boundingBox.addRec(e.Curve.boundingBox).diagonal;let s=Math.max(t.Curve.boundingBox.diagonal,e.Curve.boundingBox.diagonal);if(this.TotalRequiredWidth>s){let o=this.TotalRequiredWidth/s;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){let i=this.SourceBase.Curve.boundingBox.diagonal/2,r=this.TargetBase.Curve.boundingBox.diagonal/2,s=uo.Create4gon(this.SourceBase.Position,this.TargetBase.Position,i*2,r*2);this.tightObstaclesInTheBoundingBox=Array.from(t.AllHitItems(s.boundingBox,o=>!e.has(o)&&G.ClosedCurveInteriorsIntersect(s,o)))}SetEndParamsSymmetrically(){let t=this.TargetBase.Position,e=this.SourceBase.Position,i=t.sub(e).normalize(),r=i.rotate90Ccw(),s=g.middle(t,e),o=i.mul(this.longEnoughSideLength),a=s.add(o),l=s.sub(o);if(this.SetRLParamsIfWidthIsFeasible(r.mul(this.TotalRequiredWidth/2),a,l)){this.SetInitialMidParams();return}let h=this.TotalRequiredWidth,u=0,d=h/2;for(;h-u>zr.FeasibleWidthEpsilon;)this.SetRLParamsIfWidthIsFeasible(r.mul(d/2),a,l)?u=d:h=d,d=.5*(h+u);d<=zr.FeasibleWidthEpsilon&&(this.SetRLParamsIfWidthIsFeasible_(r.mul(zr.FeasibleWidthEpsilon),new g(0,0),a,l)||this.SetRLParamsIfWidthIsFeasible_(new g(0,0),r.mul(-zr.FeasibleWidthEpsilon),a,l))&&(d=2*zr.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,r){let s={par:0},o={par:0},a={par:0},l={par:0},h=this.TrimSegWithBoundaryCurves(D.mkPP(i.add(t),r.add(t)),o,a);return h==null||this.tightObstaclesInTheBoundingBox.find(u=>G.intersectionOne(h,u,!1)!=null)||(h=this.TrimSegWithBoundaryCurves(D.mkPP(i.add(e),r.add(e)),l,s),h==null)||this.tightObstaclesInTheBoundingBox.find(u=>G.intersectionOne(h,u,!1)!=null)?!1:(this.SourceBase.IsParent?(this.SourceBase.ParStart=o.par,this.SourceBase.ParEnd=l.par):(this.SourceBase.ParStart=l.par,this.SourceBase.ParEnd=o.par),this.TargetBase.IsParent?(this.TargetBase.ParStart=s.par,this.TargetBase.ParEnd=a.par):(this.TargetBase.ParStart=a.par,this.TargetBase.ParEnd=s.par),!0)}SetInitialMidParams(){let t={par:0},e={par:0};this.TrimSegWithBoundaryCurves(D.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 r=G.getAllIntersections(t,this.SourceBase.Curve,!0);if(r.length===0)return i.par=0,e.par=0,null;let s;if(r.length===1?s=r[0]:this.SourceBase.IsParent?s=r[0].par0<r[1].par0?r[1]:r[0]:s=r[0].par0<r[1].par0?r[0]:r[1],r=G.getAllIntersections(t,this.TargetBase.Curve,!0),r.length===0)return i.par=0,e.par=0,null;let o;return r.length===1?o=r[0]:this.TargetBase.IsParent?o=r[0].par0>r[1].par0?r[1]:r[0]:o=r[0].par0>r[1].par0?r[0]:r[1],e.par=s.par1,i.par=o.par1,D.mkPP(s.x,o.x)}RotateBy(t,e,i,r,s){let o=t!==0||e!==0,a=i!==0||r!==0;o&&this.SourceBase.RotateBy(t,e,s),a&&this.TargetBase.RotateBy(i,r,s),this.UpdateSourceAndTargetBases(o,a)}UpdateSourceAndTargetBases(t,e){t&&this.UpdatePointsOnBundleBase(this.SourceBase),e&&this.UpdatePointsOnBundleBase(this.TargetBase),this.UpdateTangentsOnBases()}UpdateTangentsOnBases(){let t=this.TargetBase.length;for(let e=0;e<t;e++){let i=this.TargetBase.Points[e].sub(this.SourceBase.Points[t-1-e]),r=i.length;r>=x.tolerance&&(i=i.div(r),this.TargetBase.Tangents[e]=i,this.SourceBase.Tangents[t-1-e]=i.neg())}}UpdatePointsOnBundleBase(t){let e=t.length,i=t.Points,r=D.mkPP(t.EndPoint,t.StartPoint),s=1/this.TotalRequiredWidth,o=this.HalfWidthArray[0];i[0]=r.value(o*s);for(let a=1;a<e;a++)o+=this.HalfWidthArray[a-1]+this.HalfWidthArray[a],i[a]=r.value(o*s)}RotationIsLegal(t,e,i,r,s){if(!this.SourceBase.IsParent&&!this.TargetBase.IsParent){if(e!==0||i!==0){let o=this.SourceBase.RotateLeftPoint(e,s),a=this.TargetBase.RotateRigthPoint(i,s);if(!this.LineIsLegal(o,a))return!1}if(t!==0||r!==0){let o=this.SourceBase.RotateRigthPoint(t,s),a=this.TargetBase.RotateLeftPoint(r,s);if(!this.LineIsLegal(o,a))return!1}}else{if(e!==0||r!==0){let o=this.SourceBase.RotateLeftPoint(e,s),a=this.TargetBase.RotateLeftPoint(r,s);if(!this.LineIsLegal(o,a))return!1}if(t!==0||i!==0){let o=this.SourceBase.RotateRigthPoint(t,s),a=this.TargetBase.RotateRigthPoint(i,s);if(!this.LineIsLegal(o,a))return!1}}return!((t!==0||e!==0)&&!this.SourceBase.RelativeOrderOfBasesIsPreserved(t,e,s)||(i!==0||r!==0)&&!this.TargetBase.RelativeOrderOfBasesIsPreserved(i,r,s))}LineIsLegal(t,e){return this.tightObstaclesInTheBoundingBox.find(i=>G.intersectionOne(D.mkPP(t,e),i,!1)!=null)==null}},nu=class{get Segment(){return this.segment}set Segment(n){this.segment=n}constructor(n,t,e,i){this.Segment=n,this.Reversed=t,this.Index=e,this.BundleBase=i}value(n){return this.Reversed?this.Segment.value(this.Segment.parEnd-n):this.Segment.value(n)}},aS=class Et{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(let t of this.metroGraphData.Stations)t.BoundaryCurve==null&&(t.BoundaryCurve=Dt.mkCircle(t.Radius,t.Position));for(let t of this.metroGraphData.Stations)for(let e of t.Neighbors)if(t.SerialNumber<e.SerialNumber){let i=new ru(this.metroGraphData.RealEdgeCount(t,e),t.BoundaryCurve,t.Position,t.IsReal);t.BundleBases.set(e,i);let r=new ru(this.metroGraphData.RealEdgeCount(t,e),e.BoundaryCurve,e.Position,e.IsReal);e.BundleBases.set(t,r),G.PointRelativeToCurveLocation(e.Position,t.BoundaryCurve)!==0?(i.IsParent=!0,Dr(this.internalBases,t,i),Dr(this.externalBases,e,r)):G.PointRelativeToCurveLocation(t.Position,e.BoundaryCurve)!==0?(r.IsParent=!0,Dr(this.externalBases,t,i),Dr(this.internalBases,e,r)):(Dr(this.externalBases,t,i),Dr(this.externalBases,e,r));let s=this.metroGraphData.tightIntersections.ObstaclesToIgnoreForBundle(t,e),o=new oS(i,r,s,Array.from(this.metroOrdering.GetOrder(t,e)).map(a=>a.Width/2));i.OutgoingBundleInfo=r.IncomingBundleInfo=o,this.Bundles.push(o)}this.SetBundleBaseNeighbors()}SetBundleBaseNeighbors(){for(let t of this.externalBases.keys()){let e=this.externalBases.get(t);this.SortBundlesCounterClockwise(e),this.SetLeftRightBases(e)}for(let t of this.internalBases.keys()){let e=this.internalBases.get(t);this.SortBundlesCounterClockwise(e),this.SetLeftRightBases(e)}}SortBundlesCounterClockwise(t){if(t.length>2){let e=t[0].OppositeBase.Position,i=t[0].CurveCenter;t.sort((r,s)=>xr(e.sub(i),r.OppositeBase.Position.sub(i),s.OppositeBase.Position.sub(i)))}}SetLeftRightBases(t){let 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(let 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){let i=this.metroGraphData.PointToStations.get(e.prev.point),r=this.metroGraphData.PointToStations.get(e.point),s=this.metroGraphData.PointToStations.get(e.next.point),o=r.BundleBases.get(i),a=r.BundleBases.get(s),l=this.metroOrdering.GetLineIndexInOrder(i,r,t),h=this.metroOrdering.GetLineIndexInOrder(s,r,t),u=o.OrientedHubSegments[l]=new nu(null,!1,l,o),d=a.OrientedHubSegments[h]=new nu(null,!0,h,a);d.Other=u,u.Other=d}UpdateSourceAndTargetBases(){for(let t of this.Bundles)t.UpdateSourceAndTargetBases(!0,!0)}SetBasesRightLeftParamsToTheMiddles(){for(let t of this.Bundles){let 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){let r=t.Curve;if(r instanceof Dt){let o=r;if(o.isArc())return g.angle(o.aAxis,i.sub(e))}let s=G.getAllIntersections(r,D.mkPP(e,i),!0);for(let o of s){let a=o.x;if(a.sub(e).dot(a.sub(i))<=0)return o.par0}throw new Error}SetRightLeftParamsFeasiblySymmetrically(){for(let t of this.Bundles)t.SetParamsFeasiblySymmetrically(this.metroGraphData.TightTree)}AdjustStartEndParamsToAvoidBaseOverlaps(){for(let t of this.externalBases.values())this.AdjustCurrentBundleWidthsOnCurve(t);for(let t of this.internalBases.values())this.AdjustCurrentBundleWidthsOnCurve(t)}AdjustCurrentBundleWidthsOnCurve(t){let e=t.length;if(!(e<=1))for(let i=0;i<e;i++){let r=t[i],s=r.Next;this.ShrinkBasesToMakeTwoConsecutiveNeighborsHappy(r,s)}}ShrinkBasesToMakeTwoConsecutiveNeighborsHappy(t,e){let i=lS(t,e);if(i==null||lt(i.start,i.end))return;let r=i.rbaseMiddle,s=i.lbaseMiddle;if(r<s){let h=t;t=e,e=h}let o=t.Span,a=e.Span,l=(i.end*o+i.start*a)/(a+o);t.ParStart=t.AdjustParam(l+x.distanceEpsilon),e.ParEnd=e.AdjustParam(l-x.distanceEpsilon)}RegularCut(t,e,i,r,s,o){let a=(s*r+o*t)/(s+o),l=Math.min(e,r),h=Math.max(t,i);return a<h&&(a=h),a>l&&(a=l),a}static{this.Deltas=[[1,-1],[1,-1]]}static{this.SeparationCoeff=1}static{this.SqueezeCoeff=1}static{this.CenterCoeff=10}static{this.AssymetryCoeff=1}static{this.MaxIterations=200}static{this.MaxParameterChange=8/360}static{this.MinParameterChange=.1/360}static{this.CostThreshold=1e-5}static{this.CostDeltaThreshold=.01}RotateBundlesToDiminishCost(){let t=Et.MaxParameterChange,e={cost:this.Cost()},i=0;for(;i++<Et.MaxIterations;){let r=e.cost;if(this.RotateBundlesToDiminishCostOneIteration(t,e),t=this.UpdateParameterChange(t,r,e.cost),t<Et.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(let r of this.Bundles)this.fixedBundles.has(r)||(this.OptimizeBundle(r,t,e)?i=!0:this.fixedBundles.add(r));return i}OptimizeBundle(t,e,i){let r=this.CostBi(t);if(r<Et.CostThreshold)return!1;let s=0,o=-1,a=-1;for(let l=0;l<Et.Deltas.length-1;l++){let h=this.DeltaWithChangedAngles(Et.Deltas[l][0],Et.Deltas[l][1],0,0,t,r,e);h>Et.CostDeltaThreshold&&h>s&&(a=l,o=Et.Deltas.length-1,s=h),h=this.DeltaWithChangedAngles(0,0,Et.Deltas[l][0],Et.Deltas[l][1],t,r,e),h>Et.CostDeltaThreshold&&h>s&&(a=Et.Deltas.length-1,o=l,s=h)}return s<Et.CostDeltaThreshold?!1:(i.cost-=s,t.RotateBy(Et.Deltas[a][0],Et.Deltas[a][1],Et.Deltas[o][0],Et.Deltas[o][1],e),!0)}DeltaWithChangedAngles(t,e,i,r,s,o,a){if(!s.RotationIsLegal(t,e,i,r,a))return 0;s.RotateBy(t,e,i,r,a);let l=this.CostBN(s,o);return s.RotateBy(t*-1,e*-1,i*-1,r*-1,a),o-l}CostBi(t){return Et.SeparationCoeff*this.SeparationCost(t)+(Et.SqueezeCoeff*this.SqueezeCost(t)+(Et.AssymetryCoeff*this.AssymetryCost(t)+Et.CenterCoeff*this.CenterCostBi(t)))}CostBN(t,e){let i=0;return i=i+Et.CenterCoeff*this.CenterCostBi(t),i>e||(i=i+Et.SeparationCoeff*this.SeparationCost(t),i>e)||(i=i+Et.SqueezeCoeff*this.SqueezeCost(t),i>e)||(i=i+Et.AssymetryCoeff*this.AssymetryCost(t)),i}SqueezeCost(t){let e=t.TargetBase.MidPoint.sub(t.SourceBase.MidPoint).normalize().rotate90Ccw(),i=Math.abs(t.SourceBase.StartPoint.sub(t.SourceBase.EndPoint).dot(e)),r=Math.abs(t.TargetBase.StartPoint.sub(t.TargetBase.EndPoint).dot(e)),s=Math.abs(t.TotalRequiredWidth-i)/t.TotalRequiredWidth,o=Math.abs(t.TotalRequiredWidth-r)/t.TotalRequiredWidth,a=Math.abs(i-r)/t.TotalRequiredWidth;return Math.exp(s*10)-1+(Math.exp(o*10)-1)+a}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;let e=t.ParMid,i=Math.min(t.InitialMidParameter,e),r=Math.max(t.InitialMidParameter,e),s=Math.min(r-i,i+(Xi(t.Curve)-r));return t.CurveCenter.equal(t.Position)||t.IsParent?25*(s*s):500*(s*s)}AssymetryCost(t){return this.GetAssymetryCostForBase(t.SourceBase)+this.GetAssymetryCostForBase(t.TargetBase)}GetAssymetryCostForBase(t){if(t.BelongsToRealNode)return 0;let e=t.OppositeBase.BelongsToRealNode?200:500,i=0;for(let r of t.OrientedHubSegments){let s=r.Index,o=r.Other.Index,a=t.Points[s],l=t.Tangents[s],h=r.Other.BundleBase,u=h.Points[o],d=h.Tangents[o],c=t.Count+h.Count;i+=this.GetAssymetryCostOnData(a,l,u,d,e)/c}return i}GetAssymetryCostOnData(t,e,i,r,s){let o=t.sub(i);if(o.length<x.distanceEpsilon)return 0;let l=e.add(r).dot(o),h=g.crossProduct(o,e),u=g.crossProduct(o,r),d=h-u,c=l*l+d*d,f=h*h+u*u;return 10*c+s*f}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){let i=t.Curve,r=this.IntervalsOverlapLength(t.ParStart,t.ParEnd,e.ParStart,e.ParEnd,i),s=Math.min(t.Span,e.Span);return Math.exp(r/(s*10))-1}IntervalsOverlapLength(t,e,i,r,s){let o=s.parStart,a=s.parEnd;return t<e?i<r?this.IntersectRegularIntervals(t,e,i,r):this.IntersectRegularIntervals(t,e,i,a)+this.IntersectRegularIntervals(t,e,o,r):i<r?this.IntersectRegularIntervals(t,a,i,r)+this.IntersectRegularIntervals(o,e,i,r):this.IntersectRegularIntervals(t,a,i,a)+this.IntersectRegularIntervals(o,e,o,r)}IntersectRegularIntervals(t,e,i,r){let s=Math.max(t,i),o=Math.min(e,r);return s<o?o-s:0}Cost(){let t=0;for(let e of this.Bundles){let i=Et.SeparationCoeff*this.SeparationCost(e),r=Et.AssymetryCoeff*this.AssymetryCost(e),s=Et.SqueezeCoeff*this.SqueezeCost(e),o=Et.CenterCoeff*this.CenterCostBi(e);t+=(i+r)/2+s+o}return t}};function lS(n,t){let e=Xi(n.Curve),i=n.ParEnd,r=n.ParStart<n.ParEnd?n.ParStart:n.ParStart-e,s=t.ParEnd,o=t.ParStart<t.ParEnd?t.ParStart:t.ParStart-e;i>s?i-o>e&&(o+=e,s+=e):s-r>e&&(r+=e,i+=e);let a=Math.min(i,s),l=Math.max(r,o);return l<=a?{start:l,end:a,rbaseMiddle:(r+i)/2,lbaseMiddle:(o+s)/2}:null}var hS=class{constructor(){this.Metrolines=new Array}Add(n){this.Metrolines.push(n)}},uS=class qa{constructor(t){this.Metrolines=t,this.BuildOrder()}*GetOrder(t,e){let i=new Pe(t.Position,e.Position),r=this.bundles.get(i).Metrolines;if(t.Position===i.first)for(let s=0;s<r.length;s++)yield r[s];else for(let s=r.length-1;s>=0;s--)yield r[s]}GetLineIndexInOrder(t,e,i){let r=new Pe(t.Position,e.Position),s=t.Position!==r.first,o=this.bundles.get(r).LineIndexInOrder;return s?o.size-1-o.get(i):o.get(i)}BuildOrder(){this.bundles=new jn;for(let t of this.Metrolines)for(let e=t.Polyline.startPoint;e.next!=null;e=e.next){let i=new Pe(e.point,e.next.point),r=this.bundles.get(i);r||this.bundles.set(i,r=new hS),r.Add(t)}for(let t of this.bundles)this.BuildOrderPP(t[0],t[1])}BuildOrderPP(t,e){if(!e.orderFixed){e.Metrolines.sort((i,r)=>this.CompareLines(i,r,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,r){let s={polyPoint:null,next:null,prev:null};this.FindStationOnLine(i,r,t,s);let o=s.polyPoint,a=s.next,l=s.prev;this.FindStationOnLine(i,r,e,s);let h=s.polyPoint,u=s.next,d=s.prev,c=o,f=h,m,P;for(;(P=l(c))!=null&&(m=d(f))!=null&&P.point.equal(m.point);){let v=new Pe(P.point,c.point);if(this.bundles.get(v).orderFixed)return this.CompareOnFixedOrder(v,t,e,!P.point.equal(v.first));c=P,f=m}if(P!=null&&m!=null){let v=c.point;return-qa.IsLeft(a(c).point.sub(v),P.point.sub(v),m.point.sub(v))}for(c=o,f=h;(P=a(c))!=null&&(m=u(f))!=null&&P.point.equal(m.point);){let v=new Pe(P.point,c.point);if(this.bundles.get(v).orderFixed)return this.CompareOnFixedOrder(v,t,e,!c.point.equal(v.first));c=P,f=m}if(P!=null&&m!=null){let v=c.point;return qa.IsLeft(l(c).point.sub(v),P.point.sub(v),m.point.sub(v))}return Mt(t.Index,e.Index)}CompareOnFixedOrder(t,e,i,r){let s=this.bundles.get(t).LineIndexInOrder;return(r?-1:1)*Mt(s.get(e),s.get(i))}FindStationOnLine(t,e,i,r){for(let s=i.Polyline.startPoint;s.next!=null;s=s.next){if(s.point.equal(t)&&s.next.point.equal(e)){r.next=o=>o.next,r.prev=o=>o.prev,r.polyPoint=s;return}if(s.point.equal(e)&&s.next.point.equal(t)){r.next=o=>o.prev,r.prev=o=>o.next,r.polyPoint=s.next;return}}throw new Error}static IsLeft(t,e,i){return xr(t,e,i)}},Ua=class At extends Nt{constructor(t,e){super(null),this.metroGraphData=t,this.bundlingSettings=e}run(){this.CreateMetroOrdering(),this.InitRadii(),this.FinalizePaths()}InitRadii(){new er(this.metroGraphData,this.bundlingSettings).CreateNodeRadii()}CreateMetroOrdering(){this.metroOrdering=new uS(this.metroGraphData.Metrolines)}FinalizePaths(){this.CreateBundleBases(),this.CreateSegmentsInsideHubs(),this.CreateCurves()}CreateBundleBases(){new aS(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){let i=new G,r=At.FindCurveStart(this.metroGraphData,this.metroOrdering,t),s=At.HubSegsOfLine(this.metroGraphData,this.metroOrdering,t);for(let o of s)o!=null&&(i.addSegment(D.mkPP(r,o.start)),i.addSegment(o),r=o.end);i.addSegment(D.mkPP(r,At.FindCurveEnd(this.metroGraphData,this.metroOrdering,t))),e.curve=i}static FindCurveStart(t,e,i){let r=t.PointToStations.get(i.Polyline.startPoint.point),s=t.PointToStations.get(i.Polyline.startPoint.next.point),o=r.BundleBases.get(s),a=o.IsParent?e.GetLineIndexInOrder(r,s,i):e.GetLineIndexInOrder(s,r,i);return o.Points[a]}static FindCurveEnd(t,e,i){let r=t.PointToStations.get(i.Polyline.endPoint.prev.point),s=t.PointToStations.get(i.Polyline.endPoint.point),o=s.BundleBases.get(r),a=o.IsParent?e.GetLineIndexInOrder(s,r,i):e.GetLineIndexInOrder(r,s,i);return o.Points[a]}static*HubSegsOfLine(t,e,i){for(let r=i.Polyline.startPoint.next;r.next!=null;r=r.next)yield At.SegOnLineVertex(t,e,i,r)}static SegOnLineVertex(t,e,i,r){let s=t.PointToStations.get(r.prev.point),o=t.PointToStations.get(r.point),a=o.BundleBases.get(s),l=e.GetLineIndexInOrder(s,o,i);if(a.OrientedHubSegments[l]==null||a.OrientedHubSegments[l].Segment==null){let h=t.PointToStations.get(r.next.point),u=o.BundleBases.get(h),d=e.GetLineIndexInOrder(h,o,i);return D.mkPP(a.Points[l],u.Points[d])}return a.OrientedHubSegments[l].Segment}CreateSegmentsInsideHubs(){for(let 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){let i=this.metroGraphData.PointToStations.get(e.prev.point),r=this.metroGraphData.PointToStations.get(e.point),s=this.metroGraphData.PointToStations.get(e.next.point),o=r.BundleBases.get(i),a=r.BundleBases.get(s),l=this.metroOrdering.GetLineIndexInOrder(i,r,t),h=this.metroOrdering.GetLineIndexInOrder(s,r,t),u=this.bundlingSettings.UseCubicBezierSegmentsInsideOfHubs?At.StandardBezier(o.Points[l],o.Tangents[l],a.Points[h],a.Tangents[h]):At.BiArc(o.Points[l],o.Tangents[l],a.Points[h],a.Tangents[h]);o.OrientedHubSegments[l].Segment=u,a.OrientedHubSegments[h].Segment=u}static ShowHubs(t,e,i,r,s=[]){let o=At.GetAllDebugCurves(e,t);i!=null&&o.push(It.mkDebugCurveTWCI(255,1,"red",ce.mkDiamond(5,25,i.Position))),o=o.concat(s)}static GetAllDebugCurves(t,e){return At.GraphNodes(e).concat(At.VertexDebugCurves(t,e)).concat(At.DebugEdges(e))}static DebugEdges(t){return t.Edges.map(e=>It.mkDebugCurveTWCI(40,.1,"gray",e.curve))}static VertexDebugCurves(t,e){return At.DebugCircles(e).concat(At.DebugHubBases(e)).concat(At.DebugSegs(e)).concat(At.BetweenHubs(t,e))}static BetweenHubs(t,e){let i=[];for(let r of e.Metrolines){let s=At.GetInterestingSegs(e,t,r),o=At.GetMonotoneColor(r.Polyline.start,r.Polyline.end,s);for(let a of s)i.push(It.mkDebugCurveTWCI(100,r.Width,o,D.mkPP(a[0],a[1])))}return i}static GetInterestingSegs(t,e,i){let r=new Array;if(t.Stations.length===0||t.Stations[0].BundleBases==null||t.Stations[0].BundleBases.size===0)return[];let s=At.FindCurveStart(t,e,i),o=At.HubSegsOfLine(t,e,i);for(let a of o)a!=null&&(r.push([s,a.start]),s=a.end);return r.push([s,At.FindCurveEnd(t,e,i)]),r}static GetMonotoneColor(t,e,i){return"green"}static DebugHubBases(t){let e=new Array;for(let i of t.Stations)for(let r of i.BundleBases.values())e.push(It.mkDebugCurveTWCI(100,1,"red",D.mkPP(r.EndPoint,r.StartPoint)));return e}static DebugCircles(t){return t.Stations.map(e=>It.mkDebugCurveTWCI(100,.1,"blue",ce.mkCircle(e.Radius,e.Position)))}static DebugSegs(t){let e=new Array;for(let i of t.VirtualStations())for(let r of i.BundleBases.values())for(let s of r.OrientedHubSegments)if(s!=null)if(s.Segment==null){let o=s.Other.BundleBase,a=s.Index,l=s.Other.Index;e.push(D.mkPP(r.Points[a],o.Points[l]))}else e.push(s.Segment);return e.map(i=>It.mkDebugCurveTWCI(100,.01,"green",i))}static GraphNodes(t){return t.Edges.map(e=>e.sourcePort.Curve).concat(t.Edges.map(e=>e.targetPort.Curve)).map(e=>It.mkDebugCurveTWCI(40,1,"black",e))}static BiArc(t,e,i,r){let s=t.sub(i);if(s.length<x.distanceEpsilon)return null;let o=s.dot(e.sub(r)),a=-e.dot(r);if(e.dot(i.sub(t))<=0&&e.dot(r)<=0)return At.StandardBezier(t,e,i,r);let l=2*(a-1),h=2*o,u=s.dot(s),d;if(Math.abs(l)<x.distanceEpsilon)if(Math.abs(h)>x.distanceEpsilon)d=-u/h;else return null;else{let C=h*h-4*l*u;C<0&&(C=0),C=Math.sqrt(C),d=(-h+C)/(2*l),d<0&&(d=(-h-C)/(2*l))}let c=t.add(e.mul(d)),f=i.add(r.mul(d)),m=g.middle(c,f),P=g.getTriangleOrientation(t,c,m),v=g.getTriangleOrientation(m,f,i);if(P!==v)return At.StandardBezier(t,e,i,r);let b=new G;return b.addSegs([At.ArcOn(t,c,m),At.ArcOn(m,f,i)]),b}static ArcOn(t,e,i){let r={center:null};if(Math.abs(g.signedDoubledTriangleArea(t,e,i))<1e-4||!At.FindArcCenter(t,e,i,r))return D.mkPP(t,i);let s=r.center,o=ht(t,s);if(ht(t,e)/o<1e-4)return D.mkPP(t,i);let a=t.sub(s),l=Math.atan2(a.y,a.x),h=i.sub(s),u=Math.atan2(h.y,h.x),d=u-l;if(d<0&&(d+=2*Math.PI,u+=2*Math.PI),d<=Math.PI)return new Dt(l,u,new g(o,0),new g(0,o),s);for(u>2*Math.PI&&(u-=2*Math.PI),l=Math.PI-l,u=Math.PI-u,l<0&&(l+=2*Math.PI);u<l;)u+=2*Math.PI;return d=u-l,new Dt(l,u,new g(-o,0),new g(0,o),s)}static FindArcCenter(t,e,i,r){let s=e.sub(t).rotate90Cw(),o=e.sub(i).rotate90Cw();return r.center=g.lineLineIntersection(t,t.add(s),i,i.add(o)),r.center!=null}static StandardBezier(t,e,i,r){let s=ht(t,i)/4;return Ke.mkBezier([t,t.add(e.mul(s)),i.add(r.mul(s)),i])}FanBezierSegs(){let t=!0,e=5,i=0;for(;t&&i++<e;){t=!1;for(let r of this.metroGraphData.Stations)for(let s of r.BundleBases.values())t||=this.FanEdgesOfHubSegment(s)}}FanEdgesOfHubSegment(t){let e=!1;for(let i=0;i<t.Count-1;i++)e||=this.FanCouple(t,i,t.CurveCenter,t.Curve.boundingBox.diagonal/2);return e}FanCouple(t,e,i,r){let s=t.OrientedHubSegments[e],o=t.OrientedHubSegments[e+1];if(s==null||Cu(s.Segment.start,s.Segment.end,o.Segment.start,o.Segment.end)||g.getTriangleOrientation(s.value(0),s.value(.5),s.value(1))!=g.getTriangleOrientation(o.value(0),o.value(.5),o.value(1)))return!1;let a=this.BaseLength(s),l=this.BaseLength(o);return Math.abs(a-l)<x.intersectionEpsilon?!1:a>l?this.AdjustLongerSeg(s,o,i,r):this.AdjustLongerSeg(o,s,i,r)}AdjustLongerSeg(t,e,i,r){let s=t.value(0).sub(e.value(0)),o=t.value(1).sub(e.value(1)),a=Math.min(s.length,o.length),l=e.value(.5),h=Math.max(s.length,o.length);return this.NicelyAligned(t.Segment,s,o,l,a,h)===0?!1:this.FitLonger(t,s,o,l,a,h,i,r)}static{this.SqueezeBound=.2}FitLonger(t,e,i,r,s,o,a,l){let h=t.Segment,u=h.start,d=h.end,c=0,f=10,m=h.start.mul(1-At.SqueezeBound).add(h.B(1).mul(At.SqueezeBound)),P=h.end.mul(1-At.SqueezeBound).add(h.B(2).mul(At.SqueezeBound)),v=h.B(1).mul(2).sub(h.start),b=h.B(2).mul(2).sub(h.end),C={highP:v};this.PullControlPointToTheCircle(h.start,C,a,l),v=C.highP;let E=this.NicelyAligned(h,e,i,r,s,o);do{if(E===-1){let w=g.middle(h.B(1),m),F=g.middle(h.B(2),P);v=h.B(1),b=h.B(2),h=new Ke(u,w,F,d)}else{let w=g.middle(h.B(1),v),F=(h.B(2),b);m=h.B(1),P=h.B(2),h=new Ke(u,w,F,d)}if((E=this.NicelyAligned(h,e,i,r,s,o))===0)return t.Segment=h,t.Other.Segment=h,!0;if(c++>f)return!1}while(!0)}PullControlPointToTheCircle(t,e,i,r){let s=g.ProjectionToLine(t,e.highP,i),o=Math.sqrt(r*r-s.sub(i).lengthSquared),a=e.highP.sub(s),l=a.length;l>o&&(e.highP=s.add(a.mul(o/l)))}NicelyAligned(t,e,i,r,s,o){let a=t.value(.5).sub(r),l=a.length;return e.dot(a)<0||i.dot(a)<0||l<s-.001?1:l>o+.001?-1:0}BaseLength(t){return t.value(0).sub(t.value(1)).lengthSquared}},On=class Xe{constructor(t,e){this.stepsWithProgress=0,this.metroGraphData=t,this.bundlingSettings=e,this.costCalculator=new Te(this.metroGraphData,this.bundlingSettings),this.cache=new Kd(this.metroGraphData,this.bundlingSettings,this.costCalculator,this.metroGraphData.cdt)}static FixRouting(t,e){return this.FixRoutingMBP(t,e,null)}static FixRoutingMBP(t,e,i){return new Xe(t,e).FixRoutingP(i)}static{this.MaxIterations=100}static{this.MaxStep=50}static{this.MinStep=1}static{this.MinRelativeChange=5e-4}FixRoutingP(t){this.stationsForOptimizations=this.GetStationsForOptimizations(t),this.cache.InitializeCostCache();let e=Xe.MaxStep,i=Number.POSITIVE_INFINITY,r=this.metroGraphData.VirtualStations().map(o=>o.Position),s=0;for(;s++<Xe.MaxIterations;){let o=this.TryMoveStations();if(s<=1&&!o)return!1;if(!o)break;let a=i;i=Te.Cost(this.metroGraphData,this.bundlingSettings),e=this.UpdateMaxStep(e,a,i);let l=r;if(r=this.metroGraphData.VirtualStations().map(h=>h.Position),e<Xe.MinStep||this.Converged(e,l,r))break}return!0}static stationsArePositionedCorrectly(t){for(let e of t.VirtualEdges())if(!this.edgeIsPositionedCorrectly(e,t))return!1;return!0}static edgeIsPositionedCorrectly(t,e){let i=t[0],r=t[1],s=e.looseIntersections.ObstaclesToIgnoreForBundle(i,r),o=D.mkPP(i.Position,r.Position),a=Array.from(e.looseIntersections.obstacleTree.GetNodeItemsIntersectingRectangle(o.boundingBox)).filter(l=>!s.has(l)).filter(l=>G.CurvesIntersect(o,l));return a.length>0?(Ua.ShowHubs(e,null,null,"./tmp/badcross.svg",[It.mkDebugCurveTWCI(200,1,"Brown",o),It.mkDebugCurveTWCI(200,1,"Red",ce.mkCircle(2,i.Position)),It.mkDebugCurveTWCI(200,1,"Blue",ce.mkCircle(5,r.Position)),It.mkDebugCurveTWCI(100,1,"Blue",ce.mkCircle(5,r.Position))].concat(a.map(l=>It.mkDebugCurveTWCI(100,1,"Pink",l)))),!1):!0}GetStationsForOptimizations(t){if(t==null)return new Set(this.metroGraphData.VirtualStations());{let e=new Set;for(let i of t){let r=this.metroGraphData.PointToStations.get(i);r&&!r.IsReal&&e.add(r)}return e}}Converged(t,e,i){let r=0,s=0;for(let o=0;o<e.length;o++){let a=e[o].x-i[o].x,l=e[o].y-i[o].y;s+=a*a+l*l,r+=e[o].x*e[o].x+e[o].y*e[o].y}return Math.sqrt(s/r)<Xe.MinRelativeChange}UpdateMaxStep(t,e,i){return i+1<e?(this.stepsWithProgress++,this.stepsWithProgress>=5&&(this.stepsWithProgress=0,t=Math.min(Xe.MaxStep,t/.8))):(this.stepsWithProgress=0,t*=.8),t}TryMoveStations(){let t=!1,e=new Set;for(let i of this.stationsForOptimizations)if(this.TryMoveStation(i)){t=!0,e.add(i);for(let r of i.Neighbors)r.IsReal||e.add(r)}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<Xe.MinStep&&(e=dS(),i=this.BuildStepLength(t,e),i<Xe.MinStep))return!1;let r=e.mul(i).addInPlace(t.Position);return this.metroGraphData.PointToStations.has(r)||!this.moveIsLegalForAdjacentBundles(t,r)?!1:(this.metroGraphData.MoveNode(t,r),this.cache.UpdateCostCache(t),!0)}moveIsLegalForAdjacentBundles(t,e){for(let i of this.metroGraphData.looseIntersections.obstacleTree.AllHitItems(it.mkOnPoints([e]),r=>G.PointRelativeToCurveLocation(e,r)!==0))if(t.getELP().has(i)===!1)return!1;for(let i of t.Neighbors){let r=this.metroGraphData.looseIntersections.ObstaclesToIgnoreForBundle(i,t);if(!this.metroGraphData.cdtIntersections.EdgeIsLegal_(i.Position,e,i.cdtTriangle,r))return!1}return!0}BuildDirection(t){let e=this.BuildForceForInk(t);return e.addInPlace(this.BuildForceForPathLengths(t)),e.addInPlace(this.BuildForceForRadius(t)),e.addInPlace(this.BuildForceForBundle(t)),e.length<.1?new g(0,0):e.normalizeInPlace()}BuildStepLength(t,e){let i=new g(0,0),r=Xe.MinStep;i.copyFrom(e).mulInPlace(r).addInPlace(t.Position);let s=this.CostGain(t,i);if(s<.01)return 0;for(;2*r<=Xe.MaxStep;){i.copyFrom(e).mulInPlace(r*2).addInPlace(t.Position);let o=this.CostGain(t,i);if(o<=s)break;r*=2,s=o}return r}CostGain(t,e){let i=this.costCalculator.RadiusGain(t,e);if(i<-12345678)return-12345678;let r=this.costCalculator.BundleGain(t,e);if(r<-12345678)return-12345678;let s=this.costCalculator.InkGain(t,e),o=this.costCalculator.PathLengthsGain(t,e);return i+s+o+r}BuildForceForInk(t){let e=new g(0,0),i=new g(0,0);for(let r of t.Neighbors)i.copyFrom(r.Position).subInPlace(t.Position).normalizeInPlace(),e.addInPlace(i);return e.mulInPlace(this.bundlingSettings.InkImportance)}BuildForceForPathLengths(t){let e=new g(0,0),i=new g(0,0);for(let r of this.metroGraphData.MetroNodeInfosOfNode(t)){let s=r.Metroline,o=r.PolyPoint.next.point,a=r.PolyPoint.prev.point;i.copyFrom(o).subInPlace(t.Position),e.addInPlace(i.divInPlace(i.length*s.IdealLength)),i.copyFrom(a).subInPlace(t.Position),e.addInPlace(i.divInPlace(i.length*s.IdealLength))}return e.mulInPlace(this.bundlingSettings.PathLengthImportance)}BuildForceForRadius(t){let e=new g(0,0),i=new g(0,0),r=t.cachedIdealRadius,s={touchedObstacles:[]};if(!this.metroGraphData.looseIntersections.HubAvoidsObstaclesSPNBA(t,t.Position,r,s))throw Ua.ShowHubs(this.metroGraphData,null,t,"./tmp/hubs.svg",[It.mkDebugCurveTWCI(255,1,"Brown",uo.containingPoly),It.mkDebugCurveTWCI(100,1,"Blue",ce.mkCircle(r,t.Position))]),new Error;for(let o of s.touchedObstacles){let a=2*(1-ht(o[1],t.Position)/r);i.copyFrom(t.Position).subInPlace(o[1]).normalizeInPlace().mulInPlace(a),e.addInPlace(i)}return e.mulInPlace(this.bundlingSettings.HubRepulsionImportance)}BuildForceForBundle(t){let e=new g(0,0),i=new g(0,0);for(let r of t.Neighbors){let s=this.metroGraphData.GetWidthSSN(t,r,this.bundlingSettings.EdgeSeparation),o={closestDist:[]},a=this.metroGraphData.cdtIntersections.BundleAvoidsObstacles(t,r,t.Position,r.Position,s/2,o);for(let l of o.closestDist){let h=2*(1-ht(l[0],l[1])/(s/2));i.copyFrom(l[0]).subInPlace(l[1]).normalizeInPlace().negInPlace().mulInPlace(h),e.addInPlace(i)}}return e.mulInPlace(this.bundlingSettings.BundleRepulsionImportance)}};function dS(){return new g(1+2*Tr(),1+2*Tr())}var cS=class qr{constructor(t,e){this.metroGraphData=t,this.bundlingSettings=e}static FixRouting(t,e){let i=new qr(t,e);i.GlueConflictingStations(),i.UnglueEdgesFromBundleToSaveInk(!0);let r=0,s=10;for(;++r<s;){let o=i.GlueConflictingStations();if(o||=i.RelaxConstrainedEdges(),o||=r<=3&&i.UnglueEdgesFromBundleToSaveInk(!1),o||=i.GlueCollinearNeighbors(r),o||=r===3&&i.RemoveDoublePathCrossings(),!o)break}for(t.cdtIntersections.ComputeForcesForBundles=!0,i.RemoveDoublePathCrossings(),i.UnglueEdgesFromBundleToSaveInk(!0);i.GlueConflictingStations(););t.Initialize(!0)}GlueConflictingStations(){let t=this.GetCirclesHierarchy();if(t==null)return!1;let e=new Map,i=new Set;if(de(t,t,(s,o)=>this.TryToGlueStations(s,o,e,i)),e.size===0)return!1;for(let s=0;s<this.metroGraphData.Edges.length;s++)this.RegenerateEdge(e,s);let r=new Zt;for(let s of i){r.add(s.Position);for(let o of s.Neighbors)o.IsReal||r.add(o.Position)}return this.metroGraphData.Initialize(!1),On.FixRoutingMBP(this.metroGraphData,this.bundlingSettings,r),!0}GetCirclesHierarchy(){for(let i of this.metroGraphData.VirtualStations())i.Radius=this.GetCurrentHubRadius(i);let t=this.metroGraphData.VirtualStations().map(e);return qt(t);function e(i){let r=i.Position,s=Math.max(i.Radius,5),o=new g(s,s),a=it.mkPP(r.add(o),r.sub(o));return ne(i,a)}}GetCurrentHubRadius(t){if(t.IsReal)return t.BoundaryCurve.boundingBox.diagonal/2;{let e=t.cachedIdealRadius,i=this.metroGraphData.looseIntersections.GetMinimalDistanceToObstacles(t,t.Position,e);for(let r of t.Neighbors)i=Math.min(i,t.Position.sub(r.Position).length);return i}}TryToGlueStations(t,e,i,r){if(!qn(t.getELP(),e.getELP()))return!1;let s=t.Position.sub(e.Position).length,o=Math.max(t.Radius,5),a=Math.max(e.Radius,5);s>=o+a||this.TryGlueOrdered(t,e,r,i)||this.TryGlueOrdered(e,t,r,i)}TryGlueOrdered(t,e,i,r){return!r.has(t)&&!i.has(t)&&this.StationGluingIsAllowed(t,e,r)?(this.Map(t,e,i,r),!0):!1}Map(t,e,i,r){r.set(t,e),i.add(e)}StationGluingIsAllowed(t,e,i){for(let r of t.Neighbors){let s=qr.Glued(r,i),o=this.metroGraphData.looseIntersections.ObstaclesToIgnoreForBundle(s,t);if(!this.metroGraphData.cdtIntersections.EdgeIsLegalSSPPS(s,e,o))return!1}return!(this.ComputeCostDeltaAfterStationGluing(t,e,i)<0)}ComputeCostDeltaAfterStationGluing(t,e,i){let r=t.Position.sub(e.Position).length;if(t.Radius>=r||e.Radius>=r)return 1;let s=0,o=this.metroGraphData.Ink,a=this.metroGraphData.Ink-e.Position.sub(t.Position).length;for(let l of t.Neighbors){let h=qr.Glued(l,i);a-=h.Position.sub(t.Position).length,a+=this.metroGraphData.RealEdgeCount(h,e)===0?h.Position.sub(e.Position).length:0}s+=Te.InkError(o,a,this.bundlingSettings);for(let l of this.metroGraphData.MetroNodeInfosOfNode(t)){let h=l.Metroline.Length,u=l.Metroline.Length,d=l.PolyPoint,c=d.prev,f=d.next;u-=c.point.sub(t.Position).length+f.point.sub(t.Position).length,u+=c.point.sub(e.Position).length+f.point.sub(e.Position).length,s+=Te.PathLengthsError(h,u,l.Metroline.IdealLength,this.bundlingSettings)}return s}RegenerateEdge(t,e){let i=this.metroGraphData.Metrolines[e].Polyline;for(let o of i)if(!this.metroGraphData.PointToStations.has(o))return;let r=!1;for(let o of i)if(t.has(this.metroGraphData.PointToStations.get(o))){r=!0;break}if(!r)return;let s=Array.from(i).map(o=>this.metroGraphData.PointToStations.get(o));this.metroGraphData.Edges[e].curve=et.mkFromPoints(qr.GluedPolyline(s,t))}static GluedPolyline(t,e){let i,r=new eS.Stack;r.push(t[0]);let s=new Set;for(i=1;i<t.length-1;i++){let o=qr.Glued(t[i],e);if(s.has(o)){for(;r.top!==o;)s.delete(r.pop());continue}g.closeDistEps(o.Position,r.top.Position)||(s.add(o),r.push(o))}return r.push(t[i]),Array.from(r).reverse().map(o=>o.Position)}static Glued(t,e){return e.get(t)??t}UnglueEdgesFromBundleToSaveInk(t){let e=new jn;this.ink=this.metroGraphData.Ink,this.polylineLength=new Map;for(let s of this.metroGraphData.Metrolines){this.polylineLength.set(s,s.Length);for(let o=s.Polyline.startPoint;o.next!=null;o=o.next){let a=new Pe(o.point,o.next.point);Eu(e,a,s)}}let i=new Zt,r=!1;for(let s of this.metroGraphData.Metrolines){let o=Ri(this.metroGraphData.PointToStations.get(s.Polyline.start).getELP(),this.metroGraphData.PointToStations.get(s.Polyline.end).getELP());this.TrySeparateOnPolyline(s,e,i,o)&&(r=!0)}return r&&this.metroGraphData.Initialize(!1),(t||r)&&On.FixRoutingMBP(this.metroGraphData,this.bundlingSettings,t?null:i),r}TrySeparateOnPolyline(t,e,i,r){let s=!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,r)&&(o=!0);o&&(s=!0)}return s}TryShortcutPolypoint(t,e,i,r){return this.SeparationShortcutAllowed(t,e,r)?(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){let r=t.point,s=t.next.point,o=t.next.next.point,a=this.metroGraphData.PointToStations.get(r),l=this.metroGraphData.PointToStations.get(s),h=this.metroGraphData.PointToStations.get(o),u=ir(a.getELP(),h.getELP()),d=Df([i,l.getELP(),u]);return!(!this.metroGraphData.cdtIntersections.EdgeIsLegalSSPPS(a,h,d)||this.GetInkgain(t,e,r,s,o)<0)}GetInkgain(t,e,i,r,s){let[o,a,l]=this.FindPolylines(t,e),h=0,u=this.ink,d=this.ink,c=i.sub(r).length,f=r.sub(s).length,m=i.sub(s).length;o.size===l.size&&(d-=c),a.size===l.size&&(d-=f);let P=e.get(new Pe(i,s));(!P||P.size===0)&&(d+=m),h+=Te.InkError(u,d,this.bundlingSettings);for(let F of l){let V=this.polylineLength.get(F),q=V-(c+f-m);h+=Te.PathLengthsError(V,q,F.IdealLength,this.bundlingSettings)}let v=this.GetCurrentHubRadius(this.metroGraphData.PointToStations.get(i)),b=this.metroGraphData.GetWidthAN(Array.from(l),this.bundlingSettings.EdgeSeparation),C=this.metroGraphData.GetWidthAN(Array.from(Zr(o,l)),this.bundlingSettings.EdgeSeparation),E=er.GetMinRadiusForTwoAdjacentBundlesNPPPNNB(v,i,s,r,b,C,this.bundlingSettings);E>v&&(h-=Te.RError(E,v,this.bundlingSettings)),v=this.GetCurrentHubRadius(this.metroGraphData.PointToStations.get(s));let w=this.metroGraphData.GetWidthAN(Array.from(Zr(a,l)),this.bundlingSettings.EdgeSeparation);return E=er.GetMinRadiusForTwoAdjacentBundlesNPPPNNB(v,s,r,i,w,b,this.bundlingSettings),E>v&&(h-=Te.RError(E,v,this.bundlingSettings)),h}RemoveShortcuttedPolypoint(t,e){let i=t.point,r=t.next.point,s=t.next.next.point,[o,a,l]=this.FindPolylines(t,e),h=ht(i,r),u=ht(r,s),d=ht(i,s);o.size===l.size&&(this.ink-=h),a.size===l.size&&(this.ink-=u);let c=e.get(new Pe(i,s));(!c||c.size===0)&&(this.ink+=d);for(let f of l){let m=this.polylineLength.get(f);this.polylineLength.set(f,m-(h+u-d))}for(let f of l){let m=Array.from(f.Polyline.polylinePoints()).find(P=>P.point.equal(r));this.RemovePolypoint(m),Sh(e,[i,r],f),Sh(e,[r,s],f),Mf(e,[i,s],f)}}FindPolylines(t,e){let i=t.point,r=t.next.point,s=t.next.next.point,o=e.getPP(i,r),a=e.getPP(r,s),l=Ri(o,a);return[o,a,l]}RemovePolypoint(t){let e=t.prev,i=t.next;e.next=i,i.prev=e}GlueCollinearNeighbors(t){let e=new Zt,i=!1;for(let r of this.metroGraphData.Stations)this.GlueCollinearNeighborsSPN(r,e,t)&&(i=!0);return i&&(this.metroGraphData.Initialize(!1),On.FixRoutingMBP(this.metroGraphData,this.bundlingSettings,e)),i}GlueCollinearNeighborsSPN(t,e,i){if(t.Neighbors.length<=1)return!1;let r=new tc,s=t.Neighbors;for(let o=0;o<s.length;o++)this.TryToGlueEdges(t,s[o],s[(o+1)%s.length],r,i);if(r.isEmpty)return!1;for(let o of r)this.GlueEdge(o),e.add(o[0].Position),e.add(o[1].Position),e.add(o[2]);return!0}TryToGlueEdges(t,e,i,r,s){if(g.anglePCP(e.Position,t.Position,i.Position)<this.bundlingSettings.AngleThreshold){let o=ht(e.Position,t.Position),a=ht(i.Position,t.Position),l=Math.min(o,a)/Math.max(o,a);if(l<.05)return;if(o<a){if(this.EdgeGluingIsAllowedSSS(t,e,i)){this.AddEdgeToGlue(t,i,e,e.Position,r);return}}else if(this.EdgeGluingIsAllowedSSS(t,i,e)){this.AddEdgeToGlue(t,e,i,i.Position,r);return}if(s<5&&l>.5){let h=this.ConstructGluingPoint(t,e,i);this.EdgeGluingIsAllowedSSSP(t,e,i,h)&&this.AddEdgeToGlue(t,i,e,h,r)}}}ConstructGluingPoint(t,e,i){let r=Math.min(ht(e.Position,t.Position),ht(i.Position,t.Position)/2),s=e.Position.sub(t.Position).normalize().add(i.Position.sub(t.Position).normalize());return t.Position.add(s.mul(r/2))}EdgeGluingIsAllowedSSS(t,e,i){if(e.IsReal||i.IsReal||!qn(e.getELP(),i.getELP())||!this.metroGraphData.cdtIntersections.EdgeIsLegal(e,i,e.Position,i.Position))return!1;let r=this.metroGraphData.looseIntersections.ObstaclesToIgnoreForBundle(t,i);return!(Ga.IntersectionsOfLineAndRectangleNodeOverPolylineLR(D.mkPP(t.Position,e.Position),this.metroGraphData.LooseTree).find(s=>!r.has(s.seg1))||Ga.IntersectionsOfLineAndRectangleNodeOverPolylineLR(D.mkPP(e.Position,i.Position),this.metroGraphData.LooseTree).find(s=>!r.has(s.seg1))||this.ComputeCostDeltaAfterEdgeGluing(t,e,i,e.Position)<0)}EdgeGluingIsAllowedSSSP(t,e,i,r){return!(!this.metroGraphData.looseIntersections.HubAvoidsObstaclesPNS__(r,0,Ri(e.getELP(),i.getELP()))||!this.metroGraphData.cdtIntersections.EdgeIsLegal(t,null,t.Position,r)||!this.metroGraphData.cdtIntersections.EdgeIsLegal(e,null,e.Position,r)||!this.metroGraphData.cdtIntersections.EdgeIsLegal(i,null,i.Position,r)||this.ComputeCostDeltaAfterEdgeGluing(t,e,i,r)<0)}ComputeCostDeltaAfterEdgeGluing(t,e,i,r){let s=0,o=this.metroGraphData.Ink,a=this.metroGraphData.Ink-ht(t.Position,i.Position)-ht(t.Position,e.Position)+ht(t.Position,r)+ht(r,e.Position)+ht(r,i.Position);s+=Te.InkError(o,a,this.bundlingSettings);for(let d of this.metroGraphData.GetIjInfo(t,i).Metrolines){let c=d.Length,f=d.Length-ht(t.Position,i.Position)+ht(t.Position,r)+ht(r,i.Position);s+=Te.PathLengthsError(c,f,d.IdealLength,this.bundlingSettings)}for(let d of this.metroGraphData.GetIjInfo(t,e).Metrolines){let c=d.Length,f=d.Length-ht(t.Position,e.Position)+ht(t.Position,r)+ht(r,e.Position);s+=Te.PathLengthsError(c,f,d.IdealLength,this.bundlingSettings)}let l=t.cachedIdealRadius,h=this.GetCurrentHubRadius(t),u=er.GetMinRadiusForTwoAdjacentBundles(h,t,t.Position,e,i,this.metroGraphData,this.bundlingSettings);return u>h&&(s+=Te.RError(u,h,this.bundlingSettings)),l>ht(t.Position,r)&&!t.IsReal&&(s-=Te.RError(l,ht(t.Position,r),this.bundlingSettings)),s}AddEdgeToGlue(t,e,i,r,s){s.has(i,t)||s.has(e,t)||s.has(t,i)||s.has(t,e)||(s.set(t,i,r),s.set(t,e,r))}GlueEdge(t){let e=t[0],i=t[1],r=t[2];for(let s of e.MetroNodeInfos.map(o=>o.PolyPoint))s.next!=null&&s.next.point.equal(i.Position)?this.SplitPolylinePoint(s,r):s.prev!=null&&s.prev.point.equal(i.Position)&&this.SplitPolylinePoint(s.prev,r)}SplitPolylinePoint(t,e){if(t.point===e||t.next.point===e)return;let i=Ni.mkFromPoint(e);i.polyline=t.polyline,i.next=t.next,i.prev=t,i.next.prev=i,i.prev.next=i}RelaxConstrainedEdges(){let t=new Zt,e=!1;for(let i of this.metroGraphData.VirtualEdges())this.RelaxConstrainedEdge(i[0],i[1],t)&&(e=!0);return e&&(this.metroGraphData.Initialize(!1),On.FixRoutingMBP(this.metroGraphData,this.bundlingSettings,t)),e}RelaxConstrainedEdge(t,e,i){let r=this.metroGraphData.GetWidthSSN(t,e,this.bundlingSettings.EdgeSeparation),s={closestDist:new Array};this.metroGraphData.cdtIntersections.BundleAvoidsObstacles(t,e,t.Position,e.Position,.99*r/2,s);let o=s.closestDist;if(o.length>0){let a=-1,l;for(let h of o){let u=Math.min(ht(t.Position,h[1]),ht(e.Position,h[1])),d=ht(t.Position,e.Position);if(u/d<.1)continue;let c=ht(h[0],h[1]);(a===-1||c<a)&&(a=c,l=h[1])}if(a===-1||!this.metroGraphData.looseIntersections.HubAvoidsObstaclesPNS__(l,0,Ri(t.getELP(),e.getELP())))return!1;i.add(l),i.add(t.Position),i.add(e.Position);for(let h of this.metroGraphData.GetIjInfo(t,e).Metrolines){let u=null;for(let d of h.Polyline.polylinePoints())if(d.point.equal(t.Position)){u=d;break}u.next!=null&&u.next.point.equal(e.Position)?this.SplitPolylinePoint(u,l):this.SplitPolylinePoint(u.prev,l)}return!0}return!1}RemoveDoublePathCrossings(){let t=new za(this.metroGraphData,this.metroGraphData.PointIsAcceptableForEdge.bind(this)).run();return t&&(this.metroGraphData.Initialize(!1),On.FixRouting(this.metroGraphData,this.bundlingSettings)),t}},gS=class ja{constructor(t,e,i){this.upperBound=Number.POSITIVE_INFINITY,this._visGraph=i,i.ClearPrevEdgesTable();for(let r of i.Vertices())r.Distance=Number.POSITIVE_INFINITY;this.sources=t,this.targets=new Set(e)}GetPath(){let t=new nr;for(let e of this.sources)e.Distance=0,t.Enqueue(e,0);for(;!t.IsEmpty()&&(this._current=t.Dequeue(),!this.targets.has(this._current));){for(let e of this._current.OutEdges)this.PassableOutEdge(e)&&this.ProcessNeighbor(t,e,e.Target);for(let 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)||!ja.IsForbidden(t)}PassableInEdge(t){return this.targets.has(t.Source)||!ja.IsForbidden(t)}static IsForbidden(t){return(t.IsPassable!=null&&!t.IsPassable()||t)instanceof rr}ProcessNeighbor(t,e,i){let r=e.Length,s=this._current.Distance+r;s>=this.upperBound||(this.targets.has(i)&&(this.upperBound=s,this.closestTarget=i),this._visGraph.PreviosVertex(i)==null?(i.Distance=s,this._visGraph.SetPreviousEdge(i,e),t.Enqueue(i,s)):s<i.Distance&&(i.Distance=s,this._visGraph.SetPreviousEdge(i,e),t.DecreasePriority(i,s)))}CalculatePath(){if(this.closestTarget==null)return null;let t=new Array,e=this.closestTarget;do t.push(e),e=this._visGraph.PreviosVertex(e);while(e.Distance>0);return t.push(e),t.reverse()}},js=class extends Nt{static{this.SuperLoosePaddingCoefficient=1.1}constructor(n,t,e,i,r,s,o,a,l,h){super(null),this.bundlingSettings=i,this.bundlingSettings.edgeWidthShrinkCoeff=1,this.edgesToRoute=n,this.regularEdges=n.filter(u=>u.source!==u.target),this.VisibilityGraph=e,this.shortestPathRouter=t,this.LoosePadding=r,this.LooseHierarchy=o,this.TightHierarchy=s,this.EdgeLooseEnterable=a,this.EdgeTightEnterable=l,this.loosePolylineOfPort=h,po(0)}ThereAreOverlaps(n){return Ve(n,n,G.CurvesIntersect)}run(){if(this.ThereAreOverlaps(this.TightHierarchy)){this.Status=1;return}this.FixLocationsForHookAnywherePorts(this.edgesToRoute),this.RoutePathsWithSteinerDijkstra(),this.FixChildParentEdges(),this.bundlingSettings.StopAfterShortestPaths||this.OrderOptimizeNudgeEtc(),this.RouteSelfEdges(),this.FixArrowheads()}OrderOptimizeNudgeEtc(){let n=new tS(this.regularEdges,this.LooseHierarchy,this.TightHierarchy,this.bundlingSettings,this.shortestPathRouter.cdt,this.EdgeLooseEnterable,this.EdgeTightEnterable,this.loosePolylineOfPort);cS.FixRouting(n,this.bundlingSettings),new Ua(n,this.bundlingSettings).run()}FixChildParentEdges(){for(let n of this.regularEdges){let t=n.sourcePort,e=n.targetPort;if(t.Curve.boundingBox.containsRect(e.Curve.boundingBox)){let i=G.intersectionOne(t.Curve,D.mkPP(n.curve.start,n.curve.end),!1),r=n.curve;r.startPoint.point=i.x}if(e.Curve.boundingBox.containsRect(t.Curve.boundingBox)){let i=G.intersectionOne(e.Curve,D.mkPP(n.curve.start,n.curve.end),!0),r=n.curve;r.endPoint.point=i.x}}}FixLocationsForHookAnywherePorts(n){for(let t of n){let e=t.sourcePort instanceof Le;if(e){let i=t.sourcePort;i.SetLocation(this.FigureOutHookLocation(i.LoosePolyline,t.targetPort,t))}else if(e=t.targetPort instanceof Le,e){let i=t.targetPort;i.SetLocation(this.FigureOutHookLocation(i.LoosePolyline,t.sourcePort,t))}}}FigureOutHookLocation(n,t,e){return t instanceof Pi?this.FigureOutHookLocationForClusterOtherPort(n,t,e):this.FigureOutHookLocationForSimpleOtherPort(n,t,e)}FigureOutHookLocationForClusterOtherPort(n,t,e){let i=this.shortestPathRouter.MakeTransparentShapesOfEdgeGeometry(e),r=new gS(Array.from(t.LoosePolyline).map(this.VisibilityGraph.FindVertex.bind),Array.from(n).map(this.VisibilityGraph.FindVertex.bind),this.VisibilityGraph).GetPath();for(let s of i)s.IsTransparent=!1;return r[r.length-1].point}FigureOutHookLocationForSimpleOtherPort(n,t,e){let i=t.Location,r=this.shortestPathRouter.MakeTransparentShapesOfEdgeGeometry(e),s=new Rd(this.VisibilityGraph.FindVertex(i),Array.from(n).map(o=>this.VisibilityGraph.FindVertex(o)),this.VisibilityGraph).GetPath();for(let o of r)o.IsTransparent=!1;return s[s.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(){let n=new Map;this.shortestPathRouter.FillCrossedCdtEdges(n);let t=this.GetPathsOnCdtEdge(n);this.bundlingSettings.edgeWidthShrinkCoeff=this.CalculateEdgeWidthShrinkCoeff(t)}GetPathsOnCdtEdge(n){let t=new Map;for(let e of n.keys())for(let i of n.get(e))_s(t,i,e);return t}CalculateEdgeWidthShrinkCoeff(n){let t=0,e=this.bundlingSettings.edgeWidthShrinkCoeff;if(this.EdgeSeparationIsOkMN(n,e))return e;let i=!1;for(;!i||Math.abs(e-t)>.01;){let r=(t+e)/2;this.EdgeSeparationIsOkMN(n,r)?(t=r,i=!0):e=r}return t}EdgeSeparationIsOkMN(n,t){for(let e of n.keys())if(!this.EdgeSeparationIsOk(e,n.get(e),t))return!1;return!0}EdgeSeparationIsOk(n,t,e){return Array.from(t).map(i=>this.bundlingSettings.ActualEdgeWidth(i,e)).reduce((i,r)=>i+r,0)<=n.Capacity}RouteSelfEdges(){for(let n of this.edgesToRoute)if(n.source===n.target){let t={smoothedPolyline:null};n.curve=Fe.RouteSelfEdge(n.source.boundaryCurve,this.LoosePadding*2,t)}}FixArrowheads(){for(let n of this.edgesToRoute)ge.trimSplineAndCalculateArrowheadsII(n,n.source.boundaryCurve,n.target.boundaryCurve,n.curve,!1)}},pS=class{constructor(n,t,e){this.numberOfPassedPaths=0,this.VisibilityEdge=n,this.Source=t,this.Target=e}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--}},fS=class{constructor(n){this.InBoneEdges=new Array,this.OutBoneEdges=new Array,this.VisibilityVertex=n}get Prev(){return this.PrevEdge==null?null:this.PrevEdge.Source===this?this.PrevEdge.Target:this.PrevEdge.Source}get Point(){return this.VisibilityVertex.point}get Cost(){return this.IsSourceOfRouting?this.cost:this.Prev==null?Number.POSITIVE_INFINITY:this.cost}set Cost(n){this.cost=n}SetPreviousToNull(){this.PrevEdge=null}},ic=class Ur{constructor(t,e,i){this.EdgesToRoutes=new Map,this.EdgesToRouteSources=new Map,this.MakeTransparentShapesOfEdgeGeometry=t,this.cdt=e,this.Gates=i}CreateGraphElements(){for(let t of this.vertexArray){let e=t.VisibilityVertex;for(let i of e.InEdges){let r=new pS(i,this.VisibilityVerticesToSdVerts.get(i.Source),this.VisibilityVerticesToSdVerts.get(i.Target)),s=this.VisibilityVerticesToSdVerts.get(i.Source);t.InBoneEdges.push(r),s.OutBoneEdges.push(r)}}}CreateRoutingGraph(){this.vertexArray=[],this.VisibilityVerticesToSdVerts=new Map;for(let t of this.VisibilityGraph.Vertices()){let e=new fS(t);this.vertexArray.push(e),this.VisibilityVerticesToSdVerts.set(t,e)}this.CreateGraphElements()}RouteEdges(){this.Initialize(),this.RestoreCapacities();for(let t of this.geomEdges)this.EdgesToRoutes.set(t,this.RouteEdge(t));this.RerouteEdges();for(let t of this.geomEdges)this.SetEdgeGeometryCurve(t)}SetEdgeGeometryCurve(t){let e=new et,i=this.EdgesToRouteSources.get(t);e.addPoint(i.Point);for(let r of this.EdgesToRoutes.get(t))r.SourcePoint.equal(i.Point)?(e.addPoint(r.TargetPoint),i=r.Target):(e.addPoint(r.SourcePoint),i=r.Source);t.curve=e,t.sourcePort instanceof Pi&&Ur.ExtendPolylineStartToClusterBoundary(e,t.sourcePort.Curve),t.targetPort instanceof Pi&&Ur.ExtendPolylineEndToClusterBoundary(e,t.targetPort.Curve)}static ExtendPolylineEndToClusterBoundary(t,e){let i=e.closestParameter(t.end);t.addPoint(e.value(i))}static ExtendPolylineStartToClusterBoundary(t,e){let i=e.closestParameter(t.start);t.PrependPoint(e.value(i))}RerouteEdges(){this.RestoreCapacities();for(let t of this.geomEdges){let e=this.RerouteEdge(t);this.EdgesToRoutes.set(t,e)}}RestoreCapacities(){this.cdt!=null&&this.cdt.RestoreEdgeCapacities()}RerouteEdge(t){let e=this.EdgesToRoutes.get(t);for(let i of e)i.RemoveOccupiedEdge();return this.RouteEdge(t)}RouteEdge(t){this.CurrentEdgeGeometry=t;for(let r=0;r<this.vertexArray.length;r++){let s=this.vertexArray[r];s.SetPreviousToNull(),s.IsTargetOfRouting=s.IsSourceOfRouting=!1}let e=this.MakeTransparentShapesOfEdgeGeometry(t),i=this.RouteEdgeWithGroups();for(let r of e)r.IsTransparent=!1;return i}RouteEdgeWithGroups(){for(let t=0;t<2;t++){this.SetLengthCoefficient(),this.Queue=new nr,this.sourceLoosePoly=this.SetPortVerticesAndObstacles(this.CurrentEdgeGeometry.sourcePort,!0),this.targetLoosePoly=this.SetPortVerticesAndObstacles(this.CurrentEdgeGeometry.targetPort,!1);let 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;){let i={priority:0},r=this.Queue.DequeueAndGetPriority(i);if(!(i.priority>=this.LowestCostToTarget)){for(let s=0;s<r.OutBoneEdges.length;s++){let o=r.OutBoneEdges[s];o.IsPassable&&this.ProcessOutcomingBoneEdge(r,o,t,e)}for(let s=0;s<r.InBoneEdges.length;s++){let o=r.InBoneEdges[s];o.IsPassable&&this.ProcessIncomingBoneEdge(r,o,t,e)}}}return this.GetPathAndUpdateRelatedCosts()}ProcessOutcomingBoneEdge(t,e,i,r){r&&i.dot(e.TargetPoint.sub(e.SourcePoint))<0||this.ProcessBoneEdge(t,e.Target,e)}ProcessIncomingBoneEdge(t,e,i,r){r&&i.dot(e.SourcePoint.sub(e.TargetPoint))<0||this.ProcessBoneEdge(t,e.Source,e)}ProcessBoneEdge(t,e,i){let r=this.GetEdgeAdditionalCost(i,t.Cost);if(!(e.Cost<=r))if(e.Cost=r,e.PrevEdge=i,this.Queue.ContainsElement(e))this.Queue.DecreasePriority(e,r);else{if(e.IsTargetOfRouting){let s=0;this.CurrentEdgeGeometry.targetPort instanceof Pi&&(s=this.LengthCoefficient*e.Point.sub(this.CurrentEdgeGeometry.targetPort.Location).length),r+s<this.LowestCostToTarget&&(this.LowestCostToTarget=r+s,this.ClosestTargetVertex=e);return}this.Enqueue(e)}}GetPathAndUpdateRelatedCosts(){let t=this.ClosestTargetVertex;if(t==null)return null;let 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(let 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){let 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(let 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){let e=t.SourcePoint,i=t.Source.Triangle,r=new Set,s=t.TargetPoint;if(Ae.PointIsInsideOfTriangle(s,i))return r;let o=new qs(i,e,s);for(;o.MoveNext();){let a=o.CurrentPiercedEdge;this.Gates.has(a)&&r.add(a)}return r}static CostOfCrossingCdtEdge(t,e,i,r){let s=i.lineWidth*e.edgeWidthShrinkCoeff;r.Capacity!==r.ResidualCapacity&&(s+=e.EdgeSeparation*e.edgeWidthShrinkCoeff);let o=r.ResidualCapacity-s;return o>=0?0:-o*t}CostOfCrossingCdtEdgeLocal(t,e,i,r){return this.AdjacentToSourceOrTarget(r)?0:Ur.CostOfCrossingCdtEdge(t,e,i,r)}AdjacentToSourceOrTarget(t){return t.upperSite.Owner===this.sourceLoosePoly||t.lowerSite.Owner===this.sourceLoosePoly||t.upperSite.Owner===this.targetLoosePoly||t.lowerSite.Owner===this.targetLoosePoly}SetLengthCoefficient(){let 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 Pi){i=t.LoosePolyline;for(let r of i){let s=0;e&&(s=this.LengthCoefficient*r.sub(this.CurrentEdgeGeometry.sourcePort.Location).length),this.AddAndEnqueueVertexToEnds(r,e,s)}}else if(t instanceof Le){i=t.LoosePolyline;for(let r of i)this.AddAndEnqueueVertexToEnds(r,e,0)}else{this.AddAndEnqueueVertexToEnds(t.Location,e,0);let r=Array.from(this.ObstacleHierarchy.GetNodeItemsIntersectingRectangle(t.Curve.boundingBox)),s=r[0].boundingBox.diagonal;i=r[0];for(let o=1;o<r.length;o++){let a=r[o],l=a.boundingBox.diagonal;l<s&&(s=l,i=a)}}return i}Enqueue(t){this.Queue.Enqueue(t,this.H(t))}AddAndEnqueueVertexToEnds(t,e,i){let r=this.FindVertex(t),s=this.VisibilityVerticesToSdVerts.get(r);e?(s.IsSourceOfRouting=!0,s.Cost=i,this.Enqueue(s)):s.IsTargetOfRouting=!0}FindVertex(t){return this.VisibilityGraph.FindVertex(t)}Initialize(){this.CreateRoutingGraph(),this.cdt!=null&&(this.capacityOverlowPenaltyMultiplier=Ur.CapacityOverflowPenaltyMultiplier(this.BundlingSettings),this.SetVertexTriangles(),this.CalculateCapacitiesOfTrianglulation())}CalculateCapacitiesOfTrianglulation(){for(let t of this.Gates)Ur.CalculateCdtEdgeCapacityForEdge(t)}static CalculateCdtEdgeCapacityForEdge(t){if(t.constrained||t.CwTriangle==null||t.CcwTriangle==null)return;let e=t.upperSite.Owner,i=t.lowerSite.Owner;if(e!==i){let r=Ze.DistancePoint(new Ze(e),t.lowerSite.point),s=Ze.DistancePoint(new Ze(i),t.upperSite.point);t.Capacity=(r+s)/2}}SetVertexTriangles(){let t=qt(Array.from(this.cdt.GetTriangles()).map(i=>ne(i,i.BoundingBox()))),e=qt(this.vertexArray.map(i=>ne(i,it.mkOnPoints([i.Point]))));xe(t,e,(i,r)=>this.TryToAssigenTriangleToVertex(i,r))}TryToAssigenTriangleToVertex(t,e){e.Triangle==null&&Ae.PointIsInsideOfTriangle(e.Point,t)&&(e.Triangle=t)}static CapacityOverflowPenaltyMultiplier(t){return t.CapacityOverflowCoefficient*(t.PathLengthImportance+t.InkImportance)}FillCrossedCdtEdges(t){for(let e of this.geomEdges){this.sourceLoosePoly=this.SetPortVerticesAndObstacles(e.sourcePort,!0),this.targetLoosePoly=this.SetPortVerticesAndObstacles(e.targetPort,!1);for(let i of this.EdgesToRoutes.get(e))for(let r of this.CrossedCdtEdgesOfBoneEdge(i))this.AdjacentToSourceOrTarget(r)||_s(t,e,r)}}},mS=class Qa{constructor(t,e,i,r,s){this.multiEdges=t,this.interactiveEdgeRouter=e,this.bundlingSettings=r,this.bundlingSettings.edgeWidthShrinkCoeff=1,this.transparentShapeSetter=s,this.nodeTree=to(i,o=>o.boundingBox)}run(){for(let t of this.GetIndependantPreGraphs())new js(t.edges,new ic(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,(e,i)=>G.PointRelativeToCurveLocation(e,i)!==0?1:0).UserData}GetIndependantPreGraphs(){let t=this.CreateInitialPregraphs();do{let e=t.length,i={preGraphs:t};if(this.UniteConnectedPreGraphs(i),e<=t.length)break}while(!0);return t}UniteConnectedPreGraphs(t){let e=Qa.GetIntersectionGraphOfPreGraphs(t.preGraphs);if(e==null)return;let i=tn(e),r=new Array;for(let s of i){let o=null;for(let a of s)o==null?(o=t.preGraphs[a],r.push(o)):o.AddGraph(t.preGraphs[a])}t.preGraphs=r;for(let s of t.preGraphs)this.AddIntersectingNodes(s)}AddIntersectingNodes(t){let e=t.boundingBox;for(let i of this.nodeTree.GetNodeItemsIntersectingRectangle(e))t.AddNodeBoundary(i)}static GetIntersectionGraphOfPreGraphs(t){let e=Qa.EnumeratePairsOfIntersectedPreGraphs(t);return e.length?yi(e,t.length):null}static EnumeratePairsOfIntersectedPreGraphs(t){let e=Array.from(Array(t.length).keys()),i=to(e,s=>t[s].boundingBox),r=new Array;return de(i,i,(s,o)=>r.push(new mt(s,o))),r}CreateInitialPregraphs(){return this.multiEdges.map(t=>this.CreatePregraphFromSetOfEdgeGeometries(t))}CreatePregraphFromSetOfEdgeGeometries(t){let e=new Set,i=t[0],r=this.GetPortCurve(i.sourcePort),s=r.boundingBox;e.add(r),e.add(i.targetPort.Curve),s.addRec(i.targetPort.Curve.boundingBox);let o=this.nodeTree.GetNodeItemsIntersectingRectangle(s);for(let a of o)e.add(a);return Qy.constructorStatic(t,e)}},PS=ct(bi(),1),yS=class{constructor(){this.triangles=new Set}setCdt(n){this.cdt=n,this.cdt.SetInEdges();let t=new Set;for(let e of n.GetTriangles())for(let i of e.Sites)i.Owner!=null&&t.add(i.Owner)}outsideOfObstacles(n){if(n==null)return!1;let t=n.Sites.item0.Owner??n.Sites.item1.Owner;return t===this.sourcePoly||t===this.targetPoly||!SS(n)}run(n){if(this.triangles.clear(),this.poly=n,this.d=[],n.count<=2||this.cdt==null)return;this.sourcePoly=this.findPoly(n.start),this.targetPoly=this.findPoly(n.end),this.findChannelTriangles();let t=this.getPerimeterEdges();t=this.fillTheCollapedSites(t);let e=new Ae([],[],Array.from(t).map(r=>({A:r.lowerSite.point,B:r.upperSite.point})));e.run();let i=this.getSleeve(this.findSourceTriangle(e));if(i==null){console.log("failed to create sleeve");return}if(i.length==0){this.poly=et.mkFromPoints([n.start,n.end]);return}this.initDiagonals(i),this.refineFunnel()}getAllCrossedTriangles(n,t,e){let i=[],r=[],s=null;for(r.push(n);r.length>0;){let o=r.pop();if(s==null&&o.containsPoint(e)&&(s=o),o.intersectsLine(t,e,0)){i.push(o);for(let a of o.Edges){let l=a.GetOtherTriangle_T(o);l&&!i.includes(l)&&!r.includes(l)&&r.push(l)}}}return{triangles:i,containsEnd:s}}findChannelTriangles(){let n=this.cdt.FindSite(this.poly.start).Triangles().next().value;this.triangles.clear();for(let t=this.poly.startPoint;t.next!=null;t=t.next){let e=this.getAllCrossedTriangles(n,t.point,t.next.point);n=e.containsEnd;for(let i of e.triangles)this.outsideOfObstacles(i)&&this.triangles.add(i)}}findPoly(n){let t=this.cdt.FindSite(n);for(let e of t.Edges)return e.lowerSite.Owner??e.upperSite.Owner}fillTheCollapedSites(n){let t=new Map;for(let r of n)i(r.lowerSite,r),i(r.upperSite,r);let e=[];for(let[r,s]of t)s.length>2&&e.push(r);if(e.length==0)return n;for(let r of e)for(let s of r.Triangles())this.outsideOfObstacles(s)&&this.triangles.add(s);return this.getPerimeterEdges();function i(r,s){let o=t.get(r);o==null&&t.set(r,o=[]),o.push(s)}}findSourceTriangle(n){let t;for(let e of n.GetTriangles())if(e.containsPoint(this.poly.start)){t=e;break}return t}refineFunnel(){let n=[],t=this.poly.start,e={point:t},i={point:t},r={point:this.d[0].left,prev:e},s={point:this.d[0].right,prev:i};e.next=r,i.next=s;let o;for(let C=1;C<this.d.length;C++)l(C,this.d);this.d.push({right:this.poly.end,left:r.point}),l(this.d.length-1,this.d);let a=et.mkFromPoints(n);for(let C=i;C!=null;C=C.next)a.addPoint(C.point);this.poly=a;function l(C,E){if(E[C-1].left!==E[C].left){o=E[C].left;let w=r;for(;!(P(w)||d(w));w=w.prev);P(w)?f():b(w)}else{o=E[C].right;let w=s;for(;!(P(w)||c(w));w=w.prev);P(w)?m():v(w)}}function h(C){return C.next==null?!0:g.pointToTheLeftOfLineOrOnLine(o,C.point,C.next.point)}function u(C){return C.next==null?!0:g.pointToTheRightOfLineOrOnLine(o,C.point,C.next.point)}function d(C){return g.pointToTheLeftOfLine(o,C.prev.point,C.point)}function c(C){return g.pointToTheRightOfLine(o,C.prev.point,C.point)}function f(){let C=i;for(;!h(C);)C=C.next;if(!P(C)){let E=i;for(;!E.point.equal(C.point);E=E.next)n.push(E.point);i.point=E.point,i.next=E.next,t=E.point,s.point.equal(i.point)&&(s.prev=s.next=null)}e.point=t,r.point=o,r.prev=e,e.next=r}function m(){let C=e;for(;!u(C);)C=C.next;if(!P(C)){let E=e;for(;!E.point.equal(C.point);E=E.next)n.push(E.point);e.point=E.point,e.next=E.next,t=E.point,r.point.equal(e.point)&&(r.prev=e.next=null)}i.point=t,s.point=o,s.prev=i,i.next=s}function P(C){return C.point==t}function v(C){C!=s?(s.point=o,s.prev=C,C.next=s):(s={point:o,prev:C},C.next=s)}function b(C){C!=r?(r.point=o,r.prev=C,C.next=r):(r={point:o,prev:C},C.next=r)}}initDiagonals(n){for(let t of n){let e=t.edge,i=t.source.OppositeSite(e);g.getTriangleOrientation(i.point,e.lowerSite.point,e.upperSite.point)==1?this.d.push({left:e.upperSite.point,right:e.lowerSite.point}):this.d.push({right:e.upperSite.point,left:e.lowerSite.point})}}getSleeve(n){let t=new PS.Queue;t.enqueue(n);let e=new Map;for(e.set(n,void 0);t.length>0;){let i=t.dequeue(),r=e.get(i);if(i.containsPoint(this.poly.end))return this.recoverPath(n,e,i);for(let s of i.Edges){if(s.constrained||r!==void 0&&s===r)continue;let o=s.GetOtherTriangle_T(i);o!=null&&(e.has(o)||(e.set(o,s),t.enqueue(o)))}}}recoverPath(n,t,e){let i=[];for(let r=e;r!=n&&r!==n;){let s=t.get(r);r=s.GetOtherTriangle_T(r),i.push({source:r,edge:s})}return i.reverse()}getPerimeterEdges(){let n=new Set;for(let t of this.triangles)for(let e of t.Edges)this.triangles.has(e.GetOtherTriangle_T(t))||n.add(e);return n}};function SS(n){return n.Sites.item0.Owner==null||n.Sites.item1.Owner==null||n.Sites.item2.Owner==null?!0:n.Sites.item0.Owner==n.Sites.item1.Owner&&n.Sites.item0.Owner==n.Sites.item2.Owner}var Or=class Yt extends Nt{constructor(t,e,i=1,r=2,s=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=r,this.tightPadding=i,this.coneAngle=s,this.routeMultiEdgesAsBundles=e.length<1e3&&t.deepNodeCount<1e3}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 Yt.mk5(t,e.Padding,e.PolylinePadding,e.ConeAngle,e.bundlingSettings)}static mk4(t,e,i,r){return new Yt(t,Array.from(t.deepEdges),e,i,r,null)}static mk5(t,e,i,r,s){return new Yt(t,Array.from(t.deepEdges),e,i,r,s)}static mk6(t,e,i,r,s,o){let a=Yt.mk4(t,e,i,r),l=Wy.GetShapes(s,o);return a.Initialize(l,r),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");let t=_r.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=>ta(i.edge,t));let e=_r.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(let[i,r]of this.shapesToTightLooseCouples)this.loosePolylinesToNodes.set(r.LooseShape.BoundaryCurve,new Set([i.node.node]));return}let t=to(this.geomGraph.nodesBreadthFirst,i=>i.boundingBox),e=this.GetLooseHierarchy();xe(e,t,(i,r)=>{if(G.CurveIsInsideOther(r.boundaryCurve,i)){let s=this.loosePolylinesToNodes.get(i);for(let o of r.getAncestors())if(!(o instanceof we&&o.parent==null)&&o.boundaryCurve!=null&&G.CurveIsInsideOther(o.boundaryCurve,i))return;s==null&&this.loosePolylinesToNodes.set(i,s=new Set),s.add(r.node)}})}RouteOnRoot(){po(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(let[t,e]of this.portsToShapes){let i=new Set;Yt.EdgesAttachedToPortAvoidTheNode(t)||i.add(e),this.portsToEnterableShapes.set(t,i)}for(let t of this.rootShapes)for(let e of t.Descendants())for(let i of e.Ports){let r=this.portsToEnterableShapes.get(i);Li(r,Array.from(e.Ancestors()).filter(s=>s.BoundaryCurve!=null))}}static EdgesAttachedToPortAvoidTheNode(t){return t instanceof gi||t instanceof Pi}SetLoosePolylinesForAnywherePorts(){for(let[t,e]of this.shapesToTightLooseCouples)for(let i of t.Ports){if(i instanceof Le){let r=i;r.LoosePolyline=e.LooseShape.BoundaryCurve}if(i instanceof Pi){let r=i;r.LoosePolyline=e.LooseShape.BoundaryCurve}}}BindLooseShapes(){this.looseRoot=new Ir;for(let t of this.root.Children){let e=this.shapesToTightLooseCouples.get(t).LooseShape;this.BindLooseShapesUnderShape(t),this.looseRoot.AddChild(e)}}BindLooseShapesUnderShape(t){let e=this.shapesToTightLooseCouples.get(t).LooseShape;for(let i of t.Children){let r=this.shapesToTightLooseCouples.get(i).LooseShape;e.AddChild(r),this.BindLooseShapesUnderShape(i)}}CalculateShapeToBoundaries(t){if(this.ProgressStep(),t.Children.length===0)return;for(let i of t.Children)this.CalculateShapeToBoundaries(i);let e=Number.POSITIVE_INFINITY;this.obstacleCalculator=new qy(t,this.tightPadding,Math.min(this.AdjustedLoosePadding,e),this.shapesToTightLooseCouples),this.obstacleCalculator.Calculate(.01),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*js.SuperLoosePaddingCoefficient}GroupEdgesByPassport(){let t=new Array;for(let e of this.edges){let i=this.EdgePassport(e),r=t.find(s=>qn(s.passport,i));r||(r={passport:i,edges:[]},t.push(r)),r.edges.push(e)}return t}RouteOnVisGraph(){if(this.ancestorSets=Yt.GetAncestorSetsMap(Array.from(this.root.Descendants())),this.BundlingSettings==null){let t=this.GroupEdgesByPassport();for(let e=0;e<t.length;e++){let i=t[e],r=i.passport,s=this.GetObstaclesFromPassport(r),o=this.CreateInteractiveEdgeRouter(Array.from(s));this.RouteEdgesWithTheSamePassport(i,o,s)}}else this.RouteBundles()}rerouteOnActiveNodes(t){if(this.ancestorSets=Yt.GetAncestorSetsMap(Array.from(this.root.Descendants())),this.BundlingSettings==null)for(let e of this.GroupEdgesByPassport()){let i=e.passport,r=this.GetObstaclesFromPassport(i),s=new Set;for(let a of r){let l=this.LooseShapeOfOriginalShape(a);for(let h of this.loosePolylinesToNodes.get(l.BoundaryCurve))t.has(h)&&s.add(a)}let o=this.CreateInteractiveEdgeRouter(Array.from(s));this.rerouteEdgesWithTheSamePassportActiveNodes(e,o,s,t)}else this.RouteBundles()}getDebugCurvesFromEdgesAndCdt(t){let e=Array.from(this.geomGraph.deepEdges).map(i=>i.curve).filter(i=>i!=null).filter(i=>i.count>5).map(i=>It.mkDebugCurveTWCI(200,1,"Red",i));for(let i of t.PointsToSites.values())for(let r of i.Edges)e.push(It.mkDebugCurveTWCI(200,.5,r.constrained?"Blue":"Green",D.mkPP(r.lowerSite.point,r.upperSite.point)));return e}RouteEdgesWithTheSamePassport(t,e,i){let r={regularEdges:[],multiEdges:[]};try{let s=this.getCdtFromPassport(i);e.pathOptimizer.setCdt(s)}catch{e.pathOptimizer.setCdt(null)}if(this.RouteMultiEdgesAsBundles){if(this.SplitOnRegularAndMultiedges(t.edges,r),r.regularEdges.length>0)for(let s=0;s<r.regularEdges.length;s++)this.routeEdge(e,r.regularEdges[s]);r.multiEdges!=null&&(this.ScaleDownLooseHierarchy(e,i),this.RouteMultiEdges(r.multiEdges,e,t.passport))}else for(let s=0;s<t.edges.length;s++)this.routeEdge(e,t.edges[s])}rerouteEdgesWithTheSamePassportActiveNodes(t,e,i,r){let s={regularEdges:[],multiEdges:[]};try{let 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,s),s.regularEdges.length>0)for(let o=0;o<s.regularEdges.length;o++){let a=s.regularEdges[o];Wt.assert(ta(a.edge,r)),this.rerouteEdge(e,a)}s.multiEdges!=null&&(this.ScaleDownLooseHierarchy(e,i),this.RouteMultiEdges(s.multiEdges,e,t.passport))}else for(let o=0;o<t.edges.length;o++){let a=t.edges[o];ta(a.edge,r)&&this.rerouteEdge(e,a)}}rerouteEdge(t,e){try{t.rerouteEdge(e),ge.trimSplineAndCalculateArrowheadsII(e,e.sourcePort.Curve,e.targetPort.Curve,e.curve,!1)}catch{console.log("failed")}}getCdtFromPassport(t){let e=new Set,i=[],r=it.mkEmpty();for(let a of t){let l=this.LoosePolyOfOriginalShape(a);if(l!=null){e.add(l);for(let h of a.Ports)i.push(h.Location);r.addRecSelf(l.boundingBox)}}r.pad(Math.max(r.diagonal/4,100));let s=Array.from(e);s.push(r.perimeter());let o=new Ae(i,s,[]);return o.run(),o}get RouteMultiEdgesAsBundles(){return this.routeMultiEdgesAsBundles}set RouteMultiEdgesAsBundles(t){this.routeMultiEdgesAsBundles=t}routeEdge(t,e){let i=this.makeTransparentShapesOfEdgeAndGetTheShapes(e);this.ProgressStep(),this.RouteEdgeInternal(e,t),Yt.SetTransparency(i,!1)}ScaleDownLooseHierarchy(t,e){let i=new Array;for(let r of e){let s=this.shapesToTightLooseCouples.get(r);i.push(ye.LoosePolylineWithFewCorners(s.TightPolyline,s.Distance/1.1,0))}t.LooseHierarchy=Yt.CreateLooseObstacleHierarachy(i),t.ClearActivePolygons(),t.AddActivePolygons(i.map(r=>new Ze(r)))}RouteMultiEdges(t,e,i){let r=[];for(let o of i)for(let a of o.Children)r.push(a.BoundaryCurve);let s=new Ia;s.InkImportance=1e-5,s.EdgeSeparation=this.MultiEdgesSeparation,new mS(t,e,r,s,o=>this.makeTransparentShapesOfEdgeAndGetTheShapes(o)).run()}SplitOnRegularAndMultiedges(t,e){let i=new jn;for(let r of t)Yt.IsEdgeToParent(r)?e.regularEdges.push(r):Yt.RegisterInPortLocationsToEdges(r,i);e.multiEdges=null;for(let r of i.values())r.length===1||this.OverlapsDetected?Yi(e.regularEdges,r):(e.multiEdges==null&&(e.multiEdges=new Array),e.multiEdges.push(r))}static RegisterInPortLocationsToEdges(t,e){let i,r=new Pe(t.sourcePort.Location,t.targetPort.Location);i=e.get(r),i||(i=new Array,e.set(r,i)),i.push(t)}static IsEdgeToParent(t){return t.sourcePort instanceof Le||t.targetPort instanceof Le}CreateInteractiveEdgeRouter(t){let e=new Set(t.map(r=>this.shapesToTightLooseCouples.get(r).LooseShape.BoundaryCurve)),i=new Ga(this.cancelToken);return i.pathOptimizer=new yS,i.ObstacleCalculator=new ye(t.map(r=>r.BoundaryCurve),this.tightPadding,this.loosePadding,!1),i.VisibilityGraph=this.visGraph,i.TightHierarchy=this.CreateTightObstacleHierarachy(t),i.LooseHierarchy=Yt.CreateLooseObstacleHierarachy(Array.from(e)),i.UseSpanner=!0,i.LookForRoundedVertices=!0,i.TightPadding=this.tightPadding,i.LoosePadding=this.LoosePadding,i.UsePolylineEndShortcutting=this.UsePolylineEndShortcutting,i.UseInnerPolylingShortcutting=this.UseInnerPolylingShortcutting,i.AllowedShootingStraightLines=this.AllowedShootingStraightLines,i.AddActivePolygons(Array.from(e).map(r=>new Ze(r))),i}GetObstaclesFromPassport(t){if(t.size===0)return new Set(this.root.Children);let e=this.GetCommonAncestorsAbovePassport(t),i=this.GetAllAncestors(t),r=new Set;for(let a of t)for(let l of a.Children)i.has(l)||r.add(l);let s=ir(new Set(t),r),o=new Uy.Queue;for(let a of t)e.has(a)||o.enqueue(a);for(;o.length>0;){let a=o.dequeue();for(let l of a.Parents){for(let h of l.Children)i.has(h)||r.add(h);!e.has(l)&&!s.has(l)&&(o.enqueue(l),s.add(l))}}return r}GetAllAncestors(t){if(t.size===0)return new Set;let e=new Set(t);for(let i of t)e=ir(e,this.ancestorSets.get(i));return e}GetCommonAncestorsAbovePassport(t){if(t.size===0)return new Set;let e=Array.from(t),i=this.ancestorSets.get(e[0]);for(let r=1;r<e.length;r++){let s=e[r];i=Ri(i,this.ancestorSets.get(s))}return i}RouteBundles(){this.ScaleLooseShapesDown(),this.CalculateEdgeEnterablePolylines();let t=this.GetLooseHierarchy(),e=Zu(t),i=new ic(r=>this.makeTransparentShapesOfEdgeAndGetTheShapes(r),e,this.FindCdtGates(e));new js(this.edges,i,this.visGraph,this.BundlingSettings,this.LoosePadding,this.GetTightHierarchy(),t,this.enterableLoose,this.enterableTight,r=>this.LoosePolyOfOriginalShape(this.portsToShapes.get(r))).run()}CreateTheMapToParentLooseShapes(t,e){for(let i of t.Children){let r=this.shapesToTightLooseCouples.get(i).LooseShape.BoundaryCurve;e.set(r,t),this.CreateTheMapToParentLooseShapes(i,e)}}FindCdtGates(t){let e=new Map;this.CreateTheMapToParentLooseShapes(this.root,e);let i=new Set;for(let r of t.PointsToSites.values())for(let s of r.Edges){if(s.CwTriangle==null&&s.CcwTriangle==null)continue;let o=r.Owner,a=s.lowerSite.Owner;if(o===a)continue;let l=e.get(o);if(l){let h=e.get(a);l===h&&i.add(s)}}return i}CalculateEdgeEnterablePolylines(){this.enterableLoose=new Map,this.enterableTight=new Map;for(let t of this.edges){let 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){let r=this.portsToShapes.get(t.sourcePort),s=this.portsToShapes.get(t.targetPort);r!==this.root&&this.GetEnterablesForShape(r,e,i),s!==this.root&&this.GetEnterablesForShape(s,e,i)}GetEnterablesForShape(t,e,i){for(let r of this.ancestorSets.get(t)){let s=this.LoosePolyOfOriginalShape(r);s&&e.add(s);let o=this.TightPolyOfOriginalShape(r);o&&i.add(o)}}GetTightHierarchy(){return qt(Array.from(this.shapesToTightLooseCouples.values()).map(t=>ne(t.TightPolyline,t.TightPolyline.boundingBox)))}GetLooseHierarchy(){let t=new Set;for(let e of this.shapesToTightLooseCouples.values())t.add(e.LooseShape.BoundaryCurve);return qt(Array.from(t).map(e=>ne(e,e.boundingBox)))}ScaleLooseShapesDown(){for(let[,t]of this.shapesToTightLooseCouples)t.LooseShape.BoundaryCurve=ye.LoosePolylineWithFewCorners(t.TightPolyline,t.Distance/js.SuperLoosePaddingCoefficient,0)}EdgePassport(t){let e=new Set,i=this.portsToShapes.get(t.sourcePort),r=this.portsToShapes.get(t.targetPort);return this.IsAncestor(i,r)?(Li(e,r.Parents),e.add(i),e):this.IsAncestor(r,i)?(Li(e,i.Parents),e.add(r),e):(i!==this.looseRoot&&Li(e,i.Parents),r!==this.looseRoot&&Li(e,r.Parents),e)}*AllPorts(){for(let t of this.edges)yield t.sourcePort,yield t.targetPort}CalculatePortsToShapes(){this.portsToShapes=new Map;for(let t of this.root.Descendants())for(let e of t.Ports)this.portsToShapes.set(e,t);for(let t of this.AllPorts())this.portsToShapes.has(t)||(this.root.Ports.add(t),this.portsToShapes.set(t,this.root))}RouteEdgeInternal(t,e){let i=new Array;t.sourcePort instanceof Le||Yi(i,this.AddVisibilityEdgesFromPort(t.sourcePort)),t.targetPort instanceof Le||Yi(i,this.AddVisibilityEdgesFromPort(t.targetPort));let r={smoothedPolyline:null};if(g.closeDistEps(t.sourcePort.Location,t.targetPort.Location)?t.curve=Fe.RouteSelfEdge(t.sourcePort.Curve,Math.max(this.LoosePadding*2,t.GetMaxArrowheadLength()),r):t.curve=e.RouteSplineFromPortToPortWhenTheWholeGraphIsReady(t.sourcePort,t.targetPort,!0,r),t.smoothedPolyline=null,t.curve==null)throw new Error;for(let s of i)zt.RemoveEdge(s);ge.trimSplineAndCalculateArrowheadsII(t,t.sourcePort.Curve,t.targetPort.Curve,t.curve,!1)}*AddVisibilityEdgesFromPort(t){let e,i;if(t instanceof gi||!(e=this.portsToShapes.get(t))||!(i=this.shapesToTightLooseCouples.get(e)))return;let r=i.LooseShape;for(let s of r.BoundaryCurve)this.visGraph.FindEdgePP(t.Location,s)==null&&(yield this.visGraph.AddEdgePP(t.Location,s))}makeTransparentShapesOfEdgeAndGetTheShapes(t){let e=this.portsToShapes.get(t.sourcePort),i=this.portsToShapes.get(t.targetPort),r=new Array;for(let s of this.GetTransparentShapes(t.sourcePort,t.targetPort,e,i))s!=null&&r.push(this.LooseShapeOfOriginalShape(s));for(let s of this.portsToEnterableShapes.get(t.sourcePort))r.push(this.LooseShapeOfOriginalShape(s));for(let s of this.portsToEnterableShapes.get(t.targetPort))r.push(this.LooseShapeOfOriginalShape(s));return Yt.SetTransparency(r,!0),r}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,r){for(let s of this.ancestorSets.get(i))yield s;for(let s of this.ancestorSets.get(r))yield s;Yt.EdgesAttachedToPortAvoidTheNode(t)||(yield i),Yt.EdgesAttachedToPortAvoidTheNode(e)||(yield r)}static SetTransparency(t,e){for(let 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 qt(t.map(e=>ne(e,e.boundingBox)))}CreateTightObstacleHierarachy(t){let e=t.map(i=>this.shapesToTightLooseCouples.get(i).TightPolyline);return qt(e.map(i=>ne(i,i.boundingBox)))}CalculateVisibilityGraph(){let t=this.LineSweeperPorts!=null?Zt.mk(this.LineSweeperPorts):new Zt;this.ProcessHookAnyWherePorts(t),this.portRTree=Vn(Array.from(t.values()).map(e=>[it.rectangleOnPoint(e),e])),this.visGraph=new zt,this.FillVisibilityGraphUnderShape(this.root)}ProcessHookAnyWherePorts(t){for(let e of this.edges)e.sourcePort instanceof Le||e.sourcePort instanceof Pi||t.add(e.sourcePort.Location),e.targetPort instanceof Le||e.targetPort instanceof Pi||t.add(e.targetPort.Location)}FillVisibilityGraphUnderShape(t){let e=t.Children;for(let u=0;u<e.length;u++){let d=e[u];this.FillVisibilityGraphUnderShape(d)}let i=this.shapesToTightLooseCouples.get(t),r=i?i.LooseShape.BoundaryCurve:null,s=i?i.LooseShape:this.looseRoot,o=new Set(s.Children.map(u=>u.BoundaryCurve)),a=this.RemoveInsidePortsAndSplitBoundaryIfNeeded(r),l=new zt,h=ho.mk([],l,this.coneAngle,a,r);h.run(),l=new zt,h=ho.mk(Array.from(o),l,this.coneAngle,a,r),h.run(),this.ProgressStep();for(let u of l.Edges)this.TryToCreateNewEdgeAndSetIsPassable(u,s);this.AddBoundaryEdgesToVisGraph(r)}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){let e=new Zt;if(t==null){for(let s of this.portRTree.GetAllLeaves())e.add(s);return this.portRTree.clear(),e}let i=t.boundingBox,r=this.portRTree.GetAllIntersecting(i);for(let s of r)switch(G.PointRelativeToCurveLocation(s,t)){case 2:e.add(s),this.portRTree.Remove(it.rectangleOnPoint(s),s);break;case 1:this.portRTree.Remove(it.rectangleOnPoint(s),s);let o=Yt.FindPointOnPolylineToInsertAfter(t,s);if(o!=null)Qd.InsertPointIntoPolylineAfter(t,o,s);else throw new Error;break}return e}static FindPointOnPolylineToInsertAfter(t,e){for(let i=t.startPoint;;){let r=i.nextOnPolyline;if(g.closeDistEps(e,i.point)||g.closeDistEps(e,r.point))return null;let s=g.distToLineSegment(e,i.point,r.point).dist;if(lt(s,0))return i;if(i=r,i===t.startPoint)throw new Error}}GetOrCreateRoot(){if(this.rootShapes.length===1){let t=this.rootShapes[0];if(t.BoundaryCurve==null){this.root=t;return}}this.rootWasCreated=!0,this.root=new Ir(null);for(let t of this.rootShapes)this.root.AddChild(t)}RemoveRoot(){if(this.rootWasCreated){for(let t of this.rootShapes)t.RemoveParent(this.root);this.root=null,this.rootWasCreated=!1}}static GetAncestorSetsMap(t){let e=new Map;for(let i of t.filter(r=>!e.has(r)))e.set(i,Yt.GetAncestorSet(i,e));return e}static GetAncestorSet(t,e){let i=new Set(t.Parents);for(let r of t.Parents){let s=e.get(r);s||e.set(r,s=Yt.GetAncestorSet(r,e));for(let o of s)i.add(o)}return i}static CreatePortsIfNeeded(t){for(let e of t){if(e.sourcePort==null){let i=e;new Si(()=>i.source.boundaryCurve,()=>i.source.center,new g(0,0))}if(e.targetPort==null){let i=e;new Si(()=>i.target.boundaryCurve,()=>i.target.center,new g(0,0))}}}};function bS(n,t,e){let i=Ad(n);new Or(n,t,i.Padding,i.PolylinePadding,i.coneAngle,i.bundlingSettings,e).run()}var CS=ct(se(),1),vS=class{constructor(n,t){this.Crossings=[],this.Location=n,this.Crossings=t}},$n=class{constructor(){this.ListOfPointsAndCrossings=[],this.index=0,this.ListOfPointsAndCrossings=new Array}Count(){return this.ListOfPointsAndCrossings.length}Add(n,t){this.ListOfPointsAndCrossings.push(new vS(n,t))}Pop(){return this.ListOfPointsAndCrossings[this.index++]}CurrentIsBeforeOrAt(n){return this.index>=this.ListOfPointsAndCrossings.length?!1:R.ComparePP(this.ListOfPointsAndCrossings[this.index].Location,n)<=0}get First(){return this.ListOfPointsAndCrossings[0]}get Last(){return this.ListOfPointsAndCrossings[this.ListOfPointsAndCrossings.length-1]}Reset(){this.index=0}MergeFrom(n){if(this.Reset(),n==null)return;let t=this.ListOfPointsAndCrossings.length,e=0,i=n.ListOfPointsAndCrossings.length,r=0,s=new Array(this.ListOfPointsAndCrossings.length);for(;e<t||r<i;){if(e>=t){s.push(n.ListOfPointsAndCrossings[r++]);continue}if(r>=i){s.push(this.ListOfPointsAndCrossings[e++]);continue}let o=this.ListOfPointsAndCrossings[e],a=n.ListOfPointsAndCrossings[r],l=R.ComparePP(o.Location,a.Location);l===0?(s.push(o),++e,++r):l===-1?(s.push(o),++e):(s.push(a),++r)}this.ListOfPointsAndCrossings=s}Trim(n,t){this.Reset(),!(this.ListOfPointsAndCrossings==null||this.ListOfPointsAndCrossings.length===0)&&(this.ListOfPointsAndCrossings=this.ListOfPointsAndCrossings.filter(e=>R.ComparePP(e.Location,n)>=0&&R.ComparePP(e.Location,t)<=0))}static ToCrossingArray(n,t){let e=0,i=n.length;for(let o=0;o<i;o++)n[o].DirectionToInside===t&&e++;if(e===0)return null;let r=new Array(e),s=0;for(let o=0;o<i;o++)n[o].DirectionToInside===t&&(r[s++]=n[o]);return r}ToString(){return CS.String.format("{0} [{1}]",this.ListOfPointsAndCrossings.length,this.index)}},rt=class Gt{static EdgeDirectionVE(t){return Gt.EdgeDirectionVV(t.Source,t.Target)}static EdgeDirectionVV(t,e){return R.GetDirections(t.point,e.point)}static GetEdgeEnd(t,e){let i=Gt.EdgeDirectionVE(t);return e===i?t.Target:t.Source}static FindAdjacentVertex(t,e){for(let i of t.InEdges)if(R.GetDirections(t.point,i.SourcePoint)===e)return i.Source;for(let i of t.OutEdges)if(R.GetDirections(t.point,i.TargetPoint)===e)return i.Target;return null}static FindAdjacentEdge(t,e){for(let i of t.InEdges)if(R.GetDirections(i.SourcePoint,t.point)===e)return i;for(let i of t.OutEdges)if(R.GetDirections(t.point,i.TargetPoint)===e)return i;return null}static FindBendPointBetween(t,e,i){return Gt.IsVerticalD(i)?new g(e.x,t.y):new g(t.x,e.y)}static SegmentIntersectionPPP(t,e,i){let r=R.GetDirections(t,e);return Gt.IsVerticalD(r)?new g(t.x,i.y):new g(i.x,t.y)}static SegmentIntersectionSP(t,e){return Gt.SegmentIntersectionPPP(t.Start,t.End,e)}static SegmentsIntersection(t,e){return Gt.IntervalsIntersect(t.Start,t.End,e.Start,e.End)}static SegmentsIntersectLL(t,e){return Gt.IntervalsIntersect(t.start,t.end,e.start,e.end)}static IntervalsOverlapSS(t,e){return Gt.IntervalsOverlapPPPP(t.Start,t.End,e.Start,e.End)}static IntervalsOverlapPPPP(t,e,i,r){return Gt.IntervalsAreCollinear(t,e,i,r)&&R.ComparePP(t,r)!==R.ComparePP(e,i)}static IntervalsAreCollinear(t,e,i,r){let s=Gt.IsVerticalPP(t,e);return Gt.IsVerticalPP(i,r)===s?s?R.Equal(t.x,i.x):R.Equal(t.y,i.y):!1}static IntervalsAreSame(t,e,i,r){return R.EqualPP(t,i)&&R.EqualPP(e,r)}static IntervalsIntersect(t,e,i,r){let s=Gt.SegmentIntersectionPPP(t,e,i);return Gt.PointIsOnSegmentPPP(t,e,s)&&Gt.PointIsOnSegmentPPP(i,r,s)?s:void 0}static SegmentIntersectionEP(t,e){return Gt.SegmentIntersectionPPP(t.SourcePoint,t.TargetPoint,e)}static PointIsOnSegmentPPP(t,e,i){return R.EqualPP(t,i)||R.EqualPP(e,i)||R.GetDirections(t,i)===R.GetDirections(i,e)}static PointIsOnSegmentSP(t,e){return Gt.PointIsOnSegmentPPP(t.Start,t.End,e)}static IsVerticalD(t){return(t&5)!==0}static IsVerticalE(t){return Gt.IsVerticalD(R.GetDirections(t.SourcePoint,t.TargetPoint))}static IsVerticalPP(t,e){return Gt.IsVerticalD(R.GetDirections(t,e))}static IsVertical(t){return Gt.IsVerticalD(R.GetDirections(t.start,t.end))}static IsAscending(t){return(t&3)!==0}static Slope(t,e,i){let r=e.sub(t);return r.dot(i.PerpDirectionAsPoint)/r.dot(i.DirectionAsPoint)}static SortAscending(t,e){let i=R.GetDirections(t,e);return i===0||Gt.IsAscending(i)?[t,e]:[e,t]}static RectangleBorderIntersect(t,e,i){switch(i){case 1:case 4:return new g(e.x,Gt.GetRectangleBound(t,i));case 2:case 8:return new g(Gt.GetRectangleBound(t,i),e.y);default:throw new Error}}static GetRectangleBound(t,e){switch(e){case 1:return t.top;case 4:return t.bottom;case 2:return t.right;case 8:return t.left;default:throw new Error}}static RectangleInteriorsIntersect(t,e){return R.Compare(t.bottom,e.top)<0&&R.Compare(e.bottom,t.top)<0&&R.Compare(t.left,e.right)<0&&R.Compare(e.left,t.right)<0}static PointIsInRectangleInterior(t,e){return R.Compare(t.y,e.top)<0&&R.Compare(e.bottom,t.y)<0&&R.Compare(t.x,e.right)<0&&R.Compare(e.left,t.x)<0}},Ee=class yr{get Dir(){return this.dir}set Dir(t){this.dir=t}constructor(t){this.Dir=t,this.DirectionAsPoint=J.toPoint(this.Dir),this.PerpDirection=t===1?2:1,this.PerpDirectionAsPoint=J.toPoint(this.PerpDirection),this.OppositeDirection=J.OppositeDir(t)}get IsHorizontal(){return this.Dir===2}get IsVertical(){return this.Dir===1}Compare(t,e){let i=this.ComparePerpCoord(t,e);return i!==0?i:this.CompareScanCoord(t,e)}CompareScanCoord(t,e){return R.Compare(t.sub(e).dot(this.DirectionAsPoint),0)}ComparePerpCoord(t,e){return R.Compare(t.sub(e).dot(this.PerpDirectionAsPoint),0)}IsFlatS(t){return this.IsFlatPP(t.Start,t.End)}IsFlatPP(t,e){return R.Equal(e.sub(t).dot(this.PerpDirectionAsPoint),0)}IsPerpendicularS(t){return this.IsPerpendicularPP(t.Start,t.End)}IsPerpendicularPP(t,e){return R.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}static{this.HorizontalInstance=new yr(2)}static{this.VerticalInstance=new yr(1)}get PerpendicularInstance(){return this.IsHorizontal?yr.VerticalInstance:yr.HorizontalInstance}static GetInstance(t){return rt.IsVerticalD(t)?yr.VerticalInstance:yr.HorizontalInstance}ToString(){return this.Dir.toString()}},bt=class Qi extends Ka{static{this.NormalWeight=Kr.DefaultWeight}static{this.ReflectionWeight=5}static{this.OverlappedWeight=500}static mk(t,e){return new Qi(t,e,Qi.NormalWeight,null)}constructor(t,e,i,r){super(),this.Update(t,e),this.Weight=i,this.GroupBoundaryPointAndCrossingsList=r}get Start(){return this.startPoint}get End(){return this.endPoint}get IsVertical(){return Qi.IsVerticalSegment(this.Start,this.End)}get ScanDirection(){return this.IsVertical?Ee.VerticalInstance:Ee.HorizontalInstance}get IsOverlapped(){return Qi.OverlappedWeight===this.Weight}get IsReflection(){return Qi.ReflectionWeight===this.Weight}static IsVerticalSegment(t,e){return t.x===e.x}MergeGroupBoundaryCrossingList(t){t!=null&&(this.GroupBoundaryPointAndCrossingsList==null&&(this.GroupBoundaryPointAndCrossingsList=new $n),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(R.IsPureLower(e.point,this.HighestVisibilityVertex.point))return;this.AddGroupCrossingsBeforeHighestVisibilityVertex(t,e)||this.AppendHighestVisibilityVertex(e)}}AddVisibilityEdge(t,e){let i=new Kr(t,e,this.Weight);return zt.AddEdge(i),i}AppendHighestVisibilityVertex(t){R.EqualPP(this.HighestVisibilityVertex.point,t.point)||(this.AddVisibilityEdge(this.HighestVisibilityVertex,t),this.HighestVisibilityVertex=t)}LoadStartOverlapVertexIfNeeded(t){if(this.NeedStartOverlapVertex){let e=t.FindVertex(this.Start);this.AppendVisibilityVertex(t,e??t.AddVertexP(this.Start))}}LoadEndOverlapVertexIfNeeded(t){if(this.NeedEndOverlapVertex){let 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||R.IsPureLower(this.HighestVisibilityVertex.point,this.End))&&this.LoadEndOverlapVertexIfNeeded(t)}static Subsume(t,e,i,r,s,o,a,l){return l.extendStart=!0,l.extendEnd=!0,t.seg==null||!rt.IntervalsOverlapPPPP(t.seg.Start,t.seg.End,e,i)?!1:t.seg.Weight!==r?t.seg.Start===e&&t.seg.End===i?(t.seg.Weight=Math.min(t.seg.Weight,r),!0):!1:(l.extendStart=o.CompareScanCoord(e,t.seg.Start)===-1,l.extendEnd=o.CompareScanCoord(i,t.seg.End)===1,(l.extendStart||l.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(s)),!0)}IntersectsSegment(t){return rt.SegmentsIntersection(this,t)!==void 0}toString(){return"["+this.Start+" -> "+this.End+(this.IsOverlapped?" olap":" free")+"]"}ContainsPoint(t){return R.EqualPP(this.Start,t)||R.EqualPP(this.End,t)||R.GetDirections(this.Start,t)===R.GetDirections(t,this.End)}get HasSparsePerpendicularCoords(){return this.sparsePerpendicularCoords==null?!1:this.sparsePerpendicularCoords.size>0}CreatePointFromPerpCoord(t){return this.IsVertical?new g(this.Start.x,t):new g(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){if(this.sparsePerpendicularCoords!=null){this.AppendGroupCrossingsThroughPoint(t,this.Start);for(let e of Array.from(this.sparsePerpendicularCoords.values()).sort(Mt)){let i=this.CreatePointFromPerpCoord(e);this.AppendVisibilityVertex(t,t.FindVertex(i)??t.AddVertexP(i))}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)?(R.IsPureLower(this.HighestVisibilityVertex.point,e.point)&&(this.AddVisibilityEdge(this.HighestVisibilityVertex,e),this.HighestVisibilityVertex=e),!0):!1}AppendGroupCrossingsThroughPoint(t,e){if(this.GroupBoundaryPointAndCrossingsList==null)return!1;let i=!1;for(;this.GroupBoundaryPointAndCrossingsList.CurrentIsBeforeOrAt(e);){let r=this.GroupBoundaryPointAndCrossingsList.Pop(),s=null,o=null;R.ComparePP(r.Location,this.Start)>0&&(s=$n.ToCrossingArray(r.Crossings,this.ScanDirection.OppositeDirection)),R.ComparePP(r.Location,this.End)<0&&(o=$n.ToCrossingArray(r.Crossings,this.ScanDirection.Dir)),i=!0;let a=t.FindVertex(r.Location)??t.AddVertexP(r.Location);t.AddVertexP(r.Location),s!=null||o!=null?(this.AddLowCrossings(t,a,s),this.AddHighCrossings(t,a,o)):this.LowestVisibilityVertex==null?this.SetInitialVisibilityVertex(a):this.AppendHighestVisibilityVertex(a)}return i}static GetCrossingInteriorVertex(t,e,i){let r=i.GetInteriorVertexPoint(e.point);return t.FindVertex(r)??t.AddVertexP(r)}AddCrossingEdge(t,e,i,r){let s=null;this.HighestVisibilityVertex!=null&&(R.EqualPP(this.HighestVisibilityVertex.point,i.point)?s=t.FindEdgePP(e.point,i.point):this.AppendHighestVisibilityVertex(e)),s==null&&(s=this.AddVisibilityEdge(e,i));let o=r.map(l=>l.Group.InputShape),a=s.IsPassable;a==null?s.IsPassable=()=>{for(let l of o)if(l.IsTransparent)return!0;return!1}:s.IsPassable=()=>{for(let l of o)if(l.IsTransparent||a())return!0;return!1},this.LowestVisibilityVertex==null&&this.SetInitialVisibilityVertex(e),this.HighestVisibilityVertex=i}AddLowCrossings(t,e,i){if(i!=null){let r=Qi.GetCrossingInteriorVertex(t,e,i[0]);this.AddCrossingEdge(t,r,e,i)}}AddHighCrossings(t,e,i){if(i!=null){let r=Qi.GetCrossingInteriorVertex(t,e,i[0]);this.AddCrossingEdge(t,e,r,i)}}},su=class{constructor(n,t,e,i,r){this.IsClosed=!1,this.Vertex=n,this.Direction=t!=null?J.DirectionFromPointToPoint(t.Vertex.point,n.point):0,this.ResetEntry(t,e,i,r)}ResetEntry(n,t,e,i){this.PreviousEntry=n,this.Length=t,this.NumberOfBends=e,this.Cost=i}get PreviousVertex(){return this.PreviousEntry==null?null:this.PreviousEntry.Vertex}toString(){return this.Vertex.point+(" "+(this.Direction+(" "+(this.IsClosed+(" "+this.Cost)))))}},ga=class{constructor(){this.Clear()}Set(n,t){this.Vertex=n,this.Weight=t}Clear(){this.Vertex=null,this.Weight=Number.NaN}},Sr=class kt{constructor(){this.nextNeighbors=[new ga,new ga,new ga],this.LengthImportance=1,this.BendsImportance=1}static{this.DefaultBendPenaltyAsAPercentageOfDistance=4}CombinedCost(t,e){return this.LengthImportance*t+this.BendsImportance*e}TotalCostFromSourceToVertex(t,e){return this.CombinedCost(t,e)+this.sourceCostAdjustment}InitPath(t,e,i){if(e===i||!this.InitEntryDirectionsAtTarget(i))return!1;this.Target=i,this.Source=e;let r=this.TotalCostFromSourceToVertex(0,0)+this.HeuristicDistanceFromVertexToTarget(e.point,0);return r>=this.upperBoundOnCost?!1:(this.queue=new nr(Mt),this.visitedVertices=[e],t==null?this.EnqueueInitialVerticesFromSource(r):this.EnqueueInitialVerticesFromSourceEntries(t),this.queue.count>0)}InitEntryDirectionsAtTarget(t){this.EntryDirectionsToTarget=0;for(let e of t.OutEdges)this.EntryDirectionsToTarget=this.EntryDirectionsToTarget|J.DirectionFromPointToPoint(e.TargetPoint,t.point);for(let e of t.InEdges)this.EntryDirectionsToTarget=this.EntryDirectionsToTarget|J.DirectionFromPointToPoint(e.SourcePoint,t.point);return this.EntryDirectionsToTarget!==0}static IsInDirs(t,e){return t===(t&e)}MultistageAdjustedCostBound(t){return Number.isFinite(t)?t+this.BendsImportance:t}HeuristicDistanceFromVertexToTarget(t,e){let i=this.Target.point.sub(t);if(lt(i.x,0)&<(i.y,0))return this.targetCostAdjustment;let r=J.VectorDirection(i),s;return e===0?(e=15,s=this.GetNumberOfBends(e,r)):s=this.GetNumberOfBends(e,r),this.CombinedCost(kt.ManhattanDistance(t,this.Target.point),s)+this.targetCostAdjustment}GetNumberOfBends(t,e){return J.IsPureDirection(e)?this.GetNumberOfBendsForPureDirection(t,e):kt.GetBendsForNotPureDirection(e,t,this.EntryDirectionsToTarget)}GetNumberOfBendsForPureDirection(t,e){return(e&t)===e?kt.IsInDirs(e,this.EntryDirectionsToTarget)?0:kt.IsInDirs(kt.Left(e),this.EntryDirectionsToTarget)||kt.IsInDirs(kt.Right(e),this.EntryDirectionsToTarget)?2:4:this.GetNumberOfBendsForPureDirection(kt.AddOneTurn[t],e)+1}static GetBendsForNotPureDirection(t,e,i){let r=t&e;if(r===0)return kt.GetBendsForNotPureDirection(t,kt.AddOneTurn[e],i)+1;let s=t&i;return s===0?kt.GetBendsForNotPureDirection(t,e,kt.AddOneTurn[i])+1:(r|s)===t?1:2}static{this.AddOneTurn=[0,11,7,15,14,15,15,15,13,15,15,15,15,15,15,15]}static Left(t){switch(t){case 0:return 0;case 1:return 8;case 2:return 1;case 4:return 2;case 8:return 4;default:throw new Error("direction")}}static Right(t){switch(t){case 0:return 0;case 1:return 2;case 2:return 4;case 4:return 8;case 8:return 1;default:throw new Error("direction")}}static RestorePathV(t){return kt.RestorePath(t,null)}static RestorePath(t,e){if(t.entry==null)return[];let i=new Array,r=!1,s=0;for(;;){s===t.entry.Direction?r=!0:(r=!1,i.push(t.entry.Vertex.point),s=t.entry.Direction);let o=t.entry.PreviousEntry;if(o==null||t.entry.Vertex===e)break;t.entry=o}return r&&i.push(t.entry.Vertex.point),i.reverse(),i}QueueReversedEntryToNeighborVertexIfNeeded(t,e,i){let r={numberOfBends:0,length:0},s=e.PreviousVertex,o=kt.GetLengthAndNumberOfBendsToNeighborVertex(t,s,i,r);if(this.CombinedCost(r.length,r.numberOfBends)<this.CombinedCost(e.Length,e.NumberOfBends)||t.Vertex.Degree===1){let a=this.TotalCostFromSourceToVertex(r.length,r.numberOfBends)+this.HeuristicDistanceFromVertexToTarget(s.point,o);this.EnqueueEntry(t,s,r.length,r.numberOfBends,a)}}UpdateEntryToNeighborVertexIfNeeded(t,e,i){let r={numberOfBends:0,length:0},s=kt.GetLengthAndNumberOfBendsToNeighborVertex(t,e.Vertex,i,r);if(this.CombinedCost(r.length,r.numberOfBends)<this.CombinedCost(e.Length,e.NumberOfBends)){let o=this.TotalCostFromSourceToVertex(r.length,r.numberOfBends)+this.HeuristicDistanceFromVertexToTarget(e.Vertex.point,s);e.ResetEntry(t,r.length,r.numberOfBends,o),this.queue.DecreasePriority(e,o)}}CreateAndEnqueueEntryToNeighborVertex(t,e,i){let r={numberOfBends:0,length:0},s=kt.GetLengthAndNumberOfBendsToNeighborVertex(t,e,i,r),o=this.TotalCostFromSourceToVertex(r.length,r.numberOfBends)+this.HeuristicDistanceFromVertexToTarget(e.point,s);o<this.upperBoundOnCost&&(e.VertexEntries==null&&this.visitedVertices.push(e),this.EnqueueEntry(t,e,r.length,r.numberOfBends,o))}EnqueueEntry(t,e,i,r,s){let o=new su(e,t,i,r,s);e.SetVertexEntry(o),this.queue.Enqueue(o,o.Cost)}static GetLengthAndNumberOfBendsToNeighborVertex(t,e,i,r){r.length=t.Length+kt.ManhattanDistance(t.Vertex.point,e.point)*i;let s=J.DirectionFromPointToPoint(t.Vertex.point,e.point);return r.numberOfBends=t.NumberOfBends,t.Direction!==0&&s!==t.Direction&&r.numberOfBends++,s}static ManhattanDistance(t,e){return Math.abs(e.x-t.x)+Math.abs(e.y-t.y)}GetPathWithCost(t,e,i,r,s,o,a){if(this.upperBoundOnCost=a,this.sourceCostAdjustment=i,this.targetCostAdjustment=o,!this.InitPath(t,e,s))return null;for(;this.queue.count>0;){let l=this.queue.Dequeue(),h=l.Vertex;if(h===this.Target){if(r==null)return this.Cleanup(),l;if(l.Direction,this.EntryDirectionsToTarget===0){let d=0;for(let c of this.Target.VertexEntries)r[d++]=c;return this.Cleanup(),null}this.upperBoundOnCost=Math.min(this.MultistageAdjustedCostBound(l.Cost),this.upperBoundOnCost);continue}l.IsClosed=!0;for(let d of this.nextNeighbors)d.Clear();let u=kt.Right(l.Direction);this.ExtendPathAlongInEdges(l,h.InEdges,u),this.ExtendPathAlongOutEdges(l,h.OutEdges,u);for(let d of this.nextNeighbors)d.Vertex!=null&&this.ExtendPathToNeighborVertex(l,d.Vertex,d.Weight)}if(r!=null&&this.Target.VertexEntries!=null)for(let l=0;l<this.Target.VertexEntries.length;l++)r[l]=this.Target.VertexEntries[l];return this.Cleanup(),null}ExtendPathAlongInEdges(t,e,i){for(let r of e)this.ExtendPathAlongEdge(t,r,!0,i)}ExtendPathAlongOutEdges(t,e,i){let r=e.isEmpty()?null:e.treeMinimum();for(;r!=null;r=e.next(r))this.ExtendPathAlongEdge(t,r.item,!1,i)}ExtendPathAlongEdge(t,e,i,r){if(!kt.IsPassable(e))return;let s=i?e.Source:e.Target;if(s===t.PreviousVertex){if(t.Vertex.Degree>1||t.Vertex!==this.Source)return;this.ExtendPathToNeighborVertex(t,s,e.Weight);return}let o=J.DirectionFromPointToPoint(t.Vertex.point,s.point),a=this.nextNeighbors[2];o!==t.Direction&&(a=this.nextNeighbors[o===r?1:0]),a.Set(s,e.Weight)}EnqueueInitialVerticesFromSource(t){let e=new su(this.Source,null,0,0,t);e.IsClosed=!0;for(let i of this.Source.OutEdges)kt.IsPassable(i)&&this.ExtendPathToNeighborVertex(e,i.Target,i.Weight);for(let i of this.Source.InEdges)kt.IsPassable(i)&&this.ExtendPathToNeighborVertex(e,i.Source,i.Weight)}EnqueueInitialVerticesFromSourceEntries(t){for(let e of t)e!=null&&this.queue.Enqueue(e,e.Cost)}ExtendPathToNeighborVertex(t,e,i){let r=J.DirectionFromPointToPoint(t.Vertex.point,e.point),s=e.VertexEntries!=null?e.VertexEntries[J.ToIndex(r)]:null;s==null?this.CreateAndEnqueueReversedEntryToNeighborVertex(t,e,i)||this.CreateAndEnqueueEntryToNeighborVertex(t,e,i):s.IsClosed||this.UpdateEntryToNeighborVertexIfNeeded(t,s,i)}CreateAndEnqueueReversedEntryToNeighborVertex(t,e,i){if(t.Vertex.VertexEntries!=null){let r=J.DirectionFromPointToPoint(e.point,t.Vertex.point),s=t.Vertex.VertexEntries[J.ToIndex(r)];if(s!=null)return this.QueueReversedEntryToNeighborVertexIfNeeded(t,s,i),!0}return!1}static IsPassable(t){return t.IsPassable==null||t.IsPassable()}Cleanup(){for(let t of this.visitedVertices)t.RemoveVertexEntries();this.visitedVertices=[],this.queue=null}},xS=class Qs{constructor(t){this.bendPenaltyAsAPercentageOfDistance=Sr.DefaultBendPenaltyAsAPercentageOfDistance,this.currentPassTargetEntries=new Array(4),this.bendPenaltyAsAPercentageOfDistance=t}GetPath(t,e){let i={entry:this.GetPathStage(null,t,null,e)};return Sr.RestorePathV(i)}GetPathStage(t,e,i,r){let s=new Sr,o={bestEntry:null,bestCost:Number.MAX_VALUE/bt.OverlappedWeight},a=Number.POSITIVE_INFINITY,l=Qs.Barycenter(e),h=Qs.Barycenter(r),u=Sr.ManhattanDistance(l,h);s.BendsImportance=Math.max(.001,u*(this.bendPenaltyAsAPercentageOfDistance*.01));let d=s.LengthImportance,c=i!=null?this.currentPassTargetEntries:null,f=[];for(let v of e)for(let b of r)f.push([v,b]);f.sort(([v,b],[C,E])=>m(v,b)-m(C,E));for(let[v,b]of f){if(g.closeDistEps(v.point,b.point))continue;let C=P(v,l)*d,E=P(b,h)*d,w=o.bestCost;if(i!=null){for(let q=0;q<c.length;q++)c[q]=null;w=s.MultistageAdjustedCostBound(o.bestCost)}let F=s.GetPathWithCost(t,v,C,c,b,E,w);if(c!=null){Qs.UpdateTargetEntriesForEachDirection(i,c,o);continue}if(F==null)continue;let V=F.Cost/m(v,b);(F.Cost<o.bestCost||lt(F.Cost,o.bestCost)&&V<a)&&(o.bestCost=F.Cost,o.bestEntry=F,a=F.Cost/m(v,b))}return o.bestEntry;function m(v,b){return Sr.ManhattanDistance(v.point,b.point)}function P(v,b){return Sr.ManhattanDistance(v.point,b)}}static UpdateTargetEntriesForEachDirection(t,e,i){for(let r=0;r<e.length;r++){let s=e[r];s!=null&&(t[r]==null||s.Cost<t[r].Cost)&&(t[r]=s,s.Cost<i.bestCost&&(i.bestCost=s.Cost,i.bestEntry=s))}}static Barycenter(t){let e=new g(0,0);for(let i of t)e=e.add(i.point);return e.div(t.length)}},ES=ct(se(),1),AS=class{get PathPoints(){return this._pathPoints}set PathPoints(n){this._pathPoints=n}get Width(){return this.GeomEdge.lineWidth}constructor(n){this.GeomEdge=n}get End(){return this.LastEdge.Target}get Start(){return this.FirstEdge.Source}ArrayOfPathPoints(){return this._pathPoints instanceof wr?Array.from(ou(this._pathPoints)):this._pathPoints}*PathEdges(){for(let n=this.FirstEdge;n!=null;n=n.Next)yield n}AddEdge(n){n.Path=this,this.LastEdge.Next=n,n.Prev=this.LastEdge,this.LastEdge=n}SetFirstEdge(n){this.FirstEdge=n,this.LastEdge=n,n.Path=this}toString(){let n=new ES.StringBuilder;this.PathPoints instanceof wr&&n.Append("L");for(let t of ou(this.PathPoints))n.Append(t.toString());return n.ToString()}};function*ou(n){if(n instanceof wr)for(let t=n;t!=null;t=t.Next)yield t.Point;else for(let t of n)yield t}var rc=class extends _a{constructor(n,t,e,i){super(t),this.Slope=0,this.SlopeInverse=0,this.Obstacle=n,this.endVertex=i?t.nextOnPolyline:t.prevOnPolyline,e.IsPerpendicularPP(t.point,this.endVertex.point)||(this.Slope=rt.Slope(t.point,this.endVertex.point,e),this.SlopeInverse=1/this.Slope)}get Obstacle(){return this.obstacle}set Obstacle(n){this.obstacle=n}get EndVertex(){return this.endVertex}},Je=class extends rc{constructor(n,t,e){super(n,t,e,e.IsHorizontal)}},Hn=class extends rc{constructor(n,t,e){super(n,t,e,e.IsVertical)}},mi=class br{static{this.FirstSentinelOrdinal=1}static{this.FirstNonSentinelOrdinal=10}get PaddedPolyline(){return this._PaddedPolyline}set PaddedPolyline(t){this._PaddedPolyline=t}get looseVisibilityPolyline(){return this._looseVisibilityPolyline==null&&(this._looseVisibilityPolyline=br.CreateLoosePolyline(this.VisibilityPolyline)),this._looseVisibilityPolyline}set looseVisibilityPolyline(t){this._looseVisibilityPolyline=t}GetPortChanges(t){return t.addedPorts=Zr(this.InputShape.Ports,this.Ports),t.removedPorts=Zr(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,r){let s=br.mk(t,e,r);return s.CreateInitialSides(s.PaddedPolyline.startPoint,i),s}CreateInitialSides(t,e){this.ActiveLowSide=new Je(this,t,e),this.ActiveHighSide=new Hn(this,t,e),e.IsFlatS(this.ActiveHighSide)&&(this.ActiveHighSide=new Hn(this,this.ActiveHighSide.EndVertex,e))}constructor(t,e){t!=null&&(this.PaddedPolyline=ye.PaddedPolylineBoundaryOfNode(t.BoundaryCurve,e),br.RoundVerticesAndSimplify(this.PaddedPolyline),this.IsRectangle=this.IsPolylineRectangle(),this.InputShape=t,this.Ports=new Set(this.InputShape.Ports))}static mk(t,e,i){let r=new br(null,0);return r.PaddedPolyline=et.mkClosedFromPoints([g.RoundPoint(t),g.RoundPoint(e)]),r.Ordinal=i,r}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;let r=J.DirectionFromPointToPoint(t.point,e.point);if(r!==J.RotateRight(i))return!1;i=r}while(t!==this.PaddedPolyline.startPoint);return!0}static RoundVerticesAndSimplify(t){let e=t.startPoint;do e.point=g.RoundPoint(e.point),e=e.nextOnPolyline;while(e!==t.startPoint);br.RemoveCloseAndCollinearVerticesInPlace(t),t.setInitIsRequired()}get IsPrimaryObstacle(){return this.ConvexHull==null||this===this.ConvexHull.PrimaryObstacle}static RemoveCloseAndCollinearVerticesInPlace(t){let e=x.intersectionEpsilon*10;for(let i=t.startPoint.next;i!=null;i=i.next)g.close(i.prev.point,i.point,e)&&(i.next==null?t.RemoveEndPoint():(i.prev.next=i.next,i.next.prev=i.prev));return g.close(t.start,t.end,e)&&t.RemoveStartPoint(),t=t.RemoveCollinearVertices(),t.endPoint.prev!=null&&t.endPoint.prev!==t.startPoint&&g.getTriangleOrientation(t.endPoint.prev.point,t.end,t.start)===2&&t.RemoveEndPoint(),t.startPoint.next!=null&&t.endPoint.prev!==t.startPoint&&g.getTriangleOrientation(t.end,t.start,t.startPoint.next.point)===2&&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){let e=ye.CreatePaddedPolyline(t,x.intersectionEpsilon*10);return br.RoundVerticesAndSimplify(e),e}get IsTransparentAncestor(){return this.InputShape==null?!1:this.InputShape.IsTransparent}set IsTransparentAncestor(t){this.InputShape.IsTransparent=t}},wS=ct(se(),1),IS=class{constructor(n,t,e,i){this.IsOverlapped=!1,this.unpaddedToPaddedBorderWeight=bt.NormalWeight,this.ObstaclePort=n,this.UnpaddedBorderIntersect=t,this.OutwardDirection=e;let r=D.mkPP(this.UnpaddedBorderIntersect,rt.RectangleBorderIntersect(n.Obstacle.VisibilityBoundingBox,this.UnpaddedBorderIntersect,e)),s=G.getAllIntersections(r,n.Obstacle.VisibilityPolyline,!0);this.VisibilityBorderIntersect=g.RoundPoint(s[0].x);let o={pacList:null};this.MaxVisibilitySegment=i.CreateMaxVisibilitySegment(this.VisibilityBorderIntersect,this.OutwardDirection,o),this.pointAndCrossingsList=o.pacList,(this.Obstacle.isOverlapped||this.Obstacle.IsGroup&&!this.Obstacle.IsInConvexHull)&&(this.IsOverlapped=i.IntersectionIsInsideAnotherObstacle(null,this.Obstacle,this.VisibilityBorderIntersect,Ee.GetInstance(this.OutwardDirection)),(!this.Obstacle.IsGroup||this.IsOverlapped||this.InteriorEdgeCrossesObstacle(i))&&(this.unpaddedToPaddedBorderWeight=bt.OverlappedWeight)),this.Obstacle.IsInConvexHull&&this.unpaddedToPaddedBorderWeight===bt.NormalWeight&&this.SetUnpaddedToPaddedBorderWeightFromHullSiblingOverlaps(i)}get Obstacle(){return this.ObstaclePort.Obstacle}get InitialWeight(){return this.IsOverlapped?bt.OverlappedWeight:bt.NormalWeight}get IsCollinearWithPort(){return J.IsPureDirection(R.GetDirections(this.VisibilityBorderIntersect,this.ObstaclePort.Location))}get IsVertical(){return rt.IsVertical(this.MaxVisibilitySegment)}get WantVisibilityIntersection(){return!this.IsOverlapped&&this.CanExtend&&(!this.ObstaclePort.HasCollinearEntrances||this.IsCollinearWithPort)}get CanExtend(){return R.GetDirections(this.MaxVisibilitySegment.start,this.MaxVisibilitySegment.end)!==0}SetUnpaddedToPaddedBorderWeightFromHullSiblingOverlaps(n){(this.Obstacle.IsGroup?this.InteriorEdgeCrossesObstacle(n):this.InteriorEdgeCrossesConvexHullSiblings())&&(this.unpaddedToPaddedBorderWeight=bt.OverlappedWeight)}InteriorEdgeCrossesObstacle(n){let t=it.mkPP(this.UnpaddedBorderIntersect,this.VisibilityBorderIntersect);return this.InteriorEdgeCrossesObstacleRFI(t,e=>e.VisibilityPolyline,Array.from(n.Root.GetLeafRectangleNodesIntersectingRectangle(t)).filter(e=>!e.UserData.IsGroup&&e.UserData!==this.Obstacle).map(e=>e.UserData))}InteriorEdgeCrossesConvexHullSiblings(){let n=it.mkPP(this.UnpaddedBorderIntersect,this.VisibilityBorderIntersect);return this.InteriorEdgeCrossesObstacleRFI(n,t=>t.PaddedPolyline,this.Obstacle.ConvexHull.Obstacles.filter(t=>t!==this.Obstacle))}InteriorEdgeCrossesObstacleRFI(n,t,e){let i=null;for(let r of e){let s=t(r);if(rt.RectangleInteriorsIntersect(n,s.boundingBox)&&(i=i??D.mkPP(this.UnpaddedBorderIntersect,this.VisibilityBorderIntersect),G.intersectionOne(i,s,!1)!=null||G.PointRelativeToCurveLocation(this.UnpaddedBorderIntersect,s)!==0))return!0}return!1}get HasGroupCrossings(){return this.pointAndCrossingsList!=null&&this.pointAndCrossingsList.Count()>0}HasGroupCrossingBeforePoint(n){if(!this.HasGroupCrossings)return!1;let t=rt.IsAscending(this.OutwardDirection)?this.pointAndCrossingsList.First:this.pointAndCrossingsList.Last;return R.GetDirections(this.MaxVisibilitySegment.start,t.Location)===R.GetDirections(t.Location,n)}AddToAdjacentVertex(n,t,e,i){let r=n.VisGraph.FindVertex(this.VisibilityBorderIntersect);if(r!=null){this.ExtendEdgeChain(n,r,r,e,i);return}this.OutwardDirection===R.GetDirections(t.point,this.VisibilityBorderIntersect)?(this.VisibilityBorderIntersect=t.point,r=t):(r=n.FindOrAddVertex(this.VisibilityBorderIntersect),n.FindOrAddEdge(r,t,this.InitialWeight)),this.ExtendEdgeChain(n,r,t,e,i)}ExtendEdgeChain(n,t,e,i,r){n.ExtendEdgeChainVRLPB(e,i,this.MaxVisibilitySegment,this.pointAndCrossingsList,this.IsOverlapped);let s=n.FindOrAddVertex(this.UnpaddedBorderIntersect);n.FindOrAddEdge(s,t,this.unpaddedToPaddedBorderWeight),r&&n.ConnectVertexToTargetVertex(this.ObstaclePort.CenterVertex,s,this.OutwardDirection,this.InitialWeight)}toString(){return wS.String.format("{0} {1}~{2} {3}",this.ObstaclePort.Location,this.UnpaddedBorderIntersect,this.VisibilityBorderIntersect,this.OutwardDirection)}},TS=class{constructor(n,t){this.HasCollinearEntrances=!1,this.VisibilityRectangle=it.mkEmpty(),this.Port=n,this.Obstacle=t,this.PortEntrances=new Array,this.Location=g.RoundPoint(this.Port.Location)}CreatePortEntrance(n,t,e){let i=new IS(this,n,t,e);this.PortEntrances.push(i),this.VisibilityRectangle.add(i.MaxVisibilitySegment.end),this.HasCollinearEntrances=this.HasCollinearEntrances||i.IsCollinearWithPort}ClearVisibility(){this.PortEntrances=[]}AddToGraph(n,t){t&&(this.CenterVertex=n.FindOrAddVertex(this.Location))}RemoveFromGraph(){this.CenterVertex=null}get LocationHasChanged(){return!g.closeDistEps(this.Location,g.RoundPoint(this.Port.Location))}get PortCurve(){return this.Port.Curve}get PortLocation(){return this.Port.Location}toString(){return this.Port+this.Obstacle.toString()}},OS=class{constructor(n,t){this.maxVisibilitySegmentsAndCrossings=new Array(4),this.OutOfBoundsDirectionFromGraph=0,this.GetVertex(n,t)}get Point(){return this.Vertex.point}get InitialWeight(){return this.IsOverlapped?bt.OverlappedWeight:bt.NormalWeight}get IsOutOfBounds(){return this.OutOfBoundsDirectionFromGraph!==0}GetVertex(n,t){this.Vertex=n.FindOrAddVertex(t)}AddEdgeToAdjacentEdge(n,t,e,i){let r=rt.SegmentIntersectionEP(t,this.Point),s=n.VisGraph.FindVertex(r);return s!=null?this.AddToAdjacentVertex(n,s,e,i):s=n.AddEdgeToTargetEdge(this.Vertex,t,r),this.ExtendEdgeChain(n,s,e,i),s}AddToAdjacentVertex(n,t,e,i){R.EqualPP(this.Point,t.point)||n.FindOrAddEdge(this.Vertex,t,this.InitialWeight),this.ExtendEdgeChain(n,t,e,i)}ExtendEdgeChain(n,t,e,i){let r=this.IsOverlapped;r&&(r=n.ObstacleTree.PointIsInsideAnObstaclePD(t.point,e));let s=this.GetSegmentAndCrossings(this.IsOverlapped?t:this.Vertex,e,n);n.ExtendEdgeChainVRLPB(t,i,s[0],s[1],r)}GetSegmentAndCrossings(n,t,e){let i=J.ToIndex(t),r=this.maxVisibilitySegmentsAndCrossings[i];if(r==null){let s={pacList:null};r=[e.ObstacleTree.CreateMaxVisibilitySegment(n.point,t,s),s.pacList],this.maxVisibilitySegmentsAndCrossings[i]=r}else R.GetDirections(n.point,r[0].start)===t&&(r[0].start=n.point);return r}MaxVisibilityInDirectionForNonOverlappedFreePoint(n,t){return this.GetSegmentAndCrossings(this.Vertex,n,t)[0].end}AddOobEdgesFromGraphCorner(n,t){let e=R.GetDirections(t,this.Vertex.point),i=n.VisGraph.FindVertex(t);n.ConnectVertexToTargetVertex(i,this.Vertex,e&5,bt.NormalWeight),n.ConnectVertexToTargetVertex(i,this.Vertex,e&10,bt.NormalWeight)}RemoveFromGraph(){this.Vertex=null}toString(){return this.Vertex.toString()}},LS=ct(se(),1),BS=ct(se(),1),nc=class{constructor(n,t){this.BoundaryWidth=x.distanceEpsilon,this.Group=n,this.DirectionToInside=t}static{this.BoundaryWidth=x.distanceEpsilon}GetInteriorVertexPoint(n){return g.RoundPoint(n.add(J.toPoint(this.DirectionToInside).mul(this.BoundaryWidth)))}toString(){return BS.String.format("{0} {1}",this.DirectionToInside,this.Group)}},pa=class extends Gi{constructor(n){super(),this.site=n}get Site(){return this.site}},mo=class extends nn{constructor(n,t){super(t),this.Obstacle=n}},Xs=class extends mo{constructor(n,t){super(n,t)}},RS=class{AddPendingPerpendicularCoord(n){this.pendingPerpCoords==null&&(this.pendingPerpCoords=new Array),this.pendingPerpCoords.push(n)}ResetForIntersections(){this.CurrentSegment=this.FirstSegment}get IsHorizontal(){return!this.FirstSegment.IsVertical}constructor(n){this.Coord=n}TraverseToSegmentContainingPoint(n){if(this.CurrentSegment.ContainsPoint(n))return!0;let t=this.IsHorizontal?n.y:n.x;if(!R.Equal(this.Coord,t)){for(;this.MoveNext(););return!1}for(;;){if((this.CurrentSegment.NextSegment==null||R.GetDirections(this.CurrentSegment.End,n)==R.GetDirections(n,this.CurrentSegment.NextSegment.Start))&&g.closeIntersections(this.CurrentSegment.End,n))return this.CurrentSegment.Update(this.CurrentSegment.Start,n),!0;if(!this.MoveNext())return!1;if(this.CurrentSegment.ContainsPoint(n))return!0;if(R.IsPureLower(n,this.CurrentSegment.Start))return this.CurrentSegment.Update(n,this.CurrentSegment.End),!0}}MoveNext(){return this.CurrentSegment=this.CurrentSegment.NextSegment,this.HasCurrent}get HasCurrent(){return this.CurrentSegment!=null}PointIsCurrentEndAndNextStart(n){return n.equal(this.CurrentSegment.End)&&this.CurrentSegment.NextSegment!=null&&n.equal(this.CurrentSegment.NextSegment.Start)}AddPerpendicularCoord(n){let t=this.IsHorizontal?new g(n,this.Coord):new g(this.Coord,n);this.TraverseToSegmentContainingPoint(t),this.CurrentSegment.AddSparseVertexCoord(n)}toString(){return this.FirstSegment==null?"-0- "+this.Coord:this.IsHorizontal?"(H) Y === "+this.Coord:"(V) X === "}AppendScanSegment(n){this.FirstSegment==null?this.FirstSegment=n:this.CurrentSegment.NextSegment=n,this.CurrentSegment=n}AddPendingPerpendicularCoordsToScanSegments(){if(this.pendingPerpCoords!=null){this.ResetForIntersections();for(let n of this.pendingPerpCoords)this.AddPerpendicularCoord(n)}}},au=class{constructor(n,t){this.CurrentSlotIndex=0,this.vector=[],this.IsHorizontal=t;let e=Array.from(n).sort((i,r)=>i>r?1:i<r?-1:0);for(let i of e)this.vector.push(new RS(i))}get Length(){return this.vector.length}get CurrentSlot(){return this.vector[this.CurrentSlotIndex]}Item(n){return this.vector[n]}CreateScanSegment(n,t,e,i){this.CurrentSlot.AppendScanSegment(new bt(n,t,e,i))}ScanSegmentsCompleteForCurrentSlot(){this.CurrentSlotIndex++}ScanSegmentsComplete(){for(let n of this.vector)n.AddPendingPerpendicularCoordsToScanSegments()}Items(){return this.vector}ResetForIntersections(){for(let n of this.vector)n.ResetForIntersections()}FindNearest(n,t){let e=0,i=this.vector.length-1;if(n<=this.vector[e].Coord)return e;if(n>=this.vector[i].Coord)return i;for(;i-e>2;){let r=e+(i-e>>1),s=this.vector[r];if(n<s.Coord){i=r;continue}if(n>s.Coord){e=r;continue}return r}for(e++;e<=i;e++){let r=this.vector[e];if(n<r.Coord)return t>0?e:e-1;if(n===r.Coord)break}return e}CreateSparseVerticesAndEdges(n){for(let t of this.vector){t.ResetForIntersections();for(let e=t.FirstSegment;e!=null;e=e.NextSegment)e.CreateSparseVerticesAndEdges(n)}}GetParallelCoord(n){return this.IsHorizontal?n.y:n.x}GetPerpendicularCoord(n){return this.IsHorizontal?n.x:n.y}ConnectAdjoiningSegmentEndpoints(){for(let n of this.vector){n.ResetForIntersections();let t=n.FirstSegment;for(let e=t.NextSegment;e!=null;e=e.NextSegment){if(e.HasSparsePerpendicularCoords&&t.HasSparsePerpendicularCoords&&e.Start===t.End){let i=this.GetPerpendicularCoord(e.Start);t.AddSparseEndpoint(i),e.AddSparseEndpoint(i)}t=e}}}toString(){return(this.IsHorizontal?"(H) count":"(V) count === ")+this.vector.length}},Qn=class sc extends Gi{constructor(t,e,i){super(),this.InitialObstacle=t,this.ReflectingObstacle=e,this.site=i}static mk(t,e,i){let r=new sc(t.ReflectingObstacle,e,i);return r.PreviousSite=t,r}IsStaircaseStep(t){return this.InitialObstacle===t}get Site(){return this.site}},lu=class{constructor(){this.eventTree=new tl((n,t)=>this.Compare(n,t))}Reset(n){this.scanDirection=n}Enqueue(n){this.eventTree.Enqueue(n)}Dequeue(){return this.eventTree.Dequeue()}get Count(){return this.eventTree.Count}Compare(n,t){if(n===t)return 0;if(n==null)return-1;if(t==null)return 1;let e=this.scanDirection.ComparePerpCoord(n.Site,t.Site);if(e)return e;let i=n instanceof Qn?0:1,r=t instanceof Qn?0:1;return e=i-r,e||this.scanDirection.CompareScanCoord(n.Site,t.Site)}},FS=ct(se(),1),oc=class{constructor(){this.pointCrossingMap=new _e,this.pointList=new Array}AddIntersection(n,t,e){let i=this.pointCrossingMap.get(n);i||(i=new Array,this.pointCrossingMap.set(n,i));let r=i.length;for(let o=0;o<r;o++){let a=i[o];if(a.Group===t)return a}let s=new nc(t,e);return i.push(s),s}Clear(){this.pointCrossingMap.clear()}GetOrderedListBetween(n,t){if(this.pointCrossingMap.size===0)return null;if(R.ComparePP(n,t)>0){let r=n;n=t,t=r}this.pointList=[];for(let r of this.pointCrossingMap.keys())R.ComparePP(r,n)>=0&&R.ComparePP(r,t)<=0&&this.pointList.push(r);this.pointList.sort((r,s)=>r.compareTo(s));let e=new $n,i=this.pointList.length;for(let r=0;r<i;r++){let s=this.pointList[r];e.Add(s,this.pointCrossingMap.get(s))}return e}toString(){return FS.String.format("{0}",this.pointCrossingMap.size)}},hu=class extends Qn{constructor(n,t,e){super(n.ReflectingObstacle,t.Obstacle,e),this.Side=t}},NS=class{constructor(n){this.staleSites=new Array,this.scanDirection=n,this.eventTree=new Re((t,e)=>this.CompareBB(t,e)),this.findFirstPred=t=>this.CompareToFindFirstPoint(t.Site)>=0}Add(n){this.eventTree.insert(n)}MarkStaleSite(n){this.staleSites.push(n)}RemoveStaleSites(){let n=this.staleSites.length;if(n>0){for(let t=0;t<n;t++)this.RemoveExact(this.staleSites[t]);this.staleSites=[]}}RemoveSitesForFlatBottom(n,t){for(let e=this.FindFirstInRange(n,t);e!=null;e=this.FindNextInRange(e,t))this.MarkStaleSite(e.item);this.RemoveStaleSites()}Find(n){return this.FindFirstInRange(n,n)}RemoveExact(n){let t=this.eventTree.find(n);return t!=null&&t.item.Site===n.Site?(this.eventTree.deleteNodeInternal(t),!0):!1}FindFirstInRange(n,t){this.findFirstPoint=n;let e=this.eventTree.findFirst(this.findFirstPred);return e!=null&&this.Compare(e.item.Site,t)<=0?e:null}CompareToFindFirstPoint(n){return this.Compare(n,this.findFirstPoint)}FindNextInRange(n,t){let e=this.eventTree.next(n);return e!=null&&this.Compare(e.item.Site,t)<=0?e:null}CompareBB(n,t){return this.scanDirection.CompareScanCoord(n.Site,t.Site)}Compare(n,t){return this.scanDirection.CompareScanCoord(n,t)}},uu=class extends mo{constructor(n,t){super(n,t)}},du=class extends mo{constructor(n,t){super(n,t)}},cu=class extends mo{constructor(n,t){super(n,t)}},gu=class extends Qn{constructor(n,t,e){super(n.ReflectingObstacle,t.obstacle,e),this.Side=t}},pu=class{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(n,t,e,i){if(rt.IsAscending(n)){this.HighNeighbor=t,this.HighOverlapEnd=e,this.GroupSideInterveningBeforeHighNeighbor=i;return}this.LowNeighbor=t,this.LowOverlapEnd=e,this.GroupSideInterveningBeforeLowNeighbor=i}},fu=class{constructor(n,t){this.Polyline=n,this.Obstacles=Array.from(t),this.PrimaryObstacle=this.Obstacles[0],mi.RoundVerticesAndSimplify(this.Polyline)}},Xa=class Ya{static MungeClosestIntersectionInfo(t,e,i){let r=e.seg1.boundingBox,s=g.RoundPoint(e.x).clone();return i?new g(Ya.MungeIntersect(t.x,s.x,r.left,r.right),s.y):new g(s.x,Ya.MungeIntersect(t.y,s.y,r.bottom,r.top))}static MungeIntersect(t,e,i,r){if(t<e){let s=Math.min(i,r);e<s&&(e=s)}else if(t>e){let s=Math.max(i,r);e>s&&(e=s)}return g.RoundDouble(e)}},GS=class $t{constructor(){this.CurrentGroupBoundaryCrossingMap=new oc,this.overlapPairs=new Fi,this.hasOverlaps=!1,this.lookupIntPair=new mt(-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=mi.FirstNonSentinelOrdinal;for(let i of this.allObstacles)i.Ordinal=e++}OrdinalToObstacle(t){return this.allObstacles[t-mi.FirstNonSentinelOrdinal]}CreateRoot(){this.Root=$t.CalculateHierarchy(this.GetAllObstacles()),this.OverlapsExist()&&(this.AccreteClumps(),this.AccreteConvexHulls(),this.GrowGroupsToAccommodateOverlaps(),this.Root=$t.CalculateHierarchy(this.GetAllObstacles().filter(t=>t.IsPrimaryObstacle)))}OverlapsExist(){return this.Root==null?!1:(de(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;let i={bIsInsideA:!1,aIsInsideB:!1};if($t.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){let e=Array.from(t).map(i=>ne(i,i.VisibilityBoundingBox));return qt(e)}AccumulateObstaclesForClumps(){this.overlapPairs.clear();let t=$t.CalculateHierarchy(this.GetAllObstacles().filter(e=>!e.IsGroup&&e.IsRectangle));t!=null&&xe(t,t,(e,i)=>this.EvaluateOverlappedPairForClump(e,i))}EvaluateOverlappedPairForClump(t,e){if(t===e||this.OverlapPairAlreadyFound(t,e))return;let i={bIsInsideA:!1,aIsInsideB:!1};!$t.ObstaclesIntersect(t,e,i)&&!i.aIsInsideB&&!i.bIsInsideA||this.overlapPairs.add(new mt(t.Ordinal,e.Ordinal))}AccumulateObstaclesForConvexHulls(){this.overlapPairs.clear();let t=$t.CalculateHierarchy(this.GetAllObstacles().filter(e=>e.IsPrimaryObstacle&&!e.IsGroup));t!=null&&xe(t,t,(e,i)=>this.EvaluateOverlappedPairForConvexHull(e,i))}EvaluateOverlappedPairForConvexHull(t,e){if(t===e||this.OverlapPairAlreadyFound(t,e))return;let i={bIsInsideA:!1,aIsInsideB:!1};!$t.ObstaclesIntersect(t,e,i)&&!i.aIsInsideB&&!i.bIsInsideA||!t.IsInConvexHull&&!e.IsInConvexHull&&t.IsRectangle&&e.IsRectangle||(this.overlapPairs.add(new mt(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(){let t=$t.CalculateHierarchy(this.GetAllObstacles().filter(i=>i.IsGroup)),e=$t.CalculateHierarchy(this.GetAllObstacles().filter(i=>i.IsPrimaryObstacle));t==null||e==null||xe(t,e,(i,r)=>this.EvaluateOverlappedPairForGroup(i,r))}EvaluateOverlappedPairForGroup(t,e){if(t===e||this.OverlapPairAlreadyFound(t,e))return;let i={bIsInsideA:!1,aIsInsideB:!1},r=$t.ObstaclesIntersect(t,e,i);if(!(!r&&!i.aIsInsideB&&!i.bIsInsideA)){if(t.IsRectangle&&e.IsRectangle){e.IsGroup||(i.aIsInsideB||$t.FirstRectangleContainsACornerOfTheOther(e.VisibilityBoundingBox,t.VisibilityBoundingBox))&&(e.OverlapsGroupCorner=!0);return}!r&&(e.IsGroup||i.bIsInsideA)||this.overlapPairs.add(new mt(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 G.PointRelativeToCurveLocation(t.start,e)!==0}AddClumpToConvexHull(t){if(t.isOverlapped){for(let e of t.clump.filter(i=>i.Ordinal!==t.Ordinal))this.overlapPairs.add(new mt(t.Ordinal,e.Ordinal));t.clump=[]}}AddConvexHullToConvexHull(t){if(t.IsInConvexHull){for(let e of t.ConvexHull.Obstacles.filter(i=>i.Ordinal!==t.Ordinal))this.overlapPairs.add(new mt(t.Ordinal,e.Ordinal));t.ConvexHull.Obstacles=[]}}CreateClumps(){let t=Ks(Array.from(this.overlapPairs.values())),e=tn(t);for(let i of e){if(i.length===1)continue;let r=i.map(s=>this.OrdinalToObstacle(s));for(let s of r)s.clump=r}}CreateConvexHulls(){let t=!1,e=Ks(Array.from(this.overlapPairs.values())),i=tn(e);for(let r of i){if(r.length===1)continue;t=!0;let s=r.map(this.OrdinalToObstacle),o=Xn(s,l=>l.VisibilityPolyline),a=new fu(Ji.createConvexHullAsClosedPolyline(o),s);for(let l of s)l.SetConvexHull(a)}return t}GrowGroupsToResolveOverlaps(){let t=!1;for(let e of this.overlapPairs.values()){t=!0;let i=this.OrdinalToObstacle(e.x),r=this.OrdinalToObstacle(e.y);$t.ResolveGroupAndGroupOverlap(i,r)||$t.ResolveGroupAndObstacleOverlap(i,r)}return this.overlapPairs.clear(),t}static ResolveGroupAndGroupOverlap(t,e){return e.IsGroup?(t.VisibilityPolyline.boundingBox.area>e.VisibilityPolyline.boundingBox.area?$t.ResolveGroupAndObstacleOverlap(t,e):$t.ResolveGroupAndObstacleOverlap(e,t),!0):!1}static ResolveGroupAndObstacleOverlap(t,e){let i=e.looseVisibilityPolyline;$t.GrowGroupAroundLoosePolyline(t,i);let r={bIsInsideA:!1,aIsInsideB:!1};for(;$t.ObstaclesIntersect(e,t,r)||!r.aIsInsideB;)i=mi.CreateLoosePolyline(i),$t.GrowGroupAroundLoosePolyline(t,i)}static GrowGroupAroundLoosePolyline(t,e){let i=Array.from(t.VisibilityPolyline).concat(Array.from(e));t.SetConvexHull(new fu(Ji.createConvexHullAsClosedPolyline(i),[t]))}static ObstaclesIntersect(t,e,i){return G.CurvesIntersect(t.VisibilityPolyline,e.VisibilityPolyline)?(i.aIsInsideB=!1,i.bIsInsideA=!1,!0):(i.aIsInsideB=$t.FirstPolylineStartIsInsideSecondPolyline(t.VisibilityPolyline,e.VisibilityPolyline),i.bIsInsideA=!i.aIsInsideB&&$t.FirstPolylineStartIsInsideSecondPolyline(e.VisibilityPolyline,t.VisibilityPolyline),t.IsRectangle&&e.IsRectangle?!1:$t.ObstaclesAreCloseEnoughToBeConsideredTouching(t,e,i.aIsInsideB,i.bIsInsideA)?(i.aIsInsideB=!1,i.bIsInsideA=!1,!0):!1)}static ObstaclesAreCloseEnoughToBeConsideredTouching(t,e,i,r){if(!i&&!r)return G.CurvesIntersect(t.looseVisibilityPolyline,e.VisibilityPolyline);let s=i?t.looseVisibilityPolyline:e.looseVisibilityPolyline,o=i?e.VisibilityPolyline:t.VisibilityPolyline;for(let a of s)if(G.PointRelativeToCurveLocation(a,o)===0){let l=G.ClosestPoint(o,a);if(!g.closeIntersections(a,l))return!0}return!1}AdjustSpatialAncestors(){if(this.SpatialAncestorsAdjusted)return!1;for(let e of this.GetAllGroups()){let i=e.VisibilityBoundingBox;for(let r of this.Root.GetNodeItemsIntersectingRectangle(i))if(r!==e&&G.ClosedCurveInteriorsIntersect(r.VisibilityPolyline,e.VisibilityPolyline)){if(r.IsInConvexHull)for(let s of r.ConvexHull.Obstacles)this.AncestorSets.get(s.InputShape).add(e.InputShape);this.AncestorSets.get(r.InputShape).add(e.InputShape)}}let t=new Array;for(let e of this.Root.GetAllLeaves()){let i=e.VisibilityBoundingBox;t=t.concat(Array.from(this.AncestorSets.get(e.InputShape)).filter(r=>!i.intersects(this.shapeIdToObstacleMap.get(r).VisibilityBoundingBox)));for(let r of t)this.AncestorSets.get(e.InputShape).delete(r);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){let r=rt.RectangleBorderIntersect(this.GraphBox,t,e);if(R.GetDirections(t,r)===0)return i.pacList=null,D.mkPP(t,t);let s=this.RestrictSegmentWithObstacles(t,r);return i.pacList=this.CurrentGroupBoundaryCrossingMap.GetOrderedListBetween(s.start,s.end),s}GetAllObstacles(){return this.allObstacles}GetAllPrimaryObstacles(){return this.Root.GetAllLeaves()}IntersectionIsInsideAnotherObstacle(t,e,i,r){return this.insideHitTestIgnoreObstacle1=e,this.insideHitTestIgnoreObstacle2=t,this.insideHitTestScanDirection=r,this.Root.FirstHitNodeWithPredicate(i,this.InsideObstacleHitTest.bind(this))!=null}PointIsInsideAnObstaclePD(t,e){return this.PointIsInsideAnObstacle(t,Ee.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||!rt.PointIsInRectangleInterior(t,e.VisibilityBoundingBox))return 0;let i=rt.RectangleBorderIntersect(e.VisibilityBoundingBox,t,this.insideHitTestScanDirection.dir).add(this.insideHitTestScanDirection.DirectionAsPoint),r=rt.RectangleBorderIntersect(e.VisibilityBoundingBox,t,this.insideHitTestScanDirection.OppositeDirection).sub(this.insideHitTestScanDirection.DirectionAsPoint),s=D.mkPP(r,i),o=G.getAllIntersections(s,e.VisibilityPolyline,!0);if(o.length===2){let a=g.RoundPoint(o[0].x),l=g.RoundPoint(o[1].x);if(!R.EqualPP(t,a)&&!R.EqualPP(t,l)&&t.compareTo(a)!==t.compareTo(l)&&!lt(Math.floor(o[0].par1),Math.floor(o[1].par1)))return 1}return 0}SegmentCrossesAnObstacle(t,e){this.stopAtGroups=!0,this.wantGroupCrossings=!1;let i=this.RestrictSegmentPrivate(t,e);return!R.EqualPP(i.end,e)}SegmentCrossesANonGroupObstacle(t,e){this.stopAtGroups=!1,this.wantGroupCrossings=!1;let i=this.RestrictSegmentPrivate(t,e);return!R.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=D.mkPP(t,e),this.restrictedRayLengthSquared=t.sub(e).lengthSquared,this.CurrentGroupBoundaryCrossingMap.Clear(),this.RecurseRestrictRayWithObstacles(this.Root),this.currentRestrictedRay}GetRestrictedIntersectionTestSegment(t,e){let i=R.GetDirections(t,e),r=i===8?this.GraphBox.right:i===2?this.GraphBox.left:t.x,s=i===8?this.GraphBox.left:i===2?this.GraphBox.right:e.x,o=i===4?this.GraphBox.top*2:i===1?this.GraphBox.bottom:t.y,a=i===4?this.GraphBox.bottom:i===1?this.GraphBox.top:t.y;this.restrictedIntersectionTestSegment=D.mkPP(new g(r,o),new g(s,a))}RecurseRestrictRayWithObstacles(t){if(!rt.RectangleInteriorsIntersect(this.currentRestrictedRay.boundingBox,t.irect))return;let e=t.UserData;if(e!=null){let i=G.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,r=this.restrictedRayLengthSquared,s=R.GetDirections(this.restrictedIntersectionTestSegment.start,this.restrictedIntersectionTestSegment.end);for(let o of t){let a=g.RoundPoint(o.x),l=R.GetDirections(this.currentRestrictedRay.start,a);if(l===J.OppositeDir(s))continue;if(e++,l===0){r=0,i=o;continue}let h=a.sub(this.currentRestrictedRay.start).lengthSquared;if(h<r){if(o.x.sub(this.currentRestrictedRay.start).lengthSquared<x.squareOfDistanceEpsilon)continue;r=h,i=o}}if(i!=null){if(e===1){let o=g.RoundPoint(i.x);if(g.closeIntersections(o,this.currentRestrictedRay.start)||g.closeIntersections(o,this.currentRestrictedRay.end))return}this.restrictedRayLengthSquared=r,this.currentRestrictedRay.end=Xa.MungeClosestIntersectionInfo(this.currentRestrictedRay.start,i,!rt.IsVerticalPP(this.currentRestrictedRay.start,this.currentRestrictedRay.end))}}AddGroupIntersectionsToRestrictedRay(t,e){for(let i of e){let r=g.RoundPoint(i.x);if(r.sub(this.currentRestrictedRay.start).lengthSquared>this.restrictedRayLengthSquared)continue;let s=R.GetDirections(this.currentRestrictedRay.start,this.currentRestrictedRay.end),o=i.seg1,a=J.VectorDirection(o.derivative(i.par1)),l=s;(a&J.RotateRight(s))!==0&&(l=J.OppositeDir(l)),this.CurrentGroupBoundaryCrossingMap.AddIntersection(r,t,l)}}},DS=class{constructor(n,t){this.scanDirection=n,this.SideTree=new Re((e,i)=>this.Compare(e,i)),this.linePositionAtLastInsertOrRemove=t}Insert(n,t){return this.linePositionAtLastInsertOrRemove=t,this.SideTree.insert(n)}get Count(){return this.SideTree.count}Remove(n,t){this.linePositionAtLastInsertOrRemove=t,this.SideTree.remove(n)}Find(n){return this.scanDirection.ComparePerpCoord(this.linePositionAtLastInsertOrRemove,n.Start)===-1?null:this.SideTree.find(n)}NextLowB(n){return this.NextLowR(this.Find(n))}NextLowR(n){return this.SideTree.previous(n)}NextHighB(n){return this.NextHighR(this.Find(n))}NextHighR(n){return this.SideTree.next(n)}Next(n,t){return rt.IsAscending(n)?this.SideTree.next(t):this.SideTree.previous(t)}Lowest(){return this.SideTree.treeMinimum()}Compare(n,t){if(n.Obstacle===t.Obstacle)return n===t?0:n instanceof Je?-1:1;let e=Ja.ScanLineIntersectSidePBS(this.linePositionAtLastInsertOrRemove,n,this.scanDirection),i=Ja.ScanLineIntersectSidePBS(this.linePositionAtLastInsertOrRemove,t,this.scanDirection),r=e.compareTo(i);if(r===0){let s=n instanceof Je,o=t instanceof Je;r=xf(s,o),r===0&&(r=Mt(n.Obstacle.Ordinal,t.Obstacle.Ordinal))}return r}},Fs=class{constructor(n){this.lookupSegment=bt.mk(new g(0,0),new g(0,1)),this.ScanDirection=n,this.segmentTree=new Re((t,e)=>this.Compare(t,e)),this.findIntersectorPred=t=>this.CompareIntersector(t),this.findPointPred=t=>this.CompareToPoint(t)}get Segments(){return this.segmentTree.allNodes()}InsertUnique(n){return this.AssertValidSegmentForInsertion(n),this.segmentTree.find(n)??this.segmentTree.insert(n)}AssertValidSegmentForInsertion(n){}Remove(n){this.segmentTree.remove(n)}Find(n,t){this.lookupSegment.Update(n,t);let e=this.segmentTree.find(this.lookupSegment);return e!=null&&R.EqualPP(e.item.End,t)?e.item:null}FindLowestIntersector(n,t){let e=this.FindLowestIntersectorNode(n,t);return e!=null?e.item:null}FindLowestIntersectorNode(n,t){this.lookupSegment.Update(n,n);let e=this.segmentTree.findLast(this.findIntersectorPred);if(R.EqualPP(n,t))e!=null&&this.ScanDirection.Compare(e.item.End,n)<0&&(e=null);else for(this.lookupSegment.Update(n,t);e!=null&&!e.item.IntersectsSegment(this.lookupSegment);){if(this.ScanDirection.Compare(e.item.Start,t)>0)return null;e=this.segmentTree.next(e)}return e}FindHighestIntersector(n,t){this.lookupSegment.Update(t,t);let e=this.segmentTree.findLast(this.findIntersectorPred);if(R.EqualPP(n,t))e!=null&&this.ScanDirection.Compare(e.item.End,n)<0&&(e=null);else for(this.lookupSegment.Update(n,t);e!=null&&!e.item.IntersectsSegment(this.lookupSegment);){if(this.ScanDirection.Compare(e.item.End,n)<0)return null;e=this.segmentTree.previous(e)}return e!=null?e.item:null}CompareIntersector(n){return this.ScanDirection.Compare(n.Start,this.lookupSegment.Start)<=0}FindSegmentContainingPoint(n,t){return this.FindSegmentOverlappingPoints(n,n,t)}FindSegmentOverlappingPoints(n,t,e){this.lookupSegment.Update(n,t);let i=this.segmentTree.findFirst(this.findPointPred);if(i!=null){let r=i.item;if(this.ScanDirection.Compare(r.Start,t)<=0)return r}return null}CompareToPoint(n){return this.ScanDirection.Compare(n.End,this.lookupSegment.Start)>=0}MergeAndRemoveNextNode(n,t){return this.ScanDirection.Compare(n.End,t.item.End)===-1&&n.Update(n.Start,t.item.End),n.MergeGroupBoundaryCrossingList(t.item.GroupBoundaryPointAndCrossingsList),this.segmentTree.deleteNodeInternal(t),this.segmentTree.find(n)}MergeSegments(){if(this.segmentTree.count<2)return;let n=this.segmentTree.treeMinimum(),t=this.segmentTree.next(n);for(;t!=null;t=this.segmentTree.next(n))switch(this.ScanDirection.Compare(t.item.Start,n.item.End)){case 1:n=t;break;case 0:t.item.IsOverlapped===n.item.IsOverlapped?n=this.MergeAndRemoveNextNode(n.item,t):(n.item.NeedEndOverlapVertex=!0,t.item.NeedStartOverlapVertex=!0,n=t);break;default:if(n.item.IsOverlapped!==t.item.IsOverlapped){if(n.item.IsOverlapped)n.item.Start===t.item.Start?n=this.MergeAndRemoveNextNode(t.item,n):(n.item.Update(n.item.Start,t.item.Start),n=t);else if(n.item.End===t.item.End)n=this.MergeAndRemoveNextNode(n.item,t);else{let e=t.item,i=n.item;this.segmentTree.deleteNodeInternal(t),e.Update(i.End,e.End),this.segmentTree.insert(e),e.TrimGroupBoundaryCrossingList(),n=this.segmentTree.find(i)}break}n=this.MergeAndRemoveNextNode(n.item,t);break}}Compare(n,t){if(n===t)return 0;if(n==null)return-1;if(t==null)return 1;let e=this.ScanDirection.Compare(n.Start,t.Start);return e===0&&(e=this.ScanDirection.Compare(n.End,t.End)*-1),e}},MS=class extends Bu{constructor(n){super(n)}SetVertexEntry(n){this.VertexEntries==null&&(this.VertexEntries=new Array(4)),this.VertexEntries[J.ToIndex(n.Direction)]=n}RemoveVertexEntries(){this.VertexEntries=null}},Ja=class Jt{constructor(t){this.ObstacleTree=new GS,this.CurrentGroupBoundaryCrossingMap=new oc,this.LowNeighborSides=new pu,this.HighNeighborSides=new pu,this.ScanDirection=Ee.HorizontalInstance,this.eventQueue=new lu,this.HorizontalScanSegments=new Fs(Ee.HorizontalInstance),this.VerticalScanSegments=new Fs(Ee.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{this.SentinelOffset=1}static NewVisibilityGraph(){let t=new zt;return t.VertexFactory=e=>new MS(e),t}GenerateVisibilityGraph(){if(this.ObstacleTree.Root==null)return;this.InitializeEventQueue(Ee.HorizontalInstance);let t=mi.FirstSentinelOrdinal,e=new g(this.ObstacleTree.GraphBox.left-Jt.SentinelOffset,this.ObstacleTree.GraphBox.bottom-Jt.SentinelOffset),i=new g(this.ObstacleTree.GraphBox.left-Jt.SentinelOffset,this.ObstacleTree.GraphBox.top+Jt.SentinelOffset),r=mi.CreateSentinel(e,i,this.ScanDirection,t++);this.scanLine.Insert(r.ActiveHighSide,this.ObstacleTree.GraphBox.leftBottom),e=new g(this.ObstacleTree.GraphBox.right+Jt.SentinelOffset,this.ObstacleTree.GraphBox.bottom-Jt.SentinelOffset),i=new g(this.ObstacleTree.GraphBox.right+Jt.SentinelOffset,this.ObstacleTree.GraphBox.top+Jt.SentinelOffset),r=mi.CreateSentinel(e,i,this.ScanDirection,t++),this.scanLine.Insert(r.ActiveLowSide,this.ObstacleTree.GraphBox.leftBottom),this.ProcessEvents(),this.InitializeEventQueue(Ee.VerticalInstance),e=new g(this.ObstacleTree.GraphBox.left-Jt.SentinelOffset,this.ObstacleTree.GraphBox.bottom-Jt.SentinelOffset),i=new g(this.ObstacleTree.GraphBox.right+Jt.SentinelOffset,this.ObstacleTree.GraphBox.bottom-Jt.SentinelOffset),r=mi.CreateSentinel(e,i,this.ScanDirection,t++),this.scanLine.Insert(r.ActiveHighSide,this.ObstacleTree.GraphBox.leftBottom),e=new g(this.ObstacleTree.GraphBox.left-Jt.SentinelOffset,this.ObstacleTree.GraphBox.top+Jt.SentinelOffset),i=new g(this.ObstacleTree.GraphBox.right+Jt.SentinelOffset,this.ObstacleTree.GraphBox.top+Jt.SentinelOffset),r=mi.CreateSentinel(e,i,this.ScanDirection,t),this.scanLine.Insert(r.ActiveLowSide,this.ObstacleTree.GraphBox.leftBottom),this.ProcessEvents()}static ScanLineIntersectSidePBS(t,e,i){let r=e.Direction,s=e.Start.x,o=e.Start.y;return i.IsHorizontal?(s+=r.x/r.y*(t.y-e.Start.y),s=Xa.MungeIntersect(t.x,s,e.Start.x,e.End.x),o=t.y):(s=t.x,o+=r.y/r.x*(t.x-e.Start.x),o=Xa.MungeIntersect(t.y,o,e.Start.y,e.End.y)),new g(s,o)}GetOpenVertex(t){let e=t.startPoint,i=this.TraversePolylineForEvents(e),r=this.PointCompare(i.point,e.point);for(;;i=this.TraversePolylineForEvents(i)){let s=this.PointCompare(i.point,e.point);if(s<=0)e=i;else if(s>0&&r<=0)break;r=s}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 DS(this.ScanDirection,this.ObstacleTree.GraphBox.leftBottom),this.lookaheadScan=new NS(this.ScanDirection)}EnqueueBottomVertexEvents(){for(let t of this.ObstacleTree.GetAllPrimaryObstacles()){let e=this.GetOpenVertex(t.VisibilityPolyline);this.eventQueue.Enqueue(new Xs(t,e))}}IsFlat(t){return this.ScanDirection.IsFlatS(t)}IsPerpendicular(t){return this.ScanDirection.IsPerpendicularS(t)}ScanLineIntersectSide(t,e){return Jt.ScanLineIntersectSidePBS(t,e,this.ScanDirection)}SideReflectsUpward(t){return t instanceof Je?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 Je?this.ScanDirection.Coord(t.End)<this.ScanDirection.Coord(t.Start):this.ScanDirection.Coord(t.End)>this.ScanDirection.Coord(t.Start)}StoreLookaheadSite(t,e,i,r){if(this.wantReflections&&!this.IsPerpendicular(e)){if(!r&&!rt.PointIsInRectangleInterior(i,e.Obstacle.VisibilityBoundingBox))return;this.SideReflectsUpward(e)&&this.lookaheadScan.Find(i)==null&&this.lookaheadScan.Add(new Qn(t,e.Obstacle,i))}}LoadReflectionEvents(t){this.LoadReflectionEventsBB(t,t)}LoadReflectionEventsBB(t,e){if(t==null||this.SideReflectsUpward(t)||this.IsPerpendicular(t))return;let i=it.mkPP(t.Start,t.End),r=it.mkPP(e.Start,e.End);if(this.ScanDirection.IsHorizontal?!i.intersectsOnX(r):!i.intersectsOnY(r))return;let s=it.intersect(i,r),o=s.leftBottom,a=s.rightTop,l=this.lookaheadScan.FindFirstInRange(o,a);for(;l!=null;){let h=Jt.ScanLineIntersectSidePBS(l.item.Site,t,this.ScanDirection.PerpendicularInstance);this.ScanDirection.ComparePerpCoord(h,l.item.Site)>0?this.AddReflectionEvent(l.item,t,h):l.item.ReflectingObstacle!==t.Obstacle&&this.lookaheadScan.MarkStaleSite(l.item),l=this.lookaheadScan.FindNextInRange(l,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(!rt.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,r){{let s=this.ScanLineIntersectSide(r.Site,e??i),o=e!=null?s:r.Site,a=e!=null?r.Site:s;return e==null?e=this.scanLine.NextLowB(i).item:i=this.scanLine.NextHighB(e).item,this.InsertParallelReflectionSegment(o,a,t,e,i,r)}}AddReflectionEvent(t,e,i){let r=e;r!=null?this.eventQueue.Enqueue(new gu(t,r,i)):this.eventQueue.Enqueue(new hu(t,e,i))}AddSideToScanLine(t,e){let 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 lu,this.HorizontalScanSegments=new Fs(Ee.HorizontalInstance),this.VerticalScanSegments=new Fs(Ee.VerticalInstance),this.VisibilityGraph=null}ProcessEvents(){for(;this.eventQueue.Count>0;){let t=this.eventQueue.Dequeue();t instanceof Xs?this.ProcessEventO(t):t instanceof uu?this.ProcessEventLB(t):t instanceof du?this.ProcessEventHB(t):t instanceof cu?this.ProcessEventCV(t):t instanceof gu?this.ProcessEventLR(t):t instanceof hu?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){let r=t instanceof Xs?e.item.Start:e.item.End,s={lowNborSideNode:null,highNborSideNode:null};this.FindInitialNeighborSides(e,s),this.SkipToNeighbor(this.ScanDirection.OppositeDirection,e.item,r,s.lowNborSideNode,i),this.SkipToNeighbor(this.ScanDirection.Dir,e.item,r,s.highNborSideNode,i)}SkipToNeighbor(t,e,i,r,s){let o=null,a=null;for(;;r=this.scanLine.Next(t,r))if(r.item.Obstacle!==e.Obstacle){if(r.item.Obstacle.IsGroup){this.ProcessGroupSideEncounteredOnTraversalToNeighbor(r,i,t)&&a==null&&(a=r.item);continue}if(r.item instanceof Hn===rt.IsAscending(t)){this.ScanLineCrossesObstacle(i,r.item.Obstacle)&&(o=r,a=null);continue}break}s.SetSides(t,r,o,a)}ProcessGroupSideEncounteredOnTraversalToNeighbor(t,e,i){if(!this.ScanLineCrossesObstacle(e,t.item.Obstacle))return!1;let r=t.item instanceof Je===rt.IsAscending(i)?i:J.OppositeDir(i),s=this.ScanLineIntersectSide(e,t.item);return this.CurrentGroupBoundaryCrossingMap.AddIntersection(s,t.item.Obstacle,r),!0}FindNeighborsAndProcessVertexEvent(t,e,i){this.CurrentGroupBoundaryCrossingMap.Clear(),this.FindNeighborsBRR(i,t,e),this.ProcessVertexEvent(t,e,i),this.CurrentGroupBoundaryCrossingMap.Clear()}ProcessEventO(t){let e=t.Obstacle;e.CreateInitialSides(t.Vertex,this.ScanDirection),this.AddSideToScanLine(e.ActiveLowSide,t.Site);let i=this.AddSideToScanLine(e.ActiveHighSide,t.Site),r=this.scanLine.Find(e.ActiveLowSide);this.FindNeighborsAndProcessVertexEvent(r,i,t);let s=this.LowNeighborSides.GroupSideInterveningBeforeLowNeighbor??this.LowNeighborSides.LowNeighborSide;this.SideReflectsUpward(s)&&this.LoadReflectionEvents(e.ActiveLowSide);let o=this.HighNeighborSides.GroupSideInterveningBeforeHighNeighbor??this.HighNeighborSides.HighNeighborSide;if(this.SideReflectsUpward(o)&&this.LoadReflectionEvents(e.ActiveHighSide),e.ActiveHighSide.Start!==e.ActiveLowSide.Start){let a=new Hn(e,t.Vertex,this.ScanDirection);this.lookaheadScan.RemoveSitesForFlatBottom(a.Start,a.End)}this.EnqueueLowBendVertexEvent(e.ActiveLowSide),this.EnqueueHighBendOrCloseVertexEvent(e.ActiveHighSide)}ProcessEventLB(t){let e=t.Obstacle,i=new Je(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 uu(t.Obstacle,t.EndVertex))}ProcessEventHB(t){let e=t.Obstacle,i=new Hn(e,t.Vertex,this.ScanDirection);this.RemoveSideFromScanLine(this.scanLine.Find(e.ActiveHighSide),t.Site);let r=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)){let s=this.scanLine.NextHighR(r);s.item instanceof Je&&this.SideReflectsDownward(s.item)&&(!e.isOverlapped||!this.ObstacleTree.PointIsInsideAnObstacle(i.Start,this.ScanDirection))&&(this.StoreLookaheadSite(s.item.Obstacle,i,i.Start,!0),this.LoadReflectionEvents(s.item))}}EnqueueHighBendOrCloseVertexEvent(t){let 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 du(e,t.EndVertex)):this.eventQueue.Enqueue(new cu(e,t.EndVertex))}CreateCloseEventSegmentsAndFindNeighbors(t){let e=t.Obstacle,i=this.scanLine.Find(e.ActiveLowSide),r=this.scanLine.Find(e.ActiveHighSide);if(this.scanLine.Compare(e.ActiveLowSide,e.ActiveHighSide)===1){let s=i;i=r,r=s}if(this.FindNeighborsAndProcessVertexEvent(i,r,t),this.wantReflections&&e.isOverlapped)for(let s=this.scanLine.NextHighR(i);s.item!==r.item;s=this.scanLine.NextHighR(s))this.LoadReflectionEvents(s.item);this.scanLine.Remove(e.ActiveLowSide,t.Site),this.scanLine.Remove(e.ActiveHighSide,t.Site)}ProcessEventCV(t){this.CreateCloseEventSegmentsAndFindNeighbors(t);let e=this.LowNeighborSides.LowNeighbor.item,i=this.HighNeighborSides.HighNeighbor.item,r=t.Obstacle;this.LoadReflectionEvents(e),this.LoadReflectionEvents(i),r.Close()}ProcessEventLR(t){let 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){let 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){let e=Math.max(t.x,this.ObstacleTree.GraphBox.left),i=Math.max(t.y,this.ObstacleTree.GraphBox.bottom);return new g(Math.min(e,this.ObstacleTree.GraphBox.right),Math.min(i,this.ObstacleTree.GraphBox.top))}IsInBoundsV(t){return this.IsInBoundsP(t.point)}IsInBoundsP(t){return R.EqualPP(t,this.MakeInBoundsLocation(t))}},Za=class di extends Ja{constructor(){super(!1),this.horizontalVertexPoints=new Zt,this.verticalVertexPoints=new Zt,this.boundingBoxSteinerPoints=new Zt,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(let 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 au(this.yCoordAccumulator,!0),this.verticalScanSegmentVector=new au(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(let e of this.yCoordAccumulator)this.eventQueue.Enqueue(new pa(new g(this.ObstacleTree.GraphBox.left-di.SentinelOffset,e)));return}for(let e of this.xCoordAccumulator)this.eventQueue.Enqueue(new pa(new g(e,this.ObstacleTree.GraphBox.bottom-di.SentinelOffset)))}ProcessCustomEvent(t){this.ProcessAxisCoordinate(t)||super.ProcessCustomEvent(t)}ProcessAxisCoordinate(t){return t instanceof pa?(this.CreateScanSegmentsOnAxisCoordinate(t.Site),!0):!1}InsertPerpendicularReflectionSegment(t,e){return!1}InsertParallelReflectionSegment(t,e,i,r,s,o){return!1}ProcessVertexEvent(t,e,i){let r=this.ScanDirection.IsHorizontal?this.horizontalVertexPoints:this.verticalVertexPoints;r.add(i.Site);let s=this.LowNeighborSides.LowNeighbor.item,o=this.HighNeighborSides.HighNeighbor.item,a=this.ScanDirection.Dir,l=this.ScanDirection.OppositeDirection,h=this.ScanLineIntersectSide(i.Site,s),u=this.ScanLineIntersectSide(i.Site,o);if(this.ObstacleTree.GraphBox.contains(h)){let c=rt.RectangleBorderIntersect(s.Obstacle.VisibilityBoundingBox,h,a);R.IsPureLower(c,i.Site)&&this.boundingBoxSteinerPoints.add(c)}if(this.ObstacleTree.GraphBox.contains(u)){let c=rt.RectangleBorderIntersect(o.Obstacle.VisibilityBoundingBox,u,l);R.IsPureLower(i.Site,c)&&this.boundingBoxSteinerPoints.add(c)}let d={lowCorner:void 0,highCorner:void 0};di.GetBoundingCorners(t.item.Obstacle.VisibilityBoundingBox,i instanceof Xs,this.ScanDirection.IsHorizontal,d),(R.IsPureLower(h,d.lowCorner)||s.Obstacle.IsInSameClump(i.Obstacle))&&r.add(d.lowCorner),(R.IsPureLower(d.highCorner,u)||o.Obstacle.IsInSameClump(i.Obstacle))&&r.add(d.highCorner)}static GetBoundingCorners(t,e,i,r){if(e){r.lowCorner=t.leftBottom,r.highCorner=i?t.rightBottom:t.leftTop;return}r.lowCorner=i?t.leftTop:t.rightBottom,r.highCorner=t.rightTop}CreateScanSegmentsOnAxisCoordinate(t){this.CurrentGroupBoundaryCrossingMap.Clear();let e=this.scanLine.Lowest(),i=this.scanLine.NextHighR(e),r=0,s=t,o=!1;for(;i!=null;i=this.scanLine.NextHighR(i))if(!this.SkipSide(s,i.item)){if(i.item.Obstacle.IsGroup){(r===0||o)&&this.HandleGroupCrossing(t,i.item);continue}if(i.item instanceof Je){if(r>0){r++;continue}s=this.CreateScanSegment(s,i.item,bt.NormalWeight),this.CurrentGroupBoundaryCrossingMap.Clear(),r=1,o=i.item.Obstacle.isOverlapped;continue}r--,!(r>0)&&(s=i.item.Obstacle.isOverlapped||i.item.Obstacle.OverlapsGroupCorner?this.CreateScanSegment(s,i.item,bt.OverlappedWeight):this.ScanLineIntersectSide(s,i.item),this.CurrentGroupBoundaryCrossingMap.Clear(),o=!1)}let a=this.ScanDirection.IsHorizontal?new g(this.ObstacleTree.GraphBox.right+di.SentinelOffset,s.y):new g(s.x,this.ObstacleTree.GraphBox.top+di.SentinelOffset);this.parallelSegmentVector.CreateScanSegment(s,a,bt.NormalWeight,this.CurrentGroupBoundaryCrossingMap.GetOrderedListBetween(s,a)),this.parallelSegmentVector.ScanSegmentsCompleteForCurrentSlot()}HandleGroupCrossing(t,e){if(!this.ScanLineCrossesObstacle(t,e.Obstacle))return;let i=e instanceof Je?this.ScanDirection.Dir:this.ScanDirection.OppositeDirection,r=this.ScanLineIntersectSide(t,e),s=this.CurrentGroupBoundaryCrossingMap.AddIntersection(r,e.Obstacle,i);this.AddPerpendicularCoordForGroupCrossing(r);let o=s.GetInteriorVertexPoint(r);this.AddPerpendicularCoordForGroupCrossing(o)}AddPerpendicularCoordForGroupCrossing(t){let 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;let 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){let r=this.ScanLineIntersectSide(t,e);return t!==r&&this.parallelSegmentVector.CreateScanSegment(t,r,i,this.CurrentGroupBoundaryCrossingMap.GetOrderedListBetween(t,r)),r}GenerateSparseIntersectionsFromVertexPoints(){this.VisibilityGraph=di.NewVisibilityGraph(),this.GenerateSparseIntersectionsAlongHorizontalAxis(),this.GenerateSparseIntersectionsAlongVerticalAxis(),this.ConnectAdjoiningScanSegments(),this.horizontalScanSegmentVector.CreateSparseVerticesAndEdges(this.VisibilityGraph),this.verticalScanSegmentVector.CreateSparseVerticesAndEdges(this.VisibilityGraph)}GenerateSparseIntersectionsAlongHorizontalAxis(){this.currentAxisPointComparer=Ns;let t=Array.from(this.horizontalVertexPoints.values()).sort(this.currentAxisPointComparer),e=Array.from(this.boundingBoxSteinerPoints.values()).sort(this.currentAxisPointComparer);this.ScanDirection=Ee.HorizontalInstance,this.SetVectorsAndCoordMaps(this.ScanDirection),this.GenerateSparseIntersections(t,e)}GenerateSparseIntersectionsAlongVerticalAxis(){this.currentAxisPointComparer=(i,r)=>i.compareTo(r);let t=Array.from(this.verticalVertexPoints.values()).sort(this.currentAxisPointComparer),e=Array.from(this.boundingBoxSteinerPoints.values()).sort(this.currentAxisPointComparer);this.ScanDirection=Ee.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,r={j:0};for(let s of this.parallelSegmentVector.Items())for(;!(!s.CurrentSegment.ContainsPoint(t[i])&&(!this.AddSteinerPointsToInterveningSegments(t[i],e,r,s)||!s.TraverseToSegmentContainingPoint(t[i])));){if(this.AddPointsToCurrentSegmentIntersections(e,r,s),this.GenerateIntersectionsFromVertexPointForCurrentSegment(t[i],s),s.PointIsCurrentEndAndNextStart(t[i])){s.MoveNext();continue}if(++i>=t.length)return}}AddSteinerPointsToInterveningSegments(t,e,i,r){for(;i.j<e.length&&this.currentAxisPointComparer(e[i.j],t)===-1;){if(!r.TraverseToSegmentContainingPoint(e[i.j]))return!1;this.AddPointsToCurrentSegmentIntersections(e,i,r)}return!0}AddPointsToCurrentSegmentIntersections(t,e,i){for(;e.j<t.length&&i.CurrentSegment.ContainsPoint(t[e.j]);e.j++){let r=this.FindPerpendicularSlot(t[e.j],0);this.AddSlotToSegmentIntersections(i,r)}}GenerateIntersectionsFromVertexPointForCurrentSegment(t,e){let i=this.FindPerpendicularSlot(e.CurrentSegment.Start,1),r=this.FindPerpendicularSlot(e.CurrentSegment.End,-1),s=this.FindPerpendicularSlot(t,0);i>=r||(this.AddSlotToSegmentIntersections(e,i),this.AddSlotToSegmentIntersections(e,r),s>i&&s<r&&(this.AddSlotToSegmentIntersections(e,s),this.AddBinaryDivisionSlotsToSegmentIntersections(e,i,s,r)))}FindPerpendicularSlot(t,e){return di.FindIntersectingSlot(this.perpendicularSegmentVector,this.perpendicularCoordMap,t,e)}static FindIntersectingSlot(t,e,i,r){let s=t.GetParallelCoord(i),o=e.get(s);return o!==void 0?o:r===0?-1:t.FindNearest(s,r)}AddSlotToSegmentIntersections(t,e){let i=this.perpendicularSegmentVector.Item(e);t.CurrentSegment.AddSparseVertexCoord(i.Coord),i.AddPerpendicularCoord(t.Coord)}AddBinaryDivisionSlotsToSegmentIntersections(t,e,i,r){let s=0,o=this.perpendicularSegmentVector.Length-1;for(;o-s>1;){let a=s+Math.floor((o-s)/2);if(i<=a){o=a,i<o&&o<=r&&this.AddSlotToSegmentIntersections(t,o);continue}s=a,i>s&&s>=e&&this.AddSlotToSegmentIntersections(t,s)}}CreateScanSegmentTrees(){di.CreateScanSegmentTree(this.horizontalScanSegmentVector,this.HorizontalScanSegments),di.CreateScanSegmentTree(this.verticalScanSegmentVector,this.VerticalScanSegments)}static CreateScanSegmentTree(t,e){for(let i of t.Items())for(let r=i.FirstSegment;r!=null;r=r.NextSegment)r.HasVisibility()&&e.InsertUnique(r)}},mu=class Ye{constructor(t){this.AddedVertices=new Array,this.AddedEdges=new Array,this.edgesToRestore=new Array,this.LimitPortVisibilitySpliceToEndpointBoundingBox=!1,this.GraphGenerator=t}get ObstacleTree(){return this.GraphGenerator.ObstacleTree}get VisGraph(){return this.GraphGenerator.VisibilityGraph}get IsSparseVg(){return this.GraphGenerator instanceof Za}AddVertex(t){let e=this.VisGraph.AddVertexP(t);return this.AddedVertices.push(e),e}FindOrAddVertex(t){return this.VisGraph.FindVertex(t)??this.AddVertex(t)}FindOrAddEdgeVV(t,e){return this.FindOrAddEdge(t,e,bt.NormalWeight)}FindOrAddEdge(t,e,i){let r=R.GetPureDirectionVV(t,e),s={bracketSource:void 0,bracketTarget:void 0,splitVertex:void 0};Ye.GetBrackets(t,e,r,s);let o=this.VisGraph.FindEdgePP(s.bracketSource.point,s.bracketTarget.point);return o=o!=null?this.SplitEdge(o,s.splitVertex):this.CreateEdge(s.bracketSource,s.bracketTarget,i),o}static GetBrackets(t,e,i,r){if(r.splitVertex=e,!Ye.FindBracketingVertices(t,e.point,i,r)){let s={bracketSource:null,bracketTarget:null};Ye.FindBracketingVertices(e,t.point,J.OppositeDir(i),s)&&(r.bracketSource=s.bracketTarget,r.splitVertex=t),r.bracketTarget=s.bracketSource}}static FindBracketingVertices(t,e,i,r){for(r.bracketSource=t;r.bracketTarget=rt.FindAdjacentVertex(r.bracketSource,i),r.bracketTarget!=null;){if(g.closeDistEps(r.bracketTarget.point,e))return!0;if(i!==R.GetDirections(r.bracketTarget.point,e))break;r.bracketSource=r.bracketTarget}return r.bracketTarget!=null}CreateEdge(t,e,i){let r=t,s=e;R.IsPureLower(r.point,s.point)||(r=e,s=t);let o=new rr(r,s,i);return zt.AddEdge(o),this.AddedEdges.push(o),o}RemoveFromGraph(){this.RemoveAddedVertices(),this.RemoveAddedEdges(),this.RestoreRemovedEdges()}RemoveAddedVertices(){for(let t of this.AddedVertices)this.VisGraph.FindVertex(t.point)!=null&&this.VisGraph.RemoveVertex(t);this.AddedVertices=[]}RemoveAddedEdges(){for(let t of this.AddedEdges)this.VisGraph.FindVertex(t.SourcePoint)!=null&&zt.RemoveEdge(t);this.AddedEdges=[]}RestoreRemovedEdges(){for(let t of this.edgesToRestore)zt.AddEdge(t);this.edgesToRestore=[]}FindNextEdge(t,e){return rt.FindAdjacentEdge(t,e)}FindPerpendicularOrContainingEdge(t,e,i){for(;;){let r=rt.FindAdjacentVertex(t,e);if(r==null)break;let s=R.GetDirections(r.point,i);if((J.OppositeDir(e)&s)!==0)return this.VisGraph.FindEdgePP(t.point,r.point);t=r}return null}FindNearestPerpendicularOrContainingEdge(t,e,i){let r;e&R.GetDirections(t.point,i);let s=t,o=r;for(;o!==0;){let l=rt.FindAdjacentVertex(s,r);if(l==null||(J.OppositeDir(r)&R.GetDirections(l.point,i))!==0)break;s=l,e&R.GetDirections(s.point,i)}let a;for(;a=this.FindPerpendicularOrContainingEdge(s,e,i),!(a!=null||s===t);)s=rt.FindAdjacentVertex(s,J.OppositeDir(r));return a}ConnectVertexToTargetVertex(t,e,i,r){if(g.closeDistEps(t.point,e.point))return;let s=R.GetDirections(t.point,e.point);if(R.IsPureDirectionD(s)){this.FindOrAddEdgeVV(t,e);return}let o=rt.FindBendPointBetween(t.point,e.point,i),a=this.FindOrAddVertex(o);this.FindOrAddEdge(t,a,r),this.FindOrAddEdge(a,e,r)}AddEdgeToTargetEdge(t,e,i){let r=this.VisGraph.FindVertex(i);return r==null&&(r=this.AddVertex(i),this.SplitEdge(e,r)),this.FindOrAddEdgeVV(t,r),r}SplitEdge(t,e){return t==null?null:g.closeDistEps(t.Source.point,e.point)||g.closeDistEps(t.Target.point,e.point)?t:(t instanceof rr||this.edgesToRestore.push(t),zt.RemoveEdge(t),(this.IsSparseVg||t.Weight===bt.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,r,s){let o=R.GetDirections(i.start,i.end);if(o===0)return;let a=rt.GetRectangleBound(e,o),l=rt.IsVerticalD(o)?g.RoundPoint(new g(t.point.x,a)):g.RoundPoint(new g(a,t.point.y));if(g.closeDistEps(l,t.point)||R.GetDirections(t.point,l)!==o)return;let h=i;R.GetDirections(l,h.end)===o&&(h=D.mkPP(h.start,l)),this.ExtendEdgeChain(t,o,h,i,r,s)}ExtendEdgeChain(t,e,i,r,s,o){if(R.GetDirections(t.point,i.end)!==e)return;let a=J.RotateLeft(e),l=rt.FindAdjacentVertex(t,a);if(l==null&&(a=J.OppositeDir(a),l=rt.FindAdjacentVertex(t,a),l==null))return;let h=J.OppositeDir(a),u={spliceTarget:null};this.ExtendSpliceWorker(l,e,h,i,r,o,u)&&this.ExtendSpliceWorker(u.spliceTarget,e,a,i,r,o,u),this.SpliceGroupBoundaryCrossings(s,t,i)}SpliceGroupBoundaryCrossings(t,e,i){if(t==null||t.Count()===0)return;t.Reset();let r=i.start,s=i.end,o=R.GetDirections(r,s);rt.IsAscending(o)||(r=i.end,s=i.start,o=J.OppositeDir(o)),e=Ye.TraverseToFirstVertexAtOrAbove(e,r,J.OppositeDir(o));for(let a=e;a!=null;a=rt.FindAdjacentVertex(a,o)){let l=R.ComparePP(a.point,s)>=0;for(;t.CurrentIsBeforeOrAt(a.point);){let h=t.Pop();R.ComparePP(h.Location,e.point)>0&&R.ComparePP(h.Location,s)<=0&&this.SpliceGroupBoundaryCrossing(a,h,J.OppositeDir(o)),R.ComparePP(h.Location,e.point)>=0&&R.ComparePP(h.Location,s)<0&&this.SpliceGroupBoundaryCrossing(a,h,o)}if(l)break}}static TraverseToFirstVertexAtOrAbove(t,e,i){let r=t,s=J.OppositeDir(i);for(;;){let o=rt.FindAdjacentVertex(r,i);if(o==null||R.GetDirections(o.point,e)===s)break;r=o}return r}SpliceGroupBoundaryCrossing(t,e,i){let r=$n.ToCrossingArray(e.Crossings,i);if(r!=null){let s=this.VisGraph.FindVertex(e.Location)??this.AddVertex(e.Location);t.point.equal(s.point)||this.FindOrAddEdgeVV(t,s);let o=r[0].GetInteriorVertexPoint(e.Location),a=this.VisGraph.FindVertex(o)??this.AddVertex(o),l=this.FindOrAddEdgeVV(s,a),h=r.map(u=>u.Group.InputShape);l.IsPassable=()=>h.some(u=>u.IsTransparent)}}ExtendSpliceWorker(t,e,i,r,s,o,a){let l=rt.FindAdjacentVertex(t,i);a.spliceTarget=rt.FindAdjacentVertex(l,i);let h={spliceSource:t};for(;Ye.GetNextSpliceSource(h,i,e);){let u=rt.FindBendPointBetween(l.point,h.spliceSource.point,J.OppositeDir(i));if(Ye.IsPointPastSegmentEnd(s,u))break;if(a.spliceTarget=Ye.GetSpliceTarget(h,i,u),a.spliceTarget==null){if(this.IsSkippableSpliceSourceWithNullSpliceTarget(h.spliceSource,e))continue;if(this.ObstacleTree.SegmentCrossesAnObstacle(h.spliceSource.point,u))return!1}let d=this.VisGraph.FindVertex(u);if(d!=null){if(a.spliceTarget==null||this.VisGraph.FindEdgePP(l.point,u)!=null)return a.spliceTarget==null&&this.FindOrAddEdge(l,d,o?bt.OverlappedWeight:bt.NormalWeight),!1}else d=this.AddVertex(u);if(this.FindOrAddEdge(l,d,o?bt.OverlappedWeight:bt.NormalWeight),this.FindOrAddEdge(h.spliceSource,d,o?bt.OverlappedWeight:bt.NormalWeight),o&&(o=this.SeeIfSpliceIsStillOverlapped(e,d)),l=d,(e&R.GetDirections(u,r.end))===0){a.spliceTarget=null;break}}return a.spliceTarget!=null}static GetNextSpliceSource(t,e,i){let r=rt.FindAdjacentVertex(t.spliceSource,i);if(r==null)for(r=t.spliceSource;;){if(r=rt.FindAdjacentVertex(r,J.OppositeDir(e)),r==null)return!1;let s=rt.FindAdjacentVertex(r,i);if(s!=null){r=s;break}}return t.spliceSource=r,!0}static GetSpliceTarget(t,e,i){let r=R.GetDirections(t.spliceSource.point,i),s=r,o=t.spliceSource;for(;s===r&&(t.spliceSource=o,o=rt.FindAdjacentVertex(t.spliceSource,e),o!=null);){if(g.closeDistEps(o.point,i)){o=rt.FindAdjacentVertex(o,e);break}s=R.GetDirections(o.point,i)}return o}SeeIfSpliceIsStillOverlapped(t,e){let i=this.FindNextEdge(e,J.RotateLeft(t)),r=i==null?!1:bt.NormalWeight===i.Weight;return r||(i=this.FindNextEdge(e,J.RotateRight(t)),r=i==null?!1:bt.NormalWeight===i.Weight),!r||this.ObstacleTree.PointIsInsideAnObstaclePD(e.point,t)}IsSkippableSpliceSourceWithNullSpliceTarget(t,e){if(Ye.IsSkippableSpliceSourceEdgeWithNullTarget(rt.FindAdjacentEdge(t,e)))return!0;let i=rt.FindAdjacentEdge(t,J.OppositeDir(e));return Ye.IsSkippableSpliceSourceEdgeWithNullTarget(i)||Ye.IsReflectionEdge(i)}static IsSkippableSpliceSourceEdgeWithNullTarget(t){return t!=null&&t.IsPassable!=null&<(t.Length,nc.BoundaryWidth)}static IsReflectionEdge(t){return t!=null&&t.Weight===bt.ReflectionWeight}static IsPointPastSegmentEnd(t,e){return R.GetDirections(t.start,t.end)===R.GetDirections(t.end,e)}toString(){return LS.String.format("{0} {1}",this.AddedVertices.length,this.edgesToRestore.length)}},VS=class Ys{constructor(t){this.obstaclePortMap=new Map,this.freePointMap=new _e,this.freePointLocationsUsedByRouteEdges=new Zt,this.RouteToCenterOfObstacles=!1,this.obstaclePortsInGraph=new Array,this.freePointsInGraph=new Set,this.activeAncestors=new Array,this.TransUtil=new mu(t),this.graphGenerator=t}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}Clear(){this.TransUtil.RemoveFromGraph(),this.obstaclePortMap.clear()}CreateObstaclePorts(t){for(let e of t.Ports)this.CreateObstaclePort(t,e)}CreateObstaclePort(t,e){if(e.Curve==null)return null;let i=g.RoundPoint(e.Location);if(G.PointRelativeToCurveLocation(i,t.InputShape.BoundaryCurve)===0||t.InputShape.BoundaryCurve!==e.Curve&&G.PointRelativeToCurveLocation(i,e.Curve)===0)return null;let r=new TS(e,t);return this.obstaclePortMap.set(e,r),r}FindVertices(t){let e=new Array,i=this.obstaclePortMap.get(t);if(i)if(this.RouteToCenterOfObstacles)e.push(i.CenterVertex);else for(let r of i.PortEntrances){let s=this.VisGraph.FindVertex(r.UnpaddedBorderIntersect);s!=null&&e.push(s)}else e.push(this.VisGraph.FindVertex(g.RoundPoint(t.Location)));return e}RemoveObstaclePorts(t){for(let e of t.Ports)this.RemoveObstaclePort(e)}RemoveObstaclePort(t){this.obstaclePortMap.delete(t)}AddControlPointsToGraph(t,e){this.GetPortSpliceLimitRectangle(t),this.activeAncestors=[];let i={oport:null},r={oport:null},s=this.FindAncestorsAndObstaclePort(t.sourcePort,i),o=this.FindAncestorsAndObstaclePort(t.targetPort,r);if(this.AncestorSets.size>0&&i.oport!=null&&r.oport!=null){let a=Zr(o,s),l=Zr(s,o);this.ActivateAncestors(l,a,e)}this.AddPortToGraph(t.sourcePort,i.oport),this.AddPortToGraph(t.targetPort,r.oport)}ConnectOobWaypointToEndpointVisibilityAtGraphBoundary(t,e){if(t==null||!t.IsOutOfBounds)return;let i=this.FindVertices(e),r=t.OutOfBoundsDirectionFromGraph&5;this.ConnectToGraphAtPointsCollinearWithVertices(t,r,i),r=t.OutOfBoundsDirectionFromGraph&10,this.ConnectToGraphAtPointsCollinearWithVertices(t,r,i)}ConnectToGraphAtPointsCollinearWithVertices(t,e,i){if(e===0)return;let r=J.OppositeDir(e);for(let s of i){let o=this.InBoundsGraphBoxIntersect(s.point,e),a=this.VisGraph.FindVertex(o);a!=null&&this.TransUtil.ConnectVertexToTargetVertex(t.Vertex,a,r,bt.NormalWeight)}}SetAllAncestorsActive(t,e){if(this.AncestorSets.size===0)return!1;this.ObstacleTree.AdjustSpatialAncestors(),this.ClearActiveAncestors();let i={oport:null},r={oport:null},s=this.FindAncestorsAndObstaclePort(t.sourcePort,r),o=this.FindAncestorsAndObstaclePort(t.targetPort,i);return this.AncestorSets.size>0&&s!=null&&o!=null?(this.ActivateAncestors(s,o,e),!0):!1}SetAllGroupsActive(){this.ClearActiveAncestors();for(let 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(it.mkPP(t.Location,t.Location),i=>i.IsGroup)).map(i=>i.InputShape))}ActivateAncestors(t,e,i){for(let r of ir(t,e)){let s=i.get(r);s.IsTransparentAncestor=!0,this.activeAncestors.push(s)}}ClearActiveAncestors(){for(let t of this.activeAncestors)t.IsTransparentAncestor=!1;this.activeAncestors=[]}RemoveControlPointsFromGraph(){this.ClearActiveAncestors(),this.RemoveObstaclePortsFromGraph(),this.RemoveFreePointsFromGraph(),this.TransUtil.RemoveFromGraph(),this.portSpliceLimitRectangle=it.mkEmpty()}RemoveObstaclePortsFromGraph(){for(let t of this.obstaclePortsInGraph)t.RemoveFromGraph();this.obstaclePortsInGraph=[]}RemoveFreePointsFromGraph(){for(let t of this.freePointsInGraph)t.RemoveFromGraph();this.freePointsInGraph.clear()}RemoveStaleFreePoints(){if(this.freePointMap.size>this.freePointLocationsUsedByRouteEdges.size){let t=Array.from(this.freePointMap).filter(e=>!this.freePointLocationsUsedByRouteEdges.has(e[0]));for(let e of t)this.freePointMap.deleteP(e[0])}}ClearVisibility(){this.freePointMap.clear();for(let 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){let i={removedPorts:null,addedPorts:null};if(e.Obstacle.GetPortChanges(i)){for(let r of i.addedPorts)this.CreateObstaclePort(e.Obstacle,r);for(let r of i.removedPorts)this.RemoveObstaclePort(r);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(let e of t.PortEntrances)this.AddObstaclePortEntranceToGraph(e)}}CreateObstaclePortEntrancesIfNeeded(t){t.PortEntrances.length>0||this.CreateObstaclePortEntrancesFromPoints(t)}GetPortVisibilityIntersection(t){let 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(let r of e.PortEntrances)if(r.WantVisibilityIntersection)for(let s of i.PortEntrances){if(!s.WantVisibilityIntersection)continue;let o=r.IsVertical===s.IsVertical?Ys.GetPathPointsFromOverlappingCollinearVisibility(r,s):Ys.GetPathPointsFromIntersectingVisibility(r,s);if(o!=null)return o}return null}static GetPathPointsFromOverlappingCollinearVisibility(t,e){return!rt.IntervalsAreSame(t.MaxVisibilitySegment.start,t.MaxVisibilitySegment.end,e.MaxVisibilitySegment.end,e.MaxVisibilitySegment.start)||t.HasGroupCrossings||e.HasGroupCrossings||g.closeDistEps(t.UnpaddedBorderIntersect,e.UnpaddedBorderIntersect)?null:[t.UnpaddedBorderIntersect,e.UnpaddedBorderIntersect]}static GetPathPointsFromIntersectingVisibility(t,e){let i=rt.SegmentsIntersectLL(t.MaxVisibilitySegment,e.MaxVisibilitySegment);return!i||t.HasGroupCrossingBeforePoint(i)||e.HasGroupCrossingBeforePoint(i)?null:[t.UnpaddedBorderIntersect,i,e.UnpaddedBorderIntersect]}CreateObstaclePortEntrancesFromPoints(t){let e=this.graphGenerator.ObstacleTree.GraphBox,i=it.mkPP(g.RoundPoint(t.PortCurve.boundingBox.leftBottom),g.RoundPoint(t.PortCurve.boundingBox.rightTop)),r=g.RoundPoint(t.PortLocation),s=!1,o={xx0:null,xx1:null};if(!R.Equal(r.y,i.top)&&!R.Equal(r.y,i.bottom)){s=!0;let a=new D(e.left,r.y,e.right,r.y);this.GetBorderIntersections(r,a,t.PortCurve,o);let l=new g(Math.min(o.xx0.x,o.xx1.x),r.y);l.x<i.left&&(l=new g(i.left,l.y));let h=new g(Math.max(o.xx0.x,o.xx1.x),r.y);h.x>i.right&&(h=new g(i.right,h.y)),this.CreatePortEntrancesAtBorderIntersections(i,t,r,l,h)}if(!R.Equal(r.x,i.left)&&!R.Equal(r.x,i.right)){s=!0;let a=new D(r.x,e.bottom,r.x,e.top);this.GetBorderIntersections(r,a,t.PortCurve,o);let l=new g(r.x,Math.min(o.xx0.y,o.xx1.y));l.y<e.bottom&&(l=new g(l.x,e.bottom));let h=new g(r.x,Math.max(o.xx0.y,o.xx1.y));h.y>e.top&&(h=new g(h.x,e.top)),this.CreatePortEntrancesAtBorderIntersections(i,t,r,l,h)}s||this.CreateEntrancesForCornerPort(i,t,r)}GetBorderIntersections(t,e,i,r){let s=G.getAllIntersections(e,i,!0);r.xx0=g.RoundPoint(s[0].x),r.xx1=g.RoundPoint(s[1].x)}CreatePortEntrancesAtBorderIntersections(t,e,i,r,s){let o=R.GetDirections(r,s);R.EqualPP(r,i)||this.CreatePortEntrance(t,e,s,o),R.EqualPP(s,i)||this.CreatePortEntrance(t,e,r,J.OppositeDir(o))}static GetDerivative(t,e){let i=t.PortCurve.closestParameter(e),r=t.PortCurve.derivative(i),s=(t.PortCurve.parStart+t.PortCurve.parEnd)/2;return ye.CurveIsClockwise(t.PortCurve,t.PortCurve.value(s))||(r=r.mul(-1)),r}CreatePortEntrance(t,e,i,r){e.CreatePortEntrance(i,r,this.ObstacleTree);let s=Ee.GetInstance(r),o=rt.GetRectangleBound(t,r)-s.Coord(i);if(o<0&&(o=-o),o>x.intersectionEpsilon){let a=J.VectorDirection(Ys.GetDerivative(e,i)),l;r|J.OppositeDir(r),(r&a)!==0&&(l=J.OppositeDir(l)),e.CreatePortEntrance(i,l,this.ObstacleTree)}}CreateEntrancesForCornerPort(t,e,i){let r=1;R.EqualPP(i,t.leftBottom)?r=4:R.EqualPP(i,t.leftTop)?r=8:R.EqualPP(i,t.rightTop)?r=1:R.EqualPP(i,t.rightBottom)&&(r=2),e.CreatePortEntrance(i,r,this.ObstacleTree),e.CreatePortEntrance(i,J.RotateRight(r),this.ObstacleTree)}AddObstaclePortEntranceToGraph(t){let e=this.VisGraph.FindVertex(t.VisibilityBorderIntersect);if(e){t.ExtendEdgeChain(this.TransUtil,e,e,this.portSpliceLimitRectangle,this.RouteToCenterOfObstacles);return}let i={targetVertex:null},r=t.IsOverlapped?bt.OverlappedWeight:bt.NormalWeight;this.FindorCreateNearestPerpEdgePPDNT(t.MaxVisibilitySegment.end,t.VisibilityBorderIntersect,t.OutwardDirection,r,i)!=null&&t.AddToAdjacentVertex(this.TransUtil,i.targetVertex,this.portSpliceLimitRectangle,this.RouteToCenterOfObstacles)}InBoundsGraphBoxIntersect(t,e){return rt.RectangleBorderIntersect(this.graphGenerator.ObstacleTree.GraphBox,t,e)}FindorCreateNearestPerpEdgePPDN(t,e,i,r){let s={targetVertex:null};return this.FindorCreateNearestPerpEdgePPDNT(t,e,i,r,s)}FindorCreateNearestPerpEdgePPDNT(t,e,i,r,s){let o=rt.SortAscending(t,e),a=o[0],l=o[1],h=rt.IsVerticalD(i)?this.HScanSegments:this.VScanSegments,u=rt.IsAscending(i)?h.FindLowestIntersector(a,l):h.FindHighestIntersector(a,l);if(u==null)return s.targetVertex=null,null;let d=rt.SegmentIntersectionSP(u,a);return this.FindOrCreateNearestPerpEdgeFromNearestPerpSegment(rt.IsAscending(i)?a:l,u,d,r,s)}FindOrCreateNearestPerpEdgeFromNearestPerpSegment(t,e,i,r,s){let o={segsegVertex:this.VisGraph.FindVertex(i),targetVertex:null};if(o.segsegVertex==null){let u=this.FindOrCreateSegmentIntersectionVertexAndAssociatedEdge(t,i,e,r,o);if(u!=null)return u}else if(R.EqualPP(t,i))return s.targetVertex=o.segsegVertex,this.TransUtil.FindNextEdge(s.targetVertex,J.OppositeDir(e.ScanDirection.Dir));let a=R.GetDirections(i,t),l=R.GetDirections(o.segsegVertex.point,t);if(a===l){let u={bracketTarget:null,bracketSource:null};return mu.FindBracketingVertices(o.segsegVertex,t,a,u),this.TransUtil.FindNextEdge(u.bracketSource,J.RotateLeft(a))??this.TransUtil.FindNextEdge(u.bracketSource,J.RotateRight(a))}l&=~a;let h=this.TransUtil.FindNearestPerpendicularOrContainingEdge(o.segsegVertex,l,t);return h==null?(s.targetVertex=this.TransUtil.AddVertex(i),this.TransUtil.FindOrAddEdge(s.targetVertex,e.HighestVisibilityVertex,e.Weight)):(o.segsegVertex=rt.GetEdgeEnd(h,J.OppositeDir(l)),i=rt.SegmentIntersectionPPP(t,i,o.segsegVertex.point),R.EqualPP(o.segsegVertex.point,i)?(s.targetVertex=o.segsegVertex,this.TransUtil.FindNextEdge(o.segsegVertex,l)):(s.targetVertex=this.TransUtil.FindOrAddVertex(i),this.TransUtil.FindOrAddEdge(o.segsegVertex,s.targetVertex,r)))}FindOrCreateSegmentIntersectionVertexAndAssociatedEdge(t,e,i,r,s){let o=(i.IsVertical?this.HScanSegments:this.VScanSegments).FindHighestIntersector(i.Start,e);if(o==null)return s.segsegVertex=null,s.targetVertex=this.TransUtil.AddVertex(e),this.TransUtil.FindOrAddEdge(s.targetVertex,i.LowestVisibilityVertex,i.Weight);let a=rt.SegmentsIntersection(i,o);if(s.segsegVertex=this.VisGraph.FindVertex(a),!s.segsegVertex){s.segsegVertex=this.TransUtil.AddVertex(a);let l=this.AddEdgeToClosestSegmentEnd(i,s.segsegVertex,i.Weight);if(this.AddEdgeToClosestSegmentEnd(o,s.segsegVertex,o.Weight),R.EqualPP(s.segsegVertex.point,e))return s.targetVertex=s.segsegVertex,l}return R.EqualPP(t,e)?(s.targetVertex=this.TransUtil.FindOrAddVertex(e),this.TransUtil.FindOrAddEdge(s.segsegVertex,s.targetVertex,r)):(s.targetVertex=null,null)}AddEdgeToClosestSegmentEnd(t,e,i){return R.IsPureLower(t.HighestVisibilityVertex.point,e.point)?this.TransUtil.FindOrAddEdge(t.HighestVisibilityVertex,e,i):R.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){let e=this.obstaclePortMap.get(t);return e?e.Obstacle.VisibilityBoundingBox.clone():it.mkOnPoints([g.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 OS(this.TransUtil,t),this.freePointMap.set(t,e)),this.freePointsInGraph.add(e),this.freePointLocationsUsedByRouteEdges.add(t),e}AddFreePointToGraph(t){t=g.RoundPoint(t);let 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 r=null;i.IsOverlapped=this.ObstacleTree.PointIsInsideAnObstacle(i.Point,this.HScanSegments.ScanDirection);let s;if(this.VScanSegments.FindSegmentContainingPoint(t,!0),s!=null){let a={targetVertex:null};r=this.FindOrCreateNearestPerpEdgeFromNearestPerpSegment(t,s,t,i.InitialWeight,a)}let o=4;if(r!=null)o=rt.EdgeDirectionVE(r),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){let e=t.Point,i=this.graphGenerator.MakeInBoundsLocation(e),r=R.GetDirections(i,e);if(t.OutOfBoundsDirectionFromGraph=r,!R.IsPureDirectionD(r)){t.AddOobEdgesFromGraphCorner(this.TransUtil,i);return}let s=this.VisGraph.FindVertex(i),o=J.OppositeDir(r);if(s!=null)t.AddToAdjacentVertex(this.TransUtil,s,o,this.portSpliceLimitRectangle);else{let h=this.FindorCreateNearestPerpEdgePPDN(e,i,r,bt.NormalWeight);h!=null&&(s=t.AddEdgeToAdjacentEdge(this.TransUtil,h,o,this.portSpliceLimitRectangle))}let a=rt.FindAdjacentVertex(s,J.RotateLeft(o));a!=null&&this.TransUtil.ConnectVertexToTargetVertex(t.Vertex,a,o,bt.NormalWeight);let l=rt.FindAdjacentVertex(s,J.RotateRight(o));l!=null&&this.TransUtil.ConnectVertexToTargetVertex(t.Vertex,l,o,bt.NormalWeight)}ConnectFreePointToLateralEdge(t,e){let i=t.IsOverlapped?this.InBoundsGraphBoxIntersect(t.Point,e):t.MaxVisibilityInDirectionForNonOverlappedFreePoint(e,this.TransUtil),r=this.FindorCreateNearestPerpEdgePPDN(i,t.Point,e,t.InitialWeight);r!=null&&t.AddEdgeToAdjacentEdge(this.TransUtil,r,e,this.portSpliceLimitRectangle)}},cl=class te extends Nt{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=Sr.DefaultBendPenaltyAsAPercentageOfDistance,this.GraphGenerator=new Za,this.PortManager=new VS(this.GraphGenerator),this.AddShapes(t)}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){g.closeDistEps(g.RoundPoint(t.sourcePort.Location),g.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 Za}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(let e of t)this.AddObstacleWithoutRebuild(e)}AddObstacle(t){this.AddObstacleWithoutRebuild(t),this.RebuildTreeAndGraph()}UpdateObstacles(t){for(let e of t)this.UpdateObstacleWithoutRebuild(e);this.RebuildTreeAndGraph()}UpdateObstacle(t){this.UpdateObstacleWithoutRebuild(t),this.RebuildTreeAndGraph()}RemoveObstacles(t){for(let 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){let e=new mi(t,this.Padding);this.ShapeToObstacleMap.set(t,e),this.PortManager.CreateObstaclePorts(e)}RemoveObstacleWithoutRebuild(t){let e=this.ShapeToObstacleMap.get(t);this.ShapeToObstacleMap.delete(t),this.PortManager.RemoveObstaclePorts(e)}RemoveAllObstacles(){this.InternalClear(!1)}RebuildTreeAndGraph(){let 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 te.constructorC(null)}static constructorC(t){return new te([],te.DefaultPadding,te.DefaultCornerFitRadius)}static{this.DefaultPadding=1}static{this.DefaultCornerFitRadius=3}static constructorI(t){return new te(t,te.DefaultPadding,te.DefaultCornerFitRadius)}static constructorINN(t,e,i){return new te(t,e,i)}static constructorGNAN(t,e,i,r){let s=new te(_r.GetShapes(t),i,r);if(e==null)for(let o of t.deepEdges)s.AddEdgeGeometryToRoute(o);else for(let o of e)s.AddEdgeGeometryToRoute(o);return s}run(){this.GenerateVisibilityGraph(),this.GeneratePaths()}GeneratePaths(){let t=this.EdgesToRoute.map(e=>new AS(e));this.FillEdgePathsWithShortestPaths(t),this.NudgePaths(t),this.RouteSelfEdges(),this.FinaliseEdgeGeometries()}RouteSelfEdges(){for(let t of this.selfEdges){let e={smoothedPolyline:null};t.curve=Fe.RouteSelfEdge(t.sourcePort.Curve,Math.max(this.Padding,2*t.GetMaxArrowheadLength()),e)}}FillEdgePathsWithShortestPaths(t){this.PortManager.BeginRouteEdges();let e=new xS(this.BendPenaltyAsAPercentageOfDistance);for(let i of t)this.AddControlPointsAndGeneratePath(e,i);this.PortManager.EndRouteEdges()}AddControlPointsAndGeneratePath(t,e){let 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){let r=this.PortManager.FindVertices(e.GeomEdge.sourcePort),s=this.PortManager.FindVertices(e.GeomEdge.targetPort);return te.GetSingleStagePath(e,t,r,s,i)}static GetSingleStagePath(t,e,i,r,s){return t.PathPoints=e.GetPath(i,r),s&&te.EnsureNonNullPath(t),t.PathPoints!=null&&t.PathPoints.length>0}static EnsureNonNullPath(t){t.PathPoints==null&&(R.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 g(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){let e=this.ObsTree.SpatialAncestorsAdjusted?Or.GetAncestorSetsMap(this.Obstacles):this.AncestorsSets;Tm.NudgePaths(t,this.edgeSeparatian,this.PaddedObstacles,e,this.RemoveStaircases)}get RemoveStaircases(){return this.removeStaircases}set RemoveStaircases(t){this.removeStaircases=t}FinaliseEdgeGeometries(){for(let t of this.EdgesToRoute.concat(this.selfEdges))t.curve!=null&&(t.curve instanceof et&&(t.curve=te.FitArcsIntoCorners(this.CornerFitRadius,Array.from(t.curve))),te.CalculateArrowheads(t))}CreateVisibilityGraph(){this.GraphGenerator.Clear(),this.InitObstacleTree(),this.GraphGenerator.GenerateVisibilityGraph()}static CalculateArrowheads(t){ge.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=Or.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(let 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 et.mkFromPoints(e);let i=te.GetFittedArcSegs(t,e),r=new G,s=null;for(let o of i){let a=te.EllipseIsAlmostLineSegment(o);s!=null?a?G.continueWithLineSegmentP(r,te.CornerPoint(o)):(G.continueWithLineSegmentP(r,o.start),r.addSegment(o)):a?G.addLineSegment(r,e[0],te.CornerPoint(o)):(G.addLineSegment(r,e[0],o.start),r.addSegment(o)),s=o}return r.segs.length>0?G.continueWithLineSegmentP(r,e[e.length-1]):G.addLineSegment(r,e[0],e[e.length-1]),r}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]),r=i.normalize(),s=Math.min(t,i.length/2);for(let o=1;o<e.length-1;o++){i=e[o+1].sub(e[o]);let a=i.length;if(a<x.intersectionEpsilon){yield new Dt(0,0,new g(0,0),new g(0,0),e[o]);continue}let l=i.div(a);Math.abs(l.dot(r))>.9&&(yield new Dt(0,0,new g(0,0),new g(0,0),e[o]));let h=Math.min(t,i.length/2),u=l.mul(-h),d=r.mul(s);yield new Dt(0,Math.PI/2,u,d,e[o].sub(d.add(u))),r=l,s=h}}};var gl=[[0,-.5],[.5,0],[0,.5],[-.5,0]];function kS(n,t){let e=new Set,i=new Map,r=t.map(s=>{let o=s.toward.x-n.x,a=s.toward.y-n.y,l=Math.hypot(o,a)||1,h=gl.map(([d,c])=>(d*2*o+c*2*a)/l),u=[...h.keys()].sort((d,c)=>h[c]-h[d]);return{end:s,order:u,margin:h[u[0]]-h[u[1]]}}).sort((s,o)=>o.margin-s.margin);for(let{end:s,order:o}of r){let a=n.exclusive?o.find(l=>!e.has(l))??o[0]:o[0];e.add(a),i.set(s,a)}return i}function ac(n){let t=new Map,e=new Map,i=new Map,r=(h,u,d,c)=>{let f=new Si(()=>h.BoundaryCurve,()=>new g(u.x,u.y),new g(d,c));return h.Ports.add(f),f},s=Map.groupBy(n.conns.flatMap(h=>[h.from,h.to]).filter(h=>h.shape!==void 0),h=>h.shape);for(let h of n.shapes){let u=new Ir(et.mkClosedFromPoints(h.outline.map(m=>new g(m.x,m.y))));t.set(h.id,u);let d=r(u,h,0,0),c=s.get(h.id)??[],f=new Map((h.ports??[]).map(m=>[m.id,m]));for(let m of c){let P=f.get(m.port);if(!P){e.set(m,d);continue}let[v,b]=P.side==="left"||P.side==="right"?[(P.side==="left"?-1:1)*h.w/2,P.at-h.y]:[P.at-h.x,(P.side==="top"?-1:1)*h.h/2];e.set(m,r(u,h,v,b)),i.set(m,{x:h.x+v,y:h.y+b})}if(h.diamond)for(let[m,P]of kS(h,c.filter(v=>v.port===void 0&&v.toward))){let[v,b]=[gl[P][0]*h.w,gl[P][1]*h.h];e.set(m,r(u,h,v,b)),i.set(m,{x:h.x+v,y:h.y+b})}}for(let h of n.shapes)for(let u of h.children??[])t.get(h.id).AddChild(t.get(u));let o=h=>h.point?new ve(null,new g(h.point.x,h.point.y)):e.get(h),a=n.conns.map(({from:h,to:u})=>{let d=new Fe(null);return d.sourcePort=o(h),d.targetPort=o(u),d}),l=new cl([...t.values()],n.padding,0);l.edgeSeparatian=n.spacing/2;for(let h of a)l.AddEdgeGeometryToRoute(h);return l.run(),a.map((h,u)=>({path:h.curve?Array.from(h.curve,d=>({x:d.x,y:d.y})):[],pins:[i.get(n.conns[u].from),i.get(n.conns[u].to)]}))}function lc({items:n,groups:t,links:e,sep:i}){let r=new we(new Be("__root__")),s=new Map,o=u=>u?s.get(u):r,a=[],l=u=>{a.includes(u)||(u.parent&&l(t.find(d=>d.id===u.parent)),a.push(u))};t.forEach(l);for(let u of a){let d=new Be(u.id);o(u.parent).graph.addNode(d);let c=new we(d);c.labelSize=new fi(0,u.title),c.margins={left:u.margin,right:u.margin,top:u.margin,bottom:u.margin},s.set(u.id,c)}for(let u of n){let d=new sn(u.id);o(u.group).graph.addNode(d);let c=new ke(d);c.boundaryCurve=ce.mkRectangleWithRoundedCorners(u.w,u.h,0,0,new g(0,0)),s.set(u.id,c)}for(let[u,d]of e)new Fe(new Yn(s.get(u).node??s.get(u).graph,s.get(d).node??s.get(d).graph));let h=new Jn;return h.layerDirection=ll.TB,h.commonSettings.NodeSeparation=i,h.LayerSeparation=i,h.commonSettings.edgeRoutingSettings.EdgeRoutingMode=al.None,r.layoutSettings=h,Ed(r),new Map(n.map(u=>{let d=s.get(u.id).center;return[u.id,{x:d.x,y:-d.y}]}))}function hc({obstacles:n,edges:t,pad:e}){let i=a=>{let l=new ke(new sn(""));return l.boundaryCurve=ce.mkRectangleWithRoundedCorners(a.x1-a.x0,a.y1-a.y0,0,0,new g((a.x0+a.x1)/2,(a.y0+a.y1)/2)),l},r=t.map(({path:a,label:l})=>{let[h,u]=[new ke(new sn("")),new ke(new sn(""))],d=new Yn(h.node,u.node),c=new Fe(d);return c.curve=et.mkFromPoints(a.map(f=>new g(f.x,f.y))),l&&(d.label=new Od(d),c.label=new il(d.label,new fi(l.w+2*e,l.h+2*e))),c}),s=new fo(n.map(i),r);s.edges=r.filter(a=>a.label);for(let a of s.edges)s.edgeInfos.get(a).placementOffset=0;s.run();let o=new Map;return r.forEach((a,l)=>{a.label&&o.set(l,{x:a.label.center.x,y:a.label.center.y})}),o}var yo=64,pl=60,uc=14,$S=40,Po=40,HS=2*yo-2*Po;function WS(n){let t=[],e=uc;for(let i=-e;i<=e;i++)for(let r=-e;r<=e;r++)t.push({x:n.x+i*pl,y:n.y+r*pl});return t}function zS(n){let t=[...n.items.values()].filter(l=>!(l.kind==="note"&&l.attach)),e=new Set([...t.map(l=>l.id),...n.groups.map(l=>l.id)]),i=lc({items:t.map(l=>({id:l.id,w:l.w+2*Po,h:l.h+2*Po,group:l.group})),groups:n.groups.map(l=>({id:l.id,parent:l.parent,margin:gt.groupPad-Po,title:l.style.fontSize+26})),links:n.edges.filter(l=>e.has(l.from)&&e.has(l.to)&&l.from!==l.to).map(l=>[l.from,l.to]),sep:HS}),r=t.filter(l=>l.x!==void 0),s=1,o=0,a=0;if(r.length){let l=P=>r.reduce((v,b)=>v+P(b),0)/r.length,[h,u]=[l(P=>i.get(P.id).x),l(P=>i.get(P.id).y)],[d,c]=[l(P=>P.x),l(P=>P.y)],f=r.reduce((P,v)=>P+(i.get(v.id).x-h)*(v.x-d)+(i.get(v.id).y-u)*(v.y-c),0),m=r.reduce((P,v)=>P+(i.get(v.id).x-h)**2+(i.get(v.id).y-u)**2,0);m>0&&f>0&&(s=f/m),[o,a]=[d-s*h,c-s*u]}return new Map([...i].map(([l,h])=>[l,{x:h.x*s+o,y:h.y*s+a}]))}function qS(n,t){let e=[],i=n.w/2+t.w/2+yo,r=n.h/2+t.h/2+yo;for(let s=0;s<uc;s++){let o=s*pl,a=[[i+o,0],[-(i+o),0],[0,r+o],[0,-(r+o)],[i+o,r+o],[-(i+o),r+o],[i+o,-(r+o)],[-(i+o),-(r+o)]];for(let l of[-1,1])a.push([i+o,l*(t.h/2+o)],[-(i+o),l*(t.h/2+o)]),a.push([l*(t.w/2+o),r+o],[l*(t.w/2+o),-(r+o)]);for(let[l,h]of a)e.push({x:n.x+l,y:n.y+h,ring:s})}return e}function dc(n){let t=()=>[...n.items.values()].filter(r=>r.x!==void 0),e=[...n.nodes.filter(r=>!r.pinned&&r.x===void 0),...n.notes.filter(r=>!r.pinned&&r.x===void 0)],i=e.length?zS(n):new Map;if(![...n.items.values()].some(r=>r.x!==void 0)){for(let r of e.filter(s=>i.has(s.id)))[r.x,r.y]=[Math.round(i.get(r.id).x),Math.round(i.get(r.id).y)];e.splice(0,e.length,...e.filter(r=>r.x===void 0))}for(let r of e){let s=ki(n),o=r.kind==="note"&&r.attach,a=o?n.items.get(r.attach):{...i.get(r.id),w:0,h:0},l=t().filter(f=>f!==r).map(f=>We(f,yo)),h=n.edges.map(f=>[n.items.get(f.from),n.items.get(f.to)]).filter(([f,m])=>f?.x!==void 0&&m?.x!==void 0&&f!==r&&m!==r),u=a.group?s.get(a.group):null,d=yh(n,r),c=null;for(let f of o?qS(a,r):WS(a)){let m=We({...r,x:f.x,y:f.y}),P=We({...r,x:f.x,y:f.y},$S);if(l.some(b=>Cs(b,m)))continue;let v=Math.hypot(f.x-a.x,f.y-a.y);if(v+=600*h.filter(([b,C])=>vs(b,C,We({...r,x:f.x,y:f.y},10))).length,r.kind==="note")for(let[b,C]of s)Cs(C,P)&&!Jo(C,P)?v+=400:Jo(C,m)&&u&&C!==u&&(v+=300);else for(let[b,C]of s)Cs(C,P)&&!d.has(b)&&(v+=2e3);(!c||v<c.cost)&&(c={...f,cost:v})}if(!c)throw new Error(`could not place ${r.id}: no free spot near ${a.id??"its neighbours"}`);r.x=Math.round(c.x),r.y=Math.round(c.y)}for(let r of n.items.values())if(!Number.isFinite(r.x)||!Number.isFinite(r.y))throw new Error(`could not place ${r.id}`);return n}var US=40;function bo(n){let{x:t,y:e,w:i,h:r}=n;return n.shape==="diamond"?[{x:t,y:e-r/2},{x:t+i/2,y:e},{x:t,y:e+r/2},{x:t-i/2,y:e}]:[{x:t-i/2,y:e-r/2},{x:t+i/2,y:e-r/2},{x:t+i/2,y:e+r/2},{x:t-i/2,y:e+r/2}]}function cc(n,t,e){let i=[];for(let r=0;r<e.length;r++){let s=e[r],o=e[(r+1)%e.length],a=(t.x-n.x)*(o.y-s.y)-(t.y-n.y)*(o.x-s.x);if(Math.abs(a)<1e-9)continue;let l=((s.x-n.x)*(o.y-s.y)-(s.y-n.y)*(o.x-s.x))/a,h=((s.x-n.x)*(t.y-n.y)-(s.y-n.y)*(t.x-n.x))/a;l>=0&&l<=1&&h>=0&&h<=1&&i.push(l)}return i}var gc=(n,t,e)=>({x:n.x+(t.x-n.x)*e,y:n.y+(t.y-n.y)*e});function pc(n,t,e){let i=n.slice();if(t){let r=bo(t);for(let s=0;s<i.length-1;s++){let o=cc(i[s],i[s+1],r);if(o.length){i=[gc(i[s],i[s+1],Math.max(...o)),...i.slice(s+1)];break}}}if(e){let r=bo(e);for(let s=i.length-1;s>0;s--){let o=cc(i[s-1],i[s],r);if(o.length){i=[...i.slice(0,s),gc(i[s-1],i[s],Math.min(...o))];break}}}return jS(i)}function jS(n){let t=[];for(let e of n){let i=t[t.length-1];if(i&&Math.abs(i.x-e.x)<.01&&Math.abs(i.y-e.y)<.01)continue;let r=t[t.length-2];if(i&&r&&(Math.abs(r.x-i.x)<.01&&Math.abs(i.x-e.x)<.01||Math.abs(r.y-i.y)<.01&&Math.abs(i.y-e.y)<.01)){t[t.length-1]=e;continue}t.push(e)}return t}function So(n,t,e,i){n.length>1&&(Math.abs(n[t].y-n[e].y)<Math.abs(n[t].x-n[e].x)?n[e]={...n[e],y:i.y}:n[e]={...n[e],x:i.x}),n[t]=i}var fc=30;function QS(n,t,e){let i=(r,s)=>{if(!s||s.shape==="diamond"||r.length<4)return r;let o=r.length,[a,l,h,u]=[r[o-4],r[o-3],r[o-2],r[o-1]],d=Math.abs(a.x-l.x)<.5&&Math.abs(h.x-u.x)<.5&&Math.abs(l.y-h.y)<.5,c=Math.abs(a.y-l.y)<.5&&Math.abs(h.y-u.y)<.5&&Math.abs(l.x-h.x)<.5;return d&&Math.abs(l.x-h.x)<=fc&&Math.abs(a.x-s.x)<=s.w/2-gt.linePitch?[...r.slice(0,o-3),{x:a.x,y:u.y}]:c&&Math.abs(l.y-h.y)<=fc&&Math.abs(a.y-s.y)<=s.h/2-gt.linePitch?[...r.slice(0,o-3),{x:u.x,y:a.y}]:r};return i(i(n,e).reverse(),t).reverse()}function XS(n){let t=[n[0]];for(let e=1;e<n.length;e++){let i=t[t.length-1],r=n[e];Math.abs(i.x-r.x)>.5&&Math.abs(i.y-r.y)>.5&&t.push({x:r.x,y:i.y}),t.push(r)}return t}function mc(n){let t=Math.max(1,...n.edges.map(b=>b.lines.length))*gt.linePitch,e=Math.min(t/2+4,24),i=t+6,r=new Map;for(let[b,C]of ki(n)){let E=C.x1-C.x0,w=C.y1-C.y0;r.set(b,{id:b,x:C.x0+E/2,y:C.y0+w/2,w:E,h:w,shape:"box"})}for(let b of n.edges)for(let C of[b.from,b.to])if(n.groupById.has(C)&&!r.has(C))throw new Error(`edge ${b.id}: container ${C} has no members to draw it around`);let s=b=>n.items.get(b)??r.get(b),o=(b,C)=>{let E=C==="from"?b.via[0]:b.via[b.via.length-1];return E&&{x:E[0],y:E[1]}},a=(b,C)=>{let E=C==="from"?"to":"from",w=o(b,C)??s(b[E]);return w&&{x:w.x,y:w.y}},l=new Set,h=(b,C)=>{let E=We(b),w=n.groupById.get(b.id),F=(w?US:6)+C/2,V={box:E,x0:E.x0+F,x1:E.x1-F,y0:E.y0+F,y1:E.y1-F,top:E.x0+F};return w&&(V.y0=Math.max(V.y0,E.y0+26+w.style.fontSize+24+C/2),V.top=Math.max(V.top,E.x0+20+ni(w.label,w.style.fontSize)+16+C/2)),V},u=b=>{let C=[];for(let E of n.edges)for(let w of["from","to"]){if(E[w]!==b.id)continue;let F=E.lines.length*gt.linePitch,V=h(b,F),{box:q}=V,_=s(w==="from"?E.to:E.from),B=o(E,w)??(r.has(_.id)?null:_),z=B?{x0:B.x,x1:B.x,y0:B.y,y1:B.y,box:{x0:B.x,x1:B.x,y0:B.y,y1:B.y}}:h(_,F),tt=null,O,L,U,[st,W]=[Math.max(V.y0,z.y0),Math.min(V.y1,z.y1)];if(st<=W&&(z.box.x1<q.x0||z.box.x0>q.x1))[tt,O,L,U]=[z.box.x1<q.x0?"left":"right",(st+W)/2,V.y0,V.y1];else if(z.box.y1<q.y0||z.box.y0>q.y1){tt=z.box.y1<q.y0?"top":"bottom",[L,U]=[tt==="top"?V.top:V.x0,V.x1];let[K,at]=[Math.max(L,tt==="bottom"&&!B?z.top:z.x0),Math.min(U,z.x1)];K<=at?O=(K+at)/2:tt=null}tt&&L<=U&&C.push({id:`${E.id} ${w}`,side:tt,at:O,width:F,lo:L,hi:U})}for(let E of Map.groupBy(C,w=>w.side).values()){E.sort((F,V)=>F.at-V.at);for(let F=1;F<E.length;F++)E[F].at=Math.max(E[F].at,E[F-1].at+(E[F-1].width+E[F].width)/2+16);let w=E[E.length-1].at-E[E.length-1].hi;if(w>0)for(let F of E)F.at=Math.max(F.lo,F.at-w)}for(let E of C)l.add(E.id);return C.map(({id:E,side:w,at:F})=>({id:E,side:w,at:F}))},d=[];for(let b of n.items.values()){let C={id:b.id,x:b.x,y:b.y,w:b.w,h:b.h,outline:bo(b),ports:[]};if(b.shape==="diamond"){let E=n.edges.filter(w=>w.from===b.id||w.to===b.id).length+n.notes.filter(w=>w.attach===b.id).length;Object.assign(C,{diamond:!0,exclusive:E<=4})}else b.kind==="node"&&b.shape!=="person"&&(C.ports=u(b));d.push(C)}for(let b of r.values()){let C=[...n.items.values()].filter(w=>w.group===b.id).map(w=>w.id).concat(n.groups.filter(w=>w.parent===b.id&&r.has(w.id)).map(w=>w.id)),E={...b,w:b.w-2*e,h:b.h-2*e};d.push({...E,outline:bo(E),ports:u(b),children:C})}let c=(b,C)=>{let E=`${b.id} ${C}`;return l.has(E)?{shape:b[C],port:E}:{shape:b[C],toward:a(b,C)}},f=[],m=n.edges.map(b=>{let C=[c(b,"from"),...b.via.map(([w,F])=>({point:{x:w,y:F}})),c(b,"to")],E=f.length;for(let w=0;w<C.length-1;w++)f.push({from:C[w],to:C[w+1]});return{e:b,first:E,count:C.length-1}}),P=n.notes.filter(b=>b.attach).map(b=>{let C=n.items.get(b.attach);return f.push({from:{shape:b.id,toward:{x:C.x,y:C.y}},to:{shape:b.attach,toward:{x:b.x,y:b.y}}}),{note:b,index:f.length-1}}),v=ac({shapes:d,conns:f,padding:e,spacing:i});for(let{e:b,first:C,count:E}of m){let w=v.slice(C,C+E),F=[w[0].pins?.[0],...b.via.map(([q,_])=>({x:q,y:_})),w[E-1].pins?.[1]],V=w.flatMap(({path:q},_)=>{let T=q.slice(),[B,z]=[F[_],F[_+1]];return _>0&&_<E-1&&(Math.abs(B.x-z.x)<.5||Math.abs(B.y-z.y)<.5)&&(T=[B,z]),T.length===2?(B&&(T[0]=B),z&&(T[1]=z)):(B&&So(T,0,1,B),z&&So(T,T.length-1,T.length-2,z)),_?T.slice(1):T});b.path=pc(XS(V),s(b.from),s(b.to)),b.path=QS(b.path,s(b.from),s(b.to))}return n.noteLinks=P.map(({note:b,index:C})=>{let{path:E,pins:w}=v[C],F=E.slice();return F.length>1&&(w?.[0]&&So(F,0,1,w[0]),w?.[1]&&So(F,F.length-1,F.length-2,w[1])),{from:b.id,to:b.attach,path:pc(F,b,n.items.get(b.attach))}}),n}var Cc=32,on=gt.lineWidth*1.15,Co=gt.lineWidth*.3,vo=n=>({x:n.y,y:-n.x});function YS(n,t){let e=[];for(let i=0;i<n.length;i++){let r=i>0?vo(si(le(n[i],n[i-1]))):null,s=i<n.length-1?vo(si(le(n[i+1],n[i]))):null,o;r&&s?o=r.x*s.x+r.y*s.y>.99?r:{x:r.x+s.x,y:r.y+s.y}:o=r??s,e.push({x:n[i].x+o.x*t,y:n[i].y+o.y*t})}return e}function Pc(n,t){if(n.length<2)return"";let e=`M${N(n[0].x)},${N(n[0].y)}`;for(let r=1;r<n.length-1;r++){let s=n[r-1],o=n[r],a=n[r+1],l=si(le(o,s)),h=si(le(a,o)),u=l.x*h.y-l.y*h.x,d=Math.max(2,Math.min(Cc+Math.sign(u)*t,$i(le(o,s))/2,$i(le(a,o))/2)),c={x:o.x-l.x*d,y:o.y-l.y*d},f={x:o.x+h.x*d,y:o.y+h.y*d};e+=` L${N(c.x)},${N(c.y)} Q${N(o.x)},${N(o.y)} ${N(f.x)},${N(f.y)}`}let i=n[n.length-1];return e+` L${N(i.x)},${N(i.y)}`}function vc(n){for(let t of n.edges){let e=t.path,i=bc(n.items.get(t.from),e[0],e[1],Sc(t)),r=bc(n.items.get(t.to),e[e.length-1],e[e.length-2],Sc(t)),s=[...t.lines].sort((h,u)=>h.index-u.index),o=s.length;t.width=o*gt.linePitch;let a=t0(e,o,i,r),l=KS(e,i?i+2:0,r?r+2:0);t.strands=s.map((h,u)=>{let d=(u-(o-1)/2)*gt.linePitch,c=YS(l,-d),f=a.map(({p:b,u:C})=>{let E=vo(C);return _S({x:b.x-E.x*d,y:b.y-E.y*d},C)}),m=c.length-1,P={p:c[0],u:si(le(c[1],c[0]))},v={p:c[m],u:si(le(c[m],c[m-1]))};return{line:h,d:Pc(c,-d),marks:f,start:P,end:v}}),t.casing=Pc(l,0)}return ZS(n),n}var JS=12,yc=6;function ZS(n){if(!n.edges.filter(o=>o.label).length)return;let e=Math.max(...n.edges.map(o=>o.width))/2+yc,i=[...n.items.values()].map(o=>We(o));for(let[o,a]of ki(n)){let{label:l,style:h}=n.groupById.get(o);l&&i.push({x0:a.x0,y0:a.y0,x1:a.x0+30+ni(l,h.fontSize),y1:a.y0+44})}let r=[];for(let o of n.edges)for(let a=1;a<o.path.length;a++){let[l,h]=[o.path[a-1],o.path[a]],u=Math.max(1,Math.round($i(le(h,l))/JS));for(let d=0;d<u;d++){let c=f=>({x:l.x+(h.x-l.x)*f,y:l.y+(h.y-l.y)*f});r.push({path:[c(d/u),c((d+1)/u)]})}}let s=hc({obstacles:i,edges:[...n.edges.map(o=>({path:o.path,label:o.label&&Cn(o.label)})),...r],pad:e});n.edges.forEach((o,a)=>{if(!s.has(a))return;let l=s.get(a),{w:h,h:u}=Cn(o.label),d=null;for(let P=1;P<o.path.length;P++){let[v,b]=[o.path[P-1],o.path[P]],C=Math.max(0,Math.min(1,((l.x-v.x)*(b.x-v.x)+(l.y-v.y)*(b.y-v.y))/($i(le(b,v))**2||1))),E={x:v.x+(b.x-v.x)*C,y:v.y+(b.y-v.y)*C},w=$i(le(l,E));(!d||w<d.d)&&(d={d:w,p:E,horizontal:Math.abs(b.y-v.y)<Math.abs(b.x-v.x)})}let c=o.width/2+yc,{p:f,horizontal:m}=d;o.labelAt=m?{x:l.x,y:f.y+Math.sign(l.y-f.y||1)*Math.min(Math.abs(l.y-f.y),c+u/2)}:{x:f.x+Math.sign(l.x-f.x||1)*Math.min(Math.abs(l.x-f.x),c+h/2),y:l.y}})}var Sc=n=>n.lines.length;function bc(n,t,e,i){if(!n||n.shape!=="diamond"||!e)return 0;let r=i*gt.linePitch/2;return Math.abs(e.x-t.x)>Math.abs(e.y-t.y)?r*(n.w/n.h):r*(n.h/n.w)}function KS(n,t,e){let i=n.map(r=>({...r}));if(t){let r=si(le(i[1],i[0]));i[0]={x:i[0].x-r.x*t,y:i[0].y-r.y*t}}if(e){let r=i.length-1,s=si(le(i[r],i[r-1]));i[r]={x:i[r].x+s.x*e,y:i[r].y+s.y*e}}return i}function _S(n,t){let e=vo(t),i={x:n.x+t.x*on/2,y:n.y+t.y*on/2},r={x:n.x-t.x*on/2,y:n.y-t.y*on/2};return[i,{x:r.x+e.x*Co,y:r.y+e.y*Co},{x:r.x-e.x*Co,y:r.y-e.y*Co}]}function t0(n,t,e=0,i=0){let r=Cc+(t+1)/2*gt.linePitch,s=(l,h)=>({p:l,u:h}),o=[],a=n.length-2;for(let l=0;l<=a;l++){let h=n[l],u=n[l+1],d=$i(le(u,h)),c=si(le(u,h)),f=l===0?e+4:r,m=l===a?0:r,P=v=>({x:h.x+c.x*v,y:h.y+c.y*v});if(l===a){let v=d-i-on/2-6;v>f&&o.push(s(P(v),c));for(let b=v-gt.markerSpacing;b>f+on;b-=gt.markerSpacing)o.push(s(P(b),c))}else{let v=d-f-m,b=Math.floor(v/gt.markerSpacing);for(let C=1;C<=b;C++)o.push(s(P(f+v*C/(b+1)),c))}}return o}function an(n){let t=parseInt(n.slice(1),16),[e,i,r]=[t>>16&255,t>>8&255,t&255].map(s=>{let o=s/255;return o<=.03928?o/12.92:((o+.055)/1.055)**2.4});return .2126*e+.7152*i+.0722*r>.35?"rgba(0,0,0,0.6)":"#ffffff"}var e0=12,xc=.4,i0=26;function fl(n,t,e){let i={x0:n.x-n.w/2,x1:n.x+n.w/2,y0:n.y-n.h/2,y1:n.y+n.h/2},r=[];return e.x>1e-6&&r.push((i.x1-t.x)/e.x),e.x<-1e-6&&r.push((i.x0-t.x)/e.x),e.y>1e-6&&r.push((i.y1-t.y)/e.y),e.y<-1e-6&&r.push((i.y0-t.y)/e.y),Math.max(0,Math.min(...r))}var Ec=.55;function r0(n,t,e,i,r){let s=e.x*r.x+e.y*r.y,o=e.x*r.y-e.y*r.x,a={x:i.x-t.x,y:i.y-t.y},l,h;if(Math.abs(o)>.5){let u=(a.x*r.y-a.y*r.x)/o,d=(a.x*e.y-a.y*e.x)/o;u>0&&d>0?[l,h]=[u*Ec,d*Ec]:[l,h]=[Math.max(18,Math.hypot(a.x,a.y)*.5),Math.max(18,Math.hypot(a.x,a.y)*.5)]}else if(s>0){let u=Math.max(18,a.x*e.x+a.y*e.y);[l,h]=[u/2,u/2]}else{let u=Math.max(24,Math.hypot(a.x,a.y));[l,h]=[u*.65,u*.65]}return l=Math.min(l,fl(n,t,e)*.9),h=Math.min(h,fl(n,i,{x:-r.x,y:-r.y})*.9),[t,bs(t,e,l),bs(i,r,-h),i]}function n0(n,t,e){let i=(s,o)=>{let a=(C,E)=>({x:C.x+(E.x-C.x)*o,y:C.y+(E.y-C.y)*o}),[l,h,u,d]=s,c=a(l,h),f=a(h,u),m=a(u,d),P=a(c,f),v=a(f,m),b=a(P,v);return[[l,c,P,b],[b,v,m,d]]},r=i(n,t)[1];return i(r,(e-t)/(1-t))[0]}var Ac=n=>`M${N(n[0].x)},${N(n[0].y)} C${N(n[1].x)},${N(n[1].y)} ${N(n[2].x)},${N(n[2].y)} ${N(n[3].x)},${N(n[3].y)}`,s0=(n,t=24)=>Array.from({length:t+1},(e,i)=>{let r=i/t,s=1-r;return{x:s*s*s*n[0].x+3*s*s*r*n[1].x+3*s*r*r*n[2].x+r*r*r*n[3].x,y:s*s*s*n[0].y+3*s*s*r*n[1].y+3*s*r*r*n[2].y+r*r*r*n[3].y}});function o0(n,t){let e=n.label.split(`
|
|
964
|
+
`),i=Math.max(...e.map(m=>m.length))*n.style.fontSize*.58+8,r=e.length*n.style.lineHeight+4,s=gt.lineWidth/2+3,o=n.x-n.w/2+10+i/2+(n.shape==="queue"?6:0),a=n.x+n.w/2-10-i/2-(n.shape==="queue"?22:0),l=n.y-n.h/2+8+r/2+(n.shape==="cylinder"?14:0),h=n.y+n.h/2-8-r/2,u=(m,P,v)=>P<=m?[(m+P)/2]:Array.from({length:v+1},(b,C)=>m+(P-m)*C/v),d=u(o,a,6),c=u(l,h,Math.max(4,Math.round((h-l)/18))),f=null;for(let m of c)for(let P of d){let v={x0:P-i/2-s,x1:P+i/2+s,y0:m-r/2-s,y1:m+r/2+s},b=0;for(let E of t)for(let w=1;w<E.length;w++)vs(E[w-1],E[w],v)&&(b+=Math.min(vn(E[w],E[w-1]),i));let C=[Math.round(b/12),Math.abs(m-l)+Math.abs(P-n.x)*.5];(!f||C[0]<f.score[0]||C[0]===f.score[0]&&C[1]<f.score[1])&&(f={x:P,y:m,score:C})}return{x:f.x,y:f.y}}function wc(n){for(let t of n.nodes){if(!t.through)continue;let e=n.edges.filter(u=>u.to===t.id).flatMap(u=>u.strands.map(d=>({e:u,line:d.line,p:d.end.p,u:d.end.u}))),i=n.edges.filter(u=>u.from===t.id).flatMap(u=>u.strands.map(d=>({e:u,line:d.line,p:d.start.p,u:d.start.u}))),r=new Map,s=u=>i.filter(d=>d.line===u.line).length,o=u=>e.filter(d=>d.line===u.line).length;for(let u of e)for(let d of i.filter(c=>c.line===u.line)){let c=`${u.e.id} ${d.e.id}`;r.has(c)||r.set(c,[]);let f=r0(t,u.p,u.u,d.p,d.u),m=vn(f[0],f[1])+vn(f[1],f[2])+vn(f[2],f[3]),P=Math.min(.3,e0/Math.max(m,1)),v=s(u)>1?xc:P,b=o(d)>1?1-xc:1-P;r.get(c).push({line:u.line,d:Ac(f),casing:Ac(n0(f,v,b)),pts:s0(f)})}let a=[...r.values()].sort((u,d)=>d.length-u.length),l=[],h=(u,d)=>{let c=d?u.u:{x:-u.u.x,y:-u.u.y},f=Math.min(i0,fl(t,u.p,c)*.6),m=bs(u.p,c,f),P={x:-c.y,y:c.x},v=gt.lineWidth*.9;l.push({line:u.line,pts:[u.p,m],d:`M${N(u.p.x)},${N(u.p.y)} L${N(m.x)},${N(m.y)}`,bar:`M${N(m.x-P.x*v)},${N(m.y-P.y*v)} L${N(m.x+P.x*v)},${N(m.y+P.y*v)}`})};for(let u of e)i.some(d=>d.line===u.line)||h(u,!0);for(let u of i)e.some(d=>d.line===u.line)||h(u,!1);t.inside={subBundles:a,termini:l,labelAt:o0(t,[...a.flat().map(u=>u.pts),...l.map(u=>u.pts)])}}return n}var $e=n=>String(n).replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,"""),Ct=n=>$e(n).replace(/\n/g," ").replace(/\r/g," ").replace(/\t/g,"	");function xo(n,t,e,{size:i=gt.font,lh:r=gt.lineHeight,anchor:s="middle",attrs:o=""}={}){let a=String(n).split(`
|
|
965
|
+
`),l=e-(a.length-1)*r/2,h=a.map((u,d)=>`<tspan x="${N(t)}" y="${N(l+d*r)}">${$e(u)}</tspan>`).join("");return`<text font-size="${i}" text-anchor="${s}" dominant-baseline="central" ${o}>${h}</text>`}var Ci=n=>{let t=Object.entries(n).filter(([,e])=>e!=null);return t.length?` style="${$e(t.map(([e,i])=>`${e}:${i}`).join(";"))}"`:""},a0=' stroke-width="5" stroke-linejoin="round" paint-order="stroke"',Eo=(n,t="lm-label",e={})=>({size:n.fontSize,lh:n.lineHeight,attrs:`class="${t}"${t.includes("lm-halo")?a0:""}${n.italic?' font-style="italic"':""}${Ci({fill:n.fontColor,"font-weight":n.bold?600:void 0,...e})}`});function l0(n,t){let e=new Set;for(let h of t.edges){let u=h.from===n.id?h.path[0]:h.to===n.id?h.path[h.path.length-1]:null;if(!u)continue;let d=(u.x-n.x)/n.w,c=(u.y-n.y)/n.h;e.add(Math.abs(d)>Math.abs(c)?d>0?"right":"left":c>0?"bottom":"top")}let i=String(n.label).split(`
|
|
966
|
+
`),r=Math.max(...i.map(h=>ni(h,n.style.fontSize))),s=i.length*n.style.lineHeight,o=n.x-n.w/2,a=n.y-n.h/2;return{bottom:{x:n.x,y:a+n.h+8+s/2,anchor:"middle",box:{x0:n.x-r/2,y0:a+n.h,x1:n.x+r/2,y1:a+n.h+8+s}},right:{x:o+n.w*.86+6,y:n.y+n.h*.18,anchor:"start",box:{x0:o+n.w,y0:n.y,x1:o+n.w*.86+6+r,y1:n.y+s}},left:{x:o+n.w*.14-6,y:n.y+n.h*.18,anchor:"end",box:{x0:o+n.w*.14-6-r,y0:n.y,x1:o,y1:n.y+s}},top:{x:n.x,y:a-8-s/2,anchor:"middle",box:{x0:n.x-r/2,y0:a-8-s,x1:n.x+r/2,y1:a}},under:{x:n.x+n.w*.2,y:a+n.h+8+s/2,anchor:"start",box:{x0:n.x,y0:a+n.h,x1:n.x+n.w*.2+r,y1:a+n.h+8+s}}}[["bottom","right","left","top"].find(h=>!e.has(h))??"under"]}function Ic(n,t,e,i){if(t<2.5*i.length)return"";let r=Math.max(1,Math.round(t/i.period)),s=Math.floor(1e5/r)/1e3,o=`${N(i.length/2)},0 ${N(-i.length/2)},${N(-i.half)} ${N(-i.length/2)},${N(i.half)}`,a=l=>`<polygon points="${o}" class="lm-arrow${l===0?" lm-arrow-in":""}${l===r-1?" lm-arrow-out":""}" style="--lm-i:${l}"/>`;return`<g class="lm-arrows" data-line="${Ct(e.id)}" visibility="hidden" style="--lm-p:path('${n}');--lm-s:${s}%;--lm-t:${(t/r/i.speed).toFixed(2)}s">${Array.from({length:r},(l,h)=>a(h)).join("")}</g>`}var Tc=n=>n.slice(1).reduce((t,e,i)=>t+Math.hypot(e.x-n[i].x,e.y-n[i].y),0),Ao={radius:{node:10,group:16,note:6,label:99},fx:{filter:()=>""}};function Oc(n,t=Ao){let{x:e,y:i,w:r,h:s,style:o}=n,a=e-r/2,l=i-s/2,h=`class="lm-shape"${Ci({fill:o.fill,stroke:o.stroke})}${t.fx.filter("node")}`,u=`class="lm-shape-line"${Ci({stroke:o.stroke})}`,d=(m,P,v)=>xo(m,P,v,Eo(o)),c=t.sheen?.(s),f=(m,P)=>`<${m} ${P} ${h}/>`+(c?`<${m} ${P} class="lm-sheen" fill="url(#${c})"/>`:"");switch(n.shape){case"diamond":return f("polygon",`points="${N(e)},${N(l)} ${N(a+r)},${N(i)} ${N(e)},${N(l+s)} ${N(a)},${N(i)}"`)+d(n.label,e,i);case"cylinder":return f("path",`d="M${N(a)},${N(l+14)} A${r/2},14 0 0 1 ${N(a+r)},${N(l+14)} V${N(l+s-14)} A${r/2},14 0 0 1 ${N(a)},${N(l+s-14)} Z"`)+`<path d="M${N(a)},${N(l+14)} A${r/2},14 0 0 0 ${N(a+r)},${N(l+14)}" ${u}/>`+d(n.label,e,i+14/2);case"queue":return f("path",`d="M${N(a+16)},${N(l)} H${N(a+r-16)} A16,${s/2} 0 0 1 ${N(a+r-16)},${N(l+s)} H${N(a+16)} A16,${s/2} 0 0 1 ${N(a+16)},${N(l)} Z"`)+`<path d="M${N(a+r-16)},${N(l)} A16,${s/2} 0 0 0 ${N(a+r-16)},${N(l+s)}" ${u}/>`+d(n.label,e-16/2,i);case"person":{let m=r*.17,P=l+s*.3,v=`M${N(e-r*.36)},${N(l+s)} V${N(l+s*.78)} Q${N(e-r*.36)},${N(l+s*.52)} ${N(e)},${N(l+s*.52)} Q${N(e+r*.36)},${N(l+s*.52)} ${N(e+r*.36)},${N(l+s*.78)} V${N(l+s)} Z`,b=Ci({fill:o.fill}),C=t.personAt??{x:e,y:l+s+16,anchor:"middle"};return`<circle cx="${N(e)}" cy="${N(P)}" r="${N(m)}" class="lm-person"${b}/><path d="${v}" class="lm-person"${b}/>`+xo(n.label,C.x,C.y,{...Eo(o,"lm-label lm-halo",{stroke:t.haloFill}),anchor:C.anchor})}default:return f("rect",`x="${N(a)}" y="${N(l)}" width="${r}" height="${s}" rx="${N(Math.min(t.radius.node,r/2,s/2))}"`)+d(n.label,e,i)}}function h0(n,t){let e=[Oc({...n,label:""},t)],i=Ci({stroke:n.style.fill});for(let o of n.inside.subBundles){for(let a of o)e.push(`<path d="${a.casing}" class="lm-casing lm-casing-in" stroke-width="${gt.lineWidth+4}"${i}/>`);for(let a of o)e.push(`<path d="${a.d}" class="lm-strand" stroke="${Ct(a.line.color)}" stroke-width="${gt.lineWidth}" data-line="${Ct(a.line.id)}"><title>${$e(a.line.label)}</title></path>`)}for(let o of n.inside.termini)e.push(`<path d="${o.d}" class="lm-strand" stroke="${Ct(o.line.color)}" stroke-width="${gt.lineWidth}" data-line="${Ct(o.line.id)}"/>`),e.push(`<path d="${o.bar}" class="lm-strand" stroke="${Ct(o.line.color)}" stroke-width="4" stroke-linecap="round" data-line="${Ct(o.line.id)}"/>`);if(t.line?.flow)for(let o of n.inside.subBundles.flat())e.push(Ic(o.d,Tc(o.pts),o.line,t.line.flow));let{x:r,y:s}=n.inside.labelAt;return e.push(xo(n.label,r,s,Eo({...n.style,bold:!0},"lm-label lm-halo lm-halo-in",{stroke:n.style.fill}))),e.join("")}function u0(n,t=Ao){let e=n.x-n.w/2,i=n.y-n.h/2,r=n.style,s=n.label.split(`
|
|
967
|
+
`).map((a,l)=>{let h=i+gt.notePad+r.lineHeight*(l+.5);return`<tspan x="${N(e+gt.notePad)}" y="${N(h)}">${$e(a)}</tspan>`}),o=Eo({...r,italic:!1},"lm-note-text");return`<rect x="${N(e)}" y="${N(i)}" width="${n.w}" height="${n.h}" rx="${t.radius.note}" class="lm-note-box"${Ci({fill:r.fill,stroke:r.stroke})}${t.fx.filter("small")}/><text font-size="${o.size}" ${o.attrs} dominant-baseline="central">${s.join("")}</text>`}function d0(n,t,e=Ao){let s=96+Math.max(...n.lines.map(d=>ni(d.label??d.id,14)))+18,o=n.lines.length*28+36+22,a=n.legend.at??[t.x0+s/2,t.y1+60+o/2],l=a[0]-s/2,h=a[1]-o/2,u=n.lines.map((d,c)=>{let f=h+18+32+c*28;return`<g class="legend-row" data-line="${Ct(d.id)}"${d.hidden?' opacity="0.35"':""}><line x1="${N(l+18+4)}" y1="${N(f)}" x2="${N(l+18+56)}" y2="${N(f)}" stroke="${Ct(d.color)}" stroke-width="${gt.lineWidth}" stroke-linecap="round"/><polygon points="${N(l+18+35)},${N(f)} ${N(l+18+25)},${N(f-gt.lineWidth*.3)} ${N(l+18+25)},${N(f+gt.lineWidth*.3)}" fill="${Ct(an(d.color))}"/><text x="${N(l+18+74)}" y="${N(f)}" font-size="14" class="lm-legend-text" dominant-baseline="central">${$e(d.label??d.id)}</text></g>`});return{svg:`<g class="legend"><rect x="${N(l)}" y="${N(h)}" width="${N(s)}" height="${o}" rx="${Math.min(e.radius.group,12)}" class="lm-legend-box"${e.fx.filter("small")}/><text x="${N(l+18)}" y="${N(h+18+4)}" font-size="12" class="lm-legend-title" dominant-baseline="central">LINES</text>${u.join("")}</g>`,rect:{x0:l,y0:h,x1:l+s,y1:h+o}}}function wo(n,{legend:t=!0,theme:e,css:i=""}={}){if(/<\/style/i.test(i))throw new Error('css: must not contain "</style"');let r=e??n.theme??ri,s=lh(r);yn(n.lines,s);let o=dh(s,r),a=new Map,l=s.node.sheen?T=>{let B=Math.min(.6,Math.round(s.node.sheen.depth/T*20)/20||.05);return a.has(B)||a.set(B,`lm-sheen-${Ct(r)}-${Math.round(B*100)}`),a.get(B)}:null,h={radius:{...Ao.radius,...s.radius},fx:o,sheen:l,line:s.line},u=ki(n),d=new Map(n.nodes.filter(T=>T.shape==="person").map(T=>[T.id,l0(T,n)])),c=[...n.items.values()].map(T=>({x0:T.x-T.w/2,y0:T.y-T.h/2,x1:T.x+T.w/2,y1:T.y+T.h/2}));for(let T of d.values())c.push(T.box);for(let T of n.edges)for(let B of T.path)c.push({x0:B.x,y0:B.y,x1:B.x,y1:B.y});c.push(...u.values());let f={x0:Math.min(...c.map(T=>T.x0)),y0:Math.min(...c.map(T=>T.y0)),x1:Math.max(...c.map(T=>T.x1)),y1:Math.max(...c.map(T=>T.y1))},m=t?d0(n,f,h):null;if(m){for(let T of["x0","y0"])f[T]=Math.min(f[T],m.rect[T]);for(let T of["x1","y1"])f[T]=Math.max(f[T],m.rect[T])}let P=40,v=[f.x0-P,f.y0-P,f.x1-f.x0+2*P,f.y1-f.y0+2*P].map(N),b=[];b.push(`<svg xmlns="http://www.w3.org/2000/svg" viewBox="${v.join(" ")}" width="${v[2]}" height="${v[3]}" class="linemap lm-root lm-theme-${Ct(r)}" data-theme="${Ct(r)}" font-family="${$e(s.font)}" fill="${s.ink}">`),b.push(`<style>
|
|
968
|
+
${Xo(s)}${i?`
|
|
969
|
+
${i}`:""}
|
|
970
|
+
</style>`),o.defs&&b.push(o.defs);let C=b.length;if(b.push(""),b.push(`<rect x="${v[0]}" y="${v[1]}" width="${v[2]}" height="${v[3]}" class="lm-bg" fill="${s.bg}"/>`),s.grid){let T=s.grid.step,B=(z,tt)=>{let O=[];for(let L=Math.ceil(v[0]/z)*z;L<=v[0]+v[2];L+=z)O.push(`M${L},${v[1]}V${N(v[1]+v[3])}`);for(let L=Math.ceil(v[1]/z)*z;L<=v[1]+v[3];L+=z)O.push(`M${v[0]},${L}H${N(v[0]+v[2])}`);return`<path class="${tt}" d="${O.join("")}"/>`};b.push(`<g class="lm-grid">${B(T,"lm-grid-minor")}${B(T*5,"lm-grid-major")}</g>`)}let E=new Map,w=[],F=[];for(let T of n.groups){let B=u.get(T.id);if(!B)continue;let z=T.style,tt=T.accent?hh(s,T.accent):{},O=z.fill??tt.fill;E.set(T.id,O??s.group.fill),b.push(`<g class="${$e(["group",T.classes].filter(Boolean).join(" "))}" id="${Ct(T.id)}" data-label="${Ct(T.label)}">`),b.push(`<rect x="${N(B.x0)}" y="${N(B.y0)}" width="${N(B.x1-B.x0)}" height="${N(B.y1-B.y0)}" rx="${h.radius.group}" class="lm-group-box"${Ci({fill:O,stroke:tt.stroke})}${o.filter("group")}/>`);let L=z.italic?' font-style="italic"':"";if(s.group.titles==="tab"){let U=Math.round(z.fontSize*.78),st=U+12,W=ni(T.label,U)*1.1+22,K=B.x0+Math.max(18,h.radius.group);for(let at=!0;at;){at=!1;for(let ut of w)K<ut.x1+8&&K+W>ut.x0-8&&Math.abs(B.y0-ut.y)<st+4&&(K=ut.x1+8,at=!0)}w.push({x0:K,x1:K+W,y:B.y0}),F.push(`<g class="group-tab" data-group="${Ct(T.id)}"><rect x="${N(K)}" y="${N(B.y0-st/2)}" width="${N(W)}" height="${st}" rx="${N(Math.min(st/2,h.radius.label))}" class="lm-group-tab"${Ci({fill:tt.title})}${o.filter("small")}/><text x="${N(K+11)}" y="${N(B.y0)}" font-size="${U}" dominant-baseline="central" class="lm-group-title lm-group-title-tab"${L}${Ci({fill:z.fontColor??(tt.title&&uh(s,tt.title)),"font-weight":z.bold?void 0:500})}>${$e(T.label)}</text></g>`)}else b.push(`<text x="${N(B.x0+20)}" y="${N(B.y0+28)}" font-size="${z.fontSize}" class="lm-group-title"${L}${Ci({fill:z.fontColor??tt.title,"font-weight":z.bold?void 0:400})}>${$e(T.label)}</text>`);b.push("</g>")}for(let T of n.noteLinks){let B=T.path.map((z,tt)=>`${tt?"L":"M"}${N(z.x)},${N(z.y)}`).join(" ");b.push(`<path d="${B}" class="lm-note-link"/>`)}for(let T of n.edges){let B=T.label?` data-label="${Ct(T.label)}"`:"";if(b.push(`<g class="edge" data-from="${Ct(T.from)}" data-to="${Ct(T.to)}" data-lines="${Ct(T.strands.map(z=>z.line.id).join(" "))}"${B}>`),b.push(`<path d="${T.casing}" class="lm-casing" stroke-width="${N(T.width+5)}"/>`),s.line?.glow){b.push('<g class="lm-glows">');for(let{grow:z,opacity:tt}of s.line.glow)for(let O of T.strands)b.push(`<path d="${O.d}" class="lm-glow" stroke="${Ct(O.line.color)}" stroke-width="${gt.lineWidth+z}" stroke-opacity="${tt}" data-line="${Ct(O.line.id)}"/>`);b.push("</g>")}for(let z of T.strands)b.push(`<path d="${z.d}" class="lm-strand" stroke="${Ct(z.line.color)}" stroke-width="${gt.lineWidth}" data-line="${Ct(z.line.id)}"><title>${$e(z.line.label??z.line.id)}</title></path>`);for(let z of T.strands){let tt=an(z.line.color);if(z.marks.length){b.push(`<g class="lm-marks" data-line="${Ct(z.line.id)}">`);for(let O of z.marks)b.push(`<polygon points="${O.map(L=>`${N(L.x)},${N(L.y)}`).join(" ")}" fill="${Ct(tt)}"/>`);b.push("</g>")}}if(s.line?.flow)for(let z of T.strands)b.push(Ic(z.d,Tc(T.path),z.line,s.line.flow));b.push("</g>")}b.push(...F);let V=(T,B)=>$e([T,B.classes].filter(Boolean).join(" ")),q=T=>`id="${Ct(T.id)}" data-label="${Ct(T.label)}"${T.url?` data-url="${Ct(T.url)}"`:""}`,_=(T,B)=>T.url?`<a href="${Ct(T.url)}">${B}</a>`:B;for(let T of n.nodes){let B={...h,personAt:d.get(T.id),haloFill:T.group?E.get(T.group):void 0};b.push(T.through?`<g class="${V("node through",T)}" ${q(T)} data-shape="${Ct(T.shape)}" data-through="true">${_(T,h0(T,h))}</g>`:`<g class="${V("node",T)}" ${q(T)} data-shape="${Ct(T.shape)}">${_(T,Oc(T,B))}</g>`)}for(let T of n.notes)b.push(`<g class="${V("note",T)}" ${q(T)}>${_(T,u0(T,h))}</g>`);for(let T of n.edges){if(!T.labelAt)continue;let{w:B,h:z}=Cn(T.label),{x:tt,y:O}=T.labelAt;b.push(`<g class="lm-edge-label-group"><rect x="${N(tt-B/2)}" y="${N(O-z/2)}" width="${N(B)}" height="${z}" rx="${N(Math.min(z/2,h.radius.label))}" class="lm-edge-label-box"${o.filter("small")}/>`),b.push(xo(T.label,tt,O,{size:12,lh:15,attrs:'class="lm-edge-label"'})+"</g>")}if(m&&b.push(m.svg),a.size){let{color:T,opacity:B}=s.node.sheen;b[C]=`<defs>${[...a].map(([z,tt])=>`<linearGradient id="${tt}" x1="0" y1="0" x2="0" y2="1"><stop offset="0" stop-color="${T}" stop-opacity="${B}"/><stop offset="${z}" stop-color="${T}" stop-opacity="0"/></linearGradient>`).join("")}</defs>`}return b.push("</svg>"),b.filter(Boolean).join(`
|
|
971
|
+
`)}function ml(n,{hiddenLines:t,through:e,fixed:i}={}){if(n.laidOut)throw new Error("layout: this model is already laid out; parse the DOT text again");if(n.laidOut=!0,e){let{mode:r="file",nodes:s}=e;if(!["file","all","none"].includes(r))throw new Error(`layout: through.mode must be file, all or none, not "${r}"`);for(let o of n.nodes)Ph(o)&&(o.through=s?.get(o.id)??(r==="all"?!0:r==="none"?!1:o.through))}for(let[r,s]of i??[]){let o=n.items.get(r);o&&!o.pinned&&([o.x,o.y]=[s.x,s.y])}if(dc(n),t?.size){for(let r of n.lines)r.hidden=t.has(r.id);for(let r of n.edges)r.lines=r.lines.filter(s=>!s.hidden);n.edges=n.edges.filter(r=>r.lines.length)}return mc(n),vc(n),wc(n),n}var Pl=n=>[...n.items.values()].filter(t=>!t.pinned).map(({id:t,x:e,y:i})=>({id:t,x:e,y:i}));var c0=["file","all","none"],yl=()=>({hidden:new Set,mode:"file",theme:null});function Lc(n=yl()){let t=n,e=new Set;return{get:()=>t,set(i){t={...t,...i};for(let r of e)r(t)},reset(){this.set(yl())},onChange(i){e.add(i)}}}var g0=n=>encodeURIComponent(n),p0=n=>{try{return decodeURIComponent(n)}catch{return n}};function Sl(n=location.hash){let t=yl(),e=null;for(let i of n.replace(/^#/,"").split("&")){let r=i.indexOf("=");if(r<0)continue;let[s,o]=[i.slice(0,r),i.slice(r+1)];if(s==="hide")t.hidden=new Set(o.split(",").filter(Boolean).map(p0));else if(s==="through"&&c0.includes(o))t.mode=o;else if(s==="theme"&&hr.includes(o))t.theme=o;else if(s==="view"){let a=o.split(",").map(Number);a.length===4&&a.every(Number.isFinite)&&a[2]>0&&a[3]>0&&(e={x:a[0],y:a[1],w:a[2],h:a[3]})}}return{settings:t,view:e}}function f0(n,t){let e=[];return n.hidden.size&&e.push(`hide=${[...n.hidden].map(g0).join(",")}`),n.mode!=="file"&&e.push(`through=${n.mode}`),n.theme&&e.push(`theme=${n.theme}`),t&&e.push(`view=${[t.x,t.y,t.w,t.h].map(i=>Math.round(i)).join(",")}`),e.length?`#${e.join("&")}`:""}function Bc(n=250){let t=0;return(e,i)=>{clearTimeout(t),t=setTimeout(()=>{let r=f0(e,i);if(!(r===location.hash||!r&&!location.hash))try{history.replaceState(null,"",location.pathname+location.search+r)}catch{}},n)}}function Rc({onResult:n}){let t=null,e=null,i=!1,r=null;async function s(a,l){let h=performance.now(),{hidden:u,mode:d,theme:c}=l;if(t?.text!==a){let C=ml(Ss(a));t={text:a,model:C,fixed:new Map(Pl(C).map(({id:E,x:w,y:F})=>[E,{x:w,y:F}]))}}let f=new Set(t.model.lines.map(C=>C.id)),m=new Set([...u].filter(C=>f.has(C))),P=JSON.stringify([d,[...m].sort()]),v=t.model;e?.base===t&&e.key===P?v=e.model:(m.size||d!=="file")&&(v=ml(Ss(a),{hiddenLines:m,through:{mode:d},fixed:t.fixed})),e={base:t,key:P,model:v};let b=c??v.theme??ri;return yn(t.model.lines,jt[b]),{ok:!0,model:v,base:t.model,theme:b,svg:wo(v,{legend:!1,theme:b}),ms:performance.now()-h}}async function o(a,l,h={}){if(i){r={text:a,settings:l,meta:{...r?.meta,...h,fresh:!!(r?.meta.fresh||h.fresh)}};return}i=!0;let u={text:a,settings:l,meta:h};for(;u;){let d;try{d=await s(u.text,u.settings)}catch(f){d={ok:!1,error:f?.message??String(f)}}let c=r;r=null,c?c.meta={...u.meta,...c.meta,fresh:!!(u.meta.fresh||c.meta.fresh)}:n(d,u.meta),u=c}i=!1}return{request:o,busy:()=>i,exportSvg:(a,l)=>wo(a,{legend:!0,theme:l}),positions:a=>Pl(a)}}var Fc="linemap:last",Io="linemap:recent";var ln={get(n){try{return JSON.parse(localStorage.getItem(n))}catch{return null}},set(n,t){try{localStorage.setItem(n,JSON.stringify(t))}catch{}}},Lr=()=>/^https?:$/.test(location.protocol),m0=n=>decodeURIComponent(String(n).split(/[?#]/)[0].split("/").pop()||n),P0=n=>/^\s*(\/\/[^\n]*\n\s*|\/\*[\s\S]*?\*\/\s*|#[^\n]*\n\s*)*(strict\s+)?(di)?graph\b/i.test(n);function Nc({onText:n,onError:t,onWatch:e,embedded:i=[]}){let r=null,s=0,o=!1;function a(C,E,w,F,{keep:V=!0}={}){let q=!r||r.text!==C||r.name!==E;r={text:C,name:E,src:w},q&&V&&l(C,E,w),n({text:C,name:E,src:w,fresh:F})}function l(C,E,w){ln.set(Fc,{text:C,name:E,src:w});let F=(ln.get(Io)??[]).filter(V=>V&&V.name!==E);F.unshift({name:E,text:C,src:w,time:Date.now()}),ln.set(Io,F.slice(0,8))}async function h(C){let E=await fetch(C,{cache:"no-store"});if(!E.ok)throw new Error(`${E.status} ${E.statusText||""}`.trim());return E.text()}async function u(C,{fresh:E=!0}={}){try{return a(await h(C),m0(C),C,E),!0}catch(w){let F=location.protocol==="file:"?`
|
|
972
|
+
|
|
973
|
+
Browsers do not let a page opened from a file fetch other files. Serve over http, e.g. with npx @linemap/cli studio, or open the file with Open / drag-and-drop.`:"";return t(`Could not load ${C}`,`${w.message}${F}`),!1}}async function d(C){try{let E=await C.text();m(!1),a(E,C.name,null,!0)}catch(E){t(`Could not read ${C.name}`,E.message)}}function c(C,E=`${/graph\s+("?)([\w.-]+)\1\s*\{/.exec(C)?.[2]??"flow"} (pasted)`,w=null){m(!1),a(C,E,w,!0)}function f(C){let E=i[C];E&&(m(!1),a(E.text,E.name,null,!0,{keep:!1}))}function m(C){C=!!(C&&r?.src&&Lr()),clearInterval(s),s=0,C&&(s=setInterval(async()=>{if(!o){o=!0;try{let E=await h(r.src);E!==r.text&&a(E,r.name,r.src,!1)}catch{}o=!1}},1e3)),e?.(C)}async function P(){if(r)if(r.src&&Lr()){let C=r.src;try{let E=await h(C);a(E,r.name,C,!1)}catch(E){t(`Could not reload ${C}`,E.message)}}else n({...r,fresh:!1})}function v(C){let E=0,w=F=>[...F.dataTransfer?.types??[]].includes("Files");window.addEventListener("dragenter",F=>{w(F)&&(F.preventDefault(),E++,C.hidden=!1)}),window.addEventListener("dragover",F=>{w(F)&&(F.preventDefault(),F.dataTransfer.dropEffect="copy")}),window.addEventListener("dragleave",()=>{--E<=0&&(E=0,C.hidden=!0)}),window.addEventListener("drop",F=>{if(!w(F))return;F.preventDefault(),E=0,C.hidden=!0;let V=F.dataTransfer.files[0];V&&d(V)})}function b(){window.addEventListener("paste",C=>{if(C.target.closest?.("input, textarea, [contenteditable]"))return;let E=C.clipboardData?.getData("text/plain")??"";P0(E)&&(C.preventDefault(),c(E))})}return{loadUrl:u,loadFile:d,loadText:c,loadEmbedded:f,reload:P,embedded:()=>i,setWatch:m,bindDrop:v,bindPaste:b,current:()=>r,watching:()=>!!s,canWatch:()=>!!(r?.src&&Lr()),last:()=>ln.get(Fc),recent:()=>(ln.get(Io)??[]).filter(C=>C&&typeof C.text=="string"),clearRecent:()=>{ln.set(Io,[])}}}function Gc({stage:n,onChange:t,avoid:e=()=>null}){let i=null,r=null,s=0,o=0,a=1,l=n.clientWidth||1,h=n.clientHeight||1,u=0,d=null,c=$=>{let Z=Math.min(($.x1-$.x0-56)/r.w,($.y1-$.y0-56)/r.h);return{s:Z,cx:r.x+r.w/2-(($.x0+$.x1)/2-l/2)/Z,cy:r.y+r.h/2-(($.y0+$.y1)/2-h/2)/Z}};function f(){let $=c({x0:0,y0:0,x1:l,y1:h}),Z=e();if(!Z)return $;let Q=[c({x0:Z.x1,y0:0,x1:l,y1:h}),c({x0:0,y0:0,x1:l,y1:Z.y0})].reduce((ot,Xt)=>Xt.s>ot.s?Xt:ot);return Q.s>=$.s*.85?Q:$}let m=()=>r?c({x0:0,y0:0,x1:l,y1:h}).s:1,P=()=>Math.min(m()/4,8),v=$=>Math.min(8,Math.max(P(),$));function b(){if(!i)return;r&&(s=Math.min(r.x+r.w,Math.max(r.x,s)),o=Math.min(r.y+r.h,Math.max(r.y,o)));let $=l/a,Z=h/a;i.setAttribute("viewBox",`${C(s-$/2)} ${C(o-Z/2)} ${C($)} ${C(Z)}`),t?.()}let C=$=>Math.round($*100)/100,E=()=>{cancelAnimationFrame(u),u=0};function w($,Z=220){if(E(),!Z||matchMedia("(prefers-reduced-motion: reduce)").matches){$(1),b();return}let Q=performance.now(),ot=Xt=>{let ae=Math.min(1,(Xt-Q)/Z);$(1-(1-ae)**3),b(),u=ae<1?requestAnimationFrame(ot):0};u=requestAnimationFrame(ot)}let F=($,Z)=>({x:s+($-l/2)/a,y:o+(Z-h/2)/a}),V=$=>{let Z=n.getBoundingClientRect();return{x:$.clientX-Z.left,y:$.clientY-Z.top}};function q($,Z={x:l/2,y:h/2},Q=0){d=null;let ot=a,Xt={x:s,y:o},ae=v(ot*$),oe=F(Z.x,Z.y);w(or=>{a=ot*(ae/ot)**or,s=oe.x-(oe.x-Xt.x)*ot/a,o=oe.y-(oe.y-Xt.y)*ot/a},Q)}function _($,{ms:Z=260,pad:Q=.88,maxScale:ot=8}={}){d=null;let Xt=a,ae={x:s,y:o},oe=v(Math.min(ot,Math.min(l/$.w,h/$.h)*Q)),or={x:$.x+$.w/2,y:$.y+$.h/2};w(cn=>{a=Xt*(oe/Xt)**cn,s=ae.x+(or.x-ae.x)*cn,o=ae.y+(or.y-ae.y)*cn},Z)}function T($=0){if(!r)return;d={fit:!0};let Z=a,Q={x:s,y:o},ot=f(),Xt=ot.s,ae={x:ot.cx,y:ot.cy};w(oe=>{a=Z*(Xt/Z)**oe,s=Q.x+(ae.x-Q.x)*oe,o=Q.y+(ae.y-Q.y)*oe},$)}function B($){_($,{ms:0,pad:1}),d={rect:$}}function z($,Z,Q=0){d=null;let ot={x:s,y:o};w(Xt=>{s=ot.x+$/a*Xt,o=ot.y+Z/a*Xt},Q)}let tt=null;n.addEventListener("wheel",$=>{if(!i)return;$.preventDefault(),E();let Z=$.deltaMode===1?16:$.deltaMode===2?h:1,Q=$.ctrlKey?.012:.0018,ot=V($);tt||(tt={dy:0,p:ot},requestAnimationFrame(()=>{let{dy:Xt,p:ae}=tt;tt=null,q(Math.exp(-Math.max(-300,Math.min(300,Xt))*Q),ae)})),tt.dy+=$.deltaY*Z,tt.p=ot},{passive:!1});let O=new Map,L=null,U=null,st=!1,W=()=>{let[$,Z]=[...O.values()];return{x:($.x+Z.x)/2,y:($.y+Z.y)/2}},K=()=>{let[$,Z]=[...O.values()];return Math.hypot($.x-Z.x,$.y-Z.y)||1};n.addEventListener("pointerdown",$=>{if(!(!i||$.pointerType==="mouse"&&$.button!==0)&&!$.target.closest("a, button, input, .empty")){if(E(),O.set($.pointerId,V($)),O.size===1)L={start:V($),c0:{x:s,y:o},moved:!1};else if(O.size===2){L=null;let Z=W();U={d0:K(),s0:a,anchor:F(Z.x,Z.y)},ut(!0)}}}),window.addEventListener("pointermove",$=>{if(!O.has($.pointerId))return;let Z=V($);if(O.set($.pointerId,Z),U&&O.size>=2){let Q=W();d=null,a=v(U.s0*K()/U.d0),s=U.anchor.x-(Q.x-l/2)/a,o=U.anchor.y-(Q.y-h/2)/a,b()}else if(L){let Q=Z.x-L.start.x,ot=Z.y-L.start.y;if(!L.moved&&Math.hypot(Q,ot)<4)return;L.moved||(L.moved=!0,d=null,ut(!0)),s=L.c0.x-Q/a,o=L.c0.y-ot/a,b()}});let at=$=>{if(O.has($.pointerId))if(O.delete($.pointerId),(L?.moved||U)&&(st=!0),O.size<2&&(U=null),O.size===1){let[Z]=O.values();L={start:Z,c0:{x:s,y:o},moved:!0}}else O.size||(L=null,ut(!1),setTimeout(()=>{st=!1},0))};window.addEventListener("pointerup",at),window.addEventListener("pointercancel",at),n.addEventListener("click",$=>{st&&($.stopPropagation(),$.preventDefault(),st=!1)},!0),n.addEventListener("dblclick",$=>{!i||$.target.closest("a, button, input, .empty")||($.preventDefault(),q($.shiftKey?.5:2,V($),240))});function ut($){n.classList.toggle("panning",$)}return new ResizeObserver(()=>{let[$,Z]=[n.clientWidth||1,n.clientHeight||1];$===l&&Z===h||(l=$,h=Z,d?.fit?T():d?.rect?B(d.rect):b())}).observe(n),{setContent($,Z,{keep:Q=!1}={}){i=$,i.setAttribute("preserveAspectRatio","xMidYMid meet"),r=Z,Q?b():T()},clear(){i=null,r=null},fit:()=>T(240),zoomIn:()=>q(1.6,void 0,200),zoomOut:()=>q(1/1.6,void 0,200),panBy:($,Z)=>z($,Z,160),zoomTo:_,getView:()=>({x:s-l/2/a,y:o-h/2/a,w:l/a,h:h/a}),setView:B,isPanning:()=>O.size>0&&(!!U||!!L?.moved),size:()=>({w:l,h})}}var pt=n=>String(n).replace(/[&<>"']/g,t=>({"&":"&","<":"<",">":">",'"':""","'":"'"})[t]);function Dc(n){let t=null,e={x:0,y:0},i=0;function r(){i=0;let s=14,{innerWidth:o,innerHeight:a}=window,l=n.offsetWidth,h=n.offsetHeight,u=e.x+s,d=e.y+s;u+l>o-6&&(u=e.x-s-l),d+h>a-6&&(d=e.y-s-h),n.style.transform=`translate(${Math.max(6,Math.round(u))}px, ${Math.max(6,Math.round(d))}px)`}return{show(s,o,a){let l=s!==t||n.hidden;s!==t&&(n.innerHTML=s,t=s),n.hidden=!1,e={x:o,y:a},l?(cancelAnimationFrame(i),r()):this.move(o,a)},move(s,o){e={x:s,y:o},!n.hidden&&!i&&(i=requestAnimationFrame(r))},hide(){n.hidden||(n.hidden=!0,t=null)}}}var y0=/Mac|iPhone|iPad/.test(navigator.platform)?"\u2318":"Ctrl";function Mc({host:n,tooltip:t,isPanning:e,onPinChange:i}){let r=null,s=null,o=new Set,a=null,l=new Set,h=new Set,u={target:null,key:null,html:null};function d(O,L){r=O,h=new Set;for(let Q of r.querySelectorAll("title"))Q.remove();let U=new Map;for(let Q of r.querySelectorAll("[data-line]")){let ot=Q.getAttribute("data-line");U.has(ot)||U.set(ot,[]),U.get(ot).push(Q)}let st=new Map,W=new Map(L.nodes.map(Q=>[Q.id,Q]));for(let Q of r.querySelectorAll("g.node"))st.set(Q.id,Q);let K=new Map,at=new Map,ut=Q=>(K.has(Q)||K.set(Q,{in:new Set,out:new Set}),K.get(Q));for(let Q of L.edges)for(let ot of Q.lines)ut(Q.from).out.add(ot.id),ut(Q.to).in.add(ot.id),at.has(ot.id)||at.set(ot.id,new Set),at.get(ot.id).add(Q.from).add(Q.to);let $=new Map(L.groups.map(Q=>[Q.id,Q])),Z=new Map(L.groups.map(Q=>[Q.id,{nodes:0,groups:0}]));for(let Q of L.nodes)for(let ot=Q.group;ot;ot=$.get(ot)?.parent)Z.get(ot).nodes++;for(let Q of L.groups)for(let ot=Q.parent;ot;ot=$.get(ot)?.parent)Z.get(ot).groups++;s={byLine:U,nodeEls:st,nodes:W,io:K,lineNodes:at,groups:$,members:Z,notes:new Map(L.notes.map(Q=>[Q.id,Q])),lines:new Map(L.lines.map(Q=>[Q.id,Q])),label:Q=>W.get(Q)?.label??L.items.get(Q)?.label??$.get(Q)?.label??Q},l=new Set([...l].filter(Q=>U.has(Q))),o=new Set,a=null,u={target:null,key:null,html:null},t.hide(),c()}function c(){if(!r)return;let O=new Set([...l,...o]),L=new Set;for(let U of O){for(let st of s.byLine.get(U)??[])L.add(st);for(let st of s.lineNodes.get(U)??[])s.nodeEls.has(st)&&L.add(s.nodeEls.get(st))}a&&s.nodeEls.has(a)&&L.add(s.nodeEls.get(a));for(let U of h)L.has(U)||U.classList.remove("on");for(let U of L)h.has(U)||U.classList.add("on");h=L,r.classList.toggle("focus",O.size>0)}let f=(O,L)=>O.size===L.size&&[...O].every(U=>L.has(U));function m(O,L=null){let U=new Set(O??[]);f(U,o)&&L===a||(o=U,a=L,c())}function P(O){l=O,c(),i?.([...l])}let v=O=>`<span class="dot" style="background:${pt(O.color)}"></span>`,b=O=>`<span class="tt-lines">${[...O].map(L=>s.lines.get(L)).filter(Boolean).sort((L,U)=>L.index-U.index).map(L=>`<span class="tt-line">${v(L)}${pt(L.label)}</span>`).join("")}</span>`,C=O=>O?`<div class="tt-url">${pt(O)}</div>`:"",E=O=>O?`${y0}-click to open the link`:"",w=(O,L)=>L.size?`<div class="tt-row"><span class="k">${O}</span>${b(L)}</div>`:"";function F(O,L){let U=s.lines.get(O);if(!U)return null;let st=L.closest("g.edge"),W=L.closest("g.node"),K=st?`${s.label(st.getAttribute("data-from"))} \u2192 ${s.label(st.getAttribute("data-to"))}`:W?`through ${s.label(W.id)}`:"",at=l.has(O)?"Click to unpin":"Click to pin \xB7 Shift-click to add";return`<div class="tt-head">${v(U)}<span class="tt-title">${pt(U.label)}</span>${U.label!==U.id?`<span class="tt-id">${pt(U.id)}</span>`:""}</div>`+(K?`<div class="tt-sub">${pt(K.replace(/\n/g," "))}</div>`:"")+`<div class="tt-hint">${at}</div>`}function V(O){let L=s.nodes.get(O.id);if(!L)return null;let{in:U,out:st}=s.io.get(L.id)??{in:new Set,out:new Set},W=L.group?s.groups.get(L.group)?.label:null,K=[L.shape,W?`in ${W}`:"",L.through?"lines through":""].filter(Boolean).map(Q=>pt(Q.replace(/\n/g," "))).join(" \xB7 "),at=_(L.id),ut=at.length&&l.size===at.length&&at.every(Q=>l.has(Q)),Z=[at.length?ut?"Click to unpin its lines":"Click to pin its lines \xB7 Shift-click to add":"",E(L.url)].filter(Boolean).join(" \xB7 ");return`<div class="tt-title">${pt(L.label)}</div><div class="tt-sub">${K}</div>`+C(L.url)+w("In",U)+w("Out",st)+(Z?`<div class="tt-hint">${Z}</div>`:"")}function q(O){let L=s.notes.get(O.id);return L?.url?C(L.url)+`<div class="tt-hint">${E(L.url)}</div>`:null}function _(O){let{in:L,out:U}=s.io.get(O)??{in:[],out:[]};return[...new Set([...L,...U])]}function T(O){let L=(O.getAttribute("data-lines")??"").split(" ").filter(Boolean),U=O.getAttribute("data-label");return`<div class="tt-title">${pt(s.label(O.getAttribute("data-from")))} \u2192 ${pt(s.label(O.getAttribute("data-to")))}</div>`+(U?`<div class="tt-sub">\u201C${pt(U.replace(/\n/g," "))}\u201D</div>`:"")+w("Lines",new Set(L))}function B(O){let L=s.groups.get(O.id);if(!L)return null;let U=s.members.get(O.id),st=[`${U.nodes} node${U.nodes===1?"":"s"}`,U.groups?`${U.groups} container${U.groups===1?"":"s"}`:""].filter(Boolean).join(", "),{in:W,out:K}=s.io.get(O.id)??{in:new Set,out:new Set},at=L.parent?s.groups.get(L.parent)?.label:null;return`<div class="tt-title">${pt(L.label)}</div><div class="tt-sub">container \xB7 ${pt(st)}${at?` \xB7 in ${pt(at)}`:""}</div>`+w("In",W)+w("Out",K)}function z(O){if(!s||!(O instanceof Element))return null;let L=O.closest("[data-line]");if(L){let ut=L.getAttribute("data-line"),$=O.closest("g.edge, g.node");return{key:`line ${ut} ${$?.id||$?.getAttribute("data-from")+">"+$?.getAttribute("data-to")}`,lines:[ut],html:()=>F(ut,L)}}let U=O.closest("g.edge");if(U)return{key:`edge ${U.getAttribute("data-from")}>${U.getAttribute("data-to")}`,lines:(U.getAttribute("data-lines")??"").split(" ").filter(Boolean),html:()=>T(U)};let st=O.closest("g.node");if(st)return{key:`node ${st.id}`,lines:_(st.id),node:st.id,html:()=>V(st)};let W=O.closest("g.note[data-url]");if(W)return{key:`note ${W.id}`,lines:[],html:()=>q(W)};let K=O.closest("g.group-tab"),at=K?{id:K.getAttribute("data-group")}:O.closest("g.group > text")?.parentNode;return at?{key:`group ${at.id}`,lines:[],html:()=>B(at)}:null}n.addEventListener("pointermove",O=>{if(O.pointerType!=="touch"){if(e()){tt();return}if(O.target!==u.target){u.target=O.target;let L=z(O.target),U=L?.key??null;U!==u.key&&(u.key=U,u.html=L?L.html():null,m(L?.lines,L?.node??null))}u.html?t.show(u.html,O.clientX,O.clientY):t.hide()}});function tt(){u.key===null&&!o.size||(u={target:null,key:null,html:null},t.hide(),m(null))}return n.addEventListener("pointerleave",tt),n.addEventListener("click",O=>{if(!s||!(O.target instanceof Element))return;let L=O.target.closest("a[href]");if(L&&(O.preventDefault(),O.ctrlKey||O.metaKey)){window.open(L.getAttribute("href"),"_blank","noopener");return}let U=O.target.closest("[data-line]");if(U){let W=U.getAttribute("data-line"),K=new Set(O.shiftKey?l:[]);l.has(W)&&(O.shiftKey||l.size===1)?K.delete(W):K.add(W),P(K),u.key?.startsWith("line ")&&(u.html=F(W,U),t.show(u.html,O.clientX,O.clientY));return}let st=O.target.closest("g.node");if(st){let W=_(st.id);if(!W.length)return;let K=W.every(ut=>l.has(ut)),at;if(O.shiftKey){at=new Set(l);for(let ut of W)K?at.delete(ut):at.add(ut)}else at=K&&l.size===W.length?new Set:new Set(W);P(at),u.key===`node ${st.id}`&&(u.html=V(st),t.show(u.html,O.clientX,O.clientY));return}!O.target.closest("g.edge, g.note")&&l.size&&P(new Set)}),{index:d,hoverLines:O=>{u.key||m(O)},pin:O=>P(new Set(O.filter(L=>s?.byLine.has(L)))),clearPins:()=>{l.size&&P(new Set)},pinned:()=>[...l],leave:tt,lineBox(O){let L=s?.byLine.get(O);if(!L?.length)return null;let[U,st,W,K]=[1/0,1/0,-1/0,-1/0];for(let at of L){let ut=at.getBBox();U=Math.min(U,ut.x),st=Math.min(st,ut.y),W=Math.max(W,ut.x+ut.width),K=Math.max(K,ut.y+ut.height)}return{x:U,y:st,w:W-U,h:K-st}},flash(O){O&&(O.classList.remove("flash"),O.getBoundingClientRect(),O.classList.add("flash"),O.addEventListener("animationend",()=>O.classList.remove("flash"),{once:!0}))}}}function Vc({el:n,markColor:t,onToggle:e,onSolo:i,onShowAll:r,onHideAll:s,onHover:o,collapsed:a=!1}){let l=[];n.classList.toggle("collapsed",a),n.innerHTML=`
|
|
974
|
+
<div class="lg-head">
|
|
975
|
+
<button class="lg-title" aria-expanded="${!a}" title="Show or hide the legend">
|
|
976
|
+
<svg class="icon small"><use href="#i-chevron"/></svg>Lines <span class="count"></span>
|
|
977
|
+
</button>
|
|
978
|
+
<button class="btn" data-act="show" title="Show every line">Show all</button>
|
|
979
|
+
<button class="btn" data-act="hide" title="Hide every line">Hide all</button>
|
|
980
|
+
</div>
|
|
981
|
+
<ul role="list"></ul>`;let h=n.querySelector("ul"),u=n.querySelector(".lg-title");u.addEventListener("click",()=>{let f=n.classList.toggle("collapsed");u.setAttribute("aria-expanded",String(!f))}),n.querySelector('[data-act="show"]').addEventListener("click",()=>r()),n.querySelector('[data-act="hide"]').addEventListener("click",()=>s()),h.addEventListener("click",f=>{let m=f.target.closest("li[data-line]");if(!m)return;let P=m.dataset.line;f.altKey||f.shiftKey?i(P):e(P)});let d=null;h.addEventListener("pointerover",f=>{let m=f.target.closest("li[data-line]"),P=m&&!m.classList.contains("hidden")?m.dataset.line:null;P!==d&&(d=P,o(P?[P]:null))}),h.addEventListener("pointerleave",()=>{d=null,o(null)});let c=f=>`<svg class="sw" viewBox="0 0 30 10" aria-hidden="true"><rect x="0" y="0.5" width="30" height="9" rx="1.5" fill="${pt(f.color)}"/><polygon points="19,5 13,2.3 13,7.7" fill="${pt(t(f.color))}"/></svg>`;return{update(f,m,P,v=[]){l=f,n.querySelector(".count").textContent=P.size?`${l.length-P.size}/${l.length}`:String(l.length),h.innerHTML=l.map(b=>{let C=m.get(b.id)??0,E=[P.has(b.id)?"hidden":"",v.includes(b.id)?"on":""].filter(Boolean).join(" ");return`<li data-line="${pt(b.id)}" class="${E}" title="${P.has(b.id)?"Show":"Hide"} ${pt(b.label)} \xB7 Alt- or Shift-click: only this line">${c(b)}<span class="lb">${pt(b.label)}</span><span class="ct" title="bundles">${C}</span></li>`}).join(""),n.hidden=!1},setPinned(f){for(let m of h.children)m.classList.toggle("on",f.includes(m.dataset.line))},hide(){n.hidden=!0}}}var S0=12,b0={node:"node",container:"container",line:"line",note:"note"};function kc({input:n,list:t,onSelect:e}){let i=[],r=[],s=0,o=c=>String(c).replace(/\s+/g," ").trim().toLowerCase();function a(c){if(c=o(c),!c)return[];let f=[];for(let m of i){let P=m.text.indexOf(c),v=m.idText.indexOf(c);if(P<0&&v<0)continue;let b=P>=0?P:v,C=b===0||/[\s_\-./]/.test((P>=0?m.text:m.idText)[b-1]);f.push({e:m,score:(b===0?0:C?1:2)+(P<0?.5:0)+m.rank*.1})}return f.sort((m,P)=>m.score-P.score||m.e.label.length-P.e.label.length).slice(0,S0).map(m=>m.e)}let l=(c,f)=>{let m=c.toLowerCase().indexOf(f);return m<0?pt(c):`${pt(c.slice(0,m))}<mark>${pt(c.slice(m,m+f.length))}</mark>${pt(c.slice(m+f.length))}`};function h(){let c=o(n.value);if(r=a(c),s=0,!c){t.hidden=!0;return}t.innerHTML=r.length?r.map((f,m)=>`<li role="option" data-i="${m}" aria-selected="${m===s}">`+(f.color?`<span class="swatch" style="background:${pt(f.color)}"></span>`:"")+`<span class="lbl">${l(f.label,c)}</span><span class="kind">${b0[f.kind]}</span></li>`).join(""):'<li class="none">No match</li>',t.hidden=!1}function u(c){if(r.length){s=(c+r.length)%r.length;for(let f of t.children)f.setAttribute("aria-selected",String(Number(f.dataset.i)===s));t.children[s]?.scrollIntoView({block:"nearest"})}}function d(c){let f=r[c];f&&(t.hidden=!0,n.blur(),e(f))}return n.addEventListener("input",h),n.addEventListener("focus",()=>{n.value&&h()}),n.addEventListener("blur",()=>setTimeout(()=>{t.hidden=!0},120)),n.addEventListener("keydown",c=>{c.key==="ArrowDown"?(c.preventDefault(),u(s+1)):c.key==="ArrowUp"?(c.preventDefault(),u(s-1)):c.key==="Enter"?(c.preventDefault(),d(s)):c.key==="Escape"&&(c.preventDefault(),n.value?(n.value="",h()):n.blur())}),t.addEventListener("mousedown",c=>{let f=c.target.closest("li[data-i]");f&&(c.preventDefault(),d(Number(f.dataset.i)))}),{index(c){i=c.map(f=>({...f,label:f.label.replace(/\s*\n\s*/g," "),text:o(f.label),idText:o(f.id),rank:{node:0,container:1,line:2,note:3}[f.kind]})),document.activeElement===n&&h()},focus(){n.focus(),n.select()}}}function $c(n,t,e="image/svg+xml"){let i=URL.createObjectURL(new Blob([t],{type:e})),r=Object.assign(document.createElement("a"),{href:i,download:n});document.body.append(r),r.click(),r.remove(),setTimeout(()=>URL.revokeObjectURL(i),1e3)}var Hc=n=>n.map(({id:t,x:e,y:i})=>`${/^[A-Za-z_][\w]*$/.test(t)?t:JSON.stringify(t)} [pos="${e},${i}"]`).join(`
|
|
982
|
+
`);async function Wc(n,t){try{return await navigator.clipboard.writeText(n),!0}catch{return C0(t,n),!1}}function C0(n,t){let e=n.querySelector("textarea");e.value=t,n.showModal(),e.focus(),e.select()}function zc(n){let t=n.querySelector("textarea");return new Promise(e=>{n.addEventListener("close",()=>e(n.returnValue==="ok"&&t.value.trim()?t.value:null),{once:!0}),n.returnValue="",n.showModal(),t.focus(),t.select()})}function qc(n){let t=0;return e=>{n.textContent=e,n.hidden=!1,clearTimeout(t),t=setTimeout(()=>{n.hidden=!0},1800)}}var Pt=n=>document.getElementById(n),j={toolbar:document.querySelector(".toolbar"),fileName:Pt("file-name"),recent:Pt("recent"),open:Pt("open"),paste:Pt("paste"),reload:Pt("reload"),watch:Pt("watch"),through:Pt("through"),theme:Pt("theme"),themeBtn:Pt("theme-btn"),fancy:Pt("fancy"),search:Pt("search"),results:Pt("results"),export:Pt("export"),positions:Pt("positions"),helpBtn:Pt("help-btn"),menuBtn:Pt("menu-btn"),more:Pt("tb-more"),banner:Pt("banner"),stage:Pt("stage"),map:Pt("map"),empty:Pt("empty"),busy:Pt("busy"),legend:Pt("legend"),zoomIn:Pt("zoom-in"),zoomOut:Pt("zoom-out"),zoomFit:Pt("zoom-fit"),tooltip:Pt("tooltip"),toast:Pt("toast"),drop:Pt("drop"),fileInput:Pt("file-input"),pasteDialog:Pt("paste-dialog"),positionsDialog:Pt("positions-dialog"),help:Pt("help"),flows:Pt("linemap-flows")};new ResizeObserver(()=>document.documentElement.style.setProperty("--tb-h",`${j.toolbar.offsetHeight}px`)).observe(j.toolbar);var bl=qc(j.toast),Oo=[];try{Oo=JSON.parse(j.flows.textContent).filter(n=>typeof n?.text=="string")}catch{}j.flows.remove();var Lo=Sl(),Jc="linemap.theme";if(!Lo.settings.theme)try{let n=localStorage.getItem(Jc);hr.includes(n)&&(Lo.settings.theme=n)}catch{}var Vt=Lc(Lo.settings),Kn=Lo.view,Zn=null,Ut=null,Uc=!1,v0=Bc(),El=()=>v0(Vt.get(),Ut?Qt.getView():null),x0=Dc(j.tooltip),Qt=Gc({stage:j.stage,avoid:()=>{if(j.legend.hidden)return null;let n=j.legend.getBoundingClientRect(),t=j.stage.getBoundingClientRect();return{x0:n.left-t.left,y0:n.top-t.top,x1:n.right-t.left,y1:n.bottom-t.top}},onChange:()=>{vi?.leave(),El()}}),vi=Mc({host:j.map,tooltip:x0,isPanning:()=>Qt.isPanning(),onPinChange:n=>Al.setPinned(n)}),Al=Vc({el:j.legend,markColor:an,collapsed:innerWidth<640,onToggle:n=>{let t=new Set(Vt.get().hidden);t.has(n)?t.delete(n):t.add(n),Vt.set({hidden:t})},onSolo:n=>{let t=Ut.base.lines.map(r=>r.id).filter(r=>r!==n),{hidden:e}=Vt.get(),i=e.size===t.length&&t.every(r=>e.has(r));Vt.set({hidden:i?new Set:new Set(t)})},onShowAll:()=>Vt.set({hidden:new Set}),onHideAll:()=>Vt.set({hidden:new Set(Ut.base.lines.map(n=>n.id))}),onHover:n=>vi.hoverLines(n)}),Cl=kc({input:j.search,list:j.results,onSelect:O0}),wl=Rc({onResult:E0}),vl=0,xl=!1;function Zc(n={}){let t=wt.current();t&&(xl&&(n={...n,fresh:!0},xl=!1),clearTimeout(vl),vl=setTimeout(()=>{j.busy.hidden=!1},150),wl.request(t.text,Vt.get(),n))}function E0(n,t){if(clearTimeout(vl),j.busy.hidden=!0,!n.ok){rg("Could not draw the map",n.error+(Ut?`
|
|
983
|
+
|
|
984
|
+
Showing the last map that worked.`:"")),Ut||ts(!0);return}Ol(),ts(!1);let e=!!Ut&&!t.fresh;j.map.innerHTML=n.svg;let i=j.map.firstElementChild;i.removeAttribute("width"),i.removeAttribute("height");let[r,s,o,a]=i.getAttribute("viewBox").split(/\s+/).map(Number);Ut={model:n.model,base:n.base,svg:i,theme:n.theme},_c(n.theme);let l=new Map;for(let h of n.base.edges)for(let u of h.lines)l.set(u.id,(l.get(u.id)??0)+1);Al.update(n.base.lines,l,Vt.get().hidden,vi.pinned()),Qt.setContent(i,{x:r,y:s,w:o,h:a},{keep:e}),Kn&&(Qt.setView(Kn),Kn=null),vi.index(i,n.model),Zn&&(vi.pin([Zn]),ng(Zn),Zn=null),Cl.index([...n.model.nodes.map(h=>({kind:"node",id:h.id,label:h.label})),...n.model.groups.map(h=>({kind:"container",id:h.id,label:h.label})),...n.base.lines.map(h=>({kind:"line",id:h.id,label:h.label,color:h.color}))]),un(),El(),window.__linemap={ms:Math.round(n.ms),lines:n.model.lines.length,edges:n.model.edges.length}}Vt.onChange(()=>{Zc(),un(),El()});j.through.addEventListener("click",n=>{let t=n.target.closest("button[data-mode]");t&&t.dataset.mode!==Vt.get().mode&&Vt.set({mode:t.dataset.mode})});var Kc=n=>{let t=jt[n],e=t.palette??Ps;return`<span class="tsw" style="background:${t.bg};border-color:${t.node.stroke==="none"?t.muted:t.node.stroke}"><i style="background:${e[0]}"></i><i style="background:${e[1]}"></i></span>`},sr="-fancy",hn=n=>n.endsWith(sr)?n.slice(0,-sr.length):n,_n=n=>n!==hn(n),To=hr.filter(n=>!_n(n)),A0='<svg class="icon sparkles"><use href="#i-sparkles"/></svg>';j.theme.innerHTML=To.map(n=>{let t=jt[n+sr]?`<button class="item fancy" role="menuitemradio" data-theme="${n+sr}" title="${pt(jt[n].label)}, fancy: shadows, glows and moving arrows (uses more CPU)" aria-label="${pt(jt[n].label)} fancy">${A0}</button>`:"";return`<div class="row" data-base="${n}"><button class="item" role="menuitemradio" data-theme="${n}">${Kc(n)}<span class="nm">${pt(jt[n].label)}</span></button>${t}</div>`}).join("");var Il=()=>Ut?.theme??Vt.get().theme??ri;function Tl(n){try{localStorage.setItem(Jc,n)}catch{}n!==Vt.get().theme&&Vt.set({theme:n})}function dn(n){j.theme.hidden=!n,j.themeBtn.setAttribute("aria-expanded",String(n))}j.themeBtn.addEventListener("click",n=>{n.stopPropagation(),j.recent.hidden=!0,dn(j.theme.hidden)});j.theme.addEventListener("click",n=>{let t=n.target.closest("button[data-theme]");t&&(n.stopPropagation(),dn(!1),Tl(t.dataset.theme))});document.addEventListener("click",n=>{!j.theme.hidden&&!n.target.closest(".theme-pick")&&dn(!1)});j.fancy.addEventListener("click",n=>{n.stopPropagation();let t=Il(),e=hn(t);Tl(_n(t)?e:e+sr)});var w0=n=>{let t=parseInt(String(n).replace("#",""),16);return Number.isNaN(t)?1:(.2126*(t>>16&255)+.7152*(t>>8&255)+.0722*(t&255))/255};function _c(n){let t=jt[n]??jt[ri];document.body.dataset.mapTheme=n,document.body.classList.toggle("ui-dark",w0(t.bg)<.4),document.documentElement.style.setProperty("--map-bg",t.bg)}_c(Vt.get().theme??ri);function un(){let{mode:n}=Vt.get();for(let r of j.through.querySelectorAll("button"))r.setAttribute("aria-checked",String(r.dataset.mode===n));let t=Vt.get().theme??Il();for(let r of j.theme.querySelectorAll("button"))r.setAttribute("aria-checked",String(r.dataset.theme===t));for(let r of j.theme.querySelectorAll(".row"))r.classList.toggle("on",r.dataset.base===hn(t));let e=jt[hn(t)]?hn(t):t;j.themeBtn.querySelector(".cur").innerHTML=`${Kc(e)}<span class="tl">${pt(jt[e]?.label??t)}</span>`,j.fancy.hidden=!jt[e+sr],j.fancy.setAttribute("aria-pressed",String(_n(t))),j.fancy.title=_n(t)?"Fancy: on (shadows, glows, moving arrows; uses more CPU). Click for plain":"Fancy: off. Click for shadows, glows and moving arrows (uses more CPU)";let i=wt.current();j.fileName.querySelector(".name").textContent=i?.name??"No file",j.fileName.title=i?.src?`${i.src} \xB7 recent files`:"Recent files",document.title=i?`${i.name} \xB7 linemap`:"linemap studio",j.watch.hidden=!wt.canWatch(),j.watch.setAttribute("aria-pressed",String(wt.watching()));for(let r of[j.export,j.positions,j.reload,j.zoomIn,j.zoomOut,j.zoomFit])r.disabled=!Ut;document.body.classList.toggle("nomap",!Ut)}var wt=Nc({onText({src:n,fresh:t}){if(t&&Uc){Kn=null,vi.clearPins(),jc(n),xl=!0,Vt.set({hidden:new Set,mode:"file"});return}t&&jc(n),Uc=!0,Zc({fresh:t}),un()},onError:(n,t)=>{rg(n,t),Ut||ts(!0)},onWatch:()=>un(),embedded:Oo});function jc(n){if(!Lr())return;let t=new URLSearchParams(location.search);n?t.set("src",n):t.delete("src");let e=t.toString().replace(/%2F/g,"/");try{history.replaceState(null,"",location.pathname+(e?`?${e}`:"")+location.hash)}catch{}}wt.bindDrop(j.drop);wt.bindPaste();j.open.addEventListener("click",()=>j.fileInput.click());j.fileInput.addEventListener("change",()=>{let n=j.fileInput.files[0];n&&wt.loadFile(n),j.fileInput.value=""});async function tg(){let n=await zc(j.pasteDialog);n&&wt.loadText(n)}j.paste.addEventListener("click",tg);j.reload.addEventListener("click",()=>wt.reload());j.watch.addEventListener("click",()=>{let n=!wt.watching();wt.setWatch(n),bl(n?"Watching the file: the map follows every save":"Stopped watching")});var I0=n=>{let t=(Date.now()-n)/1e3;return t<60?"just now":t<3600?`${Math.round(t/60)} min ago`:t<86400?`${Math.round(t/3600)} h ago`:`${Math.round(t/86400)} d ago`};function eg(n){n.src&&Lr()?wt.loadUrl(n.src):wt.loadText(n.text,n.name,n.src)}function T0(){let n=wt.recent(),t=wt.embedded(),e=wt.current();j.recent.innerHTML=(t.length>1?'<div class="head">In this file</div>'+t.map((i,r)=>`<button class="item" role="menuitem" data-flow="${r}"${e&&!e.src&&e.name===i.name&&e.text===i.text?' aria-current="true"':""}><span class="nm">${pt(i.name)}</span></button>`).join("")+"<hr>":"")+'<div class="head">Recent</div>'+(n.length?n.map((i,r)=>`<button class="item" role="menuitem" data-i="${r}"><span class="nm">${pt(i.name)}</span><span class="when">${I0(i.time)}</span></button>`).join("")+'<hr><button class="item" data-act="clear"><span class="nm">Clear the list</span></button>':'<div class="empty-note">Files you open show up here.</div>')}j.fileName.addEventListener("click",n=>{if(n.stopPropagation(),!j.recent.hidden){j.recent.hidden=!0;return}dn(!1),T0(),j.recent.hidden=!1});j.recent.addEventListener("click",n=>{let t=n.target.closest("button");if(!t)return;if(j.recent.hidden=!0,t.dataset.act==="clear"){wt.clearRecent(),ig();return}if(t.dataset.flow!==void 0){wt.loadEmbedded(Number(t.dataset.flow));return}let e=wt.recent()[Number(t.dataset.i)];e&&eg(e)});document.addEventListener("click",n=>{!j.recent.hidden&&!n.target.closest(".file")&&(j.recent.hidden=!0)});function es(n){j.toolbar.classList.toggle("menu-open",n),n||dn(!1),j.menuBtn.setAttribute("aria-expanded",String(n))}j.menuBtn.addEventListener("click",n=>{n.stopPropagation(),j.recent.hidden=!0,es(!j.toolbar.classList.contains("menu-open"))});j.more.addEventListener("click",n=>{n.target.closest(".btn")&&es(!1)});document.addEventListener("pointerdown",n=>{n.target.closest("#tb-more, #menu-btn")||es(!1)},!0);matchMedia("(max-width: 860px)").addEventListener("change",()=>es(!1));var Qc=["examples/webshop.dot","examples/platform.dot","examples/postal.dot","docs/pipeline.dot"],Xc=!1;async function ig(){let n=wt.embedded(),t=j.empty.querySelector(".flows");t.hidden=n.length<2,j.empty.querySelector("p").textContent=n.length>1?"Pick a flow from this file, or load your own DOT file.":"Load a DOT file to explore it as a transit map.",t.querySelector(".links").innerHTML=n.map((r,s)=>`<button data-flow="${s}">${pt(r.name)}</button>`).join("");let e=wt.recent(),i=j.empty.querySelector(".recent-list");if(i.hidden=!e.length,i.querySelector(".links").innerHTML=e.slice(0,6).map((r,s)=>`<button data-i="${s}">${pt(r.name)}</button>`).join(""),!Xc&&Lr()){Xc=!0;let r=await fetch(Qc[0],{method:"HEAD",cache:"no-store"}).then(o=>o.ok,()=>!1),s=j.empty.querySelector(".examples");s.querySelector(".links").innerHTML=Qc.map(o=>`<a href="?src=${o}">${o.split("/").pop().replace(".dot","")}</a>`).join(""),s.hidden=!r}}function ts(n){j.empty.hidden=!n,n&&(ig(),Al.hide()),un()}j.empty.addEventListener("click",n=>{let t=n.target.closest("button");if(t){if(t.dataset.act==="open")j.fileInput.click();else if(t.dataset.act==="paste")tg();else if(t.dataset.flow!==void 0)wt.loadEmbedded(Number(t.dataset.flow));else if(t.dataset.i!==void 0){let e=wt.recent()[Number(t.dataset.i)];e&&eg(e)}}});function rg(n,t){j.banner.querySelector(".title").textContent=n,j.banner.querySelector(".msg").textContent=t,j.banner.hidden=!1}var Ol=()=>{j.banner.hidden=!0};j.banner.querySelector(".close").addEventListener("click",Ol);function ng(n){let t=vi.lineBox(n);t&&Qt.zoomTo({x:t.x-40,y:t.y-40,w:t.w+80,h:t.h+80})}function O0(n){if(!Ut)return;if(n.kind==="line"){if(Vt.get().hidden.has(n.id)){Zn=n.id;let i=new Set(Vt.get().hidden);i.delete(n.id),Vt.set({hidden:i});return}vi.pin([n.id]),ng(n.id);return}let t=[...j.map.querySelectorAll(n.kind==="node"?"g.node":"g.group")].find(i=>i.id===n.id);if(!t)return;let e;if(n.kind==="node"){let i=Ut.model.nodes.find(r=>r.id===n.id);e={x:i.x-i.w/2,y:i.y-i.h/2,w:i.w,h:i.h+(i.shape==="person"?30:0)},Qt.zoomTo({x:e.x-e.w,y:e.y-e.h,w:e.w*3,h:e.h*3},{maxScale:1.5})}else{let i=t.querySelector("rect").getBBox();Qt.zoomTo({x:i.x-20,y:i.y-20,w:i.width+40,h:i.height+40})}setTimeout(()=>vi.flash(t),200)}var L0=()=>(wt.current()?.name??"linemap").replace(/\.(dot|gv|txt)$/i,"");j.export.addEventListener("click",()=>{Ut&&$c(`${L0()}.svg`,wl.exportSvg(Ut.model,Ut.theme))});j.positions.addEventListener("click",async()=>{if(!Ut)return;let n=wl.positions(Ut.model);if(!n.length){bl("Every node and note is pinned already");return}await Wc(Hc(n),j.positionsDialog)&&bl(`Copied ${n.length} position${n.length===1?"":"s"}`)});var sg=()=>{j.help.open||j.help.showModal()};j.helpBtn.addEventListener("click",sg);j.zoomIn.addEventListener("click",()=>Qt.zoomIn());j.zoomOut.addEventListener("click",()=>Qt.zoomOut());j.zoomFit.addEventListener("click",()=>Qt.fit());window.addEventListener("keydown",n=>{if(document.querySelector("dialog[open]"))return;let t=n.target.closest?.("input, textarea, [contenteditable]");if((n.ctrlKey||n.metaKey)&&n.key.toLowerCase()==="f"&&Ut){n.preventDefault(),Cl.focus();return}if(t||n.ctrlKey||n.metaKey||n.altKey)return;let e=n.shiftKey?400:120,r={"/":()=>Cl.focus(),"?":sg,"+":()=>Qt.zoomIn(),"=":()=>Qt.zoomIn(),"-":()=>Qt.zoomOut(),_:()=>Qt.zoomOut(),0:()=>Qt.fit(),ArrowLeft:()=>Qt.panBy(-e,0),ArrowRight:()=>Qt.panBy(e,0),ArrowUp:()=>Qt.panBy(0,-e),ArrowDown:()=>Qt.panBy(0,e),r:()=>wt.reload(),t:()=>{let s=Il(),o=To[(To.indexOf(hn(s))+1)%To.length];Tl(_n(s)&&jt[o+sr]?o+sr:o)},Escape:()=>{j.recent.hidden=!0,dn(!1),es(!1),vi.clearPins(),Ol()}}[n.key];!r||!Ut&&!["/","?","Escape"].includes(n.key)||(n.preventDefault(),r())});window.addEventListener("hashchange",()=>{let{settings:n,view:t}=Sl();t&&Ut?Qt.setView(t):Kn=t,Vt.set(n)});un();var Yc=new URLSearchParams(location.search).get("src");if(Oo.length===1)wt.loadEmbedded(0);else if(Oo.length)ts(!0);else if(Yc)wt.loadUrl(Yc);else{let n=wt.last();n?.text?wt.loadText(n.text,n.name,n.src):ts(!0)}})();
|
|
985
|
+
/*!
|
|
986
|
+
vendor/msagl.mjs: parts of @msagl/core (https://github.com/microsoft/msagljs), bundled and
|
|
987
|
+
minified by scripts/build-msagl.mjs, with a patch (patches/@msagl__core@1.1.24.patch). Do not edit.
|
|
988
|
+
It contains these packages: @msagl/core 1.1.24 (MIT), linked-list-typescript 1.0.15 (MIT), queue-typescript 1.0.1 (MIT), reliable-random 0.0.1 (Apache-2.0), stack-typescript 1.0.4 (MIT), typescript-string-operations 1.6.1 (MIT).
|
|
989
|
+
Their licenses follow.
|
|
990
|
+
|
|
991
|
+
==============================================================================
|
|
992
|
+
@msagl/core 1.1.24 (MIT)
|
|
993
|
+
==============================================================================
|
|
994
|
+
|
|
995
|
+
MIT License
|
|
996
|
+
|
|
997
|
+
Copyright (c) Microsoft Corporation.
|
|
998
|
+
|
|
999
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
1000
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
1001
|
+
in the Software without restriction, including without limitation the rights
|
|
1002
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
1003
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
1004
|
+
furnished to do so, subject to the following conditions:
|
|
1005
|
+
|
|
1006
|
+
The above copyright notice and this permission notice shall be included in all
|
|
1007
|
+
copies or substantial portions of the Software.
|
|
1008
|
+
|
|
1009
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
1010
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
1011
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
1012
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
1013
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
1014
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
1015
|
+
SOFTWARE
|
|
1016
|
+
|
|
1017
|
+
==============================================================================
|
|
1018
|
+
linked-list-typescript 1.0.15 (MIT)
|
|
1019
|
+
==============================================================================
|
|
1020
|
+
|
|
1021
|
+
MIT License
|
|
1022
|
+
|
|
1023
|
+
Copyright (c) 2018 Michael Sutherland
|
|
1024
|
+
|
|
1025
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
1026
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
1027
|
+
in the Software without restriction, including without limitation the rights
|
|
1028
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
1029
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
1030
|
+
furnished to do so, subject to the following conditions:
|
|
1031
|
+
|
|
1032
|
+
The above copyright notice and this permission notice shall be included in all
|
|
1033
|
+
copies or substantial portions of the Software.
|
|
1034
|
+
|
|
1035
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
1036
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
1037
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
1038
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
1039
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
1040
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
1041
|
+
SOFTWARE.
|
|
1042
|
+
|
|
1043
|
+
==============================================================================
|
|
1044
|
+
queue-typescript 1.0.1 (MIT)
|
|
1045
|
+
==============================================================================
|
|
1046
|
+
|
|
1047
|
+
MIT License
|
|
1048
|
+
|
|
1049
|
+
Copyright (c) 2018 Mike Sutherland
|
|
1050
|
+
|
|
1051
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
1052
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
1053
|
+
in the Software without restriction, including without limitation the rights
|
|
1054
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
1055
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
1056
|
+
furnished to do so, subject to the following conditions:
|
|
1057
|
+
|
|
1058
|
+
The above copyright notice and this permission notice shall be included in all
|
|
1059
|
+
copies or substantial portions of the Software.
|
|
1060
|
+
|
|
1061
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
1062
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
1063
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
1064
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
1065
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
1066
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
1067
|
+
SOFTWARE.
|
|
1068
|
+
|
|
1069
|
+
==============================================================================
|
|
1070
|
+
reliable-random 0.0.1 (Apache-2.0)
|
|
1071
|
+
==============================================================================
|
|
1072
|
+
|
|
1073
|
+
Apache License
|
|
1074
|
+
Version 2.0, January 2004
|
|
1075
|
+
http://www.apache.org/licenses/
|
|
1076
|
+
|
|
1077
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
1078
|
+
|
|
1079
|
+
1. Definitions.
|
|
1080
|
+
|
|
1081
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
1082
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
1083
|
+
|
|
1084
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
1085
|
+
the copyright owner that is granting the License.
|
|
1086
|
+
|
|
1087
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
1088
|
+
other entities that control, are controlled by, or are under common
|
|
1089
|
+
control with that entity. For the purposes of this definition,
|
|
1090
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
1091
|
+
direction or management of such entity, whether by contract or
|
|
1092
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
1093
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
1094
|
+
|
|
1095
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
1096
|
+
exercising permissions granted by this License.
|
|
1097
|
+
|
|
1098
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
1099
|
+
including but not limited to software source code, documentation
|
|
1100
|
+
source, and configuration files.
|
|
1101
|
+
|
|
1102
|
+
"Object" form shall mean any form resulting from mechanical
|
|
1103
|
+
transformation or translation of a Source form, including but
|
|
1104
|
+
not limited to compiled object code, generated documentation,
|
|
1105
|
+
and conversions to other media types.
|
|
1106
|
+
|
|
1107
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
1108
|
+
Object form, made available under the License, as indicated by a
|
|
1109
|
+
copyright notice that is included in or attached to the work
|
|
1110
|
+
(an example is provided in the Appendix below).
|
|
1111
|
+
|
|
1112
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
1113
|
+
form, that is based on (or derived from) the Work and for which the
|
|
1114
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
1115
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
1116
|
+
of this License, Derivative Works shall not include works that remain
|
|
1117
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
1118
|
+
the Work and Derivative Works thereof.
|
|
1119
|
+
|
|
1120
|
+
"Contribution" shall mean any work of authorship, including
|
|
1121
|
+
the original version of the Work and any modifications or additions
|
|
1122
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
1123
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
1124
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
1125
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
1126
|
+
means any form of electronic, verbal, or written communication sent
|
|
1127
|
+
to the Licensor or its representatives, including but not limited to
|
|
1128
|
+
communication on electronic mailing lists, source code control systems,
|
|
1129
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
1130
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
1131
|
+
excluding communication that is conspicuously marked or otherwise
|
|
1132
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
1133
|
+
|
|
1134
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
1135
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
1136
|
+
subsequently incorporated within the Work.
|
|
1137
|
+
|
|
1138
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
1139
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
1140
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
1141
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
1142
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
1143
|
+
Work and such Derivative Works in Source or Object form.
|
|
1144
|
+
|
|
1145
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
1146
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
1147
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
1148
|
+
(except as stated in this section) patent license to make, have made,
|
|
1149
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
1150
|
+
where such license applies only to those patent claims licensable
|
|
1151
|
+
by such Contributor that are necessarily infringed by their
|
|
1152
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
1153
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
1154
|
+
institute patent litigation against any entity (including a
|
|
1155
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
1156
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
1157
|
+
or contributory patent infringement, then any patent licenses
|
|
1158
|
+
granted to You under this License for that Work shall terminate
|
|
1159
|
+
as of the date such litigation is filed.
|
|
1160
|
+
|
|
1161
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
1162
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
1163
|
+
modifications, and in Source or Object form, provided that You
|
|
1164
|
+
meet the following conditions:
|
|
1165
|
+
|
|
1166
|
+
(a) You must give any other recipients of the Work or
|
|
1167
|
+
Derivative Works a copy of this License; and
|
|
1168
|
+
|
|
1169
|
+
(b) You must cause any modified files to carry prominent notices
|
|
1170
|
+
stating that You changed the files; and
|
|
1171
|
+
|
|
1172
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
1173
|
+
that You distribute, all copyright, patent, trademark, and
|
|
1174
|
+
attribution notices from the Source form of the Work,
|
|
1175
|
+
excluding those notices that do not pertain to any part of
|
|
1176
|
+
the Derivative Works; and
|
|
1177
|
+
|
|
1178
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
1179
|
+
distribution, then any Derivative Works that You distribute must
|
|
1180
|
+
include a readable copy of the attribution notices contained
|
|
1181
|
+
within such NOTICE file, excluding those notices that do not
|
|
1182
|
+
pertain to any part of the Derivative Works, in at least one
|
|
1183
|
+
of the following places: within a NOTICE text file distributed
|
|
1184
|
+
as part of the Derivative Works; within the Source form or
|
|
1185
|
+
documentation, if provided along with the Derivative Works; or,
|
|
1186
|
+
within a display generated by the Derivative Works, if and
|
|
1187
|
+
wherever such third-party notices normally appear. The contents
|
|
1188
|
+
of the NOTICE file are for informational purposes only and
|
|
1189
|
+
do not modify the License. You may add Your own attribution
|
|
1190
|
+
notices within Derivative Works that You distribute, alongside
|
|
1191
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
1192
|
+
that such additional attribution notices cannot be construed
|
|
1193
|
+
as modifying the License.
|
|
1194
|
+
|
|
1195
|
+
You may add Your own copyright statement to Your modifications and
|
|
1196
|
+
may provide additional or different license terms and conditions
|
|
1197
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
1198
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
1199
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
1200
|
+
the conditions stated in this License.
|
|
1201
|
+
|
|
1202
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
1203
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
1204
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
1205
|
+
this License, without any additional terms or conditions.
|
|
1206
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
1207
|
+
the terms of any separate license agreement you may have executed
|
|
1208
|
+
with Licensor regarding such Contributions.
|
|
1209
|
+
|
|
1210
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
1211
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
1212
|
+
except as required for reasonable and customary use in describing the
|
|
1213
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
1214
|
+
|
|
1215
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
1216
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
1217
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
1218
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
1219
|
+
implied, including, without limitation, any warranties or conditions
|
|
1220
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
1221
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
1222
|
+
appropriateness of using or redistributing the Work and assume any
|
|
1223
|
+
risks associated with Your exercise of permissions under this License.
|
|
1224
|
+
|
|
1225
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
1226
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
1227
|
+
unless required by applicable law (such as deliberate and grossly
|
|
1228
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
1229
|
+
liable to You for damages, including any direct, indirect, special,
|
|
1230
|
+
incidental, or consequential damages of any character arising as a
|
|
1231
|
+
result of this License or out of the use or inability to use the
|
|
1232
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
1233
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
1234
|
+
other commercial damages or losses), even if such Contributor
|
|
1235
|
+
has been advised of the possibility of such damages.
|
|
1236
|
+
|
|
1237
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
1238
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
1239
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
1240
|
+
or other liability obligations and/or rights consistent with this
|
|
1241
|
+
License. However, in accepting such obligations, You may act only
|
|
1242
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
1243
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
1244
|
+
defend, and hold each Contributor harmless for any liability
|
|
1245
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
1246
|
+
of your accepting any such warranty or additional liability.
|
|
1247
|
+
|
|
1248
|
+
END OF TERMS AND CONDITIONS
|
|
1249
|
+
|
|
1250
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
1251
|
+
|
|
1252
|
+
To apply the Apache License to your work, attach the following
|
|
1253
|
+
boilerplate notice, with the fields enclosed by brackets "{}"
|
|
1254
|
+
replaced with your own identifying information. (Don't include
|
|
1255
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
1256
|
+
comment syntax for the file format. We also recommend that a
|
|
1257
|
+
file or class name and description of purpose be included on the
|
|
1258
|
+
same "printed page" as the copyright notice for easier
|
|
1259
|
+
identification within third-party archives.
|
|
1260
|
+
|
|
1261
|
+
Copyright {yyyy} {name of copyright owner}
|
|
1262
|
+
|
|
1263
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
1264
|
+
you may not use this file except in compliance with the License.
|
|
1265
|
+
You may obtain a copy of the License at
|
|
1266
|
+
|
|
1267
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
1268
|
+
|
|
1269
|
+
Unless required by applicable law or agreed to in writing, software
|
|
1270
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
1271
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
1272
|
+
See the License for the specific language governing permissions and
|
|
1273
|
+
limitations under the License.
|
|
1274
|
+
|
|
1275
|
+
==============================================================================
|
|
1276
|
+
stack-typescript 1.0.4 (MIT)
|
|
1277
|
+
==============================================================================
|
|
1278
|
+
|
|
1279
|
+
MIT License
|
|
1280
|
+
|
|
1281
|
+
Copyright (c) 2018 Mike Sutherland
|
|
1282
|
+
|
|
1283
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
1284
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
1285
|
+
in the Software without restriction, including without limitation the rights
|
|
1286
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
1287
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
1288
|
+
furnished to do so, subject to the following conditions:
|
|
1289
|
+
|
|
1290
|
+
The above copyright notice and this permission notice shall be included in all
|
|
1291
|
+
copies or substantial portions of the Software.
|
|
1292
|
+
|
|
1293
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
1294
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
1295
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
1296
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
1297
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
1298
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
1299
|
+
SOFTWARE.
|
|
1300
|
+
|
|
1301
|
+
==============================================================================
|
|
1302
|
+
typescript-string-operations 1.6.1 (MIT)
|
|
1303
|
+
==============================================================================
|
|
1304
|
+
|
|
1305
|
+
MIT License
|
|
1306
|
+
|
|
1307
|
+
Copyright (c) 2017 Sven Ulrich
|
|
1308
|
+
|
|
1309
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
1310
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
1311
|
+
in the Software without restriction, including without limitation the rights
|
|
1312
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
1313
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
1314
|
+
furnished to do so, subject to the following conditions:
|
|
1315
|
+
|
|
1316
|
+
The above copyright notice and this permission notice shall be included in all
|
|
1317
|
+
copies or substantial portions of the Software.
|
|
1318
|
+
|
|
1319
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
1320
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
1321
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
1322
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
1323
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
1324
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
1325
|
+
SOFTWARE.
|
|
1326
|
+
*/
|
|
1327
|
+
</script>
|
|
1328
|
+
</body>
|
|
1329
|
+
</html>
|