{"version":3,"file":"index.esm.min.js","sources":["../src/esm/VertexAttr.js","../src/esm/UIDGenerator.js","../src/esm/VertexListeners.js","../src/esm/Circle.js","../src/esm/Triangle.js","../src/esm/geomutils.js","../src/esm/Vertex.js","../src/esm/VertTuple.js","../src/esm/Vector.js","../src/esm/Line.js","../src/esm/Polygon.js","../src/esm/Bounds.js","../src/esm/CubicBezierCurve.js","../src/esm/BezierPath.js","../src/esm/CircleSector.js","../src/esm/drawutilssvg.js","../src/esm/draw.js","../src/esm/drawgl.js","../src/esm/Grid.js","../src/esm/KeyHandler.js","../src/esm/MouseHandler.js","../src/esm/PBImage.js","../src/esm/PBText.js","../node_modules/alloyfinger-typescript/src/esm/alloy_finger.js","../src/esm/VEllipse.js","../src/esm/VEllipseSector.js","../src/esm/PlotBoilerplate.js","../src/esm/utils/NGons.js","../src/esm/utils/PerlinNoise.js","../src/esm/utils/SVGPathUtils.js","../src/esm/utils/datastructures/Color.js","../src/esm/utils/WebColors.js","../src/esm/utils/WebColorsContrast.js","../src/esm/utils/WebColorsMalachite.js","../src/esm/utils/algorithms/arrayFill.js","../src/esm/utils/algorithms/matrixFill.js","../src/esm/utils/datastructures/CircularIntervalSet.js","../src/esm/utils/algorithms/CircleIntersections.js","../src/esm/utils/algorithms/clearDuplicateVertices.js","../src/esm/utils/datastructures/GenericPath.js","../src/esm/utils/algorithms/detectPaths.js","../src/esm/utils/algorithms/ContourLineDetection.js","../src/esm/utils/algorithms/convexHull.js","../src/esm/utils/algorithms/convexPolygonIncircle.js","../src/esm/utils/algorithms/HobbyPath.js","../src/esm/utils/algorithms/CubicSplinePath.js","../src/esm/utils/datastructures/VoronoiCell.js","../src/esm/utils/algorithms/findPolygonSelfIntersections.js","../src/esm/utils/algorithms/getContrastColor.js","../src/esm/utils/datastructures/DataGrid2dArrayMatrix.js","../src/esm/utils/algorithms/pixelCornersToRoundPaths.js","../src/esm/utils/algorithms/splitPolygonToNonIntersecting.js","../src/esm/utils/algorithms/sutherlandHodgman.js","../src/esm/utils/algorithms/PolygonInset.js","../src/esm/utils/algorithms/PolygonTesselationOutlines.js","../src/esm/utils/datastructures/ColorGradient.js","../src/esm/utils/datastructures/GirihTile.js","../src/esm/utils/datastructures/GirihBowtie.js","../src/esm/utils/datastructures/GirihDecagon.js","../src/esm/utils/datastructures/GirihHexagon.js","../src/esm/utils/datastructures/GirihPenroseRhombus.js","../src/esm/utils/datastructures/GirihPentagon.js","../src/esm/utils/datastructures/GirihRhombus.js","../src/esm/utils/datastructures/Matrix4x4.js","../node_modules/noreact/src/esm/useRef.js","../src/esm/utils/dom/components/ColorGradientSelector.js","../src/esm/utils/dom/getFProp.js","../src/esm/utils/helpers/BezierPathInteractionHelper.js","../src/esm/utils/parsers/svg/splitSVGPathData.js","../src/esm/utils/parsers/svg/parseSVGPathData.js","../src/esm/utils/parsers/LinearColorGradientParser.js","../src/esm/utils/parsers/STLParser.js","../src/esm/utils/algorithms/CatmullRomPath.js","../src/esm/utils/helpers/CircleHelper.js","../src/esm/utils/helpers/CircleSectorHelper.js","../src/esm/utils/dom/components/ColorGradientPicker.js","../src/esm/utils/datastructures/DataGrid2dListAdapter.js","../src/esm/utils/algorithms/delaunay.js","../src/esm/utils/io/FileDrop.js","../src/esm/utils/datastructures/GeometryMesh.js","../src/esm/utils/datastructures/Girih.js","../src/esm/utils/InitializationObserver.js","../src/esm/utils/LissajousFigure.js","../src/esm/utils/algorithms/Metaballs.js","../src/esm/utils/parsers/OBJParser.js","../src/esm/utils/Params.js","../src/esm/utils/helpers/TriangleHelper.js","../src/esm/utils/helpers/VEllipseHelper.js","../src/esm/utils/helpers/VEllipseSectorHelper.js","../src/esm/utils/algorithms/arrayResize.js","../src/esm/utils/algorithms/arrayShuffle.js","../src/esm/utils/algorithms/clearPolygonDuplicateVertices.js","../src/esm/utils/cloneVertexArray.js","../src/esm/utils/createRandomizedPolygon.js","../src/esm/utils/algorithms/delaunay2voronoi.js","../src/esm/utils/detectDarkMode.js","../src/esm/utils/findInVertexArray.js","../src/esm/utils/dom/getAvailableContainerSpace.js","../src/esm/utils/dom/guiSizeToggler.js","../src/esm/utils/gup.js"],"sourcesContent":["/**\n * @author   Ikaros Kappler\n * @date     2018-08-26\n * @modified 2018-11-17 Added the 'isSelected' attribute.\n * @modified 2018-11-27 Added the global model for instantiating with custom attributes.\n * @modified 2019-03-20 Added JSDoc tags.\n * @modified 2020-02-29 Added the 'selectable' attribute.\n * @modified 2020-03-23 Ported to Typescript from JS.\n * @modified 2024-03-10 Fixed some types for Typescript 5 compatibility.\n * @version  1.1.2\n *\n * @file VertexAttr\n * @public\n **/\n/**\n * @classdesc The VertexAttr is a helper class to wrap together additional attributes\n * to vertices that do not belong to the 'standard canonical' vertex implementation.<br>\n * <br>\n * This is some sort of 'userData' object, but the constructor uses a global model\n * to obtain a (configurable) default attribute set to all instances.<br>\n */\nexport class VertexAttr {\n    /**\n     * The constructor.\n     *\n     * Attributes will be initialized as defined in the model object\n     * which serves as a singleton.\n     *\n     * @constructor\n     * @name VertexAttr\n     **/\n    constructor() {\n        this.draggable = true;\n        this.selectable = true;\n        this.isSelected = false;\n        this.visible = true;\n        for (var key in VertexAttr.model)\n            this[key] = VertexAttr.model[key];\n    }\n    ;\n}\n/**\n * This is the global attribute model. Set these object on the initialization\n * of your app to gain all VertexAttr instances have these attributes.\n *\n * @type {object}\n **/\nVertexAttr.model = {\n    draggable: true,\n    selectable: true,\n    isSelected: false,\n    visible: true\n};\n//# sourceMappingURL=VertexAttr.js.map","/**\n * @classdesc A static UIDGenerator.\n *\n * @author  Ikaros Kappler\n * @date    2021-01-20\n * @version 1.0.0\n */\nexport class UIDGenerator {\n    static next() {\n        return `${UIDGenerator.current++}`;\n    }\n}\nUIDGenerator.current = 0;\n//# sourceMappingURL=UIDGenerator.js.map","/**\n * @author   Ikaros Kappler\n * @date     2018-08-27\n * @modified 2018-11-28 Added the vertex-param to the constructor and extended the event. Vertex events now have a 'params' attribute object.\n * @modified 2019-03-20 Added JSDoc tags.\n * @modified 2020-02-22 Added 'return this' to the add* functions (for chanining).\n * @modified 2020-03-23 Ported to Typescript from JS.\n * @modified 2020-11-17 Added the `click` handler.\n * @modified 2026-04-04 Adding null-listeners will now throw an error.\n * @version  1.2.0\n *\n * @file VertexListeners\n * @public\n **/\n/**\n * @classdesc An event listeners wrapper. This is just a set of three listener\n *              queues (drag, dragStart, dragEnd) and their respective firing\n *              functions.\n *\n */\nexport class VertexListeners {\n    /**\n     * The constructor.\n     *\n     * @constructor\n     * @name VertexListeners\n     * @param {Vertex} vertex - The vertex to use these listeners on (just a backward reference).\n     **/\n    constructor(vertex) {\n        this.click = [];\n        this.drag = [];\n        this.dragStart = [];\n        this.dragEnd = [];\n        this.vertex = vertex;\n    }\n    /**\n     * Add a click listener.\n     *\n     * @method addClickListener\n     * @param {VertexListeners~dragListener} listener - The click listener to add (a callback).\n     * @return {VertexListeners} this (for chaining)\n     * @instance\n     * @memberof VertexListeners\n     **/\n    addClickListener(listener) {\n        VertexListeners._addListener(this.click, listener);\n        return this;\n    }\n    /**\n     * The click listener is a function with a single drag event param.\n     * @callback VertexListeners~clickListener\n     * @param {Event} e - The (extended) click event.\n     */\n    /**\n     * Remove a drag listener.\n     *\n     * @method removeDragListener\n     * @param {VertexListeners~dragListener} listener - The drag listener to remove (a callback).\n     * @return {VertexListeners} this (for chaining)\n     * @instance\n     * @memberof VertexListeners\n     **/\n    removeClickListener(listener) {\n        this.click = VertexListeners._removeListener(this.click, listener);\n        return this;\n    }\n    /**\n     * The click listener is a function with a single drag event param.\n     * @callback VertexListeners~clickListener\n     * @param {Event} e - The (extended) click event.\n     */\n    /**\n     * Add a drag listener.\n     *\n     * @method addDragListener\n     * @param {VertexListeners~dragListener} listener - The drag listener to add (a callback).\n     * @return {VertexListeners} this (for chaining)\n     * @instance\n     * @memberof VertexListeners\n     **/\n    addDragListener(listener) {\n        VertexListeners._addListener(this.drag, listener);\n        return this;\n    }\n    /**\n     * The drag listener is a function with a single drag event param.\n     * @callback VertexListeners~dragListener\n     * @param {Event} e - The (extended) drag event.\n     */\n    /**\n     * Remove a drag listener.\n     *\n     * @method removeDragListener\n     * @param {VertexListeners~dragListener} listener - The drag listener to remove (a callback).\n     * @return {VertexListeners} this (for chaining)\n     * @instance\n     * @memberof VertexListeners\n     **/\n    removeDragListener(listener) {\n        this.drag = VertexListeners._removeListener(this.drag, listener);\n        return this;\n    }\n    /**\n     * Add a dragStart listener.\n     *\n     * @method addDragListener\n     * @param {VertexListeners~dragStartListener} listener - The drag-start listener to add (a callback).\n     * @return {VertexListeners} this (for chaining)\n     * @instance\n     * @memberof VertexListeners\n     **/\n    addDragStartListener(listener) {\n        VertexListeners._addListener(this.dragStart, listener);\n        return this;\n    }\n    /**\n     * The drag-start listener is a function with a single drag event param.\n     * @callback VertexListeners~dragStartListener\n     * @param {Event} e - The (extended) drag event.\n     */\n    /**\n     * Remove a dragStart listener.\n     *\n     * @method addDragStartListener\n     * @param {VertexListeners~dragListener} listener - The drag listener to remove (a callback).\n     * @return {VertexListeners} this (for chaining)\n     * @instance\n     * @memberof VertexListeners\n     **/\n    removeDragStartListener(listener) {\n        this.dragStart = VertexListeners._removeListener(this.dragStart, listener);\n        return this;\n    }\n    /**\n     * Add a dragEnd listener.\n     *\n     * @method addDragListener\n     * @param {VertexListeners~dragEndListener} listener - The drag-end listener to add (a callback).\n     * @return {VertexListeners} this (for chaining)\n     * @instance\n     * @memberof VertexListeners\n     **/\n    addDragEndListener(listener) {\n        // this.dragEnd.push( listener );\n        VertexListeners._addListener(this.dragEnd, listener);\n        return this;\n    }\n    /**\n     * The drag-end listener is a function with a single drag event param.\n     * @callback VertexListeners~dragEndListener\n     * @param {Event} e - The (extended) drag event.\n     */\n    /**\n     * Remove a drag listener.\n     *\n     * @method removeDragEndListener\n     * @param {VertexListeners~clickListener} listener - The drag listener to remove (a callback).\n     * @return {VertexListeners} this (for chaining)\n     * @instance\n     * @memberof VertexListeners\n     **/\n    removeDragEndListener(listener) {\n        // this.drag.push( listener );\n        this.dragEnd = VertexListeners._removeListener(this.dragEnd, listener);\n        return this;\n    }\n    /**\n     * Fire a click event with the given event instance to all\n     * installed click listeners.\n     *\n     * @method fireClickEvent\n     * @param {VertEvent|XMouseEvent} e - The click event itself to be fired to all installed drag listeners.\n     * @return {void}\n     * @instance\n     * @memberof VertexListeners\n     **/\n    fireClickEvent(e) {\n        VertexListeners._fireEvent(this, this.click, e);\n    }\n    /**\n     * Fire a drag event with the given event instance to all\n     * installed drag listeners.\n     *\n     * @method fireDragEvent\n     * @param {VertEvent|XMouseEvent} e - The drag event itself to be fired to all installed drag listeners.\n     * @return {void}\n     * @instance\n     * @memberof VertexListeners\n     **/\n    fireDragEvent(e) {\n        VertexListeners._fireEvent(this, this.drag, e);\n    }\n    /**\n     * Fire a dragStart event with the given event instance to all\n     * installed drag-start listeners.\n     *\n     * @method fireDragStartEvent\n     * @param {VertEvent|XMouseEvent} e - The drag-start event itself to be fired to all installed dragStart listeners.\n     * @return {void}\n     * @instance\n     * @memberof VertexListeners\n     **/\n    fireDragStartEvent(e) {\n        VertexListeners._fireEvent(this, this.dragStart, e);\n    }\n    /**\n     * Fire a dragEnd event with the given event instance to all\n     * installed drag-end listeners.\n     *\n     * @method fireDragEndEvent\n     * @param {VertEvent|XMouseEvent} e - The drag-end event itself to be fired to all installed dragEnd listeners.\n     * @return {void}\n     * @instance\n     * @memberof VertexListeners\n     **/\n    fireDragEndEvent(e) {\n        VertexListeners._fireEvent(this, this.dragEnd, e);\n    }\n    /**\n     * Removes all listeners from this listeners object.\n     */\n    removeAllListeners() {\n        this.click = [];\n        this.drag = [];\n        this.dragStart = [];\n        this.dragEnd = [];\n    }\n    /**\n     * @private\n     **/\n    static _fireEvent(_self, listeners, e) {\n        const ve = e;\n        if (typeof ve.params == \"undefined\")\n            ve.params = { vertex: _self.vertex };\n        else\n            ve.params.vertex = _self.vertex;\n        for (var i in listeners) {\n            listeners[i](ve);\n        }\n    }\n    /**\n     * @private\n     */\n    static _addListener(listeners, newListener) {\n        if (!newListener) {\n            throw new Error(\"Cannot add null listener. This would lead to unpredictable errors during event handling.\");\n        }\n        for (var i in listeners) {\n            if (listeners[i] == newListener)\n                return false;\n        }\n        listeners.push(newListener);\n        return true;\n    }\n    /**\n     * @private\n     */\n    static _removeListener(listeners, oldListener) {\n        for (var i = 0; i < listeners.length; i++) {\n            if (listeners[i] == oldListener)\n                return listeners.splice(i, 1);\n        }\n        return listeners;\n    }\n}\n//# sourceMappingURL=VertexListeners.js.map","/**\n * @author   Ikaros Kappler\n * @date     2020-05-04\n * @modified 2020-05-09 Ported to typescript.\n * @modified 2020-05-25 Added the vertAt and tangentAt functions.\n * @mofidied 2020-09-07 Added the circleIntersection(Circle) function.\n * @modified 2020-09-07 Changed the vertAt function by switching sin and cos! The old version did not return the correct vertex (by angle) accoring to the assumed circle math.\n * @modified 2020-10-16 Added the containsCircle(...) function.\n * @modified 2021-01-20 Added UID.\n * @modified 2022-02-02 Added the `destroy` method.\n * @modified 2022-02-02 Cleared the `toSVGString` function (deprecated). Use `drawutilssvg` instead.\n * @modified 2022-08-15 Added the `containsPoint` function.\n * @modified 2022-08-23 Added the `lineIntersection` function.\n * @modified 2022-08-23 Added the `closestPoint` function.\n * @modified 2025-04-09 Added the `Circle.move(amount: XYCoords)` method.\n * @modified 2025-04-16 Class `Circle` now implements interface `Intersectable`.\n * @modified 2026-06-10 Adding the utility function `Circle.circleUtils.containsPoint`.\n * @modified 2026-06-10 Adding the `Circle.clone` method.\n * @modified 2026-01-13 Adding helper function `Circle.circleUtils.containsPoint` and refactored the member method `containsPoint`.\n * @modified 2026-07-03 Adding the optional `epsilon` parameter to the `Circle.containsCircle` method.\n * @modified 2026-07-03 Fixing the `Circle.clone` method; the center had not been cloned at all, this was fixed.\n * @modified 2026-07-08 Adding the `Circle.setRadius` method (for chaining).\n * @mofified 2026-07-31 Adding the `radicalAxis(Circle)` method. Added the `Circle.circleUtils.createRadicalAxisHelperCircle` and `.circleDistance` helper methods.\n *\n * @version  1.7.0\n **/\nimport { Bounds } from \"./Bounds\";\nimport { Line } from \"./Line\";\nimport { UIDGenerator } from \"./UIDGenerator\";\nimport { Vector } from \"./Vector\";\nimport { Vertex } from \"./Vertex\";\nimport { geomutils } from \"./geomutils\";\n/**\n * @classdesc A simple circle: center point and radius.\n *\n * @requires Line\n * @requires Vector\n * @requires VertTuple\n * @requires Vertex\n * @requires SVGSerializale\n * @requires UID\n * @requires UIDGenerator\n **/\nexport class Circle {\n    /**\n     * Create a new circle with given center point and radius.\n     *\n     * @constructor\n     * @name Circle\n     * @param {Vertex} center - The center point of the circle.\n     * @param {number} radius - The radius of the circle.\n     */\n    constructor(center, radius) {\n        /**\n         * Required to generate proper CSS classes and other class related IDs.\n         **/\n        this.className = \"Circle\";\n        this.uid = UIDGenerator.next();\n        this.center = center;\n        this.radius = radius;\n    }\n    /**\n     * Set the radius of this circle.\n     * The method is meant for chaining, you may also alter the `radius` attribute directly.\n     *\n     * @method setRadius\n     * @param {number} radius - The amount to move.\n     * @instance\n     * @memberof Circle\n     * @return {Circle} this for chaining\n     **/\n    setRadius(radius) {\n        this.radius = radius;\n        return this;\n    }\n    /**\n     * Move the circle by the given amount.\n     *\n     * @method move\n     * @param {XYCoords} amount - The amount to move.\n     * @instance\n     * @memberof Circle\n     * @return {Circle} this for chaining\n     **/\n    move(amount) {\n        this.center.add(amount);\n        return this;\n    }\n    /**\n     * Check if the given circle is fully contained inside this circle.\n     *\n     * @method containsPoint\n     * @param {XYCoords} point - The point to check if it is contained in this circle.\n     * @instance\n     * @memberof Circle\n     * @return {boolean} `true` if the given point is inside this circle.\n     */\n    containsPoint(point) {\n        // return this.center.distance(point) < this.radius;//\n        return Circle.circleUtils.containsPoint(this.center, this.radius, point);\n    }\n    /**\n     * Check if the given circle is fully contained inside this circle.\n     *\n     * @method containsCircle\n     * @param {Circle} circle - The circle to check if it is contained in this circle.\n     * @instance\n     * @memberof Circle\n     * @return {boolean} `true` if any only if the given circle is completely inside this circle.\n     */\n    containsCircle(circle, epsilon) {\n        if (typeof epsilon === \"undefined\" || Number.isNaN(epsilon)) {\n            return this.center.distance(circle.center) + circle.radius < this.radius;\n        }\n        else {\n            return this.center.distance(circle.center) + circle.radius < this.radius + Math.abs(epsilon);\n        }\n    }\n    /**\n     * Calculate the distance from this circle to the given line.\n     *\n     * * If the line does not intersect this ciecle then the returned\n     *   value will be the minimal distance.\n     * * If the line goes through this circle then the returned value\n     *   will be max inner distance and it will be negative.\n     *\n     * @method lineDistance\n     * @param {Line} line - The line to measure the distance to.\n     * @return {number} The minimal distance from the outline of this circle to the given line.\n     * @instance\n     * @memberof Circle\n     */\n    lineDistance(line) {\n        const closestPointOnLine = line.getClosestPoint(this.center);\n        return closestPointOnLine.distance(this.center) - this.radius;\n    }\n    /**\n     * Get the vertex on the this circle for the given angle.\n     *\n     * @method vertAt\n     * @param {number} angle - The angle (in radians) to use.\n     * @return {Vertex} The vertex (point) at the given angle.\n     * @instance\n     * @memberof Circle\n     **/\n    vertAt(angle) {\n        // Find the point on the circle respective the angle. Then move relative to center.\n        return Circle.circleUtils.vertAt(angle, this.radius).add(this.center);\n    }\n    /**\n     * Get a tangent line of this circle for a given angle.\n     *\n     * Point a of the returned line is located on the circle, the length equals the radius.\n     *\n     * @method tangentAt\n     * @instance\n     * @param {number} angle - The angle (in radians) to use.\n     * @return {Line} The tangent line.\n     * @memberof Circle\n     **/\n    tangentAt(angle) {\n        const pointA = Circle.circleUtils.vertAt(angle, this.radius);\n        // Construct the perpendicular of the line in point a. Then move relative to center.\n        return new Vector(pointA, new Vertex(0, 0)).add(this.center).perp();\n        // return (new Vector(this.center.clone(), pointA).add(pointA) as Vector).perp() as Vector;\n    }\n    //--- BEGIN --- Implement interface `Intersectable`\n    /**\n     * Get the bounding box (bounds) of this Circle.\n     *\n     * @method getBounds\n     * @instance\n     * @memberof Circle\n     * @return {Bounds} The rectangular bounds of this Circle.\n     **/\n    getBounds() {\n        return new Bounds(this.center.clone().subXY(Math.abs(this.radius), Math.abs(this.radius)), this.center.clone().addXY(Math.abs(this.radius), Math.abs(this.radius)));\n    }\n    //--- END --- Implement interface `Intersectable`\n    /**\n     * Calculate the intersection points (if exists) with the given circle.\n     *\n     * @method circleIntersection\n     * @instance\n     * @memberof Circle\n     * @param {Circle} circle\n     * @return {Line|null} The intersection points (as a line) or null if the two circles do not intersect.\n     **/\n    circleIntersection(circle) {\n        // Circles do not intersect at all?\n        if (this.center.distance(circle.center) > this.radius + circle.radius) {\n            return null;\n        }\n        // One circle is fully inside the other?\n        if (this.center.distance(circle.center) < Math.abs(this.radius - circle.radius)) {\n            return null;\n        }\n        // Based on the C++ implementation by Robert King\n        //    https://stackoverflow.com/questions/3349125/circle-circle-intersection-points\n        // and the 'Circles and spheres' article by Paul Bourke.\n        //    http://paulbourke.net/geometry/circlesphere/\n        //\n        // This is the original C++ implementation:\n        //\n        // pair<Point, Point> intersections(Circle c) {\n        //    Point P0(x, y);\n        //    Point P1(c.x, c.y);\n        //    float d, a, h;\n        //    d = P0.distance(P1);\n        //    a = (r*r - c.r*c.r + d*d)/(2*d);\n        //    h = sqrt(r*r - a*a);\n        //    Point P2 = P1.sub(P0).scale(a/d).add(P0);\n        //    float x3, y3, x4, y4;\n        //    x3 = P2.x + h*(P1.y - P0.y)/d;\n        //    y3 = P2.y - h*(P1.x - P0.x)/d;\n        //    x4 = P2.x - h*(P1.y - P0.y)/d;\n        //    y4 = P2.y + h*(P1.x - P0.x)/d;\n        //    return pair<Point, Point>(Point(x3, y3), Point(x4, y4));\n        // }\n        var p0 = this.center;\n        var p1 = circle.center;\n        var d = p0.distance(p1);\n        var a = (this.radius * this.radius - circle.radius * circle.radius + d * d) / (2 * d);\n        var h = Math.sqrt(this.radius * this.radius - a * a);\n        var p2 = p1.clone().scale(a / d, p0);\n        var x3 = p2.x + (h * (p1.y - p0.y)) / d;\n        var y3 = p2.y - (h * (p1.x - p0.x)) / d;\n        var x4 = p2.x - (h * (p1.y - p0.y)) / d;\n        var y4 = p2.y + (h * (p1.x - p0.x)) / d;\n        return new Line(new Vertex(x3, y3), new Vertex(x4, y4));\n    }\n    /**\n     * Calculate the intersection points (if exists) with the given infinite line (defined by two points).\n     *\n     * @method lineIntersection\n     * @instance\n     * @memberof Circle\n     * @param {Vertex} a- The first of the two points defining the line.\n     * @param {XYCoords} b - The second of the two points defining the line.\n     * @return {Line|null} The intersection points (as a line) or null if this circle does not intersect the line given.\n     **/\n    lineIntersection(a, b) {\n        // Based on the math from\n        //    https://mathworld.wolfram.com/Circle-LineIntersection.html\n        const interA = new Vertex();\n        const interB = new Vertex();\n        // First do a transformation, because the calculation is based on a cicle at (0,0)\n        const transA = new Vertex(a).sub(this.center);\n        const transB = new Vertex(b).sub(this.center);\n        const diff = transA.difference(transB);\n        // There is a special case if diff.y=0, where the intersection is not calcuatable.\n        // Use an non-zero epsilon here to approximate this case.\n        // TODO for the future: find a better solution\n        if (Math.abs(diff.y) === 0) {\n            diff.y = 0.000001;\n        }\n        const dist = transA.distance(transB);\n        const det = transA.x * transB.y - transA.y * transB.x;\n        const distSquared = dist * dist;\n        const radiusSquared = this.radius * this.radius;\n        // Check if circle and line have an intersection at all\n        if (radiusSquared * distSquared - det * det < 0) {\n            return null;\n        }\n        const belowSqrt = this.radius * this.radius * dist * dist - det * det;\n        const sqrt = Math.sqrt(belowSqrt);\n        interA.x = (det * diff.y + Math.sign(diff.y) * diff.x * sqrt) / distSquared;\n        interB.x = (det * diff.y - Math.sign(diff.y) * diff.x * sqrt) / distSquared;\n        interA.y = (-det * diff.x + Math.abs(diff.y) * sqrt) / distSquared;\n        interB.y = (-det * diff.x - Math.abs(diff.y) * sqrt) / distSquared;\n        return new Line(interA.add(this.center), interB.add(this.center));\n    }\n    //--- BEGIN --- Implement interface `Intersectable`\n    /**\n     * Get all line intersections with this circle.\n     *\n     * This method returns all intersections (as vertices) with this shape. The returned array of vertices is in no specific order.\n     *\n     * @param {VertTuple} line - The line to find intersections with.\n     * @param {boolean} inVectorBoundsOnly - If set to true only intersecion points on the passed vector are returned (located strictly between start and end vertex).\n     * @returns {Array<Vertex>} - An array of all intersections with the circle outline.\n     */\n    lineIntersections(line, inVectorBoundsOnly = false) {\n        // Find the intersections of all lines inside the edge bounds\n        const intersectioLine = this.lineIntersection(line.a, line.b);\n        if (!intersectioLine) {\n            return [];\n        }\n        if (inVectorBoundsOnly) {\n            // const maxDist = line.length();\n            return [intersectioLine.a, intersectioLine.b].filter((vert) => line.hasPoint(vert, true));\n        }\n        else {\n            return [intersectioLine.a, intersectioLine.b];\n        }\n    }\n    /**\n     * Get all line intersections of this polygon and their tangents along the shape.\n     *\n     * This method returns all intersection tangents (as vectors) with this shape. The returned array of vectors is in no specific order.\n     *\n     * @param line\n     * @param lineIntersectionTangents\n     * @returns\n     */\n    lineIntersectionTangents(line, inVectorBoundsOnly = false) {\n        // Find the intersections of all lines plus their tangents inside the circle bounds\n        const interSectionPoints = this.lineIntersections(line, inVectorBoundsOnly);\n        return interSectionPoints.map((vert) => {\n            // Calculate angle\n            const lineFromCenter = new Line(this.center, vert);\n            const angle = lineFromCenter.angle();\n            // console.log(\"angle\", (angle / Math.PI) * 180.0);\n            // const angle = Math.random() * Math.PI * 2; // TODO\n            // Calculate tangent at angle\n            return this.tangentAt(angle);\n        });\n    }\n    //--- END --- Implement interface `Intersectable`\n    /**\n     * Calculate the radical axis of this and a different circle.\n     * The two circles must not be co-centric.\n     *\n     * See this article for details:\n     *    https://www.cut-the-knot.org/Curriculum/Geometry/GeoGebra/RadicalAxes.shtml\n     *\n     * @method radicalAxis\n     * @instance\n     * @memberof Circle\n     * @param {Circle} circleB - The second circle to calculated the radical axis for.\n     * @return {Line} A line defining the radical axis of the two circles.\n     **/\n    radicalAxis(circleB) {\n        var helperCircle = Circle.circleUtils.createRadicalAxisHelperCircle(this, circleB);\n        var intersectionLineA = this.circleIntersection(helperCircle);\n        var intersectionLineB = circleB.circleIntersection(helperCircle);\n        var intersection = this.circleIntersection(circleB);\n        if (!intersectionLineA || !intersectionLineB) {\n            console.error(\"Critical error: none of the two intersections must be null.\");\n            return intersection; // Fallback\n        }\n        var lineA = new Line(intersectionLineA.a, intersectionLineA.b);\n        var lineB = new Line(intersectionLineB.a, intersectionLineB.b);\n        var firstRadicalAxisPoint = lineA.intersection(lineB);\n        var centerConnectLine = new Line(this.center, circleB.center);\n        var secondRadicalAxisPoint = centerConnectLine.getClosestPoint(firstRadicalAxisPoint);\n        // Create a mirrored version of the second radical axis point so both are located\n        // symmetrical from the circle connect point.\n        // (currently the second point is located ON the connect line)\n        var secondRadicalAxisPoint_mirrored = secondRadicalAxisPoint.clone().scale(2.0, firstRadicalAxisPoint);\n        var radicalAxis = new Line(firstRadicalAxisPoint, secondRadicalAxisPoint_mirrored);\n        return intersection && intersection.length() > radicalAxis.length() ? intersection : radicalAxis;\n    }\n    /**\n     * Calculate the closest point on the outline of this circle to the given point.\n     *\n     * @method closestPoint\n     * @instance\n     * @memberof Circle\n     * @param {XYCoords} vert - The point to find the closest circle point for.\n     * @return {Vertex} The closest point on this circle.\n     **/\n    closestPoint(vert) {\n        const lineIntersection = this.lineIntersection(this.center, vert);\n        if (!lineIntersection) {\n            // Note: this case should not happen as a radial from the center always intersect this circle.\n            return new Vertex();\n        }\n        // Return closed of both\n        if (lineIntersection.a.distance(vert) < lineIntersection.b.distance(vert)) {\n            return lineIntersection.a;\n        }\n        else {\n            return lineIntersection.b;\n        }\n    }\n    /**\n     * Get the two tangent vectors for the given point.\n     * If the point is on or in the circle then null is returned.\n     *\n     * @method tangentsFromPoint\n     * @instance\n     * @memberof Circle\n     * @param {Vertex} vert - The point to find the two tangents for.\n     * @return {[Vector,Vector]} The two tangent vector\n     **/\n    tangentsFromPoint(vert) {\n        // Inspired by\n        //   https://www.omnicalculator.com/math/tangent-circle\n        const centerDistance = this.center.distance(vert);\n        const tangentLength = Math.sqrt(this.radius * this.radius - centerDistance * centerDistance);\n        console.log(\"this.radius \", this.radius, \"centerDistance\", centerDistance, \"tangentLength\", tangentLength);\n        if (Number.isNaN(tangentLength)) {\n            // vertex is inside circle\n            console.log(\"tangentLength is NaN\", tangentLength);\n            return null;\n        }\n        const helperCircle = new Circle(vert, tangentLength);\n        const intersection = this.circleIntersection(helperCircle);\n        if (!intersection) {\n            // No intersection (vertex is inside circle)\n            return null;\n        }\n        return [new Vector(intersection.a, vert), new Vector(intersection.b, vert)];\n    }\n    /**\n     * Create a deep copy of this circle.\n     *\n     * @method clone\n     * @return {Circle} A new circle, an exact copy of this one.\n     * @instance\n     * @memberof Circle\n     **/\n    clone() {\n        return new Circle(this.center.clone(), this.radius);\n    }\n    static fromICircle(obj) {\n        return new Circle(new Vertex(obj.center), obj.radius);\n    }\n    // static fromObject(obj: object): Circle {\n    //   if (!obj) {\n    //     return null;\n    //   }\n    //   if (typeof obj !== \"object\") {\n    //     return null;\n    //   }\n    //   if (!obj.hasOwnProperty(\"center\") || typeof (obj as any).center != \"object\") {\n    //     return null;\n    //   }\n    //   if (!obj.hasOwnProperty(\"radius\") || typeof !(obj as any).radius != \"number\") {\n    //     return null;\n    //   }\n    //   var center = (obj as any).center;\n    //   if (!center.hasOwnProperty(\"x\") || typeof (center as any).x != \"number\") {\n    //     return null;\n    //   }\n    //   if (!center.hasOwnProperty(\"y\") || typeof (center as any).y != \"number\") {\n    //     return null;\n    //   }\n    //   return new Circle(new Vertex(center), (obj as any).radius);\n    // }\n    /**\n     * This function should invalidate any installed listeners and invalidate this object.\n     * After calling this function the object might not hold valid data any more and\n     * should not be used.\n     */\n    destroy() {\n        this.center.destroy();\n        this.isDestroyed = true;\n    }\n} // END class\nCircle.circleUtils = {\n    vertAt: (angle, radius) => {\n        /* return new Vertex( Math.sin(angle) * radius,\n                     Math.cos(angle) * radius ); */\n        return new Vertex(Math.cos(angle) * radius, Math.sin(angle) * radius);\n    },\n    containsPoint: (circleCenter, circleRadius, point) => {\n        // TODO: cleanup\n        // return (\n        //   (circle.center.x - point.x) * (circle.center.x - point.x) + (circle.center.y - point.y) * (circle.center.y - point.y) <=\n        //   circle.radius * circle.radius\n        // );\n        return geomutils.dist4(point.x, point.y, circleCenter.x, circleCenter.y) < circleRadius;\n    },\n    createRadicalAxisHelperCircle: (circleA, circleB) => {\n        // We need to create a helper circle that intersects BOTH other circles,\n        // each in TWO points.\n        var circleConnectLine = new Vector(circleA.center.clone(), circleB.center);\n        circleConnectLine.a.set(circleConnectLine.vertAt(0.5));\n        // Get the perpendicular by half the circle distance.\n        var bisector = circleConnectLine.perp();\n        var bisectorLength = Math.max(circleA.radius, circleB.radius, bisector.length());\n        bisector.setLength(bisectorLength);\n        return new Circle(bisector.b, bisector.b.distance(circleA.center));\n    },\n    /**\n     * Calculate the outer distance between two circles. If the circles touch then the\n     * distance is 0.0.\n     * If the circles intersect then the distance in negative.\n     */\n    circleDistance: (circleA, circleB) => {\n        return circleA.center.distance(circleB.center) - circleA.radius - circleB.radius;\n    }\n};\n//# sourceMappingURL=Circle.js.map","/**\n * @author    Ikaros Kappler\n * @date_init 2012-10-17 (Wrote a first version of this in that year).\n * @date      2018-04-03 (Refactored the code into a new class).\n * @modified  2018-04-28 Added some documentation.\n * @modified  2019-09-11 Added the scaleToCentroid(Number) function (used by the walking triangle demo).\n * @modified  2019-09-12 Added beautiful JSDoc compliable comments.\n * @modified  2019-11-07 Added to toSVG(options) function to make Triangles renderable as SVG.\n * @modified  2019-12-09 Fixed the determinant() function. The calculation was just wrong.\n * @modified  2020-03-16 (Corona times) Added the 'fromArray' function.\n * @modified  2020-03-17 Added the Triangle.toPolygon() function.\n * @modified  2020-03-17 Added proper JSDoc comments.\n * @modified  2020-03-25 Ported this class from vanilla-JS to Typescript.\n * @modified  2020-05-09 Added the new Circle class (ported to Typescript from the demos).\n * @modified  2020-05-12 Added getIncircularTriangle() function.\n * @modified  2020-05-12 Added getIncircle() function.\n * @modified  2020-05-12 Fixed the signature of getCircumcirle(). Was still a generic object.\n * @modified  2020-06-18 Added the `getIncenter` function.\n * @modified  2020-12-28 Added the `getArea` function.\n * @modified  2021-01-20 Added UID.\n * @modified  2021-01-22 Always updating circumcircle when retieving it.\n * @modified  2022-02-02 Added the `destroy` method.\n * @modified  2022-02-02 Cleared the `Triangle.toSVGString` function (deprecated). Use `drawutilssvg` instead.\n * @modified  2024-11-22 Added static utility function Triangle.utils.determinant; adapted method `determinant`.\n * @modified  2024-11-22 Changing visibility of `Triangle.utils` from `private` to `public`.\n * @modified  2025-14-16 Class `Triangle` now implements interface `Intersectable`.\n * @modified  2025-14-16 Class `Triangle` now implements interface `IBounded`.\n * @modified  2025-14-16 Class `Triangle` now implements interface `Intersectable`.\n * @modified  2025-14-16 Added method `Triangle.move`.\n * @modified  2026-06-10 Refactoring the `Trianble.bounds` method and added a plain `Triangle.utils.bounds` method.\n * @modified  2026-06-10 Refactoring the `Trianble.calcCircumCircle` method and added a plain `Triangle.utils.calcCircumCircle` method.\n * @modified  2026-06-13 Adding `Triangle.getVertices()`.\n * @version   2.11.0\n *\n * @file Triangle\n * @fileoverview A simple triangle class: three vertices.\n * @public\n **/\nimport { Bounds } from \"./Bounds\";\nimport { Circle } from \"./Circle\";\nimport { Line } from \"./Line\";\nimport { Polygon } from \"./Polygon\";\nimport { UIDGenerator } from \"./UIDGenerator\";\nimport { Vector } from \"./Vector\";\nimport { VertTuple } from \"./VertTuple\";\nimport { Vertex } from \"./Vertex\";\nimport { geomutils } from \"./geomutils\";\n/**\n * @classdesc A triangle class for triangulations.\n *\n * The class was written for a Delaunay trinagulation demo so it might\n * contain some strange and unexpected functions.\n *\n * @requires Bounds\n * @requires Circle\n * @requires Line\n * @requires Vertex\n * @requires Polygon\n * @requires SVGSerializale\n * @requires UID\n * @requires UIDGenerator\n * @requires geomutils\n *\n */\nexport class Triangle {\n    /**\n     * The constructor.\n     *\n     * @constructor\n     * @name Triangle\n     * @param {Vertex} a - The first vertex of the triangle.\n     * @param {Vertex} b - The second vertex of the triangle.\n     * @param {Vertex} c - The third vertex of the triangle.\n     **/\n    constructor(a, b, c) {\n        /**\n         * Required to generate proper CSS classes and other class related IDs.\n         **/\n        this.className = \"Triangle\";\n        this.uid = UIDGenerator.next();\n        this.a = a;\n        this.b = b;\n        this.c = c;\n        this.calcCircumcircle();\n    }\n    /**\n     * Create a new triangle from the given array of vertices.\n     *\n     * The array must have at least three vertices, otherwise an error will be raised.\n     * This function will not create copies of the vertices.\n     *\n     * @method fromArray\n     * @static\n     * @param {Array<Vertex>} arr - The required array with at least three vertices.\n     * @memberof Vertex\n     * @return {Triangle}\n     **/\n    static fromArray(arr) {\n        if (arr.length < 3)\n            throw `Cannot create triangle from array with less than three vertices (${arr.length})`;\n        return new Triangle(arr[0], arr[1], arr[2]);\n    }\n    /**\n     * Get the area of this triangle. The returned area is never negative.\n     *\n     * If you are interested in the signed area, please consider using the\n     * `Triangle.utils.signedArea` helper function. This method just returns\n     * the absolute value of the signed area.\n     *\n     * @method getArea\n     * @instance\n     * @memberof Triangle\n     * @return {number} The non-negative area of this triangle.\n     */\n    getArea() {\n        return Math.abs(Triangle.utils.signedArea(this.a.x, this.a.y, this.b.x, this.b.y, this.c.x, this.c.y));\n    }\n    /**\n     * Get the centroid of this triangle.\n     *\n     * The centroid is the average midpoint for each side.\n     *\n     * @method getCentroid\n     * @return {Vertex} The centroid\n     * @instance\n     * @memberof Triangle\n     **/\n    getCentroid() {\n        return new Vertex((this.a.x + this.b.x + this.c.x) / 3, (this.a.y + this.b.y + this.c.y) / 3);\n    }\n    /**\n     * Scale the triangle towards its centroid.\n     *\n     * @method scaleToCentroid\n     * @param {number} - The scale factor to use. That can be any scalar.\n     * @return {Triangle} this (for chaining)\n     * @instance\n     * @memberof Triangle\n     */\n    scaleToCentroid(factor) {\n        let centroid = this.getCentroid();\n        this.a.scale(factor, centroid);\n        this.b.scale(factor, centroid);\n        this.c.scale(factor, centroid);\n        return this;\n    }\n    //--- BEGIN --- Implement interface `IBounded`\n    /**\n     * Get the bounding box (bounds) of this Triangle.\n     *\n     * @method getBounds\n     * @instance\n     * @memberof Triangle\n     * @return {Bounds} The rectangular bounds of this Triangle.\n     **/\n    getBounds() {\n        // return Bounds.computeFromVertices([this.a, this.b, this.c]);\n        return this.bounds();\n    }\n    //--- END --- Implement interface `IBounded`\n    /**\n     * Move the Triangle's vertices by the given amount.\n     *\n     * @method move\n     * @param {XYCoords} amount - The amount to move.\n     * @instance\n     * @memberof Triangle\n     * @return {Triangle} this for chaining\n     **/\n    move(amount) {\n        this.a.add(amount);\n        this.b.add(amount);\n        this.c.add(amount);\n        return this;\n    }\n    /**\n     * Get the circumcircle of this triangle.\n     *\n     * The circumcircle is that unique circle on which all three\n     * vertices of this triangle are located on.\n     *\n     * Please note that for performance reasons any changes to vertices will not reflect in changes\n     * of the circumcircle (center or radius). Please call the calcCirumcircle() function\n     * after triangle vertex changes.\n     *\n     * @method getCircumcircle\n     * @return {Circle} - The circle touching exactly all three triangle vertices.\n     * @instance\n     * @memberof Triangle\n     */\n    getCircumcircle() {\n        // if( !this.center || !this.radius )\n        this.calcCircumcircle();\n        return new Circle(this.center.clone(), this.radius);\n    }\n    /**\n     * Calculates the minimun enclosing circle.\n     *\n     * @method getMinimumEnclosingCircle\n     * @return {Object} - { center:Vertex, radius:float }\n     * @instance\n     * @memberof Triangle\n     * @returns\n     */\n    getMinimumEnclosingCircle() {\n        // First option: two points construct a circle and the third point is contained.\n        var circleAB = VertTuple.vtutils.calcCircumcircle(this.a, this.b);\n        if (Circle.circleUtils.containsPoint(circleAB.center, circleAB.radius, this.c)) {\n            return Circle.fromICircle(circleAB);\n        }\n        var circleBC = VertTuple.vtutils.calcCircumcircle(this.b, this.c);\n        if (Circle.circleUtils.containsPoint(circleBC.center, circleBC.radius, this.c)) {\n            return Circle.fromICircle(circleBC);\n        }\n        var circleCA = VertTuple.vtutils.calcCircumcircle(this.c, this.a);\n        if (Circle.circleUtils.containsPoint(circleCA.center, circleCA.radius, this.c)) {\n            return Circle.fromICircle(circleCA);\n        }\n        // If none of the three upper cases applies: return the circumcircle.\n        var circumCircle = Triangle.utils.calcCircumcircle(this.a, this.b, this.c);\n        return Circle.fromICircle(circumCircle);\n    }\n    /**\n     * Check if this triangle and the passed triangle share an\n     * adjacent edge.\n     *\n     * For edge-checking Vertex.equals is used which uses an\n     * an epsilon for comparison.\n     *\n     * @method isAdjacent\n     * @param {Triangle} tri - The second triangle to check adjacency with.\n     * @return {boolean} - True if this and the passed triangle have at least one common edge.\n     * @instance\n     * @memberof Triangle\n     */\n    isAdjacent(tri) {\n        var a = this.a.equals(tri.a) || this.a.equals(tri.b) || this.a.equals(tri.c);\n        var b = this.b.equals(tri.a) || this.b.equals(tri.b) || this.b.equals(tri.c);\n        var c = this.c.equals(tri.a) || this.c.equals(tri.b) || this.c.equals(tri.c);\n        return (a && b) || (a && c) || (b && c);\n    }\n    /**\n     * Get that vertex of this triangle (a,b,c) that is not vert1 nor vert2 of\n     * the passed two.\n     *\n     * @method getThirdVertex\n     * @param {Vertex} vert1 - The first vertex.\n     * @param {Vertex} vert2 - The second vertex.\n     * @return {Vertex} - The third vertex of this triangle that makes up the whole triangle with vert1 and vert2.\n     * @instance\n     * @memberof Triangle\n     */\n    getThirdVertex(vert1, vert2) {\n        if ((this.a.equals(vert1) && this.b.equals(vert2)) || (this.a.equals(vert2) && this.b.equals(vert1)))\n            return this.c;\n        if ((this.b.equals(vert1) && this.c.equals(vert2)) || (this.b.equals(vert2) && this.c.equals(vert1)))\n            return this.a;\n        //if( this.c.equals(vert1) && this.a.equals(vert2) || this.c.equals(vert2) && this.a.equals(vert1) )\n        return this.b;\n    }\n    /**\n     * Get the three triangele vertices in a 3-element array.\n     *\n     * @method getVertices\n     * @returns {[Vertex, Vertex, Vertex]} - The three vertices – real instances, not copies.\n     * @instance\n     * @memberof Triangle\n     */\n    getVertices() {\n        return [this.a, this.b, this.c];\n    }\n    /**\n     * Re-compute the circumcircle of this triangle (if the vertices\n     * have changed).\n     *\n     * The circumcenter and radius are stored in this.center and\n     * this.radius. There is a third result: radius_squared (for internal computations).\n     *\n     * @method calcCircumcircle\n     * @return void\n     * @instance\n     * @memberof Triangle\n     */\n    calcCircumcircle() {\n        // // From\n        // //    http://www.exaflop.org/docs/cgafaq/cga1.html\n        // const A: number = this.b.x - this.a.x;\n        // const B: number = this.b.y - this.a.y;\n        // const C: number = this.c.x - this.a.x;\n        // const D: number = this.c.y - this.a.y;\n        // const E: number = A * (this.a.x + this.b.x) + B * (this.a.y + this.b.y);\n        // const F: number = C * (this.a.x + this.c.x) + D * (this.a.y + this.c.y);\n        // const G: number = 2.0 * (A * (this.c.y - this.b.y) - B * (this.c.x - this.b.x));\n        // let dx: number, dy: number;\n        // if (Math.abs(G) < Triangle.EPSILON) {\n        //   // Collinear - find extremes and use the midpoint\n        //   const bounds: Bounds = this.bounds();\n        //   this.center = new Vertex((bounds.min.x + bounds.max.x) / 2, (bounds.min.y + bounds.max.y) / 2);\n        //   dx = this.center.x - bounds.min.x;\n        //   dy = this.center.y - bounds.min.y;\n        // } else {\n        //   const cx: number = (D * E - B * F) / G;\n        //   const cy: number = (A * F - C * E) / G;\n        //   this.center = new Vertex(cx, cy);\n        //   dx = this.center.x - this.a.x;\n        //   dy = this.center.y - this.a.y;\n        // }\n        // this.radius_squared = dx * dx + dy * dy;\n        // this.radius = Math.sqrt(this.radius_squared);\n        const tmpCircle = Triangle.utils.calcCircumcircle(this.a, this.b, this.c);\n        this.center = new Vertex(tmpCircle.center.x, tmpCircle.center.y);\n        this.radius = tmpCircle.radius;\n        this.radius_squared = tmpCircle.radius_squared;\n    } // END calcCircumcircle\n    /**\n     * Check if the passed vertex is inside this triangle's\n     * circumcircle.\n     *\n     * @method inCircumcircle\n     * @param {Vertex} v - The vertex to check.\n     * @return {boolean}\n     * @instance\n     * @memberof Triangle\n     */\n    inCircumcircle(v) {\n        const dx = this.center.x - v.x;\n        const dy = this.center.y - v.y;\n        const dist_squared = dx * dx + dy * dy;\n        return dist_squared <= this.radius_squared;\n    }\n    /**\n     * Get the rectangular bounds for this triangle.\n     *\n     * @method bounds\n     * @return {Bounds} - The min/max bounds of this triangle.\n     * @instance\n     * @memberof Triangle\n     */\n    bounds() {\n        // return new Bounds(\n        //   new Vertex(Triangle.utils.min3(this.a.x, this.b.x, this.c.x), Triangle.utils.min3(this.a.y, this.b.y, this.c.y)),\n        //   new Vertex(Triangle.utils.max3(this.a.x, this.b.x, this.c.x), Triangle.utils.max3(this.a.y, this.b.y, this.c.y))\n        // );\n        return Triangle.utils.bounds(this.a, this.b, this.c);\n    }\n    //--- BEGIN --- Implement interface `Intersectable`\n    /**\n     * Get all line intersections with this polygon.\n     *\n     * This method returns all intersections (as vertices) with this shape. The returned array of vertices is in no specific order.\n     *\n     * See demo `47-closest-vector-projection-on-polygon` for how it works.\n     *\n     * @param {VertTuple} line - The line to find intersections with.\n     * @param {boolean} inVectorBoundsOnly - If set to true only intersecion points on the passed vector are returned (located strictly between start and end vertex).\n     * @returns {Array<Vertex>} - An array of all intersections within the polygon bounds.\n     */\n    lineIntersections(line, inVectorBoundsOnly = false) {\n        // Find the intersections of all lines inside the edge bounds\n        return Polygon.utils\n            .locateLineIntersecion(line, [this.a, this.b, this.c], false, inVectorBoundsOnly)\n            .map(intersectionTuple => intersectionTuple.intersection);\n    }\n    /**\n     * Get all line intersections of this polygon and their tangents along the shape.\n     *\n     * This method returns all intersection tangents (as vectors) with this shape. The returned array of vectors is in no specific order.\n     *\n     * @param line\n     * @param inVectorBoundsOnly\n     * @returns\n     */\n    lineIntersectionTangents(line, inVectorBoundsOnly = false) {\n        // Find the intersection tangents of all lines inside the edge bounds\n        return Polygon.utils\n            .locateLineIntersecion(line, [this.a, this.b, this.c], false, inVectorBoundsOnly)\n            .map(intersectionTuple => {\n            // const polyLine = this.getEdgeAt(intersectionTuple.edgeIndex);\n            const polyLine = this.getEdgeAt(intersectionTuple.edgeIndex);\n            return new Vector(polyLine.a.clone(), polyLine.b.clone()).moveTo(intersectionTuple.intersection);\n        });\n    }\n    //--- END --- Implement interface `Intersectable`\n    getEdgeAt(edgeIndex) {\n        var modIndex = edgeIndex % 3;\n        return modIndex === 0 ? new Line(this.a, this.b) : modIndex === 1 ? new Line(this.b, this.c) : new Line(this.c, this.a);\n    }\n    /**\n     * Convert this triangle to a polygon instance.\n     *\n     * Plase note that this conversion does not perform a deep clone.\n     *\n     * @method toPolygon\n     * @return {Polygon} A new polygon representing this triangle.\n     * @instance\n     * @memberof Triangle\n     **/\n    toPolygon() {\n        return new Polygon([this.a, this.b, this.c]);\n    }\n    /**\n     * Get the determinant of this triangle.\n     *\n     * @method determinant\n     * @return {number} - The determinant (float).\n     * @instance\n     * @memberof Triangle\n     */\n    determinant() {\n        // (b.y - a.y)*(c.x - b.x) - (c.y - b.y)*(b.x - a.x);\n        // return (this.b.y - this.a.y) * (this.c.x - this.b.x) - (this.c.y - this.b.y) * (this.b.x - this.a.x);\n        return Triangle.utils.determinant(this.a, this.b, this.c);\n    }\n    /**\n     * Checks if the passed vertex (p) is inside this triangle.\n     *\n     * Note: matrix determinants rock.\n     *\n     * @method containsPoint\n     * @param {Vertex} p - The vertex to check.\n     * @return {boolean}\n     * @instance\n     * @memberof Triangle\n     */\n    containsPoint(p) {\n        return Triangle.utils.pointIsInTriangle(p.x, p.y, this.a.x, this.a.y, this.b.x, this.b.y, this.c.x, this.c.y);\n    }\n    /**\n     * Get that inner triangle which defines the maximal incircle.\n     *\n     * @return {Triangle} The triangle of those points in this triangle that define the incircle.\n     */\n    getIncircularTriangle() {\n        const lineA = new Line(this.a, this.b);\n        const lineB = new Line(this.b, this.c);\n        const lineC = new Line(this.c, this.a);\n        const bisector1 = geomutils.nsectAngle(this.b, this.a, this.c, 2)[0]; // bisector of first angle (in b)\n        const bisector2 = geomutils.nsectAngle(this.c, this.b, this.a, 2)[0]; // bisector of second angle (in c)\n        // Cast to non-null here because we know there _is_ an intersection\n        const intersection = bisector1.intersection(bisector2);\n        // Find the closest points on one of the polygon lines (all have same distance by construction)\n        const circleIntersA = lineA.getClosestPoint(intersection);\n        const circleIntersB = lineB.getClosestPoint(intersection);\n        const circleIntersC = lineC.getClosestPoint(intersection);\n        return new Triangle(circleIntersA, circleIntersB, circleIntersC);\n    }\n    /**\n     * Get the incircle of this triangle. That is the circle that touches each side\n     * of this triangle in exactly one point.\n     *\n     * Note this just calls getIncircularTriangle().getCircumcircle()\n     *\n     * @return {Circle} The incircle of this triangle.\n     */\n    getIncircle() {\n        return this.getIncircularTriangle().getCircumcircle();\n    }\n    /**\n     * Get the incenter of this triangle (which is the center of the circumcircle).\n     *\n     * Note: due to performance reasonst the incenter is buffered inside the triangle because\n     *       computing it is relatively expensive. If a, b or c have changed you should call the\n     *       calcCircumcircle() function first, otherwise you might get wrong results.\n     * @return Vertex The incenter of this triangle.\n     **/\n    getIncenter() {\n        if (!this.center || !this.radius) {\n            this.calcCircumcircle();\n        }\n        return this.center.clone();\n    }\n    /**\n     * Converts this triangle into a human-readable string.\n     *\n     * @method toString\n     * @return {string}\n     * @instance\n     * @memberof Triangle\n     */\n    toString() {\n        return \"{ a : \" + this.a.toString() + \", b : \" + this.b.toString() + \", c : \" + this.c.toString() + \"}\";\n    }\n    /**\n     * This function should invalidate any installed listeners and invalidate this object.\n     * After calling this function the object might not hold valid data any more and\n     * should not be used.\n     */\n    destroy() {\n        this.a.destroy();\n        this.b.destroy();\n        this.c.destroy();\n        this.isDestroyed = true;\n    }\n}\n/**\n * An epsilon for comparison.\n * This should be the same epsilon as in Vertex.\n *\n * @private\n **/\nTriangle.EPSILON = 1.0e-6;\nTriangle.utils = {\n    // Used in the bounds() function.\n    max3(a, b, c) {\n        return a >= b && a >= c ? a : b >= a && b >= c ? b : c;\n    },\n    min3(a, b, c) {\n        return a <= b && a <= c ? a : b <= a && b <= c ? b : c;\n    },\n    signedArea(p0x, p0y, p1x, p1y, p2x, p2y) {\n        return 0.5 * (-p1y * p2x + p0y * (-p1x + p2x) + p0x * (p1y - p2y) + p1x * p2y);\n    },\n    /**\n     * Used by the containsPoint() function.\n     *\n     * @private\n     **/\n    pointIsInTriangle(px, py, p0x, p0y, p1x, p1y, p2x, p2y) {\n        //\n        // Point-in-Triangle test found at\n        //   http://stackoverflow.com/questions/2049582/how-to-determine-a-point-in-a-2d-triangle\n        // var area : number = 1/2*(-p1y*p2x + p0y*(-p1x + p2x) + p0x*(p1y - p2y) + p1x*p2y);\n        var area = Triangle.utils.signedArea(p0x, p0y, p1x, p1y, p2x, p2y);\n        var s = (1 / (2 * area)) * (p0y * p2x - p0x * p2y + (p2y - p0y) * px + (p0x - p2x) * py);\n        var t = (1 / (2 * area)) * (p0x * p1y - p0y * p1x + (p0y - p1y) * px + (p1x - p0x) * py);\n        return s > 0 && t > 0 && 1 - s - t > 0;\n    },\n    /**\n     * Calculate the determinant of the three vertices a, b and c (in this order).\n     * @param {XYCords} a - The first vertex.\n     * @param {XYCords} b - The first vertex.\n     * @param {XYCords} c - The first vertex.\n     * @returns {nmber}\n     */\n    determinant: (a, b, c) => {\n        return (b.y - a.y) * (c.x - b.x) - (c.y - b.y) * (b.x - a.x);\n    },\n    bounds: (a, b, c) => {\n        return new Bounds(new Vertex(Triangle.utils.min3(a.x, b.x, c.x), Triangle.utils.min3(a.y, b.y, c.y)), new Vertex(Triangle.utils.max3(a.x, b.x, c.x), Triangle.utils.max3(a.y, b.y, c.y)));\n    },\n    /**\n     * Re-compute the circumcircle of this triangle (if the vertices\n     * have changed).\n     *\n     * The circumcenter and radius are stored in this.center and\n     * this.radius. There is a third result: radius_squared (for internal computations).\n     *\n     * @method calcCircumcircle\n     * @return void\n     * @instance\n     * @memberof Triangle\n     */\n    calcCircumcircle: (a, b, c) => {\n        // From\n        //    http://www.exaflop.org/docs/cgafaq/cga1.html\n        const A = b.x - a.x;\n        const B = b.y - a.y;\n        const C = c.x - a.x;\n        const D = c.y - a.y;\n        const E = A * (a.x + b.x) + B * (a.y + b.y);\n        const F = C * (a.x + c.x) + D * (a.y + c.y);\n        const G = 2.0 * (A * (c.y - b.y) - B * (c.x - b.x));\n        let dx, dy;\n        let center;\n        if (Math.abs(G) < Triangle.EPSILON) {\n            // Collinear - find extremes and use the midpoint\n            // const bounds: Bounds = this.bounds();\n            const bounds = Triangle.utils.bounds(a, b, c);\n            center = new Vertex((bounds.min.x + bounds.max.x) / 2, (bounds.min.y + bounds.max.y) / 2);\n            dx = center.x - bounds.min.x;\n            dy = center.y - bounds.min.y;\n        }\n        else {\n            const cx = (D * E - B * F) / G;\n            const cy = (A * F - C * E) / G;\n            center = new Vertex(cx, cy);\n            dx = center.x - a.x;\n            dy = center.y - a.y;\n        }\n        const radius_squared = dx * dx + dy * dy;\n        const radius = Math.sqrt(radius_squared);\n        return { center: center, radius: radius, radius_squared: radius_squared };\n    } // END calcCircumcircle\n};\n//# sourceMappingURL=Triangle.js.map","/**\n * @author   Ikaros Kappler\n * @date     2019-02-03\n * @modified 2021-03-01 Added `wrapMax` function.\n * @modified 2024-11-15 Adding helper function `geomutils.mapAngleTo2PI(number)` for mapping any value into the interval [0,2*PI).\n * @modified 2024-11-22 Adding helper function `geomutils.dotProduct(number)` for calculating the dot product of two vertices (as vectors).\n *\n * @version  1.2.0\n **/\nimport { Line } from \"./Line\";\nimport { Triangle } from \"./Triangle\";\n/**\n * A collection of usefull geometry utilities.\n *\n * @global\n **/\nexport const geomutils = {\n    /**\n     * Map any angle (any numeric value) to [0, Math.PI).\n     *\n     * @param {number} angle - The numeric value to map.\n     * @return {number} The mapped angle inside [0,PI*2].\n     **/\n    mapAngleTo2PI(angle) {\n        // Source: https://forums.codeguru.com/showthread.php?384172-get-angle-into-range-0-2*pi\n        const new_angle = Math.asin(Math.sin(angle));\n        if (Math.cos(angle) < 0) {\n            return Math.PI - new_angle;\n        }\n        else if (new_angle < 0) {\n            return new_angle + 2 * Math.PI;\n        }\n        else {\n            return new_angle;\n        }\n    },\n    /**\n     * Calculate the euclidean distance between two points given by four coordinates (two coordinates each).\n     *\n     * @param {number} x1\n     * @param {number} y1\n     * @param {number} x2\n     * @param {number} y2\n     * @returns {number}\n     */\n    dist4(x1, y1, x2, y2) {\n        return Math.sqrt(Math.pow(x2 - x1, 2) + Math.pow(y1 - y2, 2));\n    },\n    /**\n     * Map any angle (any numeric value) to [0, Math.PI).\n     *\n     * A × B := (A.x * B.x) + (A.y * B.y)\n     *\n     * @param {XYCoords} vertA - The first vertex.\n     * @param {XYCoords} vertB - The second vertex.\n     * @return {number} The dot product of the two vertices.\n     **/\n    dotProduct(vertA, vertB) {\n        return vertA.x * vertB.x + vertA.y * vertB.y;\n    },\n    /**\n     * Compute the n-section of the angle – described as a triangle (A,B,C) – in point A.\n     *\n     * @param {Vertex} pA - The first triangle point.\n     * @param {Vertex} pB - The second triangle point.\n     * @param {Vertex} pC - The third triangle point.\n     * @param {number} n - The number of desired angle sections (example: 2 means the angle will be divided into two sections,\n     *                      means an returned array with length 1, the middle line).\n     *\n     * @return {Line[]} An array of n-1 lines secting the given angle in point A into n equal sized angle sections. The lines' first vertex is A.\n     */\n    nsectAngle(pA, pB, pC, n) {\n        const triangle = new Triangle(pA, pB, pC);\n        const lineAB = new Line(pA, pB);\n        const lineAC = new Line(pA, pC);\n        // Compute the difference; this is the angle between AB and AC\n        var insideAngle = lineAB.angle(lineAC);\n        // We want the inner angles of the triangle, not the outer angle;\n        //   which one is which depends on the triangle 'direction'\n        const clockwise = triangle.determinant() > 0;\n        // For convenience convert the angle [-PI,PI] to [0,2*PI]\n        if (insideAngle < 0)\n            insideAngle = 2 * Math.PI + insideAngle;\n        if (!clockwise)\n            insideAngle = (2 * Math.PI - insideAngle) * -1;\n        // Scale the rotated lines to the max leg length (looks better)\n        const lineLength = Math.max(lineAB.length(), lineAC.length());\n        const scaleFactor = lineLength / lineAB.length();\n        var result = [];\n        for (var i = 1; i < n; i++) {\n            // Compute the i-th inner sector line\n            result.push(new Line(pA, pB.clone().rotate(-i * (insideAngle / n), pA)).scale(scaleFactor));\n        }\n        return result;\n    },\n    /**\n     * Wrap the value (e.g. an angle) into the given range of [0,max).\n     *\n     * @name wrapMax\n     * @param {number} x - The value to wrap.\n     * @param {number} max - The max bound to use for the range.\n     * @return {number} The wrapped value inside the range [0,max).\n     */\n    wrapMax(x, max) {\n        // Found at\n        //    https://stackoverflow.com/questions/4633177/c-how-to-wrap-a-float-to-the-interval-pi-pi\n        return (max + (x % max)) % max;\n    },\n    /**\n     * Wrap the value (e.g. an angle) into the given range of [min,max).\n     *\n     * @name wrapMinMax\n     * @param {number} x - The value to wrap.\n     * @param {number} min - The min bound to use for the range.\n     * @param {number} max - The max bound to use for the range.\n     * @return {number} The wrapped value inside the range [min,max).\n     */\n    // Currently un-used\n    wrapMinMax(x, min, max) {\n        return min + geomutils.wrapMax(x - min, max - min);\n    }\n};\n//# sourceMappingURL=geomutils.js.map","/**\n * @author   Ikaros Kappler\n * @date     2012-10-17\n * @modified 2018-04-03 Refactored the code of october 2012 into a new class.\n * @modified 2018-04-28 Added some documentation.\n * @modified 2018-08-16 Added the set() function.\n * @modified 2018-08-26 Added VertexAttr.\n * @modified 2018-10-31 Extended the constructor by object{x,y}.\n * @modified 2018-11-19 Extended the set(number,number) function to set(Vertex).\n * @modified 2018-11-28 Added 'this' to the VertexAttr constructor.\n * @modified 2018-12-05 Added the sub(...) function. Changed the signature of the add() function! add(Vertex) and add(number,number) are now possible.\n * @modified 2018-12-21 (It's winter solstice) Added the inv()-function.\n * @modified 2019-01-30 Added the setX(Number) and setY(Number) functions.\n * @modified 2019-02-19 Added the difference(Vertex) function.\n * @modified 2019-03-20 Added JSDoc tags.\n * @modified 2019-04-24 Added the randomVertex(ViewPort) function.\n * @modified 2019-11-07 Added toSVGString(object) function.\n * @modified 2019-11-18 Added the rotate(number,Vertex) function.\n * @modified 2019-11-21 Fixed a bug in the rotate(...) function (elements were moved).\n * @modified 2020-03-06 Added functions invX() and invY().\n * @modified 2020-03-23 Ported to Typescript from JS.\n * @modified 2020-05-26 Added functions addX(number) and addY(number).\n * @modified 2020-10-30 Changed the warnings in `sub(...)` and `add(...)` into real errors.\n * @modified 2021-03-01 Changed the second param `center` in the `rotate` function from Vertex to XYCoords.\n * @modified 2021-12-01 Changed the type of param of `scale` to XYCoords.\n * @modified 2021-12-01 Added function `scaleXY` for non uniform scaling.\n * @modified 2021-12-17 Added the functions `lerp` and `lerpAbs` for linear interpolations.\n * @modified 2022-01-31 Added `Vertex.utils.arrayToJSON`.\n * @modified 2022-02-02 Added the `destroy` method.\n * @modified 2022-02-02 Cleared the `Vertex.toSVGString` function (deprecated). Use `drawutilssvg` instead.\n * @modified 2022-11-28 Added the `subXY`, `subX` and `subY` methods to the `Vertex` class.\n * @modified 2023-09-29 Downgraded types for the `Vertex.utils.buildArrowHead` function (replacing Vertex params by more generic XYCoords type).\n * @modified 2023-09-29 Added the `Vertex.abs()` method as it seems useful.\n * @modified 2024-03-08 Added the optional `precision` param to the `toString` method.\n * @modified 2024-12-17 Outsourced the euclidean distance calculation of `Vertex.distance` to `geomutils.dist4`.\n * @modified 2025-03-24 Making the second parameter `center` of the `Vertex.rotate` method optional.\n * @modified 2025-04-13 Adding the `Vertex.move(amount: XYCoords)` method (does the same as `add`, added by naming convention).\n * @modified 2025-05-07 Class `Vertex` is now implementing interface `IBounded` (to meet convention).\n * @modified 2026-06-10 Adding methods `Vertex.findClosestPoint` and `Vertex.findFarestPoint`.\n * @version  2.12.0\n *\n * @file Vertex\n * @public\n **/\nimport { VertexAttr } from \"./VertexAttr\";\nimport { UIDGenerator } from \"./UIDGenerator\";\nimport { VertexListeners } from \"./VertexListeners\";\nimport { geomutils } from \"./geomutils\";\nimport { Bounds } from \"./Bounds\";\n/**\n * @classdesc A vertex is a pair of two numbers.<br>\n * <br>\n * It is used to identify a 2-dimensional point on the x-y-plane.\n *\n * @requires IVertexAttr\n * @requires SVGSerializable\n * @requires UID\n * @requires UIDGenerator\n * @requires VertexAttr\n * @requires VertexListeners\n * @requires XYCoords\n *\n */\nexport class Vertex {\n    /**\n     * The constructor for the vertex class.\n     *\n     * @constructor\n     * @name Vertex\n     * @param {number} x - The x-coordinate of the new vertex.\n     * @param {number} y - The y-coordinate of the new vertex.\n     **/\n    constructor(x, y) {\n        /**\n         * Required to generate proper CSS classes and other class related IDs.\n         **/\n        this.className = \"Vertex\";\n        this.uid = UIDGenerator.next();\n        if (typeof x == \"undefined\") {\n            this.x = 0;\n            this.y = 0;\n        }\n        else if (typeof x == \"number\" && typeof y == \"number\") {\n            this.x = x;\n            this.y = y;\n        }\n        else {\n            const tuple = x;\n            if (typeof tuple.x == \"number\" && typeof tuple.y == \"number\") {\n                this.x = tuple.x;\n                this.y = tuple.y;\n            }\n            else {\n                if (typeof x == \"number\")\n                    this.x = x;\n                else if (typeof x == \"undefined\")\n                    this.x = 0;\n                else\n                    this.x = NaN;\n                if (typeof y == \"number\")\n                    this.y = y;\n                else if (typeof y == \"undefined\")\n                    this.y = 0;\n                else\n                    this.y = NaN;\n            }\n        }\n        this.attr = new VertexAttr();\n        this.listeners = new VertexListeners(this);\n    }\n    /**\n     * Set the x- and y- component of this vertex.\n     *\n     * @method set\n     * @param {number} x - The new x-component.\n     * @param {number} y - The new y-component.\n     * @return {Vertex} this\n     * @instance\n     * @memberof Vertex\n     **/\n    set(x, y) {\n        if (typeof x == \"number\" && typeof y == \"number\") {\n            this.x = x;\n            this.y = y;\n        }\n        else {\n            const tuple = x;\n            if (typeof tuple.x == \"number\" && typeof tuple.y == \"number\") {\n                this.x = tuple.x;\n                this.y = tuple.y;\n            }\n            else {\n                if (typeof x == \"number\")\n                    this.x = x;\n                else if (typeof x == \"undefined\")\n                    this.x = 0;\n                else\n                    this.x = NaN;\n                if (typeof y == \"number\")\n                    this.y = y;\n                else if (typeof y == \"undefined\")\n                    this.y = 0;\n                else\n                    this.y = NaN;\n            }\n        }\n        return this;\n    }\n    /**\n     * Set the x-component of this vertex.\n     *\n     * @method setX\n     * @param {number} x - The new x-component.\n     * @return {Vertex} this\n     * @instance\n     * @memberof Vertex\n     **/\n    setX(x) {\n        this.x = x;\n        return this;\n    }\n    /**\n     * Set the y-component of this vertex.\n     *\n     * @method setY\n     * @param {number} y - The new y-component.\n     * @return {Vertex} this\n     * @instance\n     * @memberof Vertex\n     **/\n    setY(y) {\n        this.y = y;\n        return this;\n    }\n    /**\n     * Set the x-component if this vertex to the inverse of its value.\n     *\n     * @method invX\n     * @return {Vertex} this\n     * @instance\n     * @memberof Vertex\n     **/\n    invX() {\n        this.x = -this.x;\n        return this;\n    }\n    /**\n     * Set the y-component if this vertex to the inverse of its value.\n     *\n     * @method invY\n     * @return {Vertex} this\n     * @instance\n     * @memberof Vertex\n     **/\n    invY() {\n        this.y = -this.y;\n        return this;\n    }\n    /**\n     * Add the passed amount to x- and y- component of this vertex.<br>\n     * <br>\n     * This function works with add( {number}, {number} ) and\n     * add( {Vertex} ), as well.\n     *\n     * @method add\n     * @param {(number|Vertex)} x - The amount to add to x (or a vertex itself).\n     * @param {number=} y - The amount to add to y.\n     * @return {Vertex} this\n     * @instance\n     * @memberof Vertex\n     **/\n    add(x, y) {\n        if (typeof x == \"number\" && typeof y == \"number\") {\n            this.x += x;\n            this.y += y;\n        }\n        else {\n            const tuple = x;\n            if (typeof tuple.x == \"number\" && typeof tuple.y == \"number\") {\n                this.x += tuple.x;\n                this.y += tuple.y;\n            }\n            else {\n                if (typeof x == \"number\")\n                    this.x += x;\n                else\n                    throw `Cannot add ${typeof x} to numeric x component!`;\n                if (typeof y == \"number\")\n                    this.y += y;\n                else\n                    throw `Cannot add ${typeof y} to numeric y component!`;\n            }\n        }\n        return this;\n    }\n    /**\n     * Move this point by the given amount.\n     *\n     * This method just calls `add(amount).\n     *\n     *\n     * @method move\n     * @param {Vertex} amount - The amount to move this vertex.\n     * @return {Vertex} this - For chaining.\n     * @instance\n     * @memberof Vertex\n     */\n    move(amount) {\n        return this.add(amount);\n    }\n    /**\n     * Add the passed amounts to the x- and y- components of this vertex.\n     *\n     * @method addXY\n     * @param {number} x - The amount to add to x.\n     * @param {number} y - The amount to add to y.\n     * @return {Vertex} this\n     * @instance\n     * @memberof Vertex\n     **/\n    addXY(amountX, amountY) {\n        this.x += amountX;\n        this.y += amountY;\n        return this;\n    }\n    /**\n     * Add the passed amounts to the x-component of this vertex.\n     *\n     * @method addX\n     * @param {number} x - The amount to add to x.\n     * @return {Vertex} this\n     * @instance\n     * @memberof Vertex\n     **/\n    addX(amountX) {\n        this.x += amountX;\n        return this;\n    }\n    /**\n     * Add the passed amounts to the y-component of this vertex.\n     *\n     * @method addY\n     * @param {number} y - The amount to add to y.\n     * @return {Vertex} this\n     * @instance\n     * @memberof Vertex\n     **/\n    addY(amountY) {\n        this.y += amountY;\n        return this;\n    }\n    /**\n     * Substract the passed amount from x- and y- component of this vertex.<br>\n     * <br>\n     * This function works with sub( {number}, {number} ) and\n     * sub( {Vertex} ), as well.\n     *\n     * @method sub\n     * @param {(number|Vertex)} x - The amount to substract from x (or a vertex itself).\n     * @param {number=} y - The amount to substract from y.\n     * @return {Vertex} this\n     * @instance\n     * @memberof Vertex\n     **/\n    sub(x, y) {\n        if (typeof x == \"number\" && typeof y == \"number\") {\n            this.x -= x;\n            this.y -= y;\n        }\n        else {\n            const tuple = x;\n            if (typeof tuple.x == \"number\" && typeof tuple.y == \"number\") {\n                this.x -= tuple.x;\n                this.y -= tuple.y;\n            }\n            else {\n                if (typeof x == \"number\")\n                    this.x -= x;\n                else\n                    throw `Cannot add ${typeof x} to numeric x component!`;\n                if (typeof y == \"number\")\n                    this.y -= y;\n                else\n                    throw `Cannot add ${typeof y} to numeric y component!`;\n            }\n        }\n        return this;\n    }\n    /**\n     * Substract the passed amounts from the x- and y- components of this vertex.\n     *\n     * @method subXY\n     * @param {number} x - The amount to substract from x.\n     * @param {number} y - The amount to substract from y.\n     * @return {Vertex} this\n     * @instance\n     * @memberof Vertex\n     **/\n    subXY(amountX, amountY) {\n        this.x -= amountX;\n        this.y -= amountY;\n        return this;\n    }\n    /**\n     * Substract the passed amounts from the x-component of this vertex.\n     *\n     * @method addX\n     * @param {number} x - The amount to substract from x.\n     * @return {Vertex} this\n     * @instance\n     * @memberof Vertex\n     **/\n    subX(amountX) {\n        this.x -= amountX;\n        return this;\n    }\n    /**\n     * Substract the passed amounts from the y-component of this vertex.\n     *\n     * @method subY\n     * @param {number} y - The amount to substract from y.\n     * @return {Vertex} this\n     * @instance\n     * @memberof Vertex\n     **/\n    subY(amountY) {\n        this.y -= amountY;\n        return this;\n    }\n    /**\n     * Check if this vertex equals the passed one.\n     * <br>\n     * This function uses an internal epsilon as tolerance.\n     *\n     * @method equals\n     * @param {Vertex} vertex - The vertex to compare this with.\n     * @return {boolean}\n     * @instance\n     * @memberof Vertex\n     **/\n    equals(vertex) {\n        var eqX = Math.abs(this.x - vertex.x) < Vertex.EPSILON;\n        var eqY = Math.abs(this.y - vertex.y) < Vertex.EPSILON;\n        var result = eqX && eqY;\n        return result;\n    }\n    /**\n     * Create a copy of this vertex.\n     *\n     * @method clone\n     * @return {Vertex} A new vertex, an exact copy of this.\n     * @instance\n     * @memberof Vertex\n     **/\n    clone() {\n        return new Vertex(this.x, this.y);\n    }\n    /**\n     * Get the distance to the passed point (in euclidean metric)\n     *\n     * @method distance\n     * @param {XYCoords} vert - The vertex to measure the distance to.\n     * @return {number}\n     * @instance\n     * @memberof Vertex\n     **/\n    distance(vert) {\n        // return Math.sqrt(Math.pow(vert.x - this.x, 2) + Math.pow(vert.y - this.y, 2));\n        return geomutils.dist4(this.x, this.y, vert.x, vert.y);\n    }\n    /**\n     * Get the angle of this point (relative to (0,0) or to the given other origin point).\n     *\n     * @method angle\n     * @param {XYCoords} origin - The vertex to measure the angle from.\n     * @return {number}\n     * @instance\n     * @memberof Vertex\n     **/\n    angle(origin) {\n        const a = typeof origin === \"undefined\"\n            ? Math.PI / 2 - Math.atan2(this.x, this.y)\n            : Math.PI / 2 - Math.atan2(origin.x - this.x, origin.y - this.y);\n        // Map to positive value\n        return a < 0 ? Math.PI * 2 + a : a;\n    }\n    /**\n     * Get the difference to the passed point.<br>\n     * <br>\n     * The difference is (vert.x-this.x, vert.y-this.y).\n     *\n     * @method difference\n     * @param {Vertex} vert - The vertex to measure the x-y-difference to.\n     * @return {Vertex} A new vertex.\n     * @instance\n     * @memberof Vertex\n     **/\n    difference(vert) {\n        return new Vertex(vert.x - this.x, vert.y - this.y);\n    }\n    /**\n     * This is a vector-like behavior and 'scales' this vertex\n     * towards/from a given center by one uniform scale factor.\n     *\n     * @method scale\n     * @param {number} factor - The factor to 'scale' this vertex; 1.0 means no change.\n     * @param {XYCoords=} center - The origin of scaling; default is (0,0).\n     * @return {Vertex} this\n     * @instance\n     * @memberof Vertex\n     **/\n    scale(factor, center) {\n        return this.scaleXY({ x: factor, y: factor }, center);\n    }\n    /**\n     * Perform a linear interpolation towards the given target vertex.\n     * The amount value `t` is relative, `t=0.0` means no change, `t=1.0`\n     * means this point will be moved to the exact target position.\n     *\n     * `t=0.5` will move this point to the middle of the connecting\n     * linear segment.\n     *\n     * @param {XYCoords} target - The target position to lerp this vertex to.\n     * @param {number} t - The relative amount, usually in [0..1], but other values will work, too.\n     * @returns\n     */\n    lerp(target, t) {\n        var diff = this.difference(target);\n        // return new Vertex(this.x + diff.x * t, this.y + diff.y * t);\n        this.x += diff.x * t;\n        this.y += diff.y * t;\n        return this;\n    }\n    /**\n     * Perform a linear interpolation towards the given target vertex (absolute variant).\n     * The amount value `t` is absolute, which means the lerp amount is a direct distance\n     * value. This point will have move the amount of the passed distance `u`.\n     *\n     * @param {XYCoords} target - The target position to lerp this vertex to.\n     * @param {number} t - The absolute move amount to use to lerping.\n     * @returns\n     */\n    lerpAbs(target, u) {\n        var dist = this.distance(target);\n        var diff = this.difference(target);\n        var step = { x: diff.x / dist, y: diff.y / dist };\n        // return new Vertex(this.x + step.x * u, this.y + step.y * u);\n        this.x += step.x * u;\n        this.y += step.y * u;\n        return this;\n    }\n    /**\n     * This is a vector-like behavior and 'scales' this vertex\n     * towards/from a given center by two independent x- and y- scale factors.\n     *\n     * @method scale\n     * @param {number} factor - The factor to 'scale' this vertex; 1.0 means no change.\n     * @param {XYCoords=} center - The origin of scaling; default is (0,0).\n     * @return {Vertex} this\n     * @instance\n     * @memberof Vertex\n     **/\n    scaleXY(factors, center) {\n        if (!center || typeof center === \"undefined\") {\n            center = { x: 0, y: 0 };\n        }\n        this.x = center.x + (this.x - center.x) * factors.x;\n        this.y = center.y + (this.y - center.y) * factors.y;\n        return this;\n    }\n    /**\n     * This is a vector-like behavior and 'rotates' this vertex\n     * around given center.\n     *\n     * @method rotate\n     * @param {number} angle - The angle to 'rotate' this vertex; 0.0 means no change.\n     * @param {XYCoords=} center - The center of rotation; default is (0,0).\n     * @return {Vertex} this\n     * @instance\n     * @memberof Vertex\n     **/\n    rotate(angle, center) {\n        if (!center || typeof center === \"undefined\") {\n            center = { x: 0, y: 0 };\n        }\n        this.sub(center);\n        angle += Math.atan2(this.y, this.x);\n        let len = this.distance(Vertex.ZERO); // {x:0,y:0});\n        this.x = len * Math.cos(angle);\n        this.y = len * Math.sin(angle);\n        this.add(center);\n        return this;\n    }\n    /**\n     * Multiply both components of this vertex with the given scalar.<br>\n     * <br>\n     * Note: as in<br>\n     *    https://threejs.org/docs/#api/math/Vector2.multiplyScalar\n     *\n     * @method multiplyScalar\n     * @param {number} scalar - The scale factor; 1.0 means no change.\n     * @return {Vertex} this\n     * @instance\n     * @memberof Vertex\n     **/\n    multiplyScalar(scalar) {\n        this.x *= scalar;\n        this.y *= scalar;\n        return this;\n    }\n    /**\n     * Round the two components x and y of this vertex.\n     *\n     * @method round\n     * @return {Vertex} this\n     * @instance\n     * @memberof Vertex\n     **/\n    round() {\n        this.x = Math.round(this.x);\n        this.y = Math.round(this.y);\n        return this;\n    }\n    /**\n     * Change this vertex (x,y) to its inverse (-x,-y).\n     *\n     * @method inv\n     * @return {Vertex} this\n     * @instance\n     * @memberof Vertex\n     **/\n    inv() {\n        this.x = -this.x;\n        this.y = -this.y;\n        return this;\n    }\n    /**\n     * Set both coordinates of this vertex to their absolute value (abs(x), abs(y)).\n     *\n     * @method abs\n     * @return {Vertex} this\n     * @instance\n     * @memberof Vertex\n     */\n    abs() {\n        this.x = Math.abs(this.x);\n        this.y = Math.abs(this.y);\n        return this;\n    }\n    //--- BEGIN --- Implement interface `IBounded`\n    /**\n     * Get the bounding box (bounds) of this Vertex.\n     * This is just by convention – any vertex is just a position without any useful with or height (0).\n     *\n     * @method getBounds\n     * @instance\n     * @memberof Vertex\n     * @return {Bounds} The rectangular bounds of this Vertex (width and height are zero).\n     **/\n    getBounds() {\n        // return Bounds.computeFromVertices([this.a, this.b, this.c]);\n        return Bounds.computeFromVertices([this]);\n    }\n    //--- END --- Implement interface `IBounded`\n    /**\n     * Find the one of two given points that's closest to this point.\n     *\n     * @method findClosestPoint\n     * @instance\n     * @memberof Vertex\n     * @param {XYCoords | Vertex} pointA\n     * @param {XYCoords | Vertex} pointB\n     * @returns  {XYCoords | Vertex}\n     */\n    findClosestPoint(pointA, pointB) {\n        // TODO: put this implementation to geomutils?\n        var distA = this.distance(pointA);\n        var distB = this.distance(pointB);\n        if (distA < distB) {\n            return pointA;\n        }\n        else {\n            return pointB;\n        }\n    }\n    /**\n     * Find the one of two given points that's farest from this point.\n     *\n     * @method findFarestPoint\n     * @instance\n     * @memberof Vertex\n     * @param {XYCoords | Vertex} pointA\n     * @param {XYCoords | Vertex} pointB\n     * @returns  {XYCoords | Vertex}\n     */\n    findFarestPoint(pointA, pointB) {\n        var distA = this.distance(pointA);\n        var distB = this.distance(pointB);\n        if (distA > distB) {\n            return pointA;\n        }\n        else {\n            return pointB;\n        }\n    }\n    /**\n     * Get a string representation of this vertex.\n     *\n     * @method toString\n     * @return {string} The string representation of this vertex.\n     * @instance\n     * @memberof Vertex\n     **/\n    toString(precision) {\n        if (typeof precision === \"undefined\") {\n            return \"(\" + this.x + \",\" + this.y + \")\";\n        }\n        else {\n            return \"(\" + this.x.toFixed(precision) + \",\" + this.y.toFixed(precision) + \")\";\n        }\n    }\n    /**\n     * This function should invalidate any installed listeners and invalidate this object.\n     * After calling this function the object might not hold valid data any more and\n     * should not be used.\n     */\n    destroy() {\n        this.listeners.removeAllListeners();\n        this.isDestroyed = true;\n    }\n    /**\n     * Create a new random vertex inside the given viewport.\n     *\n     * @param {ViewPort} viewPort - A {min:Vertex, max:Vertex} viewport specifying the bounds.\n     * @return A new vertex with a random position.\n     **/\n    static randomVertex(viewPort) {\n        return new Vertex(viewPort.min.x + Math.random() * (viewPort.max.x - viewPort.min.x), viewPort.min.y + Math.random() * (viewPort.max.y - viewPort.min.y));\n    }\n}\nVertex.ZERO = new Vertex(0, 0);\n/**\n * An epsilon for comparison\n *\n * @private\n * @readonly\n **/\nVertex.EPSILON = 1.0e-6;\nVertex.utils = {\n    /**\n     * Generate a four-point arrow head, starting at the vector end minus the\n     * arrow head length.\n     *\n     * The first vertex in the returned array is guaranteed to be the located\n     * at the vector line end minus the arrow head length.\n     *\n     *\n     * Due to performance all params are required.\n     *\n     * The params scaleX and scaleY are required for the case that the scaling is not uniform (x and y\n     * scaling different). Arrow heads should not look distored on non-uniform scaling.\n     *\n     * If unsure use 1.0 for scaleX and scaleY (=no distortion).\n     * For headlen use 8, it's a good arrow head size.\n     *\n     * Example:\n     *    buildArrowHead( new Vertex(0,0), new Vertex(50,100), 8, 1.0, 1.0 )\n     *\n     * @param {XYCoords} zA - The start vertex of the vector to calculate the arrow head for.\n     * @param {XYCoords} zB - The end vertex of the vector.\n     * @param {number} headlen - The length of the arrow head (along the vector direction. A good value is 12).\n     * @param {number} scaleX  - The horizontal scaling during draw.\n     * @param {number} scaleY  - the vertical scaling during draw.\n     **/\n    // @DEPRECATED: use Vector.utils.buildArrowHead instead!!!\n    buildArrowHead: (zA, zB, headlen, scaleX, scaleY) => {\n        console.warn(\"[DEPRECATION] Vertex.utils.buildArrowHead is deprecated. Please use Vector.utils.buildArrowHead instead.\");\n        var angle = Math.atan2((zB.y - zA.y) * scaleY, (zB.x - zA.x) * scaleX);\n        var vertices = [];\n        vertices.push(new Vertex(zB.x * scaleX - headlen * Math.cos(angle), zB.y * scaleY - headlen * Math.sin(angle)));\n        vertices.push(new Vertex(zB.x * scaleX - headlen * 1.35 * Math.cos(angle - Math.PI / 8), zB.y * scaleY - headlen * 1.35 * Math.sin(angle - Math.PI / 8)));\n        vertices.push(new Vertex(zB.x * scaleX, zB.y * scaleY));\n        vertices.push(new Vertex(zB.x * scaleX - headlen * 1.35 * Math.cos(angle + Math.PI / 8), zB.y * scaleY - headlen * 1.35 * Math.sin(angle + Math.PI / 8)));\n        return vertices;\n    },\n    /**\n     * Convert the given vertices (array) to a JSON string.\n     *\n     * @param {number?} precision - (optional) The numeric precision to be used (number of precision digits).\n     * @returns {string}\n     */\n    arrayToJSON: (vertices, precision) => {\n        return JSON.stringify(vertices.map(function (vert) {\n            return typeof precision === undefined\n                ? { x: vert.x, y: vert.y }\n                : { x: Number(vert.x.toFixed(precision)), y: Number(vert.y.toFixed(precision)) };\n        }));\n    }\n};\n//# sourceMappingURL=Vertex.js.map","/**\n * @author Ikaros Kappler\n * @date   2020-03-24\n * @modified 2020-05-04 Fixed a serious bug in the pointDistance function.\n * @modified 2020-05-12 The angle(line) param was still not optional. Changed that.\n * @modified 2020-11-11 Generalized the `add` and `sub` param from `Vertex` to `XYCoords`.\n * @modified 2020-12-04 Changed`vtutils.dist2` params from `Vertex` to `XYCoords` (generalized).\n * @modified 2020-12-04 Changed `getClosestT` param from `Vertex` to `XYCoords` (generalized).\n * @modified 2020-12-04 Added the `hasPoint(XYCoords)` function.\n * @modified 2021-01-20 Added UID.\n * @modified 2022-02-02 Added the `destroy` method.\n * @modified 2023-09-29 Fixed a calculation error in the VertTuple.hasPoint() function; distance measure was broken!\n * @modified 2024-09-10 Chaging the first param of `pointDistance` from `Vertex` to less strict type `XYCoords`. This should not break anything.\n * @modified 2024-09-10 Adding the optional `epsilon` param to the `hasPoint` method.\n * @modified 2024-12-02 Added the `epsilon` param to the `colinear` method. Default is 1.0e-6.\n * @modified 2025-03-31 Added the `VertTuple.revert` method.\n * @modified 2025-04-15 Changed param of `VertTuple.moveTo` method from `Vertex` to `XYCoords`.\n * @modified 2025-04-15 Added method `VertTuple.move` method.\n * @modified 2026-06-10 Adding helper function `VertTuple.utils.calcCircumcircle`.\n * @version 1.5.0\n */\nimport { Vertex } from \"./Vertex\";\nimport { UIDGenerator } from \"./UIDGenerator\";\n/**\n * @classdesc An abstract base classes for vertex tuple constructs, like Lines or Vectors.\n * @abstract\n * @requires UID\n * @requires Vertex\n * @requires XYCoords\n */\nexport class VertTuple {\n    /**\n     * Creates an instance.\n     *\n     * @constructor\n     * @name VertTuple\n     * @param {Vertex} a The tuple's first point.\n     * @param {Vertex} b The tuple's second point.\n     **/\n    constructor(a, b, factory) {\n        this.uid = UIDGenerator.next();\n        this.a = a;\n        this.b = b;\n        this.factory = factory;\n    }\n    /**\n     * Get the length of this line.\n     *\n     * @method length\n     * @instance\n     * @memberof VertTuple\n     **/\n    length() {\n        return Math.sqrt(Math.pow(this.b.x - this.a.x, 2) + Math.pow(this.b.y - this.a.y, 2));\n    }\n    /**\n     * Set the length of this vector to the given amount. This only works if this\n     * vector is not a null vector.\n     *\n     * @method setLength\n     * @param {number} length - The desired length.\n     * @memberof VertTuple\n     * @return {T} this (for chaining)\n     **/\n    setLength(length) {\n        return this.scale(length / this.length());\n    }\n    /**\n     * Substract the given vertex from this line's end points.\n     *\n     * @method sub\n     * @param {XYCoords} amount The amount (x,y) to substract.\n     * @return {VertTuple} this\n     * @instance\n     * @memberof VertTuple\n     **/\n    sub(amount) {\n        this.a.sub(amount);\n        this.b.sub(amount);\n        return this;\n    }\n    /**\n     * Add the given vertex to this line's end points.\n     *\n     * @method add\n     * @param {XYCoords} amount The amount (x,y) to add.\n     * @instance\n     * @memberof VertTuple\n     * @return {VertTuple<T>} this\n     **/\n    add(amount) {\n        this.a.add(amount);\n        this.b.add(amount);\n        return this;\n    }\n    /**\n     * Reverse this vertex tuple: a becomes b, and b becomes a.\n     * This operation is in-place.\n     *\n     * @method add\n     * @param {XYCoords} amount The amount (x,y) to add.\n     * @instance\n     * @memberof VertTuple\n     * @return {VertTuple<T>} this\n     */\n    revert() {\n        const tmp = this.a;\n        this.a = this.b;\n        this.b = tmp;\n        return this;\n    }\n    /**\n     * Normalize this line (set to length 1).\n     *\n     * @method normalize\n     * @return {VertTuple} this\n     * @instance\n     * @memberof VertTuple\n     **/\n    normalize() {\n        this.b.set(this.a.x + (this.b.x - this.a.x) / this.length(), this.a.y + (this.b.y - this.a.y) / this.length());\n        return this;\n    }\n    /**\n     * Scale this line by the given factor.\n     *\n     * @method scale\n     * @param {number} factor The factor for scaling (1.0 means no scale).\n     * @return {VertTuple} this\n     * @instance\n     * @memberof VertTuple\n     **/\n    scale(factor) {\n        this.b.set(this.a.x + (this.b.x - this.a.x) * factor, this.a.y + (this.b.y - this.a.y) * factor);\n        return this;\n    }\n    /**\n     * Move this line to a new location.\n     *\n     * @method moveTo\n     * @param {XYCoords} newA - The new desired location of 'a'. Vertex 'b' will be moved, too.\n     * @return {VertTuple} this\n     * @instance\n     * @memberof VertTuple\n     **/\n    moveTo(newA) {\n        let diff = this.a.difference(newA);\n        this.a.add(diff);\n        this.b.add(diff);\n        return this;\n    }\n    /**\n     * Move this line by the given amount\n     *\n     * @method move\n     * @param {XYCoords} amount - The amount to move both point of this tuple.\n     * @return {VertTuple} this\n     * @instance\n     * @memberof VertTuple\n     **/\n    move(amount) {\n        this.a.add(amount);\n        this.b.add(amount);\n        return this;\n    }\n    /**\n     * Get the angle between this and the passed line (in radians).\n     *\n     * @method angle\n     * @param {VertTuple} line - (optional) The line to calculate the angle to. If null the baseline (x-axis) will be used.\n     * @return {number} this\n     * @instance\n     * @memberof VertTuple\n     **/\n    angle(line) {\n        if (line == null || typeof line == \"undefined\") {\n            line = this.factory(new Vertex(0, 0), new Vertex(100, 0));\n        }\n        // Compute the angle from x axis and the return the difference :)\n        const v0 = this.b.clone().sub(this.a);\n        const v1 = line.b.clone().sub(line.a);\n        // Thank you, Javascript, for this second atan function. No additional math is needed here!\n        // The result might be negative, but isn't it usually nicer to determine angles in positive values only?\n        return Math.atan2(v1.x, v1.y) - Math.atan2(v0.x, v0.y);\n    }\n    /**\n     * Get line point at position t in [0 ... 1]:<br>\n     * <pre>[P(0)]=[A]--------------------[P(t)]------[B]=[P(1)]</pre><br>\n     * <br>\n     * The counterpart of this function is Line.getClosestT(Vertex).\n     *\n     * @method vertAt\n     * @param {number} t The position scalar.\n     * @return {Vertex} The vertex a position t.\n     * @instance\n     * @memberof VertTuple\n     **/\n    vertAt(t) {\n        return new Vertex(this.a.x + (this.b.x - this.a.x) * t, this.a.y + (this.b.y - this.a.y) * t);\n    }\n    /**\n     * Get the denominator of this and the given line.\n     *\n     * If the denominator is zero (or close to zero) both line are co-linear.\n     *\n     * @method denominator\n     * @param {VertTuple} line\n     * @instance\n     * @memberof VertTuple\n     * @return {Number}\n     **/\n    denominator(line) {\n        // http://jsfiddle.net/justin_c_rounds/Gd2S2/\n        return (line.b.y - line.a.y) * (this.b.x - this.a.x) - (line.b.x - line.a.x) * (this.b.y - this.a.y);\n    }\n    /**\n     * Checks if this and the given line are co-linear.\n     *\n     * The constant Vertex.EPSILON is used for tolerance.\n     *\n     * @method colinear\n     * @param {VertTuple} line\n     * @param {epsilon?=1.0e-6} epsilon - The epsilon to use (default is 1.0e-6).\n     * @instance\n     * @memberof VertTuple\n     * @return true if both lines are co-linear.\n     */\n    colinear(line, epsilon) {\n        return Math.abs(this.denominator(line)) < (typeof epsilon === \"undefined\" ? Vertex.EPSILON : epsilon);\n    }\n    /**\n     * Get the closest position T from this line to the specified point.\n     *\n     * The counterpart for this function is Line.vertAt(Number).\n     *\n     * @name getClosetT\n     * @method getClosestT\n     * @param {XYCoords} p The point (vertex) to measure the distance to.\n     * @return {number} The line position t of minimal distance to p.\n     * @instance\n     * @memberof VertTuple\n     **/\n    getClosestT(p) {\n        var l2 = VertTuple.vtutils.dist2(this.a, this.b);\n        if (l2 === 0)\n            return 0;\n        var t = ((p.x - this.a.x) * (this.b.x - this.a.x) + (p.y - this.a.y) * (this.b.y - this.a.y)) / l2;\n        // Do not wrap to [0,1] here.\n        // Other results are of interest, too.\n        // t = Math.max(0, Math.min(1, t));\n        return t;\n    }\n    /**\n     * Check if the given point is located on this line. Optionally also check if\n     * that point is located between point `a` and `b`.\n     *\n     * @method hasPoint\n     * @param {Vertex} point - The point to check.\n     * @param {boolean=} insideBoundsOnly - [optional] If set to to true (default=false) the point must be between start and end point of the line.\n     * @param {number=Vertex.EPSILON} epsilon - [optional] A tolerance.\n     * @return {boolean} True if the given point is on this line.\n     * @instance\n     * @memberof VertTuple\n     */\n    hasPoint(point, insideBoundsOnly, epsilon) {\n        const t = this.getClosestT(point);\n        // Compare to pointDistance?\n        const distance = Math.sqrt(VertTuple.vtutils.dist2(point, this.vertAt(t)));\n        if (typeof insideBoundsOnly !== \"undefined\" && insideBoundsOnly) {\n            return distance < (epsilon !== null && epsilon !== void 0 ? epsilon : Vertex.EPSILON) && t >= 0 && t <= 1;\n        }\n        else {\n            return distance < (epsilon !== null && epsilon !== void 0 ? epsilon : Vertex.EPSILON); // t >= 0 && t <= 1;\n        }\n    }\n    /**\n     * Get the closest point on this line to the specified point.\n     *\n     * @method getClosestPoint\n     * @param {Vertex} p The point (vertex) to measre the distance to.\n     * @return {Vertex} The point on the line that is closest to p.\n     * @instance\n     * @memberof VertTuple\n     **/\n    getClosestPoint(p) {\n        var t = this.getClosestT(p);\n        return this.vertAt(t);\n    }\n    /**\n     * The the minimal distance between this line and the specified point.\n     *\n     * @method pointDistance\n     * @param {XYCoords} p The point (vertex) to measre the distance to.\n     * @return {number} The absolute minimal distance.\n     * @instance\n     * @memberof VertTuple\n     **/\n    pointDistance(p) {\n        // Taken From:\n        // https://stackoverflow.com/questions/849211/shortest-distance-between-a-point-and-a-line-segment\n        return Math.sqrt(VertTuple.vtutils.dist2(p, this.vertAt(this.getClosestT(p))));\n    }\n    /**\n     * Create a deep clone of this instance.\n     *\n     * @method cloneLine\n     * @return {T} A type safe clone if this instance.\n     * @instance\n     * @memberof VertTuple\n     **/\n    clone() {\n        return this.factory(this.a.clone(), this.b.clone());\n    }\n    /**\n     * Create a string representation of this line.\n     *\n     * @method totring\n     * @return {string} The string representing this line.\n     * @instance\n     * @memberof VertTuple\n     **/\n    toString() {\n        return \"{ a : \" + this.a.toString() + \", b : \" + this.b.toString() + \" }\";\n    }\n    /**\n     * This function should invalidate any installed listeners and invalidate this object.\n     * After calling this function the object might not hold valid data any more and\n     * should not be used.\n     */\n    destroy() {\n        this.a.destroy();\n        this.b.destroy();\n        this.isDestroyed = true;\n    }\n}\n/**\n * @private\n **/\nVertTuple.vtutils = {\n    dist2: (v, w) => {\n        return (v.x - w.x) * (v.x - w.x) + (v.y - w.y) * (v.y - w.y);\n    },\n    calcCircumcircle: (p1, p2) => {\n        const p1x = p1.x, p1y = p1.y, p2x = p2.x, p2y = p2.y, cx = 0.5 * (p1x + p2x), cy = 0.5 * (p1y + p2y);\n        return { center: { x: cx, y: cy }, radius: Math.sqrt((p1x - cx) * (p1x - cx) + (p1y - cy) * (p1y - cy)) };\n    }\n};\n//# sourceMappingURL=VertTuple.js.map","/**\n * @author   Ikaros Kappler\n * @date     2019-01-30\n * @modified 2019-02-23 Added the toSVGString function, overriding Line.toSVGString.\n * @modified 2019-03-20 Added JSDoc tags.\n * @modified 2019-04-19 Added the clone function (overriding Line.clone()).\n * @modified 2019-09-02 Added the Vector.perp() function.\n * @modified 2019-09-02 Added the Vector.inverse() function.\n * @modified 2019-12-04 Added the Vector.inv() function.\n * @modified 2020-03-23 Ported to Typescript from JS.\n * @modified 2021-01-20 Added UID.\n * @modified 2022-02-02 Added the `destroy` method.\n * @modified 2022-02-02 Cleared the `Vector.toSVGString` function (deprecated). Use `drawutilssvg` instead.\n * @modified 2022-10-25 Added the `getOrthogonal` method.\n * @modified 2025-04-14 Added the `Vector.rotate(number)` method.\n * @version  1.6.0\n *\n * @file Vector\n * @public\n **/\nimport { VertTuple } from \"./VertTuple\";\nimport { Vertex } from \"./Vertex\";\n/**\n * @classdesc A vector (Vertex,Vertex) is a line with a visible direction.<br>\n *            <br>\n *            Vectors are drawn with an arrow at their end point.<br>\n *            <b>The Vector class extends the Line class.</b>\n *\n * @requires VertTuple\n * @requires Vertex\n **/\nexport class Vector extends VertTuple {\n    /**\n     * The constructor.\n     *\n     * @constructor\n     * @name Vector\n     * @extends Line\n     * @param {Vertex} vertA - The start vertex of the vector.\n     * @param {Vertex} vertB - The end vertex of the vector.\n     **/\n    constructor(vertA, vertB) {\n        super(vertA, vertB, (a, b) => new Vector(a, b));\n        /**\n         * Required to generate proper CSS classes and other class related IDs.\n         **/\n        this.className = \"Vector\";\n    }\n    /**\n     * Get the perpendicular of this vector which is located at a.\n     *\n     * @return {Vector} A new vector being the perpendicular of this vector sitting on a.\n     **/\n    perp() {\n        var v = this.clone();\n        v.sub(this.a);\n        v = new Vector(new Vertex(), new Vertex(-v.b.y, v.b.x));\n        v.a.add(this.a);\n        v.b.add(this.a);\n        return v;\n    }\n    /**\n     * The inverse of a vector is a vector with the same magnitude but oppose direction.\n     *\n     * Please not that the origin of this vector changes here: a->b becomes b->a.\n     *\n     * @return {Vector}\n     **/\n    inverse() {\n        var tmp = this.a;\n        this.a = this.b;\n        this.b = tmp;\n        return this;\n    }\n    /**\n     * This function computes the inverse of the vector, which means 'a' stays untouched.\n     *\n     * @return {Vector} this for chaining.\n     **/\n    inv() {\n        this.b.x = this.a.x - (this.b.x - this.a.x);\n        this.b.y = this.a.y - (this.b.y - this.a.y);\n        return this;\n    }\n    /**\n     * Get the intersection if this vector and the specified vector.\n     *\n     * @method intersection\n     * @param {Vector} line The second vector.\n     * @return {Vertex} The intersection (may lie outside the end-points).\n     * @instance\n     * @memberof Line\n     **/\n    intersection(line) {\n        var denominator = this.denominator(line);\n        if (denominator == 0)\n            return null;\n        var a = this.a.y - line.a.y;\n        var b = this.a.x - line.a.x;\n        var numerator1 = (line.b.x - line.a.x) * a - (line.b.y - line.a.y) * b;\n        var numerator2 = (this.b.x - this.a.x) * a - (this.b.y - this.a.y) * b;\n        a = numerator1 / denominator; // NaN if parallel lines\n        b = numerator2 / denominator;\n        // TODO:\n        // FOR A VECTOR THE LINE-INTERSECTION MUST BE ON BOTH VECTORS\n        // if we cast these lines infinitely in both directions, they intersect here:\n        return new Vertex(this.a.x + a * (this.b.x - this.a.x), this.a.y + a * (this.b.y - this.a.y));\n    }\n    /**\n     * Get the orthogonal \"vector\" of this vector (rotated by 90° clockwise).\n     *\n     * @name getOrthogonal\n     * @method getOrthogonal\n     * @return {Vector} A new vector with the same length that stands on this vector's point a.\n     * @instance\n     * @memberof Vector\n     **/\n    getOrthogonal() {\n        // Orthogonal of vector (0,0)->(x,y) is (0,0)->(-y,x)\n        const linePoint = this.a.clone();\n        const startPoint = this.b.clone().sub(this.a);\n        const tmp = startPoint.x;\n        startPoint.x = -startPoint.y;\n        startPoint.y = tmp;\n        return new Vector(linePoint, startPoint.add(this.a));\n    }\n    /**\n     * Rotate this vector by the given angle around the first point `a`.\n     *\n     * @name rotate\n     * @method rotate\n     * @return {Vector} this - for chaining.\n     * @instance\n     * @memberof Vector\n     */\n    rotate(angle) {\n        this.b.rotate(angle, this.a);\n        return this;\n    }\n}\nVector.utils = {\n    /**\n     * Generate a four-point arrow head, starting at the vector end minus the\n     * arrow head length.\n     *\n     * The first vertex in the returned array is guaranteed to be the located\n     * at the vector line end minus the arrow head length.\n     *\n     *\n     * Due to performance all params are required.\n     *\n     * The params scaleX and scaleY are required for the case that the scaling is not uniform (x and y\n     * scaling different). Arrow heads should not look distored on non-uniform scaling.\n     *\n     * If unsure use 1.0 for scaleX and scaleY (=no distortion).\n     * For headlen use 8, it's a good arrow head size.\n     *\n     * Example:\n     *    buildArrowHead( new Vertex(0,0), new Vertex(50,100), 8, 1.0, 1.0 )\n     *\n     * @param {XYCoords} zA - The start vertex of the vector to calculate the arrow head for.\n     * @param {XYCoords} zB - The end vertex of the vector.\n     * @param {number} headlen - The length of the arrow head (along the vector direction. A good value is 12).\n     * @param {number} scaleX  - The horizontal scaling during draw.\n     * @param {number} scaleY  - the vertical scaling during draw.\n     **/\n    buildArrowHead: (zA, zB, headlen, scaleX, scaleY) => {\n        const angle = Math.atan2((zB.y - zA.y) * scaleY, (zB.x - zA.x) * scaleX);\n        const vertices = [];\n        vertices.push(new Vertex(zB.x * scaleX - headlen * Math.cos(angle), zB.y * scaleY - headlen * Math.sin(angle)));\n        vertices.push(new Vertex(zB.x * scaleX - headlen * 1.35 * Math.cos(angle - Math.PI / 8), zB.y * scaleY - headlen * 1.35 * Math.sin(angle - Math.PI / 8)));\n        vertices.push(new Vertex(zB.x * scaleX, zB.y * scaleY));\n        vertices.push(new Vertex(zB.x * scaleX - headlen * 1.35 * Math.cos(angle + Math.PI / 8), zB.y * scaleY - headlen * 1.35 * Math.sin(angle + Math.PI / 8)));\n        return vertices;\n    }\n};\n//# sourceMappingURL=Vector.js.map","/**\n * @author   Ikaros Kappler\n * @date     2016-03-12\n * @modified 2018-12-05 Refactored the code from the morley-triangle script.\n * @modified 2019-03-20 Added JSDoc tags.\n * @modified 2019-04-28 Fixed a bug in the Line.sub( Vertex ) function (was not working).\n * @modified 2019-09-02 Added the Line.add( Vertex ) function.\n * @modified 2019-09-02 Added the Line.denominator( Line ) function.\n * @modified 2019-09-02 Added the Line.colinear( Line ) function.\n * @modified 2019-09-02 Fixed an error in the Line.intersection( Line ) function (class Point was renamed to Vertex).\n * @modified 2019-12-15 Added the Line.moveTo(Vertex) function.\n * @modified 2020-03-16 The Line.angle(Line) parameter is now optional. The baseline (x-axis) will be used if not defined.\n * @modified 2020-03-23 Ported to Typescript from JS.\n * @modified 2020-12-04 The `intersection` function returns undefined if both lines are parallel.\n * @modified 2022-02-02 Added the `destroy` method.\n * @modified 2022-10-09 Changed the actual return value of the `intersection` function to null (was undefined before).\n * @modified 2022-10-17 Adding these methods from the `PathSegment` interface: getStartPoint, getEndPoint, revert.\n * @modified 2023-09-25 Changed param type of `intersection()` from Line to VertTuple.\n * @modified 2025-04-15 Class `Line` now implements interface `Intersectable`.\n * @modified 2025-04-16 Class `Line` now implements interface `IBounded`.\n * @version  2.4.0\n *\n * @file Line\n * @public\n **/\nimport { Bounds } from \"./Bounds\";\nimport { Vector } from \"./Vector\";\nimport { VertTuple } from \"./VertTuple\";\nimport { Vertex } from \"./Vertex\";\n/**\n * @classdesc A line consists of two vertices a and b.<br>\n * <br>\n * This is some refactored code from my 'Morley Triangle' test<br>\n *   https://github.com/IkarosKappler/morleys-trisector-theorem\n *\n * @requires Vertex\n */\nexport class Line extends VertTuple {\n    /**\n     * Creates an instance of Line.\n     *\n     * @constructor\n     * @name Line\n     * @param {Vertex} a The line's first point.\n     * @param {Vertex} b The line's second point.\n     **/\n    constructor(a, b) {\n        super(a, b, (a, b) => new Line(a, b));\n        /**\n         * Required to generate proper CSS classes and other class related IDs.\n         **/\n        this.className = \"Line\";\n    }\n    /**\n     * Get the intersection if this line and the specified line.\n     *\n     * @method intersection\n     * @param {Line} line The second line.\n     * @return {Vertex|undefined} The intersection (may lie outside the end-points) or `undefined` if both lines are parallel.\n     * @instance\n     * @memberof Line\n     **/\n    // !!! DO NOT MOVE TO VertTuple\n    intersection(line) {\n        const denominator = this.denominator(line);\n        if (denominator == 0) {\n            return null;\n        }\n        let a = this.a.y - line.a.y;\n        let b = this.a.x - line.a.x;\n        const numerator1 = (line.b.x - line.a.x) * a - (line.b.y - line.a.y) * b;\n        const numerator2 = (this.b.x - this.a.x) * a - (this.b.y - this.a.y) * b;\n        a = numerator1 / denominator; // NaN if parallel lines\n        b = numerator2 / denominator;\n        // Catch NaN?\n        const x = this.a.x + a * (this.b.x - this.a.x);\n        const y = this.a.y + a * (this.b.y - this.a.y);\n        if (isNaN(a) || isNaN(x) || isNaN(y)) {\n            return null;\n        }\n        // if we cast these lines infinitely in both directions, they intersect here:\n        return new Vertex(x, y);\n    }\n    //--- BEGIN --- Implement interface `IBounded`\n    /**\n     * Get the bounding box (bounds) of this Line.\n     *\n     * @method getBounds\n     * @instance\n     * @memberof Line\n     * @return {Bounds} The rectangular bounds of this Line.\n     **/\n    getBounds() {\n        return Bounds.computeFromVertices([this.a, this.b]);\n    }\n    //--- END --- Implement interface `IBounded`\n    //--- Implement PathSegment ---\n    /**\n     * Get the start point of this path segment.\n     *\n     * @method getStartPoint\n     * @memberof PathSegment\n     * @return {Vertex} The start point of this path segment.\n     */\n    getStartPoint() {\n        return this.a;\n    }\n    /**\n     * Get the end point of this path segment.\n     *\n     * @method getEndPoint\n     * @memberof PathSegment\n     * @return {Vertex} The end point of this path segment.\n     */\n    getEndPoint() {\n        return this.b;\n    }\n    /**\n     * Get the tangent's end point at the start point of this segment.\n     *\n     * @method getStartTangent\n     * @memberof PathSegment\n     * @return {Vertex} The end point of the starting point's tangent.\n     */\n    getStartTangent() {\n        return this.b;\n    }\n    /**\n     * Get the tangent's end point at the end point of this segment.\n     *\n     * @method getEndTangent\n     * @memberof PathSegment\n     * @return {Vertex} The end point of the ending point's tangent.\n     */\n    getEndTangent() {\n        return this.a;\n    }\n    /**\n     * Inverse this path segment (in-place) and return this same instance (useful for chaining).\n     *\n     * @method reverse\n     * @memberof PathSegment\n     * @return {PathSegment} This path segment instance (for chaining).\n     */\n    reverse() {\n        var tmp = this.a;\n        this.a = this.b;\n        this.b = tmp;\n        return this;\n    }\n    //--- END Implement PathSegment ---\n    //--- BEGIN --- Implement interface `Intersectable`\n    /**\n     * Get all line intersections with this polygon.\n     *\n     * This method returns all intersections (as vertices) with this shape. The returned array of vertices is in no specific order.\n     *\n     * See demo `47-closest-vector-projection-on-polygon` for how it works.\n     *\n     * @param {VertTuple} line - The line to find intersections with.\n     * @param {boolean} inVectorBoundsOnly - If set to true only intersecion points on the passed vector are returned (located strictly between start and end vertex).\n     * @returns {Array<Vertex>} - An array of all intersections within the polygon bounds.\n     */\n    lineIntersections(line, inVectorBoundsOnly = false) {\n        // Find the intersections of all lines inside the edge bounds\n        const intersection = this.intersection(line);\n        if (!intersection) {\n            return []; // Both lines parallel\n        }\n        if (this.hasPoint(intersection, true) && (!inVectorBoundsOnly || line.hasPoint(intersection, inVectorBoundsOnly))) {\n            return [intersection];\n        }\n        else {\n            return [];\n        }\n    }\n    /**\n     * Get all line intersections of this polygon and their tangents along the shape.\n     *\n     * This method returns all intersection tangents (as vectors) with this shape. The returned array of vectors is in no specific order.\n     *\n     * @param line\n     * @param inVectorBoundsOnly\n     * @returns\n     */\n    lineIntersectionTangents(line, inVectorBoundsOnly = false) {\n        // Find the intersection tangents of all lines inside the edge bounds\n        const intersections = this.lineIntersections(line, inVectorBoundsOnly);\n        if (intersections.length === 0) {\n            return [];\n        }\n        const intrsctn = intersections[0];\n        return [new Vector(this.a.clone(), this.b.clone()).moveTo(intrsctn)];\n    }\n}\n//# sourceMappingURL=Line.js.map","/**\n * @author   Ikaros Kappler\n * @date     2018-04-14\n * @modified 2018-11-17 Added the containsVert function.\n * @modified 2018-12-04 Added the toSVGString function.\n * @modified 2019-03-20 Added JSDoc tags.\n * @modified 2019-10-25 Added the scale function.\n * @modified 2019-11-06 JSDoc update.\n * @modified 2019-11-07 Added toCubicBezierPath(number) function.\n * @modified 2019-11-22 Added the rotate(number,Vertex) function.\n * @modified 2020-03-24 Ported this class from vanilla-JS to Typescript.\n * @modified 2020-10-30 Added the `addVertex` function.\n * @modified 2020-10-31 Added the `getVertexAt` function.\n * @modified 2020-11-06 Added the `move` function.\n * @modified 2020-11-10 Added the `getBounds` function.\n * @modified 2020-11-11 Generalized `move(Vertex)` to `move(XYCoords)`.\n * @modified 2021-01-20 Added UID.\n * @modified 2021-01-29 Added the `signedArea` function (was global function in the demos before).\n * @modified 2021-01-29 Added the `isClockwise` function.\n * @modified 2021-01-29 Added the `area` function.\n * @modified 2021-01-29 Changed the param type for `containsVert` from Vertex to XYCoords.\n * @modified 2021-12-14 Added the `perimeter()` function.\n * @modified 2021-12-16 Added the `getEvenDistributionPolygon()` function.\n * @modified 2022-02-02 Added the `destroy` method.\n * @modified 2022-02-02 Cleared the `Polygon.toSVGString` function (deprecated). Use `drawutilssvg` instead.\n * @modified 2022-03-08 Added the `Polygon.clone()` function.\n * @modified 2023-09-25 Added the `Polygon.getInterpolationPolygon(number)` function.\n * @modified 2023-09-25 Added the `Polygon.lineIntersections(Line,boolean)` function.\n * @modified 2023-09-29 Added the `Polygon.closestLineIntersection(Line,boolean)` function.\n * @modified 2023-11-24 Added the `Polygon.containsPolygon(Polygon)' function.\n * @modified 2024-10-12 Added the `getEdgeAt` method.\n * @modified 2024-10-30 Added the `getEdges` method.\n * @modified 2024-12-02 Added the `elimitateColinearEdges` method.\n * @modified 2025-02-12 Added the `containsVerts` method to test multiple vertices for containment.\n * @modified 2025-03-28 Added the `Polygon.utils.locateLineIntersecion` static helper method.\n * @modified 2025-03-28 Added the `Polygon.lineIntersectionTangents` method.\n * @modified 2025-04-09 Added the `Polygon.getCentroid` method.\n * @modified 2025-05-16 Class `Polygon` now implements `IBounded`.\n * @modified 2025-05-20 Tweaking `Polygon.getInnerAngleAt` and `Polygo.isAngleAcute` to handle indices out of array bounds as well.\n * @modified 2025-06-07 Adding `Polygon.closestLineIntersectionIndex` to determine line intersections plus detected edge index.\n * @version 1.16.0\n *\n * @file Polygon\n * @public\n **/\nimport { BezierPath } from \"./BezierPath\";\nimport { Bounds } from \"./Bounds\";\nimport { Line } from \"./Line\";\nimport { Triangle } from \"./Triangle\";\nimport { UIDGenerator } from \"./UIDGenerator\";\nimport { Vector } from \"./Vector\";\nimport { Vertex } from \"./Vertex\";\nimport { geomutils } from \"./geomutils\";\n/**\n * @classdesc A polygon class. Any polygon consists of an array of vertices; polygons can be open or closed.\n *\n * @requires BezierPath\n * @requires Bounds\n * @requires SVGSerializabe\n * @requires UID\n * @requires UIDGenerator\n * @requires Vertex\n * @requires XYCoords\n */\nexport class Polygon {\n    /**\n     * The constructor.\n     *\n     * @constructor\n     * @name Polygon\n     * @param {Vertex[]} vertices - An array of 2d vertices that shape the polygon.\n     * @param {boolean} isOpen - Indicates if the polygon should be rendered as an open or closed shape.\n     **/\n    constructor(vertices, isOpen) {\n        /**\n         * Required to generate proper CSS classes and other class related IDs.\n         **/\n        this.className = \"Polygon\";\n        this.uid = UIDGenerator.next();\n        if (typeof vertices == \"undefined\") {\n            vertices = [];\n        }\n        this.vertices = vertices;\n        this.isOpen = isOpen || false;\n    }\n    /**\n     * Add a vertex to the end of the `vertices` array.\n     *\n     * @method addVertex\n     * @param {Vertex} vert - The vertex to add.\n     * @instance\n     * @memberof Polygon\n     **/\n    addVertex(vert) {\n        this.vertices.push(vert);\n    }\n    /**\n     * Add a vertex at a particular position of the `vertices` array.\n     *\n     * @method addVertexAt\n     * @param {Vertex} vert - The vertex to add.\n     * @param {number} index - The position to add the vertex at. Will be handled modulo.\n     * @instance\n     * @memberof Polygon\n     **/\n    addVertexAt(vert, index) {\n        // var moduloIndex = index % (this.vertices.length + 1);\n        this.vertices.splice(index, 0, vert);\n    }\n    /**\n     * Get a new instance of the line at the given start index. The returned line will consist\n     * of the vertex at `vertIndex` and `vertIndex+1` (will be handled modulo).\n     *\n     * @method getEdgeAt\n     * @param {number} vertIndex - The vertex index of the line to start.\n     * @instance\n     * @memberof Polygon\n     * @return {Line}\n     **/\n    getEdgeAt(vertIndex) {\n        return new Line(this.getVertexAt(vertIndex), this.getVertexAt(vertIndex + 1));\n    }\n    /**\n     * Converts this polygon into a sequence of lines. Please note that each time\n     * this method is called new lines are created. The underlying line vertices are no clones\n     * (instances).\n     *\n     * @method getEdges\n     * @instance\n     * @memberof Polygon\n     * @return {Array<Line>}\n     */\n    getEdges() {\n        const lines = [];\n        for (var i = 0; i + 1 < this.vertices.length; i++) {\n            // var line = this.getLineAt(i).clone();\n            lines.push(this.getEdgeAt(i));\n        }\n        if (!this.isOpen && this.vertices.length > 0) {\n            lines.push(this.getEdgeAt(this.vertices.length - 1));\n        }\n        return lines;\n    }\n    /**\n     * Checks if the angle at the given polygon vertex (index) is acute. Please not that this is\n     * only working for clockwise polygons. If this polygon is not clockwise please use the\n     * `isClockwise` method and reverse polygon vertices if needed.\n     *\n     * @method isAngleAcute\n     * @instance\n     * @memberof Polygon\n     * @param {number} vertIndex - The index of the polygon vertex to check.\n     * @returns {boolean} `true` is angle is acute, `false` is obtuse.\n     */\n    getInnerAngleAt(vertIndex) {\n        const p2 = this.vertices[vertIndex % this.vertices.length];\n        const p1 = this.vertices[(vertIndex + this.vertices.length - 1) % this.vertices.length].clone();\n        const p3 = this.vertices[(vertIndex + 1) % this.vertices.length].clone();\n        // See\n        //    https://math.stackexchange.com/questions/149959/how-to-find-the-interior-angle-of-an-irregular-pentagon-or-polygon\n        // π−arccos((P2−P1)⋅(P3−P2)|P2−P1||P3−P2|)\n        // Check if triangle is acute (will be used later)\n        // Acute angles and obtuse angles need to be handled differently.\n        const isAcute = this.isAngleAcute(vertIndex);\n        // Differences\n        const zero = new Vertex(0, 0);\n        const p2mp1 = new Vertex(p2.x - p1.x, p2.y - p1.y);\n        const p3mp2 = new Vertex(p3.x - p2.x, p3.y - p2.y);\n        const p2mp1_len = zero.distance(p2mp1);\n        const p3mp2_len = zero.distance(p3mp2);\n        // Dot products\n        const dotProduct = geomutils.dotProduct(p2mp1, p3mp2);\n        const lengthProduct = p2mp1_len * p3mp2_len;\n        if (isAcute) {\n            return Math.PI - Math.acos(dotProduct / lengthProduct);\n        }\n        else {\n            return Math.PI + Math.acos(dotProduct / lengthProduct);\n        }\n    }\n    /**\n     * Checks if the angle at the given polygon vertex (index) is acute.\n     *\n     * @method isAngleAcute\n     * @instance\n     * @memberof Polygon\n     * @param {number} vertIndex - The index of the polygon vertex to check.\n     * @returns {boolean} `true` is angle is acute, `false` is obtuse.\n     */\n    isAngleAcute(vertIndex) {\n        const A = this.vertices[(vertIndex + this.vertices.length - 1) % this.vertices.length].clone();\n        const B = this.vertices[vertIndex % this.vertices.length];\n        const C = this.vertices[(vertIndex + 1) % this.vertices.length].clone();\n        // Find local winding number for triangle A B C\n        const windingNumber = Triangle.utils.determinant(A, B, C);\n        // console.log(\"vertIndex\", vertIndex, \"windingNumber\", windingNumber);\n        return windingNumber < 0;\n    }\n    /**\n     * Get the polygon vertex at the given position (index).\n     *\n     * The index may exceed the total vertex count, and will be wrapped around then (modulo).\n     *\n     * For k >= 0:\n     *  - getVertexAt( vertices.length )     == getVertexAt( 0 )\n     *  - getVertexAt( vertices.length + k ) == getVertexAt( k )\n     *  - getVertexAt( -k )                  == getVertexAt( vertices.length -k )\n     *\n     * @method getVertexAt\n     * @param {number} index - The index of the desired vertex.\n     * @instance\n     * @memberof Polygon\n     * @return {Vertex} At the given index.\n     **/\n    getVertexAt(index) {\n        if (index < 0) {\n            return this.vertices[this.vertices.length - (Math.abs(index) % this.vertices.length)];\n        }\n        else {\n            return this.vertices[index % this.vertices.length];\n        }\n    }\n    /**\n     * Move the polygon's vertices by the given amount.\n     *\n     * @method move\n     * @param {XYCoords} amount - The amount to move.\n     * @instance\n     * @memberof Polygon\n     * @return {Polygon} this for chaining\n     **/\n    move(amount) {\n        for (var i in this.vertices) {\n            this.vertices[i].add(amount);\n        }\n        return this;\n    }\n    /**\n     * Check if the given vertex is inside this polygon.<br>\n     * <br>\n     * Ray-casting algorithm found at<br>\n     *    https://stackoverflow.com/questions/22521982/check-if-point-inside-a-polygon\n     *\n     * @method containsVert\n     * @param {XYCoords} vert - The vertex to check.\n     * @return {boolean} True if the passed vertex is inside this polygon. The polygon is considered closed.\n     * @instance\n     * @memberof Polygon\n     **/\n    containsVert(vert) {\n        // ray-casting algorithm based on\n        //    http://www.ecse.rpi.edu/Homepages/wrf/Research/Short_Notes/pnpoly.html\n        var inside = false;\n        for (var i = 0, j = this.vertices.length - 1; i < this.vertices.length; j = i++) {\n            let xi = this.vertices[i].x, yi = this.vertices[i].y;\n            let xj = this.vertices[j].x, yj = this.vertices[j].y;\n            var intersect = yi > vert.y != yj > vert.y && vert.x < ((xj - xi) * (vert.y - yi)) / (yj - yi) + xi;\n            if (intersect) {\n                inside = !inside;\n            }\n        }\n        return inside;\n    }\n    /**\n     * Check if all given vertices are inside this polygon.<br>\n     * <br>\n     * This method just uses the `Polygon.containsVert` method.\n     *\n     * @method containsVerts\n     * @param {XYCoords[]} verts - The vertices to check.\n     * @return {boolean} True if all passed vertices are inside this polygon. The polygon is considered closed.\n     * @instance\n     * @memberof Polygon\n     **/\n    containsVerts(verts) {\n        return verts.every((vert) => this.containsVert(vert));\n    }\n    /**\n     * Check if the passed polygon is completly contained inside this polygon.\n     *\n     * This means:\n     *  - all polygon's vertices must be inside this polygon.\n     *  - the polygon has no edge intersections with this polygon.\n     *\n     * @param {Polygon} polygon - The polygon to check if contained.\n     * @return {boolean}\n     */\n    containsPolygon(polygon) {\n        for (var i = 0; i < polygon.vertices.length; i++) {\n            if (!this.containsVert(polygon.vertices[i])) {\n                return false;\n            }\n        }\n        // All vertices are inside; check for intersections\n        const lineSegment = new Line(new Vertex(), new Vertex());\n        for (var i = 0; i < polygon.vertices.length; i++) {\n            lineSegment.a.set(polygon.vertices[i]);\n            lineSegment.b.set(polygon.vertices[(i + 1) % polygon.vertices.length]);\n            if (this.lineIntersections(lineSegment, true).length > 0) {\n                // Current segment has intersection(s) with this polygon.\n                return false;\n            }\n        }\n        return true;\n    }\n    /**\n     * Calculate the area of the given polygon (unsigned).\n     *\n     * Note that this does not work for self-intersecting polygons.\n     *\n     * @method area\n     * @instance\n     * @memberof Polygon\n     * @return {number}\n     */\n    area() {\n        return Polygon.utils.area(this.vertices);\n    }\n    /**\n     * Calulate the signed polyon area by interpreting the polygon as a matrix\n     * and calculating its determinant.\n     *\n     * @method signedArea\n     * @instance\n     * @memberof Polygon\n     * @return {number}\n     */\n    signedArea() {\n        return Polygon.utils.signedArea(this.vertices);\n    }\n    /**\n     * Get the winding order of this polgon: clockwise or counterclockwise.\n     *\n     * @method isClockwise\n     * @instance\n     * @memberof Polygon\n     * @return {boolean}\n     */\n    isClockwise() {\n        // return Polygon.utils.signedArea(this.vertices) < 0;\n        return Polygon.utils.isClockwise(this.vertices);\n    }\n    /**\n     * Get the perimeter of this polygon.\n     * The perimeter is the absolute length of the outline.\n     *\n     * If this polygon is open then the last segment (connecting the first and the\n     * last vertex) will be skipped.\n     *\n     * @method perimeter\n     * @instance\n     * @memberof Polygon\n     * @return {number}\n     */\n    perimeter() {\n        let length = 0;\n        for (var i = 1; i < this.vertices.length; i++) {\n            length += this.vertices[i - 1].distance(this.vertices[i]);\n        }\n        if (!this.isOpen && this.vertices.length > 1) {\n            length += this.vertices[0].distance(this.vertices[this.vertices.length - 1]);\n        }\n        return length;\n    }\n    /**\n     * Scale the polygon relative to the given center.\n     *\n     * @method scale\n     * @param {number} factor - The scale factor.\n     * @param {Vertex} center - The center of scaling.\n     * @return {Polygon} this, for chaining.\n     * @instance\n     * @memberof Polygon\n     **/\n    scale(factor, center) {\n        for (var i in this.vertices) {\n            if (typeof this.vertices[i].scale == \"function\")\n                this.vertices[i].scale(factor, center);\n            else\n                console.log(\"There seems to be a null vertex!\", this.vertices[i]);\n        }\n        return this;\n    }\n    /**\n     * Rotate the polygon around the given center.\n     *\n     * @method rotate\n     * @param {number} angle  - The rotation angle.\n     * @param {Vertex} center - The center of rotation.\n     * @instance\n     * @memberof Polygon\n     * @return {Polygon} this, for chaining.\n     **/\n    rotate(angle, center) {\n        for (var i in this.vertices) {\n            this.vertices[i].rotate(angle, center);\n        }\n        return this;\n    }\n    /**\n     * Get the mean `center` of this polygon by calculating the mean value of all vertices.\n     *\n     * Mean: (v[0] + v[1] + ... v[n-1]) / n\n     *\n     * @method getMeanCenter\n     * @instance\n     * @memberof Polygon\n     * @return {Vertex|null} `null` is no vertices are available.\n     */\n    getMeanCenter() {\n        if (this.vertices.length === 0) {\n            return null;\n        }\n        const center = this.vertices[0].clone();\n        for (var i = 1; i < this.vertices.length; i++) {\n            center.add(this.vertices[i]);\n        }\n        center.x /= this.vertices.length;\n        center.y /= this.vertices.length;\n        return center;\n    }\n    /**\n     * Get centroid.\n     * Centroids define the barycenter of any non self-intersecting convex polygon.\n     *\n     * If the polygon is self intersecting or non konvex then the barycenter is not well defined.\n     *\n     * https://mathworld.wolfram.com/PolygonCentroid.html\n     *\n     * @method getCentroid\n     * @instance\n     * @memberof Polygon\n     * @returns {Vertex|null}\n     */\n    getCentroid() {\n        if (this.vertices.length === 0) {\n            return null;\n        }\n        const center = new Vertex(0.0, 0.0);\n        const n = this.vertices.length;\n        for (var i = 0; i < n; i++) {\n            // center.add(this.vertices[i]);\n            const cur = this.vertices[i];\n            const next = this.vertices[(i + 1) % n];\n            var factor = cur.x * next.y - next.x * cur.y;\n            center.x += (cur.x + next.x) * factor;\n            center.y += (cur.y + next.y) * factor;\n        }\n        const area = this.area();\n        center.x *= 1 / (6 * area);\n        center.y *= 1 / (6 * area);\n        return center;\n    }\n    //--- BEGIN --- Implement interface `Intersectable`\n    /**\n     * Get all line intersections with this polygon.\n     *\n     * This method returns all intersections (as vertices) with this shape. The returned array of vertices is in no specific order.\n     *\n     * See demo `47-closest-vector-projection-on-polygon` for how it works.\n     *\n     * @param {VertTuple} line - The line to find intersections with.\n     * @param {boolean} inVectorBoundsOnly - If set to true only intersecion points on the passed vector are returned (located strictly between start and end vertex).\n     * @returns {Array<Vertex>} - An array of all intersections within the polygon bounds.\n     */\n    lineIntersections(line, inVectorBoundsOnly = false) {\n        // Find the intersections of all lines inside the edge bounds\n        return Polygon.utils\n            .locateLineIntersecion(line, this.vertices, this.isOpen, inVectorBoundsOnly)\n            .map(intersectionTuple => intersectionTuple.intersection);\n    }\n    /**\n     * Get all line intersections of this polygon and their tangents along the shape.\n     *\n     * This method returns all intersection tangents (as vectors) with this shape. The returned array of vectors is in no specific order.\n     *\n     * @param line\n     * @param inVectorBoundsOnly\n     * @returns\n     */\n    lineIntersectionTangents(line, inVectorBoundsOnly = false) {\n        // Find the intersection tangents of all lines inside the edge bounds\n        return Polygon.utils.locateLineIntersecion(line, this.vertices, this.isOpen, inVectorBoundsOnly).map(intersectionTuple => {\n            const polyLine = this.getEdgeAt(intersectionTuple.edgeIndex);\n            return new Vector(polyLine.a.clone(), polyLine.b.clone()).moveTo(intersectionTuple.intersection);\n        });\n    }\n    //--- END --- Implement interface `Intersectable`\n    /**\n     * Get all line intersections of this polygon and their tangents along the shape.\n     *\n     * This method returns all intersection tangents (as vectors) with this shape. The returned array of vectors is in no specific order.\n     *\n     * @param line\n     * @param inVectorBoundsOnly\n     * @returns\n     */\n    lineIntersectionTangentsIndices(line, inVectorBoundsOnly = false) {\n        // Find the intersection tangents of all lines inside the edge bounds\n        return Polygon.utils.locateLineIntersecion(line, this.vertices, this.isOpen, inVectorBoundsOnly).map(intersectionTuple => {\n            const polyLine = this.getEdgeAt(intersectionTuple.edgeIndex);\n            return {\n                intersection: new Vector(polyLine.a.clone(), polyLine.b.clone()).moveTo(intersectionTuple.intersection),\n                edgeIndex: intersectionTuple.edgeIndex\n            };\n        });\n    }\n    /**\n     * Get the closest line-polygon-intersection point (closest the line point A).\n     *\n     * See demo `47-closest-vector-projection-on-polygon` for how it works.\n     *\n     * @param {VertTuple} line - The line to find intersections with.\n     * @param {boolean} inVectorBoundsOnly - If set to true only intersecion points on the passed vector are considered (located strictly between start and end vertex).\n     * @returns {Vertex | null} - The intersection point within the polygon bounds.\n     */\n    closestLineIntersection(line, inVectorBoundsOnly = false) {\n        var closestInterSectionIndex = this.closestLineIntersectionIndex(line, inVectorBoundsOnly);\n        if (closestInterSectionIndex) {\n            return closestInterSectionIndex.intersection;\n        }\n        else {\n            return null;\n        }\n    }\n    /**\n     * Get the closest line-polygon-intersection point (closest the line point A) plus the edge index..\n     *\n     * See demo `63-measure-angles-on-polygon` for how it works.\n     *\n     * @param {VertTuple} line - The line to find intersections with.\n     * @param {boolean} inVectorBoundsOnly - If set to true only intersecion points on the passed vector are considered (located strictly between start and end vertex).\n     * @returns {PolygonIntersectionTuple| null} - A pair containing the intersection point and the affected polygon edge index.\n     */\n    closestLineIntersectionIndex(line, inVectorBoundsOnly = false) {\n        const allIntersections = this.lineIntersections(line, inVectorBoundsOnly);\n        if (allIntersections.length <= 0) {\n            // Empty polygon -> no intersections\n            return null;\n        }\n        // Find the closest intersection\n        let closestIntersection = new Vertex(Number.MAX_VALUE, Number.MAX_VALUE);\n        let closestInterSectionIndex = -1;\n        let curDist = Number.MAX_VALUE;\n        for (var i = 0; i < allIntersections.length; i++) {\n            const curVert = allIntersections[i];\n            const dist = curVert.distance(line.a);\n            if (dist < curDist) {\n                // && line.hasPoint(curVert)) {\n                curDist = dist;\n                closestIntersection = curVert;\n                closestInterSectionIndex = i;\n            }\n        }\n        // return [closestIntersection, closestInterSectionIndex];\n        return { edgeIndex: closestInterSectionIndex, intersection: closestIntersection };\n    }\n    /**\n     * Construct a new polygon from this polygon with more vertices on each edge. The\n     * interpolation count determines the number of additional vertices on each edge.\n     * An interpolation count of `0` will return a polygon that equals the source\n     * polygon.\n     *\n     * @param {number} interpolationCount\n     * @returns {Polygon} A polygon with `interpolationCount` more vertices (as as factor).\n     */\n    getInterpolationPolygon(interpolationCount) {\n        const verts = [];\n        for (var i = 0; i < this.vertices.length; i++) {\n            const curVert = this.vertices[i];\n            const nextVert = this.vertices[(i + 1) % this.vertices.length];\n            verts.push(curVert.clone());\n            // Add interpolation points\n            if (!this.isOpen || i + 1 !== this.vertices.length) {\n                const lerpAmount = 1.0 / (interpolationCount + 1);\n                for (var j = 1; j <= interpolationCount; j++) {\n                    verts.push(curVert.clone().lerp(nextVert, lerpAmount * j));\n                }\n            }\n        }\n        return new Polygon(verts, this.isOpen);\n    }\n    /**\n     * Convert this polygon into a new polygon with n evenly distributed vertices.\n     *\n     * @param {number} pointCount - Must not be negative.\n     */\n    getEvenDistributionPolygon(pointCount) {\n        if (pointCount <= 0) {\n            throw new Error(\"pointCount must be larger than zero; is \" + pointCount + \".\");\n        }\n        const result = new Polygon([], this.isOpen);\n        if (this.vertices.length === 0) {\n            return result;\n        }\n        // Fetch and add the start point from the source polygon\n        let polygonPoint = new Vertex(this.vertices[0]);\n        result.vertices.push(polygonPoint);\n        if (this.vertices.length === 1) {\n            return result;\n        }\n        const perimeter = this.perimeter();\n        const stepSize = perimeter / pointCount;\n        const n = this.vertices.length;\n        let polygonIndex = 1;\n        let nextPolygonPoint = new Vertex(this.vertices[1]);\n        let segmentLength = polygonPoint.distance(nextPolygonPoint);\n        let loopMax = this.isOpen ? n : n + 1;\n        let curSegmentU = stepSize;\n        var i = 1;\n        while (i < pointCount && polygonIndex < loopMax) {\n            // Check if next eq point is inside this segment\n            if (curSegmentU < segmentLength) {\n                let newPoint = polygonPoint.clone().lerpAbs(nextPolygonPoint, curSegmentU);\n                result.vertices.push(newPoint);\n                curSegmentU += stepSize;\n                i++;\n            }\n            else {\n                polygonIndex++;\n                polygonPoint = nextPolygonPoint;\n                nextPolygonPoint = new Vertex(this.vertices[polygonIndex % n]);\n                curSegmentU = curSegmentU - segmentLength;\n                segmentLength = polygonPoint.distance(nextPolygonPoint);\n            }\n        }\n        return result;\n    }\n    //--- BEGIN --- Implement interface `IBounded`\n    /**\n     * Get the bounding box (bounds) of this polygon.\n     *\n     * @method getBounds\n     * @instance\n     * @memberof Polygon\n     * @return {Bounds} The rectangular bounds of this polygon.\n     **/\n    getBounds() {\n        return Bounds.computeFromVertices(this.vertices);\n    }\n    //--- END --- Implement interface `IBounded`\n    /**\n     * Create a deep copy of this polygon.\n     *\n     * @method clone\n     * @instance\n     * @memberof Polygon\n     * @return {Polygon} The cloned polygon.\n     */\n    clone() {\n        return new Polygon(this.vertices.map(vert => vert.clone()), this.isOpen);\n    }\n    /**\n     * Create a new polygon without colinear adjacent edges. This method does not midify the current polygon\n     * but creates a new one.\n     *\n     * Please note that this method does NOT create deep clones of the vertices. Use Polygon.clone() if you need to.\n     *\n     * Please also note that the `tolerance` may become really large here, as the denominator of two closely\n     * parallel lines is usually pretty large. See the demo `57-eliminate-colinear-polygon-edges` to get\n     * an impression of how denominators work.\n     *\n     * @method elimitateColinearEdges\n     * @instance\n     * @memberof Polygon\n     * @param {number?} tolerance - (default is 1.0) The epsilon to detect co-linear edges.\n     * @return {Polygon} A new polygon without co-linear adjacent edges – respective the given epsilon.\n     */\n    elimitateColinearEdges(tolerance) {\n        const eps = typeof tolerance === \"undefined\" ? 1.0 : tolerance;\n        const verts = this.vertices.slice(); // Creates a shallow copy\n        let i = 0;\n        var lineA = new Line(new Vertex(), new Vertex());\n        var lineB = new Line(new Vertex(), new Vertex());\n        while (i + 1 < verts.length && verts.length > 2) {\n            const vertA = verts[i];\n            const vertB = verts[(i + 1) % verts.length];\n            lineA.a = vertA;\n            lineA.b = vertB;\n            lineB.a = vertB;\n            let areColinear = false;\n            let j = i + 2;\n            do {\n                let vertC = verts[j % verts.length];\n                lineB.b = vertC;\n                areColinear = lineA.colinear(lineB, eps);\n                // console.log(\"are colinear?\", i, i + 1, j, areColinear);\n                if (areColinear) {\n                    j++;\n                }\n            } while (areColinear);\n            // Now j points to the first vertex that's NOT colinear to the current lineA\n            // -> delete all vertices in between\n            if (j - i > 2) {\n                // Means: there have been 'colinear vertices' in between\n                verts.splice(i + 1, j - i - 2);\n            }\n            i++;\n        }\n        return new Polygon(verts, this.isOpen);\n    }\n    /**\n     * Convert this polygon to a sequence of quadratic Bézier curves.<br>\n     * <br>\n     * The first vertex in the returned array is the start point.<br>\n     * The following sequence are pairs of control-point-and-end-point:\n     * <pre>startPoint, controlPoint0, pathPoint1, controlPoint1, pathPoint2, controlPoint2, ..., endPoint</pre>\n     *\n     * @method toQuadraticBezierData\n     * @return {Vertex[]}  An array of 2d vertices that shape the quadratic Bézier curve.\n     * @instance\n     * @memberof Polygon\n     **/\n    toQuadraticBezierData() {\n        if (this.vertices.length < 3)\n            return [];\n        var qbezier = [];\n        var cc0 = this.vertices[0];\n        var cc1 = this.vertices[1];\n        var edgeCenter = new Vertex(cc0.x + (cc1.x - cc0.x) / 2, cc0.y + (cc1.y - cc0.y) / 2);\n        qbezier.push(edgeCenter);\n        var limit = this.isOpen ? this.vertices.length : this.vertices.length + 1;\n        for (var t = 1; t < limit; t++) {\n            cc0 = this.vertices[t % this.vertices.length];\n            cc1 = this.vertices[(t + 1) % this.vertices.length];\n            var edgeCenter = new Vertex(cc0.x + (cc1.x - cc0.x) / 2, cc0.y + (cc1.y - cc0.y) / 2);\n            qbezier.push(cc0);\n            qbezier.push(edgeCenter);\n            cc0 = cc1;\n        }\n        return qbezier;\n    }\n    /**\n     * Convert this polygon to a quadratic bezier curve, represented as an SVG data string.\n     *\n     * @method toQuadraticBezierSVGString\n     * @return {string} The 'd' part for an SVG 'path' element.\n     * @instance\n     * @memberof Polygon\n     **/\n    toQuadraticBezierSVGString() {\n        var qdata = this.toQuadraticBezierData();\n        if (qdata.length == 0)\n            return \"\";\n        var buffer = [\"M \" + qdata[0].x + \" \" + qdata[0].y];\n        for (var i = 1; i < qdata.length; i += 2) {\n            buffer.push(\"Q \" + qdata[i].x + \" \" + qdata[i].y + \", \" + qdata[i + 1].x + \" \" + qdata[i + 1].y);\n        }\n        return buffer.join(\" \");\n    }\n    /**\n     * Convert this polygon to a sequence of cubic Bézier curves.<br>\n     * <br>\n     * The first vertex in the returned array is the start point.<br>\n     * The following sequence are triplets of (first-control-point, secnond-control-point, end-point):<br>\n     * <pre>startPoint, controlPoint0_0, controlPoint1_1, pathPoint1, controlPoint1_0, controlPoint1_1, ..., endPoint</pre>\n     *\n     * @method toCubicBezierData\n     * @param {number=} threshold - An optional threshold (default=1.0) how strong the curve segments\n     *                              should over-/under-drive. Should be between 0.0 and 1.0 for best\n     *                              results but other values are allowed.\n     * @return {Vertex[]}  An array of 2d vertices that shape the cubic Bézier curve.\n     * @instance\n     * @memberof Polygon\n     **/\n    toCubicBezierData(threshold) {\n        if (typeof threshold == \"undefined\")\n            threshold = 1.0;\n        if (this.vertices.length < 3)\n            return [];\n        var cbezier = [];\n        var a = this.vertices[0];\n        var b = this.vertices[1];\n        var edgeCenter = new Vertex(a.x + (b.x - a.x) / 2, a.y + (b.y - a.y) / 2);\n        cbezier.push(edgeCenter);\n        var limit = this.isOpen ? this.vertices.length - 1 : this.vertices.length;\n        for (var t = 0; t < limit; t++) {\n            var a = this.vertices[t % this.vertices.length];\n            var b = this.vertices[(t + 1) % this.vertices.length];\n            var c = this.vertices[(t + 2) % this.vertices.length];\n            var aCenter = new Vertex(a.x + (b.x - a.x) / 2, a.y + (b.y - a.y) / 2);\n            var bCenter = new Vertex(b.x + (c.x - b.x) / 2, b.y + (c.y - b.y) / 2);\n            var a2 = new Vertex(aCenter.x + (b.x - aCenter.x) * threshold, aCenter.y + (b.y - aCenter.y) * threshold);\n            var b0 = new Vertex(bCenter.x + (b.x - bCenter.x) * threshold, bCenter.y + (b.y - bCenter.y) * threshold);\n            cbezier.push(a2);\n            cbezier.push(b0);\n            cbezier.push(bCenter);\n        }\n        return cbezier;\n    }\n    /**\n     * Convert this polygon to a cubic bezier curve, represented as an SVG data string.\n     *\n     * @method toCubicBezierSVGString\n     * @return {string} The 'd' part for an SVG 'path' element.\n     * @instance\n     * @memberof Polygon\n     **/\n    toCubicBezierSVGString(threshold) {\n        var qdata = this.toCubicBezierData(threshold);\n        if (qdata.length == 0) {\n            return \"\";\n        }\n        var buffer = [\"M \" + qdata[0].x + \" \" + qdata[0].y];\n        for (var i = 1; i < qdata.length; i += 3) {\n            buffer.push(\"C \" +\n                qdata[i].x +\n                \" \" +\n                qdata[i].y +\n                \", \" +\n                qdata[i + 1].x +\n                \" \" +\n                qdata[i + 1].y +\n                \", \" +\n                qdata[i + 2].x +\n                \" \" +\n                qdata[i + 2].y);\n        }\n        return buffer.join(\" \");\n    }\n    /**\n     * Convert this polygon to a cubic bezier path instance.\n     *\n     * @method toCubicBezierPath\n     * @param {number} threshold - The threshold, usually from 0.0 to 1.0.\n     * @return {BezierPath}      - A bezier path instance.\n     * @instance\n     * @memberof Polygon\n     **/\n    toCubicBezierPath(threshold) {\n        var qdata = this.toCubicBezierData(threshold);\n        // Conver the linear path vertices to a two-dimensional path array\n        var pathdata = [];\n        for (var i = 0; i + 3 < qdata.length; i += 3) {\n            pathdata.push([qdata[i], qdata[i + 3], qdata[i + 1], qdata[i + 2]]);\n        }\n        return BezierPath.fromArray(pathdata);\n    }\n    /**\n     * This function should invalidate any installed listeners and invalidate this object.\n     * After calling this function the object might not hold valid data any more and\n     * should not be used.\n     */\n    destroy() {\n        for (var i = 0; i < this.vertices.length; i++) {\n            this.vertices[i].destroy();\n        }\n        this.isDestroyed = true;\n    }\n}\nPolygon.utils = {\n    /**\n     * Calculate the area of the given polygon (unsigned).\n     *\n     * Note that this does not work for self-intersecting polygons.\n     *\n     * @name area\n     * @return {number}\n     */\n    area(vertices) {\n        // Found at:\n        //    https://stackoverflow.com/questions/16285134/calculating-polygon-area\n        let total = 0.0;\n        for (var i = 0, l = vertices.length; i < l; i++) {\n            const addX = vertices[i].x;\n            const addY = vertices[(i + 1) % l].y;\n            const subX = vertices[(i + 1) % l].x;\n            const subY = vertices[i].y;\n            total += addX * addY * 0.5;\n            total -= subX * subY * 0.5;\n        }\n        return Math.abs(total);\n    },\n    isClockwise(vertices) {\n        return Polygon.utils.signedArea(vertices) < 0;\n    },\n    /**\n     * Calulate the signed polyon area by interpreting the polygon as a matrix\n     * and calculating its determinant.\n     *\n     * @name signedArea\n     * @return {number}\n     */\n    signedArea(vertices) {\n        let sum = 0;\n        const n = vertices.length;\n        for (var i = 0; i < n; i++) {\n            const j = (i + 1) % n;\n            sum += (vertices[j].x - vertices[i].x) * (vertices[i].y + vertices[j].y);\n        }\n        return sum;\n    },\n    /**\n     * Find intersections of a line with a polygon (vertices).\n     *\n     * @param {VertTuple<any>} line - The line to find intersections with.\n     * @param {Array<Vertex>} vertices - The polygon's vertices.\n     * @param {boolean} isOpen - True if the polygon is open, false otherwise.\n     * @param {boolean} inVectorBoundsOnly - If only intersections in strict vector bounds should be returned.\n     * @returns\n     */\n    locateLineIntersecion(line, vertices, isOpen, inVectorBoundsOnly) {\n        // Find the intersections of all lines inside the edge bounds\n        const intersectionPoints = [];\n        var n = isOpen ? vertices.length - 1 : vertices.length;\n        for (var i = 0; i < n; i++) {\n            const polyLine = new Line(vertices[i % n], vertices[(i + 1) % n]);\n            const intersection = polyLine.intersection(line);\n            // true => only inside bounds\n            // ignore last edge if open\n            if (intersection !== null &&\n                polyLine.hasPoint(intersection, true) &&\n                (!inVectorBoundsOnly || line.hasPoint(intersection, inVectorBoundsOnly))) {\n                intersectionPoints.push({ edgeIndex: i, intersection: intersection });\n            }\n        }\n        return intersectionPoints;\n    }\n};\n//# sourceMappingURL=Polygon.js.map","/**\n * @author   Ikaros Kappler\n * @date     2020-05-11\n * @modified 2020-10-30 Added the static computeFromVertices function.\n * @modified 2020-11-19 Set min, max, width and height to private.\n * @modified 2021-02-02 Added the `toPolygon` method.\n * @modified 2021-06-21 (mid-summer) Added `getCenter` method.\n * @modified 2022-02-01 Added the `toString` function.\n * @modified 2022-10-09 Added the `fromDimension` function.\n * @modified 2022-11-28 Added the `clone` method.\n * @modified 2023-09-29 Added the `randomPoint` method.\n * @modified 2025-03-23 Added the `getMinDimension` and `getMaxDimension` methods.\n * @modified 2025-04-18 Change parameter type in `Bounds.computeFromVertices` from `Vertex` to more general `XYCoords`.\n * @modified 2025-04-19 Added methods to `Bounds` class: `getNorthPoint`, `getSouthPoint`, `getEastPoint` and `getWestPoint`.\n * @modified 2025-04-26 Added static method `Bounds.computeFromBoundsSet` to calculate containing bounds for a set of bounding boxes.\n * @modified 2025-10-17 Added the methods `Bounds.getSouthWestPoint`, `getNorthWestPoint`, `getNorthEastPoint` and `getSouthEastPoint`.\n * @modified 2025-10-18 Added method `Bounds.containsVert(XYCoords)`.\n * @modified 2025-10-28 Added the `Bounds.getWidth()` and `Bounds.getHeight()`.\n * @modified 2025-11-12 Added the `Bounds.getMoved()` method.\n * @version  1.11.0\n **/\nimport { Polygon } from \"./Polygon\";\nimport { Vertex } from \"./Vertex\";\n/**\n * @classdesc A bounds class with min and max values. Implementing IBounds.\n *\n * @requires XYCoords\n * @requires Vertex\n * @requires IBounds\n **/\nexport class Bounds {\n    /**\n     * The constructor.\n     *\n     * @constructor\n     * @name Bounds\n     * @param {XYCoords} min - The min values (x,y) as a XYCoords tuple.\n     * @param {XYCoords} max - The max values (x,y) as a XYCoords tuple.\n     **/\n    constructor(min, max) {\n        this.min = min;\n        this.max = max;\n        this.width = max.x - min.x;\n        this.height = max.y - min.y;\n    }\n    /**\n     * Check if the given vertex is inside this bounds.\n     *\n     * @method containsVert\n     * @param {XYCoords} vert - The vertex to check.\n     * @return {boolean} True if the passed vertex is inside this bounds.\n     * @instance\n     * @memberof Bounds\n     **/\n    containsVert(vert) {\n        return this.min.x <= vert.x && vert.x < this.max.x && this.min.y <= vert.y && vert.y < this.max.y;\n    }\n    getWidth() {\n        return this.max.x - this.min.x;\n    }\n    getHeight() {\n        return this.max.y - this.min.y;\n    }\n    getScaled(scaleFactor) {\n        const center = this.getCenter();\n        const newMin = new Vertex(this.min).scale(scaleFactor, center);\n        const newMax = new Vertex(this.max).scale(scaleFactor, center);\n        return new Bounds(newMin, newMax);\n    }\n    getMoved(moveAmount) {\n        const newMin = new Vertex(this.min).move(moveAmount);\n        const newMax = new Vertex(this.max).move(moveAmount);\n        return new Bounds(newMin, newMax);\n    }\n    /**\n     * Get the center point of the north bound.\n     *\n     * @method getNorthPoint\n     * @instance\n     * @memberof Bounds\n     * @return {Vertex} The \"northmost\" centered point of this bounding box.\n     */\n    getNorthPoint() {\n        return new Vertex(this.min.x + this.width / 2.0, this.min.y);\n    }\n    /**\n     * Get the center point of the south bound.\n     *\n     * @method getNorthPoint\n     * @instance\n     * @memberof Bounds\n     * @return {Vertex} The \"southhmost\" centered point of this bounding box.\n     */\n    getSouthPoint() {\n        return new Vertex(this.min.x + this.width / 2.0, this.max.y);\n    }\n    /**\n     * Get the center point of the west bound.\n     *\n     * @method getWestPoint\n     * @instance\n     * @memberof Bounds\n     * @return {Vertex} The \"westhmost\" centered point of this bounding box.\n     */\n    getWestPoint() {\n        return new Vertex(this.min.x, this.min.y + this.height / 2.0);\n    }\n    /**\n     * Get the center point of the east bound.\n     *\n     * @method getEastPoint\n     * @instance\n     * @memberof Bounds\n     * @return {Vertex} The \"easthmost\" centered point of this bounding box.\n     */\n    getEastPoint() {\n        return new Vertex(this.max.x, this.min.y + this.height / 2.0);\n    }\n    /**\n     * Get the upper left corner point these bounds box.\n     *\n     * @method getNorthWestPoint\n     * @instance\n     * @memberof Bounds\n     * @return {Vertex} The \"northwestmost\" point of this bounding box.\n     */\n    getNorthWestPoint() {\n        return new Vertex(this.min.x, this.min.y);\n    }\n    /**\n     * Get the upper right corner point these bounds box.\n     *\n     * @method getNorthEastPoint\n     * @instance\n     * @memberof Bounds\n     * @return {Vertex} The \"northeastmost\" point of this bounding box.\n     */\n    getNorthEastPoint() {\n        return new Vertex(this.max.x, this.min.y);\n    }\n    /**\n     * Get the lower right corner point these bounds box.\n     *\n     * @method getSouthEastPoint\n     * @instance\n     * @memberof Bounds\n     * @return {Vertex} The \"southeastmost\" point of this bounding box.\n     */\n    getSouthEastPoint() {\n        return new Vertex(this.max.x, this.max.y);\n    }\n    /**\n     * Get the lower left corner point these bounds box.\n     *\n     * @method getSouthWestPoint\n     * @instance\n     * @memberof Bounds\n     * @return {Vertex} The \"southwestmost\" point of this bounding box.\n     */\n    getSouthWestPoint() {\n        return new Vertex(this.min.x, this.max.y);\n    }\n    /**\n     * Convert this rectangular bounding box to a polygon with four vertices.\n     *\n     * @method toPolygon\n     * @instance\n     * @memberof Bounds\n     * @return {Polygon} This bound rectangle as a polygon.\n     */\n    toPolygon() {\n        return new Polygon([new Vertex(this.min), new Vertex(this.max.x, this.min.y), new Vertex(this.max), new Vertex(this.min.x, this.max.y)], false);\n    }\n    /**\n     * Get the center of this boinding box.\n     *\n     * @method getCenter\n     * @instance\n     * @memberof Bounds\n     * @returns {Vertex} The center of these bounds.\n     */\n    getCenter() {\n        return new Vertex(this.min.x + (this.max.x - this.min.x) / 2.0, this.min.y + (this.max.y - this.min.y) / 2);\n    }\n    /**\n     * Get the minimum of `width` and `height`.\n     *\n     * @returns {number} The value of Math.min( this.width, this.height )\n     */\n    getMinDimension() {\n        return Math.min(this.width, this.height);\n    }\n    /**\n     * Get the minimum of `width` and `height`.\n     *\n     * @returns {number} The value of Math.min( this.width, this.height )\n     */\n    getMaxDimension() {\n        return Math.max(this.width, this.height);\n    }\n    /**\n     * Generate a random point inside this bounds object. Safe areas at the border to avoid\n     * included.\n     *\n     * @method randomPoint\n     * @instance\n     * @memberof Bounds\n     * @param {horizontalSafeArea} - (optional) The horizonal (left and right) safe area. No vertex will be created here. Can be used as percent in (0.0 ... 0.1) interval.\n     * @param {verticalSafeArea} - (optional) The vertical (top and bottom) safe area. No vertex will be created here. Can be used as percent in (0.0 ... 0.1) interval\n     * @returns {Vertex} A pseudo random point inside these bounds.\n     */\n    randomPoint(horizontalSafeArea = 0, verticalSafeArea = 0) {\n        // Check if the safe areas are meant as percent\n        const absHorizontalSafeArea = horizontalSafeArea > 0 && horizontalSafeArea < 1 ? this.width * horizontalSafeArea : horizontalSafeArea;\n        const absVerticalSafeArea = verticalSafeArea > 0 && verticalSafeArea < 1 ? this.height * verticalSafeArea : verticalSafeArea;\n        return new Vertex(this.min.x + absHorizontalSafeArea + Math.random() * (this.width - 2 * absHorizontalSafeArea), this.min.y + absVerticalSafeArea + Math.random() * (this.height - 2 * absVerticalSafeArea));\n    }\n    /**\n     * Convert these bounds to a human readable form.\n     *\n     * Note: the returned format might change in the future, so please do not\n     * rely on the returned string format.\n     *\n     * @method toString\n     * @instance\n     * @memberof Bounds\n     * @returns {string} Get these bounds in a human readable form.\n     */\n    toString() {\n        return `{ min: ${this.min.toString()}, max : ${this.max.toString()}, width: ${this.width}, height : ${this.height} }`;\n    }\n    /**\n     * Clone this bounds object (create a deep clone).\n     *\n     * @method clone\n     * @instance\n     * @memberof Bounds\n     * @returns {Bounds} Creates a deep clone of this bounds object.\n     */\n    clone() {\n        return new Bounds({ x: this.min.x, y: this.min.y }, { x: this.max.x, y: this.max.y });\n    }\n    /**\n     * Compute the minimal bounding box for a given set of vertices.\n     *\n     * An empty vertex array will return an empty bounding box located at (0,0).\n     *\n     * @static\n     * @method computeFromVertices\n     * @memberof Bounds\n     * @param {Array<XYCoords>} vertices - The set of vertices you want to get the bounding box for.\n     * @return The minimal Bounds for the given vertices.\n     **/\n    static computeFromVertices(vertices) {\n        if (vertices.length == 0) {\n            return new Bounds(new Vertex(0, 0), new Vertex(0, 0));\n        }\n        let xMin = vertices[0].x;\n        let xMax = vertices[0].x;\n        let yMin = vertices[0].y;\n        let yMax = vertices[0].y;\n        let vert;\n        for (var i in vertices) {\n            vert = vertices[i];\n            xMin = Math.min(xMin, vert.x);\n            xMax = Math.max(xMax, vert.x);\n            yMin = Math.min(yMin, vert.y);\n            yMax = Math.max(yMax, vert.y);\n        }\n        return new Bounds(new Vertex(xMin, yMin), new Vertex(xMax, yMax));\n    }\n    /**\n     * Compute the minimal bounding box for a given set of existing bounding boxes.\n     *\n     * An empty vertex array will return an empty bounding box located at (0,0).\n     *\n     * @static\n     * @method computeFromBoundsSet\n     * @memberof Bounds\n     * @param {Array<IBounds>} boundingBoxes - The set of existing bounding boxes to get the containing bounding box for.\n     * @return The minimal Bounds for the given bounds instances.\n     **/\n    static computeFromBoundsSet(boundingBoxes) {\n        if (boundingBoxes.length == 0) {\n            return new Bounds(new Vertex(0, 0), new Vertex(0, 0));\n        }\n        let xMin = boundingBoxes[0].min.x;\n        let xMax = boundingBoxes[0].max.x;\n        let yMin = boundingBoxes[0].min.y;\n        let yMax = boundingBoxes[0].min.y;\n        let bounds;\n        for (var i in boundingBoxes) {\n            bounds = boundingBoxes[i];\n            xMin = Math.min(xMin, bounds.min.x);\n            xMax = Math.max(xMax, bounds.max.x);\n            yMin = Math.min(yMin, bounds.min.y);\n            yMax = Math.max(yMax, bounds.min.y);\n        }\n        return new Bounds(new Vertex(xMin, yMin), new Vertex(xMax, yMax));\n    }\n    /**\n     * Create a new `Bounds` instance just from `width` and `height`, located at (0,0) or the optionally given origin.\n     *\n     * @param {number} width - The width of the bounds\n     * @param {number} height  - The height of the bounds\n     * @param {XYCoords={x:0,y:0}} origin - [optional] A origin to locate the new Bounds object at.\n     * @returns {Bounds} A new `Bounds` instance width given width and height, located at (0,0) or the given origin..\n     */\n    static fromDimension(width, height, origin) {\n        return new Bounds(origin !== null && origin !== void 0 ? origin : { x: 0, y: 0 }, { x: (origin ? origin.x : 0) + width, y: (origin ? origin.y : 0) + height });\n    }\n} // END class bounds\n//# sourceMappingURL=Bounds.js.map","/**\n * @author   Ikaros Kappler\n * @date     2013-08-15\n * @modified 2018-08-16 Added a closure. Removed the wrapper class 'IKRS'. Replaced class THREE.Vector2 by Vertex class.\n * @modified 2018-11-19 Added the fromArray(Array) function.\n * @modified 2018-11-28 Added the locateCurveByPoint(Vertex) function.\n * @modified 2018-12-04 Added the toSVGPathData() function.\n * @modified 2019-03-20 Added JSDoc tags.\n * @modified 2019-03-23 Changed the signatures of getPoint, getPointAt and getTangent (!version 2.0).\n * @modified 2019-12-02 Fixed the updateArcLength function. It used the wrong pointAt function (was renamed before).\n * @modified 2020-02-06 Added the getSubCurveAt(number,number) function.\n * @modified 2020-02-06 Fixed a serious bug in the arc lenght calculation (length was never reset, urgh).\n * @modified 2020-02-07 Added the isInstance(any) function.\n * @modified 2020-02-10 Added the reverse() function.\n * @modified 2020-02-10 Fixed the translate(...) function (returning 'this' was missing).\n * @modified 2020-03-24 Ported this class from vanilla JS to Typescript.\n * @modified 2020-06-03 Added the getBounds() function.\n * @modified 2020-07-14 Changed the moveCurvePoint(...,Vertex) to moveCurvePoint(...,XYCoords), which is more generic.\n * @modified 2020-07-24 Added the getClosestT function and the helper function locateIntervalByDistance(...).\n * @modified 2021-01-20 Added UID.\n * @modified 2022-02-02 Added the `destroy` method.\n * @modified 2022-02-02 Cleared the `toSVGPathData` function (deprecated). Use `drawutilssvg` instead.\n * @modified 2022-10-17 The `CubicBezierCurve` class now implements the new `PathSegment` interface.\n * @modified 2023-09-30 Added the function `CubicbezierCurve.getSubCurve(number,number)` – similar to `getSubCurveAt(...)` but with absolute position parameters.\n * @modified 2023-10-07 Added the `trimEnd`, `trimEndAt`, `trimStart`, `trimStartAt` methods.\n * @modified 2025-04-09 Added the `CubicBezierCurve.move` method to match the convention – which just calls `translate`.\n * @modified 2025-04-09 Modified the `CubicBezierCurve.translate` method: chaning parameter `Vertex` to more generalized `XYCoords`.\n * @modified 2025-04-13 Changed visibility of `CubicBezierCurve.utils` from 'private' to  'public'.\n * @modified 2025-04-13 Added helper function `CubicBezierCurve.utils.bezierCoeffs`.\n * @modified 2025-04-13 Added helper functopn `CubicBezierCurve.utils.sgn(number)` for division safe sign calculation.\n * @modified 2025-03-13 Class `CubicBezierCurve` is now implementing interface `Intersectable`.\n * @modified 2025-04-18 Added evaluation method for cubic Bézier curves `CubicBezierCurve.utils.evaluateT`.\n * @modified 2025-04-18 Refactored method `CubicBezierCurve.getPointAt` to use `evaluateT`.\n * @modified 2025-04-18 Fixed the `CubicBezierCurve.getBounds` method: now returning the real bounding box. Before it was an approximated one.\n * @modified 2025-ß4-18 Added helper methods for bounding box calculation `CubucBezierCurve.util.cubicPolyMinMax` and `cubicPoly`.\n * @version 2.9.0\n *\n * @file CubicBezierCurve\n * @public\n **/\nimport { Bounds } from \"./Bounds\";\nimport { UIDGenerator } from \"./UIDGenerator\";\nimport { Vertex } from \"./Vertex\";\nimport { Vector } from \"./Vector\";\n/**\n * @classdesc A refactored cubic bezier curve class.\n *\n * @requires Bounds\n * @requires Vertex\n * @requires Vector\n * @requires XYCoords\n * @requires UID\n * @requires UIDGenerator\n */\nexport class CubicBezierCurve {\n    /**\n     * The constructor.\n     *\n     * @constructor\n     * @name CubicBezierCurve\n     * @param {Vertex} startPoint - The Bézier curve's start point.\n     * @param {Vertex} endPoint   - The Bézier curve's end point.\n     * @param {Vertex} startControlPoint - The Bézier curve's start control point.\n     * @param {Vertex} endControlPoint   - The Bézier curve's end control point.\n     **/\n    constructor(startPoint, endPoint, startControlPoint, endControlPoint) {\n        /** @constant {number} */\n        this.START_POINT = CubicBezierCurve.START_POINT;\n        /** @constant {number} */\n        this.START_CONTROL_POINT = CubicBezierCurve.START_CONTROL_POINT;\n        /** @constant {number} */\n        this.END_CONTROL_POINT = CubicBezierCurve.END_CONTROL_POINT;\n        /** @constant {number} */\n        this.END_POINT = CubicBezierCurve.END_POINT;\n        this.uid = UIDGenerator.next();\n        this.startPoint = startPoint;\n        this.startControlPoint = startControlPoint;\n        this.endPoint = endPoint;\n        this.endControlPoint = endControlPoint;\n        this.curveIntervals = 30;\n        // An array of vertices\n        this.segmentCache = [];\n        // An array of floats\n        this.segmentLengths = [];\n        // float\n        // this.arcLength = null;\n        this.updateArcLengths();\n    }\n    /**\n     * Move the given curve point (the start point, end point or one of the two\n     * control points).\n     *\n     * @method moveCurvePoint\n     * @param {number} pointID - The numeric identicator of the point to move. Use one of the four eBezierPoint constants.\n     * @param {XYCoords} moveAmount - The amount to move the specified point by.\n     * @param {boolean} moveControlPoint - Move the control points along with their path point (if specified point is a path point).\n     * @param {boolean} updateArcLengths - Specifiy if the internal arc segment buffer should be updated.\n     * @instance\n     * @memberof CubicBezierCurve\n     * @return {void}\n     **/\n    moveCurvePoint(pointID, moveAmount, moveControlPoint, updateArcLengths) {\n        if (pointID == this.START_POINT) {\n            this.getStartPoint().add(moveAmount);\n            if (moveControlPoint)\n                this.getStartControlPoint().add(moveAmount);\n        }\n        else if (pointID == this.START_CONTROL_POINT) {\n            this.getStartControlPoint().add(moveAmount);\n        }\n        else if (pointID == this.END_CONTROL_POINT) {\n            this.getEndControlPoint().add(moveAmount);\n        }\n        else if (pointID == this.END_POINT) {\n            this.getEndPoint().add(moveAmount);\n            if (moveControlPoint)\n                this.getEndControlPoint().add(moveAmount);\n        }\n        else {\n            console.log(`[CubicBezierCurve.moveCurvePoint] pointID '${pointID}' invalid.`);\n        }\n        if (updateArcLengths)\n            this.updateArcLengths();\n    }\n    /**\n     * Translate the whole curve by the given {x,y} amount: moves all four points.\n     *\n     * @method translate\n     * @param {XYCoords} amount - The amount to translate this curve by.\n     * @instance\n     * @memberof CubicBezierCurve\n     * @return {CubicBezierCurve} this (for chaining).\n     **/\n    translate(amount) {\n        this.startPoint.add(amount);\n        this.startControlPoint.add(amount);\n        this.endControlPoint.add(amount);\n        this.endPoint.add(amount);\n        return this;\n    }\n    /**\n     * Translate the whole curve by the given {x,y} amount: moves all four points.\n     *\n     * @method translate\n     * @param {XYCoords} amount - The amount to translate this curve by.\n     * @instance\n     * @memberof CubicBezierCurve\n     * @return {CubicBezierCurve} this (for chaining).\n     **/\n    move(amount) {\n        return this.translate(amount);\n    }\n    /**\n     * Reverse this curve, means swapping start- and end-point and swapping\n     * start-control- and end-control-point.\n     *\n     * @method reverse\n     * @instance\n     * @memberof CubicBezierCurve\n     * @return {CubicBezierCurve} this (for chaining).\n     **/\n    reverse() {\n        let tmp = this.startPoint;\n        this.startPoint = this.endPoint;\n        this.endPoint = tmp;\n        tmp = this.startControlPoint;\n        this.startControlPoint = this.endControlPoint;\n        this.endControlPoint = tmp;\n        return this;\n    }\n    /**\n     * Get the total curve length.<br>\n     * <br>\n     * As not all Bézier curved have a closed formula to calculate their lengths, this\n     * implementation uses a segment buffer (with a length of 30 segments). So the\n     * returned length is taken from the arc segment buffer.<br>\n     * <br>\n     * Note that if the curve points were changed and the segment buffer was not\n     * updated this function might return wrong (old) values.\n     *\n     * @method getLength\n     * @instance\n     * @memberof CubicBezierCurve\n     * @return {number} >= 0\n     **/\n    getLength() {\n        return this.arcLength;\n    }\n    /**\n     * Uptate the internal arc segment buffer and their lengths.<br>\n     * <br>\n     * All class functions update the buffer automatically; if any\n     * curve point is changed by other reasons you should call this\n     * function to keep actual values in the buffer.\n     *\n     * @method updateArcLengths\n     * @instance\n     * @memberof CubicBezierCurve\n     * @return {void}\n     **/\n    updateArcLengths() {\n        let pointA = this.startPoint.clone();\n        let pointB = new Vertex(0, 0);\n        let curveStep = 1.0 / this.curveIntervals;\n        // Clear segment cache\n        this.segmentCache = [];\n        // Push start point into buffer\n        this.segmentCache.push(this.startPoint);\n        this.segmentLengths = [];\n        let newLength = 0.0;\n        var t = 0.0;\n        let tmpLength;\n        while (t <= 1.0) {\n            pointB = this.getPointAt(t);\n            // Store point into cache\n            this.segmentCache.push(pointB);\n            // Calculate segment length\n            tmpLength = pointA.distance(pointB);\n            this.segmentLengths.push(tmpLength);\n            newLength += tmpLength;\n            pointA = pointB;\n            t += curveStep;\n        }\n        this.arcLength = newLength;\n    }\n    /**\n     * Get a 't' (relative position on curve) with the closest distance to point 'p'.\n     *\n     * The returned number is 0.0 <= t <= 1.0. Use the getPointAt(t) function to retrieve the actual curve point.\n     *\n     * This function uses a recursive approach by cutting the curve into several linear segments.\n     *\n     * @method getClosestT\n     * @instance\n     * @memberof CubicBezierCurve\n     * @param {Vertex} p - The point to find the closest position ('t' on the curve).\n     * @return {number}\n     **/\n    getClosestT(p) {\n        // We would like to have an error that's not larger than 1.0.\n        var desiredEpsilon = 1.0;\n        var result = { t: 0, tPrev: 0.0, tNext: 1.0 };\n        var iteration = 0;\n        do {\n            result = this.locateIntervalByDistance(p, result.tPrev, result.tNext, this.curveIntervals);\n            iteration++;\n            // Be sure: stop after 4 iterations\n        } while (iteration < 4 && this.getPointAt(result.tPrev).distance(this.getPointAt(result.tNext)) > desiredEpsilon);\n        return result.t;\n    }\n    /**\n     * This helper function locates the 't' on a fixed step interval with the minimal distance\n     * between the curve (at 't') and the given point.\n     *\n     * Furthermore you must specify a sub curve (start 't' and end 't') you want to search on.\n     * Using tStart=0.0 and tEnd=1.0 will search on the full curve.\n     *\n     * @param {Vertex} p - The point to find the closest curve point for.\n     * @param {number} tStart - The start position (start 't' of the sub curve). Should be >= 0.0.\n     * @param {number} tEnd - The end position (end 't' of the sub curve). Should be <= 1.0.\n     * @param {number} stepCount - The number of steps to check within the interval.\n     *\n     * @return {object} - An object with t, tPrev and tNext (numbers).\n     **/\n    locateIntervalByDistance(p, tStart, tEnd, stepCount) {\n        var minIndex = -1;\n        var minDist = 0;\n        var t = 0.0;\n        const tDiff = tEnd - tStart;\n        for (var i = 0; i <= stepCount; i++) {\n            t = tStart + tDiff * (i / stepCount);\n            var vert = this.getPointAt(t);\n            var dist = vert.distance(p);\n            if (minIndex == -1 || dist < minDist) {\n                minIndex = i;\n                minDist = dist;\n            }\n        }\n        return {\n            t: tStart + tDiff * (minIndex / stepCount),\n            tPrev: tStart + tDiff * (Math.max(0, minIndex - 1) / stepCount),\n            tNext: tStart + tDiff * (Math.min(stepCount, minIndex + 1) / stepCount)\n        };\n    }\n    //--- BEGIN --- Implement interface `IBounded`\n    /**\n     * Get the bounds of this bezier curve.\n     *\n     * The bounds are approximated by the underlying segment buffer; the more segment there are,\n     * the more accurate will be the returned bounds.\n     *\n     * @method getClosestT\n     * @instance\n     * @memberof CubicBezierCurve\n     * @return {Bounds} The bounds of this ellipse.\n     **/\n    getBounds() {\n        // Thanks to Richard \"RM\" for the Bézier bounds calculatin\n        //    https://jsfiddle.net/SalixAlba/QQnvm/4/\n        const xMinMax = CubicBezierCurve.utils.cubicPolyMinMax(this.startPoint.x, this.startControlPoint.x, this.endControlPoint.x, this.endPoint.x);\n        const xl = xMinMax.min;\n        const xh = xMinMax.max;\n        const yMinMax = CubicBezierCurve.utils.cubicPolyMinMax(this.startPoint.y, this.startControlPoint.y, this.endControlPoint.y, this.endPoint.y);\n        const yl = yMinMax.min;\n        const yh = yMinMax.max;\n        return Bounds.computeFromVertices([\n            { x: xl, y: yl },\n            { x: xl, y: yh },\n            { x: xh, y: yh },\n            { x: xh, y: yl }\n        ]);\n    }\n    //--- END --- Implement interface `IBounded`\n    /**\n     * Get the start point of the curve.<br>\n     * <br>\n     * This function just returns this.startPoint.\n     *\n     * @method getStartPoint\n     * @instance\n     * @memberof CubicBezierCurve\n     * @return {Vertex} this.startPoint\n     **/\n    getStartPoint() {\n        return this.startPoint;\n    }\n    /**\n     * Get the end point of the curve.<br>\n     * <br>\n     * This function just returns this.endPoint.\n     *\n     * @method getEndPoint\n     * @instance\n     * @memberof CubicBezierCurve\n     * @return {Vertex} this.endPoint\n     **/\n    getEndPoint() {\n        return this.endPoint;\n    }\n    /**\n     * Get the start control point of the curve.<br>\n     * <br>\n     * This function just returns this.startControlPoint.\n     *\n     * @method getStartControlPoint\n     * @instance\n     * @memberof CubicBezierCurve\n     * @return {Vertex} this.startControlPoint\n     **/\n    getStartControlPoint() {\n        return this.startControlPoint;\n    }\n    /**\n     * Get the end control point of the curve.<br>\n     * <br>\n     * This function just returns this.endControlPoint.\n     *\n     * @method getEndControlPoint\n     * @instance\n     * @memberof CubicBezierCurve\n     * @return {Vertex} this.endControlPoint\n     **/\n    getEndControlPoint() {\n        return this.endControlPoint;\n    }\n    /**\n     * Get one of the four curve points specified by the passt point ID.\n     *\n     * @method getEndControlPoint\n     * @param {number} id - One of START_POINT, START_CONTROL_POINT, END_CONTROL_POINT or END_POINT.\n     * @instance\n     * @memberof CubicBezierCurve\n     * @return {Vertex}\n     **/\n    getPointByID(id) {\n        if (id == this.START_POINT)\n            return this.startPoint;\n        if (id == this.END_POINT)\n            return this.endPoint;\n        if (id == this.START_CONTROL_POINT)\n            return this.startControlPoint;\n        if (id == this.END_CONTROL_POINT)\n            return this.endControlPoint;\n        throw new Error(`Invalid point ID '${id}'.`);\n    }\n    /**\n     * Get the curve point at a given position t, where t is in [0,1].<br>\n     * <br>\n     * @see Line.pointAt\n     *\n     * @method getPointAt\n     * @param {number} t - The position on the curve in [0,1] (0 means at\n     *                     start point, 1 means at end point, other values address points in bertween).\n     * @instance\n     * @memberof CubicBezierCurve\n     * @return {Vertex}\n     **/\n    getPointAt(t) {\n        // Perform some powerful math magic\n        // TODO: cleanup\n        // const x: number =\n        //   this.startPoint.x * Math.pow(1.0 - t, 3) +\n        //   this.startControlPoint.x * 3 * t * Math.pow(1.0 - t, 2) +\n        //   this.endControlPoint.x * 3 * Math.pow(t, 2) * (1.0 - t) +\n        //   this.endPoint.x * Math.pow(t, 3);\n        // const y: number =\n        //   this.startPoint.y * Math.pow(1.0 - t, 3) +\n        //   this.startControlPoint.y * 3 * t * Math.pow(1.0 - t, 2) +\n        //   this.endControlPoint.y * 3 * Math.pow(t, 2) * (1.0 - t) +\n        //   this.endPoint.y * Math.pow(t, 3);\n        const x = CubicBezierCurve.utils.evaluateT(this.startPoint.x, this.startControlPoint.x, this.endControlPoint.x, this.endPoint.x, t);\n        const y = CubicBezierCurve.utils.evaluateT(this.startPoint.y, this.startControlPoint.y, this.endControlPoint.y, this.endPoint.y, t);\n        return new Vertex(x, y);\n    }\n    /**\n     * Get the curve point at a given position u, where u is in [0,arcLength].<br>\n     * <br>\n     * @see CubicBezierCurve.getPointAt\n     *\n     * @method getPoint\n     * @param {number} u - The position on the curve in [0,arcLength] (0 means at\n     *                     start point, arcLength means at end point, other values address points in bertween).\n     * @instance\n     * @memberof CubicBezierCurve\n     * @return {Vertex}\n     **/\n    getPoint(u) {\n        return this.getPointAt(u / this.arcLength);\n    }\n    /**\n     * Get the curve tangent vector at a given absolute curve position t in [0,1].<br>\n     * <br>\n     * Note that the returned tangent vector (end point) is not normalized and relative to (0,0).\n     *\n     * @method getTangent\n     * @param {number} t - The position on the curve in [0,1].\n     * @instance\n     * @memberof CubicBezierCurve\n     * @return {Vertex}\n     **/\n    getTangentAt(t) {\n        const a = this.getStartPoint();\n        const b = this.getStartControlPoint();\n        const c = this.getEndControlPoint();\n        const d = this.getEndPoint();\n        // This is the shortened one\n        const t2 = t * t;\n        // (1 - t)^2 = (1-t)*(1-t) = 1 - t - t + t^2 = 1 - 2*t + t^2\n        const nt2 = 1 - 2 * t + t2;\n        const tX = -3 * a.x * nt2 + b.x * (3 * nt2 - 6 * (t - t2)) + c.x * (6 * (t - t2) - 3 * t2) + 3 * d.x * t2;\n        const tY = -3 * a.y * nt2 + b.y * (3 * nt2 - 6 * (t - t2)) + c.y * (6 * (t - t2) - 3 * t2) + 3 * d.y * t2;\n        // Note: my implementation does NOT normalize tangent vectors!\n        return new Vertex(tX, tY);\n    }\n    /**\n     * Trim off a start section of this curve. The position parameter `uValue` is the absolute position on the\n     * curve in `[0...arcLength]`.\n     * The remaining curve will be the one in the bounds `[uValue,1]` (so `[0.0,uValue]` is cut off).\n     *\n     * Note this function just converts the absolute parameter to a relative one and call `trimStartAt`.\n     *\n     * @method trimStart\n     * @instance\n     * @memberof CubicBezierCurve\n     * @param {number} uValue - The absolute position parameter where to cut off the head curve.\n     * @returns {CubicBezierCurve} `this` for chanining.\n     */\n    trimStart(uValue) {\n        return this.trimStartAt(this.convertU2T(uValue));\n    }\n    /**\n     * Trim off a start section of this curve. The position parameter `t` is the relative position in [0..1].\n     * The remaining curve will be the one in the bounds `[uValue,1]` (so `[0.0,uValue]` is cut off).\n     *\n     * @method trimStartAt\n     * @instance\n     * @memberof CubicBezierCurve\n     * @param {number} t - The relative position parameter where to cut off the head curve.\n     * @returns {CubicBezierCurve} `this` for chanining.\n     */\n    trimStartAt(t) {\n        const subCurbePoints = CubicBezierCurve.utils.getSubCurvePointsAt(this, t, 1.0);\n        this.startPoint.set(subCurbePoints[0]);\n        this.startControlPoint.set(subCurbePoints[2]);\n        this.endPoint.set(subCurbePoints[1]);\n        this.endControlPoint.set(subCurbePoints[3]);\n        this.updateArcLengths();\n        return this;\n    }\n    /**\n     * Trim off the end of this curve. The position parameter `uValue` is the absolute position on the\n     * curve in `[0...arcLength]`.\n     * The remaining curve will be the one in the bounds `[0,uValue]` (so `[1.0-uValue,1.0]` is cut off).\n     *\n     * Note this function just converts the absolute parameter to a relative one and call `trimEndAt`.\n     *\n     * @method trimEnd\n     * @instance\n     * @memberof CubicBezierCurve\n     * @param {number} uValue - The absolute position parameter where to cut off the tail curve.\n     * @returns {CubicBezierCurve} `this` for chanining.\n     */\n    trimEnd(uValue) {\n        return this.trimEndAt(this.convertU2T(uValue));\n    }\n    /**\n     * Trim off the end of this curve. The position parameter `t` is the relative position in [0..1].\n     * The remaining curve will be the one in the bounds `[0,t]` (so `[1.0-t,1.0]` is cut off).\n     *\n     * @method trimEndAt\n     * @instance\n     * @memberof CubicBezierCurve\n     * @param {number} t - The relative position parameter where to cut off the tail curve.\n     * @returns {CubicBezierCurve} `this` for chanining.\n     */\n    trimEndAt(t) {\n        const subCurbePoints = CubicBezierCurve.utils.getSubCurvePointsAt(this, 0.0, t);\n        this.startPoint.set(subCurbePoints[0]);\n        this.startControlPoint.set(subCurbePoints[2]);\n        this.endPoint.set(subCurbePoints[1]);\n        this.endControlPoint.set(subCurbePoints[3]);\n        this.updateArcLengths();\n        return this;\n    }\n    /**\n     * Get a sub curve at the given start end end positions (values on the curve's length, between 0 and curve.arcLength).\n     *\n     * tStart >= tEnd is allowed, you will get a reversed sub curve then.\n     *\n     * @method getSubCurve\n     * @param {number} tStart – The start position of the desired sub curve (must be in [0..arcLength]).\n     * @param {number} tEnd – The end position if the desired cub curve (must be in [0..arcLength]).\n     * @instance\n     * @memberof CubicBezierCurve\n     * @return {CubicBezierCurve} The sub curve as a new curve.\n     **/\n    getSubCurve(uStart, uEnd) {\n        return this.getSubCurveAt(this.convertU2T(uStart), this.convertU2T(uEnd));\n    }\n    /**\n     * Get a sub curve at the given start end end offsets (values between 0.0 and 1.0).\n     *\n     * tStart >= tEnd is allowed, you will get a reversed sub curve then.\n     *\n     * @method getSubCurveAt\n     * @param {number} tStart – The start offset of the desired sub curve (must be in [0..1]).\n     * @param {number} tEnd – The end offset if the desired cub curve (must be in [0..1]).\n     * @instance\n     * @memberof CubicBezierCurve\n     * @return {CubicBezierCurve} The sub curve as a new curve.\n     **/\n    getSubCurveAt(tStart, tEnd) {\n        // This 'splits' the curve at the given point at t.\n        const subCurbePoints = CubicBezierCurve.utils.getSubCurvePointsAt(this, tStart, tEnd);\n        return new CubicBezierCurve(subCurbePoints[0], subCurbePoints[1], subCurbePoints[2], subCurbePoints[3]);\n    }\n    /**\n     * Convert a relative curve position u to the absolute curve position t.\n     *\n     * @method convertU2t\n     * @param {number} u - The relative position on the curve in [0,arcLength].\n     * @instance\n     * @memberof CubicBezierCurve\n     * @return {number}\n     **/\n    convertU2T(u) {\n        return Math.max(0.0, Math.min(1.0, u / this.arcLength));\n    }\n    /**\n     * Get the curve tangent vector at a given relative position u in [0,arcLength].<br>\n     * <br>\n     * Note that the returned tangent vector (end point) is not normalized.\n     *\n     * @method getTangent\n     * @param {number} u - The position on the curve in [0,arcLength].\n     * @instance\n     * @memberof CubicBezierCurve\n     * @return {Vertex}\n     **/\n    getTangent(u) {\n        return this.getTangentAt(this.convertU2T(u));\n    }\n    /**\n     * Get the curve perpendicular at a given relative position u in [0,arcLength] as a vector.<br>\n     * <br>\n     * Note that the returned vector (end point) is not normalized.\n     *\n     * @method getPerpendicular\n     * @param {number} u - The relative position on the curve in [0,arcLength].\n     * @instance\n     * @memberof CubicBezierCurve\n     * @return {Vertex}\n     **/\n    getPerpendicular(u) {\n        return this.getPerpendicularAt(this.convertU2T(u));\n    }\n    /**\n     * Get the curve perpendicular at a given absolute position t in [0,1] as a vector.<br>\n     * <br>\n     * Note that the returned vector (end point) is not normalized.\n     *\n     * @method getPerpendicularAt\n     * @param {number} u - The absolute position on the curve in [0,1].\n     * @instance\n     * @memberof CubicBezierCurve\n     * @return {Vertex}\n     **/\n    getPerpendicularAt(t) {\n        const tangentVector = this.getTangentAt(t);\n        return new Vertex(tangentVector.y, -tangentVector.x);\n    }\n    /**\n     * Clone this Bézier curve (deep clone).\n     *\n     * @method clone\n     * @instance\n     * @memberof CubicBezierCurve\n     * @return {CubicBezierCurve}\n     **/\n    clone() {\n        return new CubicBezierCurve(this.getStartPoint().clone(), this.getEndPoint().clone(), this.getStartControlPoint().clone(), this.getEndControlPoint().clone());\n    }\n    //---BEGIN PathSegment-------------------------\n    /**\n     * Get the tangent's end point at the start point of this segment.\n     *\n     * @method getStartTangent\n     * @memberof PathSegment\n     * @return {Vertex} The end point of the starting point's tangent.\n     */\n    getStartTangent() {\n        return this.startControlPoint;\n    }\n    /**\n     * Get the tangent's end point at the end point of this segment.\n     *\n     * @method getEndTangent\n     * @memberof PathSegment\n     * @return {Vertex} The end point of the ending point's tangent.\n     */\n    getEndTangent() {\n        return this.endControlPoint;\n    }\n    //---END PathSegment-------------------------\n    //--- BEGIN --- Implement interface `Intersectable`\n    /**\n     * Get all line intersections with this shape.\n     *\n     * This method returns all intersections (as vertices) with this shape. The returned array of vertices is in no specific order.\n     *\n     * @param {VertTuple} line - The line to find intersections with.\n     * @param {boolean} inVectorBoundsOnly - If set to true only intersecion points on the passed vector are returned (located strictly between start and end vertex).\n     * @returns {Array<Vertex>} - An array of all intersections with the shape outline.\n     */\n    lineIntersections(line, inVectorBoundsOnly = false) {\n        const intersectionTs = this.lineIntersectionTs(line);\n        const intersectionPoints = intersectionTs.map((t) => {\n            return this.getPointAt(t);\n        });\n        if (inVectorBoundsOnly) {\n            // const maxDist = line.length();\n            return intersectionPoints.filter((vert) => line.hasPoint(vert, true));\n        }\n        else {\n            return intersectionPoints;\n        }\n    }\n    /**\n     * Get all line intersections of this polygon and their tangents along the shape.\n     *\n     * This method returns all intersection tangents (as vectors) with this shape. The returned array of vectors is in no specific order.\n     *\n     * @param line\n     * @param lineIntersectionTangents\n     * @returns\n     */\n    lineIntersectionTangents(line, inVectorBoundsOnly = false) {\n        const intersectionTs = this.lineIntersectionTs(line);\n        const intersectionTangents = intersectionTs.map((t) => {\n            const startPoint = this.getPointAt(t);\n            const endPoint = this.getTangentAt(t);\n            return new Vector(startPoint, endPoint.add(startPoint));\n        });\n        if (inVectorBoundsOnly) {\n            return intersectionTangents.filter((vec) => line.hasPoint(vec.a, true));\n        }\n        else {\n            return intersectionTangents;\n        }\n    }\n    //--- END --- Implement interface `Intersectable`\n    lineIntersectionTs(line) {\n        var A = line.b.y - line.a.y; // A=y2-y1\n        var B = line.a.x - line.b.x; // B=x1-x2\n        var C = line.a.x * (line.a.y - line.b.y) + line.a.y * (line.b.x - line.a.x); //C=x1*(y1-y2)+y1*(x2-x1)\n        // var bx = bezierCoeffs(px[0], px[1], px[2], px[3]);\n        // var by = bezierCoeffs(py[0], py[1], py[2], py[3]);\n        var bx = CubicBezierCurve.utils.bezierCoeffs(this.startPoint.x, this.startControlPoint.x, this.endControlPoint.x, this.endPoint.x);\n        var by = CubicBezierCurve.utils.bezierCoeffs(this.startPoint.y, this.startControlPoint.y, this.endControlPoint.y, this.endPoint.y);\n        const poly = Array(4);\n        poly[0] = A * bx[0] + B * by[0]; /*t^3*/\n        poly[1] = A * bx[1] + B * by[1]; /*t^2*/\n        poly[2] = A * bx[2] + B * by[2]; /*t*/\n        poly[3] = A * bx[3] + B * by[3] + C; /*1*/\n        var roots = CubicBezierCurve.utils.cubicRoots(poly);\n        return roots.filter((root) => root != -1);\n    }\n    /**\n     * Check if this and the specified curve are equal.<br>\n     * <br>\n     * All four points need to be equal for this, the Vertex.equals function is used.<br>\n     * <br>\n     * Please note that this function is not type safe (comparison with any object will fail).\n     *\n     * @method clone\n     * @param {CubicBezierCurve} curve - The curve to compare with.\n     * @instance\n     * @memberof CubicBezierCurve\n     * @return {boolean}\n     **/\n    equals(curve) {\n        // Note: in the earlier vanilla-JS version this was callable with plain objects.\n        //       Let's see if this restricted version works out.\n        if (!curve)\n            return false;\n        if (!curve.startPoint || !curve.endPoint || !curve.startControlPoint || !curve.endControlPoint)\n            return false;\n        return (this.startPoint.equals(curve.startPoint) &&\n            this.endPoint.equals(curve.endPoint) &&\n            this.startControlPoint.equals(curve.startControlPoint) &&\n            this.endControlPoint.equals(curve.endControlPoint));\n    }\n    /**\n     * This function should invalidate any installed listeners and invalidate this object.\n     * After calling this function the object might not hold valid data any more and\n     * should not be used.\n     */\n    destroy() {\n        this.startPoint.destroy();\n        this.endPoint.destroy();\n        this.startControlPoint.destroy();\n        this.endControlPoint.destroy();\n        this.isDestroyed = true;\n    }\n    /**\n     * Quick check for class instance.\n     * Is there a better way?\n     *\n     * @method isInstance\n     * @param {any} obj - Check if the passed object/value is an instance of CubicBezierCurve.\n     * @instance\n     * @memberof CubicBezierCurve\n     * @return {boolean}\n     **/\n    static isInstance(obj) {\n        // Note: check this again\n        /* OLD VANILLA JS IMPLEMENTATION */\n        /* if( typeof obj != \"object\" )\n            return false;\n        function hasXY(v) {\n            return typeof v != \"undefined\" && typeof v.x == \"number\" && typeof v.y == \"number\";\n        }\n        return typeof obj.startPoint == \"object\" && hasXY(obj.startPoint)\n            && typeof obj.endPoint == \"object\" && hasXY(obj.endPoint)\n            && typeof obj.startControlPoint == \"object\" && hasXY(obj.startControlPoint)\n            && typeof obj.endControlPoint == \"object\" && hasXY(obj.endControlPoint);\n        */\n        return obj instanceof CubicBezierCurve;\n    }\n    /**\n     * Convert this curve to a JSON string.\n     *\n     * @method toJSON\n     * @param {boolean=} [prettyFormat=false] - If set to true the function will add line breaks.\n     * @instance\n     * @memberof CubicBezierCurve\n     * @return {string} The JSON data.\n     **/\n    toJSON(prettyFormat) {\n        var jsonString = \"{ \" + // begin object\n            (prettyFormat ? \"\\n\\t\" : \"\") +\n            '\"startPoint\" : [' +\n            this.getStartPoint().x +\n            \",\" +\n            this.getStartPoint().y +\n            \"], \" +\n            (prettyFormat ? \"\\n\\t\" : \"\") +\n            '\"endPoint\" : [' +\n            this.getEndPoint().x +\n            \",\" +\n            this.getEndPoint().y +\n            \"], \" +\n            (prettyFormat ? \"\\n\\t\" : \"\") +\n            '\"startControlPoint\": [' +\n            this.getStartControlPoint().x +\n            \",\" +\n            this.getStartControlPoint().y +\n            \"], \" +\n            (prettyFormat ? \"\\n\\t\" : \"\") +\n            '\"endControlPoint\" : [' +\n            this.getEndControlPoint().x +\n            \",\" +\n            this.getEndControlPoint().y +\n            \"]\" +\n            (prettyFormat ? \"\\n\\t\" : \"\") +\n            \" }\"; // end object\n        return jsonString;\n    }\n    /**\n     * Parse a Bézier curve from the given JSON string.\n     *\n     * @method fromJSON\n     * @param {string} jsonString - The JSON data to parse.\n     * @memberof CubicBezierCurve\n     * @static\n     * @throws An exception if the JSON string is malformed.\n     * @return {CubicBezierCurve}\n     **/\n    static fromJSON(jsonString) {\n        var obj = JSON.parse(jsonString);\n        return CubicBezierCurve.fromObject(obj);\n    }\n    /**\n     * Try to convert the passed object to a CubicBezierCurve.\n     *\n     * @method fromObject\n     * @param {object} obj - The object to convert.\n     * @memberof CubicBezierCurve\n     * @static\n     * @throws An exception if the passed object is malformed.\n     * @return {CubicBezierCurve}\n     **/\n    static fromObject(obj) {\n        if (typeof obj !== \"object\")\n            throw \"Can only build from object.\";\n        if (!obj.startPoint)\n            throw 'Object member \"startPoint\" missing.';\n        if (!obj.endPoint)\n            throw 'Object member \"endPoint\" missing.';\n        if (!obj.startControlPoint)\n            throw 'Object member \"startControlPoint\" missing.';\n        if (!obj.endControlPoint)\n            throw 'Object member \"endControlPoint\" missing.';\n        return new CubicBezierCurve(new Vertex(obj.startPoint[0], obj.startPoint[1]), new Vertex(obj.endPoint[0], obj.endPoint[1]), new Vertex(obj.startControlPoint[0], obj.startControlPoint[1]), new Vertex(obj.endControlPoint[0], obj.endControlPoint[1]));\n    }\n    /**\n     * Convert a 4-element array of vertices to a cubic bézier curve.\n     *\n     * @method fromArray\n     * @param {Vertex[]} arr -  [ startVertex, endVertex, startControlVertex, endControlVertex ]\n     * @memberof CubicBezierCurve\n     * @throws An exception if the passed array is malformed.\n     * @return {CubicBezierCurve}\n     **/\n    static fromArray(arr) {\n        if (!Array.isArray(arr))\n            throw \"Can only build from object.\";\n        if (arr.length != 4)\n            throw \"Can only build from array with four elements.\";\n        return new CubicBezierCurve(arr[0], arr[1], arr[2], arr[3]);\n    }\n}\n/** @constant {number} */\nCubicBezierCurve.START_POINT = 0;\n/** @constant {number} */\nCubicBezierCurve.START_CONTROL_POINT = 1;\n/** @constant {number} */\nCubicBezierCurve.END_CONTROL_POINT = 2;\n/** @constant {number} */\nCubicBezierCurve.END_POINT = 3;\n/**\n * Helper utils.\n */\nCubicBezierCurve.utils = {\n    evaluateT: (p0, p1, p2, p3, t) => {\n        return p0 * Math.pow(1.0 - t, 3) +\n            p1 * 3 * t * Math.pow(1.0 - t, 2) +\n            p2 * 3 * Math.pow(t, 2) * (1.0 - t) +\n            p3 * Math.pow(t, 3);\n    },\n    cubicPolyMinMax: (p0, p1, p2, p3) => {\n        // var polyX = CubicBezierCurve.utils.cubicPoly2(\n        //   p0, // P[0].X, // bezierCurve.startPoint.x,\n        //   p1, // P[1].X, // bezierCurve.startControlPoint.x,\n        //   p2, // P[2].X, // bezierCurve.endControlPoint.x,\n        //   p3 // P[3].X // bezierCurve.endPoint.x\n        // );\n        // var a = polyX.a;\n        // var b = polyX.b;\n        // var c = polyX.c;\n        // var disc = polyX.b * polyX.b - 4 * polyX.a * polyX.c;\n        var polyX = CubicBezierCurve.utils.cubicPoly(p0, // P[0].X, // bezierCurve.startPoint.x,\n        p1, // P[1].X, // bezierCurve.startControlPoint.x,\n        p2, // P[2].X, // bezierCurve.endControlPoint.x,\n        p3 // P[3].X // bezierCurve.endPoint.x\n        );\n        var a = polyX[0]; // .a;\n        var b = polyX[1]; // .b;\n        var c = polyX[2]; // .c;\n        //alert(\"a \"+a+\" \"+b+\" \"+c);\n        // var disc = b * b - 4 * a * c;\n        var disc = polyX[1] * polyX[1] - 4 * polyX[0] * polyX[2];\n        // var polyX = CubicBezierCurve.utils.bezierCoeffs(p3,p2,p1,p0);\n        // var a = polyX[0]; //polyX.a;\n        // var b = polyX[1]; // .b;\n        // var c = polyX[2]; //.c;\n        // var disc = polyX[1] * polyX[1] - 4 * polyX[0] * polyX[2];\n        // var xl = Math.min(bCurve.endPoint.x, bCurve.startPoint.x); // P[0].X;\n        // var xh = Math.max(bCurve.endPoint.x, bCurve.startPoint.x); // P[0].X;\n        var xl = Math.min(p3, p0); // P[0].X;\n        var xh = Math.max(p3, p0); // P[0].X;\n        // if (P[3].X < xl) xl = P[3].X;\n        // if (P[3].X > xh) xh = P[3].X;\n        if (disc >= 0) {\n            var t1 = (-b + Math.sqrt(disc)) / (2 * a);\n            // alert(\"t1 \" + t1);\n            if (t1 > 0 && t1 < 1) {\n                // var x1 = evalBez(PX, t1);\n                // var x1 = bCurve.getPointAt(t1).x;\n                var x1 = CubicBezierCurve.utils.evaluateT(p0, p1, p2, p3, t1); // bCurve.getPointAt(t1).x;\n                if (x1 < xl)\n                    xl = x1;\n                if (x1 > xh)\n                    xh = x1;\n            }\n            var t2 = (-b - Math.sqrt(disc)) / (2 * a);\n            // alert(\"t2 \" + t2);\n            if (t2 > 0 && t2 < 1) {\n                // var x2 = evalBez(PX, t2);\n                // var x2 = bCurve.getPointAt(t2).x;\n                var x2 = CubicBezierCurve.utils.evaluateT(p0, p1, p2, p3, t2); //\n                if (x2 < xl)\n                    xl = x2;\n                if (x2 > xh)\n                    xh = x2;\n            }\n        }\n        return { min: xl, max: xh };\n    },\n    /**\n     * Get the points of a sub curve at the given start end end offsets (values between 0.0 and 1.0).\n     *\n     * tStart >= tEnd is allowed, you will get a reversed sub curve then.\n     *\n     * @method getSubCurvePointsAt\n     * @param {CubicBezierCurve} curve – The curve to get the sub curve points from.\n     * @param {number} tStart – The start offset of the desired sub curve (must be in [0..1]).\n     * @param {number} tEnd – The end offset if the desired cub curve (must be in [0..1]).\n     * @instance\n     * @memberof CubicBezierCurve\n     * @return {CubicBezierCurve} The sub curve as a new curve.\n     **/\n    getSubCurvePointsAt: (curve, tStart, tEnd) => {\n        const startVec = new Vector(curve.getPointAt(tStart), curve.getTangentAt(tStart));\n        const endVec = new Vector(curve.getPointAt(tEnd), curve.getTangentAt(tEnd).inv());\n        // Tangents are relative. Make absolute.\n        startVec.b.add(startVec.a);\n        endVec.b.add(endVec.a);\n        // This 'splits' the curve at the given point at t.\n        startVec.scale(0.33333333 * (tEnd - tStart));\n        endVec.scale(0.33333333 * (tEnd - tStart));\n        return [startVec.a, endVec.a, startVec.b, endVec.b];\n    },\n    /**\n     * Compute the cubic roots for the given cubic polynomial coefficients.\n     *\n     * Based on\n     *   http://mysite.verizon.net/res148h4j/javascript/script_exact_cubic.html#the%20source%20code\n     * Inspired by\n     *   https://www.particleincell.com/2013/cubic-line-intersection/\n     * Thanks to Stephan Schmitt and Particle-In-Cell!\n     *\n     * @param poly\n     * @returns\n     */\n    cubicRoots: (poly) => {\n        const a = poly[0];\n        const b = poly[1];\n        const c = poly[2];\n        const d = poly[3];\n        const A = b / a;\n        const B = c / a;\n        const C = d / a;\n        var S, T, Im;\n        const Q = (3 * B - Math.pow(A, 2)) / 9;\n        const R = (9 * A * B - 27 * C - 2 * Math.pow(A, 3)) / 54;\n        const D = Math.pow(Q, 3) + Math.pow(R, 2); // polynomial discriminant\n        const ts = []; // Array();\n        if (D >= 0) {\n            // complex or duplicate roots\n            S = CubicBezierCurve.utils.sgn(R + Math.sqrt(D)) * Math.pow(Math.abs(R + Math.sqrt(D)), 1 / 3);\n            T = CubicBezierCurve.utils.sgn(R - Math.sqrt(D)) * Math.pow(Math.abs(R - Math.sqrt(D)), 1 / 3);\n            ts[0] = -A / 3 + (S + T); // real root\n            ts[1] = -A / 3 - (S + T) / 2; // real part of complex root\n            ts[2] = -A / 3 - (S + T) / 2; // real part of complex root\n            Im = Math.abs((Math.sqrt(3) * (S - T)) / 2); // complex part of root pair\n            // Mark complex roots to be discarded\n            if (Im != 0) {\n                ts[1] = -1;\n                ts[2] = -1;\n            }\n        } // distinct real roots\n        else {\n            const th = Math.acos(R / Math.sqrt(-Math.pow(Q, 3)));\n            ts[0] = 2 * Math.sqrt(-Q) * Math.cos(th / 3) - A / 3;\n            ts[1] = 2 * Math.sqrt(-Q) * Math.cos((th + 2 * Math.PI) / 3) - A / 3;\n            ts[2] = 2 * Math.sqrt(-Q) * Math.cos((th + 4 * Math.PI) / 3) - A / 3;\n            Im = 0.0;\n        }\n        // Discard all t's out of spec and sort the rest\n        return ts.filter((t) => t >= 0 && t <= 1.0).sort();\n    },\n    /**\n     * Compute the Bézier coefficients from the given Bézier point coordinates.\n     *\n     * @param {number} p0 - The start point coordinate.\n     * @param {number} p1 - The start control point coordinate.\n     * @param {number} p2 - The end control point coordinate.\n     * @param {number} p3 - The end point coordinate.\n     * @returns {[number,number,number,number]}\n     */\n    bezierCoeffs: (p0, p1, p2, p3) => {\n        const coeffs = [NaN, NaN, NaN, NaN]; //Array(4);\n        coeffs[0] = -p0 + 3 * p1 + -3 * p2 + p3;\n        coeffs[1] = 3 * p0 - 6 * p1 + 3 * p2;\n        coeffs[2] = -3 * p0 + 3 * p1;\n        coeffs[3] = p0;\n        return coeffs;\n    },\n    /**\n     * Calculate the cubic polynomial coefficients used to find the bounding box.\n     *\n     * @param {number} p0 - The start point coordinate.\n     * @param {number} p1 - The start control point coordinate.\n     * @param {number} p2 - The end control point coordinate.\n     * @param {number} p3 - The end point coordinate.\n     * @returns {[number,number,number]}\n     */\n    cubicPoly: (p0, p1, p2, p3) => {\n        return [\n            3 * p3 - 9 * p2 + 9 * p1 - 3 * p0,\n            6 * p0 - 12 * p1 + 6 * p2,\n            3 * p1 - 3 * p0\n        ];\n    },\n    /**\n     * sign of number, but is division safe: no zero returned :)\n     */\n    sgn(x) {\n        return x < 0.0 ? -1 : 1;\n    }\n};\n//# sourceMappingURL=CubicBezierCurve.js.map","/**\n * @author Ikaros Kappler\n * @date 2013-08-19\n * @modified 2018-08-16 Added closure. Removed the 'IKRS' wrapper.\n * @modified 2018-11-20 Added circular auto-adjustment.\n * @modified 2018-11-25 Added the point constants to the BezierPath class itself.\n * @modified 2018-11-28 Added the locateCurveByStartPoint() function.\n * @modified 2018-12-04 Added the toSVGString() function.\n * @modified 2019-03-23 Added JSDoc tags.\n * @modified 2019-03-23 Changed the fuctions getPoint and getPointAt to match semantics in the Line class.\n * @modified 2019-11-18 Fixed the clone function: adjustCircular attribute was not cloned.\n * @modified 2019-12-02 Removed some excessive comments.\n * @modified 2019-12-04 Fixed the missing obtainHandleLengths behavior in the adjustNeightbourControlPoint function.\n * @modified 2020-02-06 Added function locateCurveByEndPoint( Vertex ).\n * @modified 2020-02-11 Added 'return this' to the scale(Vertex,number) and to the translate(Vertex) function.\n * @modified 2020-03-24 Ported this class from vanilla-JS to Typescript.\n * @modified 2020-06-03 Made the private helper function _locateUIndex to a private function.\n * @modified 2020-06-03 Added the getBounds() function.\n * @modified 2020-07-14 Changed the moveCurvePoint(...,Vertex) to moveCurvePoint(...,XYCoords).\n * @modified 2020-07-24 Added the getClosestT(Vertex) function.\n * @modified 2020-12-29 Constructor is now private (no explicit use intended).\n * @modified 2021-05-25 Added BezierPath.fromReducedList( Array<number> ).\n * @modified 2022-01-31 Added `BezierPath.getEvenDistributionVertices(number)`.\n * @modified 2022-02-02 Added the `destroy` method.\n * @modified 2022-02-02 Cleared the `toSVGString` function (deprecated). Use `drawutilssvg` instead.\n * @modified 2023-10-06 Adding the `BezierPath.toPathPoints()` method.\n * @modified 2023-10-07 Adding the `BezierPath.fromCurve(CubicBezierCurve)` static function.\n * @modified 2025-04-09 Added the `BezierPath.move` method to match the convention – which just calls `translate`.\n * @modified 2025-04-09 Modified the `BezierPath.translate` method: chaning parameter `Vertex` to more generalized `XYCoords`.\n * @modified 2025-04-14 Class `BezierPath` is now implementing interface `Intersectable`.\n * @version 2.7.0\n *\n * @file BezierPath\n * @public\n **/\nimport { Bounds } from \"./Bounds\";\nimport { CubicBezierCurve } from \"./CubicBezierCurve\";\nimport { UIDGenerator } from \"./UIDGenerator\";\nimport { Vertex } from \"./Vertex\";\n/**\n * @classdesc A BezierPath class.\n *\n * This was refactored from an older project.\n *\n * @requires Bounds\n * @requires Vertex\n * @requires CubicBezierCurve\n * @requires XYCoords\n * @requires SVGSerializable\n * @requires UID\n * @requires UIDGenerator\n **/\nexport class BezierPath {\n    /**\n     * The constructor.<br>\n     * <br>\n     * This constructor expects a sequence of path points and will approximate\n     * the location of control points by picking some between the points.<br>\n     * You should consider just constructing empty paths and then add more curves later using\n     * the addCurve() function.\n     *\n     * @constructor\n     * @name BezierPath\n     * @param {Vertex[]} pathPoints - An array of path vertices (no control points).\n     **/\n    constructor() {\n        /**\n         * Required to generate proper CSS classes and other class related IDs.\n         **/\n        this.className = \"BezierPath\";\n        /** @constant {number} */\n        this.START_POINT = 0;\n        /** @constant {number} */\n        this.START_CONTROL_POINT = 1;\n        /** @constant {number} */\n        this.END_CONTROL_POINT = 2;\n        /** @constant {number} */\n        this.END_POINT = 3;\n        // pathPoints: Array<Vertex> | undefined | null) {\n        this.uid = UIDGenerator.next();\n        // if (!pathPoints) {\n        //   pathPoints = [];\n        // }\n        this.totalArcLength = 0.0;\n        // Set this flag to true if you want the first point and\n        // last point of the path to be auto adjusted, too.\n        this.adjustCircular = false;\n        this.bezierCurves = [];\n    }\n    /**\n     * Add a cubic bezier curve to the end of this path.\n     *\n     * @method addCurve\n     * @param {CubicBezierCurve} curve - The curve to be added to the end of the path.\n     * @instance\n     * @memberof BezierPath\n     * @return {void}\n     **/\n    addCurve(curve) {\n        if (curve == null || typeof curve == \"undefined\")\n            throw \"Cannot add null curve to bézier path.\";\n        this.bezierCurves.push(curve);\n        if (this.bezierCurves.length > 1) {\n            curve.startPoint = this.bezierCurves[this.bezierCurves.length - 2].endPoint;\n            this.adjustSuccessorControlPoint(this.bezierCurves.length - 2, // curveIndex,\n            true, // obtainHandleLength,\n            true // updateArcLengths\n            );\n        }\n        else {\n            this.totalArcLength += curve.getLength();\n        }\n    }\n    /**\n     * Locate the curve with the given start point (function returns the index).\n     *\n     * @method locateCurveByStartPoint\n     * @param {Vertex} point - The (curve start-) point to look for.\n     * @instance\n     * @memberof BezierPath\n     * @return {number} The curve index or -1 if curve (start-) point not found\n     **/\n    locateCurveByStartPoint(point) {\n        // for( var i in this.bezierCurves ) {\n        for (var i = 0; i < this.bezierCurves.length; i++) {\n            if (this.bezierCurves[i].startPoint.equals(point))\n                return i;\n        }\n        return -1;\n    }\n    /**\n     * Locate the curve with the given end point (function returns the index).\n     *\n     * @method locateCurveByEndPoint\n     * @param {Vertex} point - The (curve end-) point to look for.\n     * @instance\n     * @memberof BezierPath\n     * @return {number} The curve index or -1 if curve (end-) point not found\n     **/\n    locateCurveByEndPoint(point) {\n        // for( var i in this.bezierCurves ) {\n        for (var i = 0; i < this.bezierCurves.length; i++) {\n            if (this.bezierCurves[i].endPoint.equals(point))\n                return i;\n        }\n        return -1;\n    }\n    /**\n     * Locate the curve with the given start point (function returns the index).\n     *\n     * @method locateCurveByStartControlPoint\n     * @param {Vertex} point - The (curve endt-) point to look for.\n     * @instance\n     * @memberof BezierPath\n     * @return {number} The curve index or -1 if curve (end-) point not found\n     **/\n    locateCurveByStartControlPoint(point) {\n        // for( var i in this.bezierCurves ) {\n        for (var i = 0; i < this.bezierCurves.length; i++) {\n            if (this.bezierCurves[i].startControlPoint.equals(point))\n                return i;\n        }\n        return -1;\n    }\n    // +---------------------------------------------------------------------------------\n    // | Locate the curve with the given end control point.\n    // |\n    // | @param point:Vertex The point to look for.\n    // | @return Number The index or -1 if not found.\n    // +-------------------------------\n    locateCurveByEndControlPoint(point) {\n        // for( var i in this.bezierCurves ) {\n        for (var i = 0; i < this.bezierCurves.length; i++) {\n            if (this.bezierCurves[i].endControlPoint.equals(point))\n                return i;\n        }\n        return -1;\n    }\n    /**\n     * Get the total length of this path.<br>\n     * <br>\n     * Note that the returned value comes from the curve buffer. Unregistered changes\n     * to the curve points will result in invalid path length values.\n     *\n     * @method getLength\n     * @instance\n     * @memberof BezierPath\n     * @return {number} The (buffered) length of the path.\n     **/\n    getLength() {\n        return this.totalArcLength;\n    }\n    /**\n     * This function is internally called whenever the curve or path configuration\n     * changed. It updates the attribute that stores the path length information.<br>\n     * <br>\n     * If you perform any unregistered changes to the curve points you should call\n     * this function afterwards to update the curve buffer. Not updating may\n     * result in unexpected behavior.\n     *\n     * @method updateArcLengths\n     * @instance\n     * @memberof BezierPath\n     * @return {void}\n     **/\n    updateArcLengths() {\n        this.totalArcLength = 0.0;\n        for (var i = 0; i < this.bezierCurves.length; i++) {\n            this.bezierCurves[i].updateArcLengths();\n            this.totalArcLength += this.bezierCurves[i].getLength();\n        }\n    }\n    /**\n     * Get the number of curves in this path.\n     *\n     * @method getCurveCount\n     * @instance\n     * @memberof BezierPath\n     * @return {number} The number of curves in this path.\n     **/\n    getCurveCount() {\n        return this.bezierCurves.length;\n    }\n    /**\n     * Get the cubic bezier curve at the given index.\n     *\n     * @method getCurveAt\n     * @param {number} index - The curve index from 0 to getCurveCount()-1.\n     * @instance\n     * @memberof BezierPath\n     * @return {CubicBezierCurve} The curve at the specified index.\n     **/\n    getCurveAt(curveIndex) {\n        return this.bezierCurves[curveIndex];\n    }\n    /**\n     * Move the whole bezier path by the given (x,y)-amount.\n     *\n     * @method translate\n     * @param {XYCoords} amount - The amount to be added (amount.x and amount.y)\n     *                          to each vertex of the curve.\n     * @instance\n     * @memberof BezierPath\n     * @return {BezierPath} this for chaining\n     **/\n    translate(amount) {\n        for (var i = 0; i < this.bezierCurves.length; i++) {\n            var curve = this.bezierCurves[i];\n            curve.getStartPoint().add(amount);\n            curve.getStartControlPoint().add(amount);\n            curve.getEndControlPoint().add(amount);\n        }\n        // Don't forget to translate the last curve's last point\n        var curve = this.bezierCurves[this.bezierCurves.length - 1];\n        curve.getEndPoint().add(amount);\n        this.updateArcLengths();\n        return this;\n    }\n    /**\n     * Move the whole bezier path by the given (x,y)-amount.\n     *\n     * @method move\n     * @param {XYCoords} amount - The amount to be added (amount.x and amount.y)\n     *                          to each vertex of the curve.\n     * @instance\n     * @memberof BezierPath\n     * @return {BezierPath} this for chaining\n     **/\n    move(amount) {\n        return this.translate(amount);\n    }\n    /**\n     * Scale the whole bezier path by the given uniform factor.\n     *\n     * @method scale\n     * @param {Vertex} anchor - The scale origin to scale from.\n     * @param {number} scaleFactor - The scalar to be multiplied with.\n     * @instance\n     * @memberof BezierPath\n     * @return {BezierPath} this for chaining.\n     **/\n    scale(anchor, scaleFactor) {\n        return this.scaleXY({ x: scaleFactor, y: scaleFactor }, anchor);\n    }\n    /**\n     * Scale the whole bezier path by the given (x,y)-factors.\n     *\n     * @method scale\n     * @param {Vertex} anchor - The scale origin to scale from.\n     * @param {number} amount - The scalar to be multiplied with.\n     * @instance\n     * @memberof BezierPath\n     * @return {BezierPath} this for chaining.\n     **/\n    scaleXY(scaleFactors, anchor) {\n        for (var i = 0; i < this.bezierCurves.length; i++) {\n            var curve = this.bezierCurves[i];\n            curve.getStartPoint().scaleXY(scaleFactors, anchor);\n            curve.getStartControlPoint().scaleXY(scaleFactors, anchor);\n            curve.getEndControlPoint().scaleXY(scaleFactors, anchor);\n            // Do NOT scale the end point here!\n            // Don't forget that the curves are connected and on curve's end point\n            // the the successor's start point (same instance)!\n        }\n        // Finally move the last end point (was not scaled yet)\n        if (this.bezierCurves.length > 0 && !this.adjustCircular) {\n            this.bezierCurves[this.bezierCurves.length - 1].getEndPoint().scaleXY(scaleFactors, anchor);\n        }\n        this.updateArcLengths();\n        return this;\n    }\n    /**\n     * Rotate the whole bezier path around a point..\n     *\n     * @method rotate\n     * @param {Vertex} angle  - The angle to rotate this path by.\n     * @param {Vertex} center - The rotation center.\n     * @instance\n     * @memberof BezierPath\n     * @return {void}\n     **/\n    rotate(angle, center) {\n        for (var i = 0; i < this.bezierCurves.length; i++) {\n            var curve = this.bezierCurves[i];\n            curve.getStartPoint().rotate(angle, center);\n            curve.getStartControlPoint().rotate(angle, center);\n            curve.getEndControlPoint().rotate(angle, center);\n            // Do NOT rotate the end point here!\n            // Don't forget that the curves are connected and on curve's end point\n            // the the successor's start point (same instance)!\n        }\n        // Finally move the last end point (was not scaled yet)\n        if (this.bezierCurves.length > 0 && !this.adjustCircular) {\n            this.bezierCurves[this.bezierCurves.length - 1].getEndPoint().rotate(angle, center);\n        }\n    }\n    /**\n     * Get the 't' position on this curve with the minimal distance to point p.\n     *\n     * @param {Vertex} p - The point to find the closest curve point for.\n     * @return {number} A value t with 0.0 <= t <= 1.0.\n     **/\n    getClosestT(p) {\n        // Find the spline to extract the value from\n        var minIndex = -1;\n        var minDist = 0.0;\n        var dist = 0.0;\n        var curveT = 0.0;\n        var uMin = 0.0;\n        var u = 0.0;\n        for (var i = 0; i < this.bezierCurves.length; i++) {\n            curveT = this.bezierCurves[i].getClosestT(p);\n            dist = this.bezierCurves[i].getPointAt(curveT).distance(p);\n            if (minIndex == -1 || dist < minDist) {\n                minIndex = i;\n                minDist = dist;\n                uMin = u + curveT * this.bezierCurves[i].getLength();\n            }\n            u += this.bezierCurves[i].getLength();\n        }\n        return Math.max(0.0, Math.min(1.0, uMin / this.totalArcLength));\n    }\n    /**\n     * Get the point on the bézier path at the given relative path location.\n     *\n     * @method getPoint\n     * @param {number} u - The relative path position: <pre>0 <= u <= this.getLength()</pre>\n     * @instance\n     * @memberof BezierPath\n     * @return {Vertex} The point at the relative path position.\n     **/\n    getPoint(u) {\n        if (u < 0 || u > this.totalArcLength) {\n            console.warn(\"[BezierPath.getPoint(u)] u is out of bounds: \" + u + \".\");\n            u = Math.min(this.totalArcLength, Math.max(u, 0));\n        }\n        // Find the spline to extract the value from\n        var i = 0;\n        var uTemp = 0.0;\n        while (i < this.bezierCurves.length && uTemp + this.bezierCurves[i].getLength() < u) {\n            uTemp += this.bezierCurves[i].getLength();\n            i++;\n        }\n        // if u == arcLength\n        //   -> i is max\n        if (i >= this.bezierCurves.length)\n            return this.bezierCurves[this.bezierCurves.length - 1].getEndPoint().clone();\n        var bCurve = this.bezierCurves[i];\n        var relativeU = u - uTemp;\n        return bCurve.getPoint(relativeU);\n    }\n    /**\n     * Get the point on the bézier path at the given path fraction.\n     *\n     * @method getPointAt\n     * @param {number} t - The absolute path position: <pre>0.0 <= t <= 1.0</pre>\n     * @instance\n     * @memberof BezierPath\n     * @return {Vertex} The point at the absolute path position.\n     **/\n    getPointAt(t) {\n        return this.getPoint(t * this.totalArcLength);\n    }\n    /**\n     * Get the tangent of the bézier path at the given path fraction.<br>\n     * <br>\n     * Note that the returned vector is not normalized.\n     *\n     * @method getTangentAt\n     * @param {number} t - The absolute path position: <pre>0.0 <= t <= 1.0</pre>\n     * @instance\n     * @memberof BezierPath\n     * @return {Vertex} The tangent vector at the absolute path position.\n     **/\n    getTangentAt(t) {\n        return this.getTangent(t * this.totalArcLength);\n    }\n    /**\n     *  Get the tangent of the bézier path at the given path location.<br>\n     * <br>\n     * Note that the returned vector is not normalized.\n     *\n     * @method getTangent\n     * @param {number} u - The relative path position: <pre>0 <= u <= getLength()</pre>\n     * @instance\n     * @memberof BezierPath\n     * @return {Vertex} The tangent vector at the relative path position.\n     **/\n    getTangent(u) {\n        if (u < 0 || u > this.totalArcLength) {\n            console.warn(\"[BezierPath.getTangent(u)] u is out of bounds: \" + u + \".\");\n            // return undefined;\n            u = Math.min(this.totalArcLength, Math.max(0, u));\n        }\n        // Find the spline to extract the value from\n        var i = 0;\n        var uTemp = 0.0;\n        while (i < this.bezierCurves.length && uTemp + this.bezierCurves[i].getLength() < u) {\n            uTemp += this.bezierCurves[i].getLength();\n            i++;\n        }\n        var bCurve = this.bezierCurves[i];\n        var relativeU = u - uTemp;\n        return bCurve.getTangent(relativeU);\n    }\n    /**\n     * Get the perpendicular of the bézier path at the given absolute path location (fraction).<br>\n     * <br>\n     * Note that the returned vector is not normalized.\n     *\n     * @method getPerpendicularAt\n     * @param {number} t - The absolute path position: <pre>0.0 <= t <= 1.0</pre>\n     * @instance\n     * @memberof BezierPath\n     * @return {Vertex} The perpendicluar vector at the absolute path position.\n     **/\n    getPerpendicularAt(t) {\n        return this.getPerpendicular(t * this.totalArcLength);\n    }\n    /**\n     * Get the perpendicular of the bézier path at the given relative path location.<br>\n     * <br>\n     * Note that the returned vector is not normalized.\n     *\n     * @method getPerpendicular\n     * @param {number} u - The relative path position: <pre>0 <= u <= getLength()</pre>\n     * @instance\n     * @memberof BezierPath\n     * @return {Vertex} The perpendicluar vector at the relative path position.\n     **/\n    getPerpendicular(u) {\n        if (u < 0 || u > this.totalArcLength) {\n            console.log(\"[BezierPath.getPerpendicular(u)] u is out of bounds: \" + u + \".\");\n            u = Math.min(this.totalArcLength, Math.max(0, u));\n        }\n        // Find the spline to extract the value from\n        var uResult = BezierPath._locateUIndex(this, u);\n        var bCurve = this.bezierCurves[uResult.i];\n        var relativeU = u - uResult.uPart;\n        return bCurve.getPerpendicular(relativeU);\n    }\n    //--- BEGIN --- Implement interface `Intersectable`\n    /**\n     * Get all line intersections with this shape.\n     *\n     * This method returns all intersections (as vertices) with this shape. The returned array of vertices is in no specific order.\n     *\n     * @param {VertTuple} line - The line to find intersections with.\n     * @param {boolean} inVectorBoundsOnly - If set to true only intersecion points on the passed vector are returned (located strictly between start and end vertex).\n     * @returns {Array<Vertex>} - An array of all intersections with the shape's outline.\n     */\n    lineIntersections(line, inVectorBoundsOnly = false) {\n        return this.bezierCurves.reduce((accu, curCurve) => {\n            return accu.concat(curCurve.lineIntersections(line, inVectorBoundsOnly));\n        }, []);\n    }\n    /**\n     * Get all line intersections of this polygon and their tangents along the shape.\n     *\n     * This method returns all intersection tangents (as vectors) with this shape. The returned array of vectors is in no specific order.\n     *\n     * @param line\n     * @param lineIntersectionTangents\n     * @returns\n     */\n    lineIntersectionTangents(line, inVectorBoundsOnly = false) {\n        return this.bezierCurves.reduce((accu, curCurve) => {\n            return accu.concat(curCurve.lineIntersectionTangents(line, inVectorBoundsOnly));\n        }, []);\n    }\n    //--- END --- Implement interface `Intersectable`\n    /**\n     * This is a helper function to locate the curve index for a given\n     * absolute path position u.\n     *\n     * I decided to put this into privat scope as it is really specific. Maybe\n     * put this into a utils wrapper.\n     *\n     * Returns:\n     * - {number} i - the index of the containing curve.\n     * - {number} uPart - the absolute curve length sum (length from the beginning to u, should equal u itself).\n     * - {number} uBefore - the absolute curve length for all segments _before_ the matched curve (usually uBefore <= uPart).\n     **/\n    static _locateUIndex(path, u) {\n        var i = 0;\n        var uTemp = 0.0;\n        var uBefore = 0.0;\n        while (i < path.bezierCurves.length && uTemp + path.bezierCurves[i].getLength() < u) {\n            uTemp += path.bezierCurves[i].getLength();\n            if (i + 1 < path.bezierCurves.length)\n                uBefore += path.bezierCurves[i].getLength();\n            i++;\n        }\n        return { i: i, uPart: uTemp, uBefore: uBefore };\n    }\n    /**\n     * Get a specific sub path from this path. The start and end position are specified by\n     * ratio number in [0..1].\n     *\n     * 0.0 is at the beginning of the path.\n     * 1.0 is at the end of the path.\n     *\n     * Values below 0 or beyond 1 are cropped down to the [0..1] interval.\n     *\n     * startT > endT is allowed, the returned sub path will have inverse direction then.\n     *\n     * @method getSubPathAt\n     * @param {number} startT - The start position of the sub path.\n     * @param {number} endT - The end position of the sub path.\n     * @instance\n     * @memberof BezierPath\n     * @return {BezierPath} The desired sub path in the bounds [startT..endT].\n     **/\n    getSubPathAt(startT, endT) {\n        startT = Math.max(0, startT);\n        endT = Math.min(1.0, endT);\n        let startU = startT * this.totalArcLength;\n        let endU = endT * this.totalArcLength;\n        var uStartResult = BezierPath._locateUIndex(this, startU); // { i:int, uPart:float, uBefore:float }\n        var uEndResult = BezierPath._locateUIndex(this, endU); // { i:int, uPart:float, uBefore:float }\n        var firstT = (startU - uStartResult.uBefore) / this.bezierCurves[uStartResult.i].getLength();\n        if (uStartResult.i == uEndResult.i) {\n            // Subpath begins and ends in the same path segment (just get a simple sub curve from that path element).\n            var lastT = (endU - uEndResult.uBefore) / this.bezierCurves[uEndResult.i].getLength();\n            var firstCurve = this.bezierCurves[uStartResult.i].getSubCurveAt(firstT, lastT);\n            return BezierPath.fromArray([firstCurve]);\n        }\n        else {\n            var curves = [];\n            if (uStartResult.i > uEndResult.i) {\n                // Back to front direction\n                var firstCurve = this.bezierCurves[uStartResult.i].getSubCurveAt(firstT, 0.0);\n                curves.push(firstCurve);\n                for (var i = uStartResult.i - 1; i > uEndResult.i; i--) {\n                    curves.push(this.bezierCurves[i].clone().reverse());\n                }\n                var lastT = (endU - uEndResult.uBefore) / this.bezierCurves[uEndResult.i].getLength();\n                curves.push(this.bezierCurves[uEndResult.i].getSubCurveAt(1.0, lastT));\n            }\n            else {\n                // Front to back direction\n                var firstCurve = this.bezierCurves[uStartResult.i].getSubCurveAt(firstT, 1.0);\n                curves.push(firstCurve);\n                for (var i = uStartResult.i + 1; i < uEndResult.i && i < this.bezierCurves.length; i++) {\n                    curves.push(this.bezierCurves[i].clone());\n                }\n                var lastT = (endU - uEndResult.uBefore) / this.bezierCurves[uEndResult.i].getLength();\n                curves.push(this.bezierCurves[uEndResult.i].getSubCurveAt(0, lastT));\n            }\n            return BezierPath.fromArray(curves);\n        }\n    }\n    /**\n     * This function moves the addressed curve point (or control point) with\n     * keeping up the path's curve integrity.<br>\n     * <br>\n     * Thus is done by moving neighbour- and control- points as needed.\n     *\n     * @method moveCurvePoint\n     * @param {number} curveIndex - The curve index to move a point from.\n     * @param {number} pointID - One of the curve's four point IDs (START_POINT,\n     *                           START_CONTROL_POINT, END_CONTRO_POINT or END_POINT).\n     * @param {XYCoords} moveAmount - The amount to move the addressed vertex by.\n     * @instance\n     * @memberof BezierPath\n     * @return {void}\n     **/\n    moveCurvePoint(curveIndex, pointID, moveAmount) {\n        var bCurve = this.getCurveAt(curveIndex);\n        bCurve.moveCurvePoint(pointID, moveAmount, true, // move control point, too\n        true // updateArcLengths\n        );\n        // If inner point and NOT control point\n        //  --> move neightbour\n        if (pointID == this.START_POINT && (curveIndex > 0 || this.adjustCircular)) {\n            // Set predecessor's control point!\n            var predecessor = this.getCurveAt(curveIndex - 1 < 0 ? this.bezierCurves.length + (curveIndex - 1) : curveIndex - 1);\n            predecessor.moveCurvePoint(this.END_CONTROL_POINT, moveAmount, true, // move control point, too\n            false // updateArcLengths\n            );\n        }\n        else if (pointID == this.END_POINT && (curveIndex + 1 < this.bezierCurves.length || this.adjustCircular)) {\n            // Set successcor\n            var successor = this.getCurveAt((curveIndex + 1) % this.bezierCurves.length);\n            successor.moveCurvePoint(this.START_CONTROL_POINT, moveAmount, true, // move control point, too\n            false // updateArcLengths\n            );\n        }\n        else if (pointID == this.START_CONTROL_POINT && curveIndex > 0) {\n            this.adjustPredecessorControlPoint(curveIndex, true, // obtain handle length?\n            false // update arc lengths\n            );\n        }\n        else if (pointID == this.END_CONTROL_POINT && curveIndex + 1 < this.getCurveCount()) {\n            this.adjustSuccessorControlPoint(curveIndex, true, // obtain handle length?\n            false // update arc lengths\n            );\n        }\n        // Don't forget to update the arc lengths!\n        // Note: this can be optimized as only two curves have changed their lengths!\n        this.updateArcLengths();\n    }\n    /**\n     * This helper function adjusts the given point's predecessor's control point.\n     *\n     * @method adjustPredecessorControlPoint\n     * @param {number} curveIndex - The curve index to move a point from.\n     * @param {boolean} obtainHandleLength - Moves the point with keeping the original handle length.\n     * @param {boolean} updateArcLength - The amount to move the addressed vertex by.\n     * @instance\n     * @private\n     * @memberof BezierPath\n     * @return {void}\n     **/\n    adjustPredecessorControlPoint(curveIndex, obtainHandleLength, updateArcLengths) {\n        if (!this.adjustCircular && curveIndex <= 0)\n            return; // false;\n        var mainCurve = this.getCurveAt(curveIndex);\n        var neighbourCurve = this.getCurveAt(curveIndex - 1 < 0 ? this.getCurveCount() + (curveIndex - 1) : curveIndex - 1);\n        BezierPath.adjustNeighbourControlPoint(mainCurve, neighbourCurve, mainCurve.getStartPoint(), // the reference point\n        mainCurve.getStartControlPoint(), // the dragged control point\n        neighbourCurve.getEndPoint(), // the neighbour's point\n        neighbourCurve.getEndControlPoint(), // the neighbour's control point to adjust\n        obtainHandleLength, updateArcLengths);\n    }\n    /**\n     * This helper function adjusts the given point's successor's control point.\n     *\n     * @method adjustSuccessorControlPoint\n     * @param {number} curveIndex - The curve index to move a point from.\n     * @param {boolean} obtainHandleLength - Moves the point with keeping the original handle length.\n     * @param {boolean} updateArcLength - The amount to move the addressed vertex by.\n     * @instance\n     * @private\n     * @memberof BezierPath\n     * @return {void}\n     **/\n    adjustSuccessorControlPoint(curveIndex, obtainHandleLength, updateArcLengths) {\n        if (!this.adjustCircular && curveIndex + 1 > this.getCurveCount())\n            return; //  false;\n        var mainCurve = this.getCurveAt(curveIndex);\n        var neighbourCurve = this.getCurveAt((curveIndex + 1) % this.getCurveCount());\n        /* return */ BezierPath.adjustNeighbourControlPoint(mainCurve, neighbourCurve, mainCurve.getEndPoint(), // the reference point\n        mainCurve.getEndControlPoint(), // the dragged control point\n        neighbourCurve.getStartPoint(), // the neighbour's point\n        neighbourCurve.getStartControlPoint(), // the neighbour's control point to adjust\n        obtainHandleLength, updateArcLengths);\n    }\n    /**\n     * This helper function adjusts the given point's successor's control point.\n     *\n     * @method adjustNeighbourControlPoint\n     * @param {CubicBezierCurve} mainCurve\n     * @param {CubicBezierCurve} neighbourCurve\n     * @param {Vertex} mainPoint\n     * @param {Vertex} mainControlPoint\n     * @param {Vertex} neighbourPoint\n     * @param {Vertex} neighbourControlPoint\n     * @param {boolean} obtainHandleLengths\n     * @param {boolean} updateArcLengths\n     * @instance\n     * @private\n     * @memberof BezierPath\n     * @return {void}\n     **/\n    static adjustNeighbourControlPoint(_mainCurve, // TODO: remove param\n    neighbourCurve, mainPoint, mainControlPoint, neighbourPoint, neighbourControlPoint, obtainHandleLengths, _updateArcLengths // TODO: remove param\n    ) {\n        // Calculate start handle length\n        var mainHandleBounds = new Vertex(mainControlPoint.x - mainPoint.x, mainControlPoint.y - mainPoint.y);\n        var neighbourHandleBounds = new Vertex(neighbourControlPoint.x - neighbourPoint.x, neighbourControlPoint.y - neighbourPoint.y);\n        var mainHandleLength = Math.sqrt(Math.pow(mainHandleBounds.x, 2) + Math.pow(mainHandleBounds.y, 2));\n        var neighbourHandleLength = Math.sqrt(Math.pow(neighbourHandleBounds.x, 2) + Math.pow(neighbourHandleBounds.y, 2));\n        if (mainHandleLength <= 0.1)\n            return; // no secure length available for division? What about zoom? Use EPSILON?\n        // Just invert the main handle (keep length or not?\n        if (obtainHandleLengths) {\n            neighbourControlPoint.set(neighbourPoint.x - mainHandleBounds.x * (neighbourHandleLength / mainHandleLength), neighbourPoint.y - mainHandleBounds.y * (neighbourHandleLength / mainHandleLength));\n        }\n        else {\n            neighbourControlPoint.set(neighbourPoint.x - mainHandleBounds.x, neighbourPoint.y - mainHandleBounds.y);\n        }\n        neighbourCurve.updateArcLengths();\n    }\n    //--- BEGIN --- Implement interface `IBounded`\n    /**\n     * Get the bounds of this Bézier path.\n     *\n     * Note the the curves' underlyung segment buffers are used to determine the bounds. The more\n     * elements the segment buffers have, the more precise the returned bounds will be.\n     *\n     * @return {Bounds} The bounds of this Bézier path.\n     **/\n    getBounds() {\n        const min = new Vertex(Number.POSITIVE_INFINITY, Number.POSITIVE_INFINITY);\n        const max = new Vertex(Number.NEGATIVE_INFINITY, Number.NEGATIVE_INFINITY);\n        var b;\n        for (var i = 0; i < this.bezierCurves.length; i++) {\n            b = this.bezierCurves[i].getBounds();\n            min.x = Math.min(min.x, b.min.x);\n            min.y = Math.min(min.y, b.min.y);\n            max.x = Math.max(max.x, b.max.x);\n            max.y = Math.max(max.y, b.max.y);\n        }\n        return new Bounds(min, max);\n    }\n    //--- END --- Implement interface `IBounded`\n    /**\n     * Get n 'equally' distributed vertices along this Bézier path.\n     *\n     * As the changing curvature of the B slines makes prediction of distances difficult, the\n     * returned vertices' distances are only relatively equal:\n     *  - the distance grows where curvature is large.\n     *  - the distance shrinks where curvature is small.\n     *\n     * Only the distance mean of all consecutive is 1/n-th of the total arc length.\n     *\n     * Usually this approximation is good enough for most use cases.\n     *\n     * @param {number} pointCount - (must be at least 2) The number of desired points (start and end point included).\n     * @return {Array<Vertex>}\n     */\n    getEvenDistributionVertices(pointCount) {\n        if (pointCount < 2) {\n            throw new Error(\"pointCount must be larger than one; is \" + pointCount + \".\");\n        }\n        const result = [];\n        if (this.bezierCurves.length === 0) {\n            return result;\n        }\n        // Fetch and add the start point from the source polygon\n        var polygonPoint = new Vertex(this.bezierCurves[0].startPoint);\n        result.push(polygonPoint);\n        // if (this.bezierCurves.length === 1) {\n        //   return result;\n        // }\n        const perimeter = this.totalArcLength;\n        const stepSize = perimeter / (pointCount - 1);\n        const n = this.bezierCurves.length;\n        let curveIndex = 0;\n        let segmentLength = this.bezierCurves[0].arcLength;\n        let curSegmentU = stepSize;\n        let i = 1;\n        while (i < pointCount && curveIndex < n) {\n            // Check if next eq point is inside this segment\n            if (curSegmentU < segmentLength) {\n                var newPoint = this.bezierCurves[curveIndex].getPoint(curSegmentU);\n                result.push(newPoint);\n                curSegmentU += stepSize;\n                i++;\n            }\n            else {\n                curveIndex++;\n                curSegmentU = curSegmentU - segmentLength;\n                segmentLength = curveIndex < n ? this.bezierCurves[curveIndex].arcLength : 0;\n            }\n        }\n        result.push(new Vertex(this.bezierCurves[n - 1].endPoint));\n        return result;\n    }\n    /**\n     * Clone this BezierPath (deep clone).\n     *\n     * @method clone\n     * @instance\n     * @memberof BezierPath\n     * @return {BezierPath}\n     **/\n    clone() {\n        var path = new BezierPath(); // undefined);\n        for (var i = 0; i < this.bezierCurves.length; i++) {\n            path.bezierCurves.push(this.bezierCurves[i].clone());\n            // Connect splines\n            if (i > 0)\n                path.bezierCurves[i - 1].endPoint = path.bezierCurves[i].startPoint;\n        }\n        path.updateArcLengths();\n        path.adjustCircular = this.adjustCircular;\n        return path;\n    }\n    /**\n     * Compare this and the passed Bézier path.\n     *\n     * @method equals\n     * @param {BezierPath} path - The pass to compare with.\n     * @instance\n     * @memberof BezierPath\n     * @return {boolean}\n     **/\n    equals(path) {\n        if (!path)\n            return false;\n        // Check if path contains the credentials\n        if (!path.bezierCurves)\n            return false;\n        if (typeof path.bezierCurves.length == \"undefined\")\n            return false;\n        if (path.bezierCurves.length != this.bezierCurves.length)\n            return false;\n        for (var i = 0; i < this.bezierCurves.length; i++) {\n            if (!this.bezierCurves[i].equals(path.bezierCurves[i]))\n                return false;\n        }\n        return true;\n    }\n    /**\n     * This function should invalidate any installed listeners and invalidate this object.\n     * After calling this function the object might not hold valid data any more and\n     * should not be used.\n     *\n     * @method destroy\n     * @instance\n     * @memberof BezierPath\n     */\n    destroy() {\n        for (var i = 0; i < this.bezierCurves.length; i++) {\n            this.bezierCurves[i].destroy();\n        }\n        this.isDestroyed = true;\n    }\n    /**\n     * Convert this path to an array of path points that can be drawn by the default DrawLib\n     * implementations.\n     *\n     * @method toPathPoints\n     * @instance\n     * @memberof BezierPath\n     * @return {Array<XYCoords>}\n     */\n    toPathPoints() {\n        if (this.bezierCurves.length === 0) {\n            return [];\n        }\n        if (this.bezierCurves.length === 1) {\n            return [\n                this.bezierCurves[0].startPoint,\n                this.bezierCurves[0].startControlPoint,\n                this.bezierCurves[0].endControlPoint,\n                this.bezierCurves[0].endPoint\n            ];\n        }\n        const arr = [];\n        arr.push(this.bezierCurves[0].startPoint);\n        arr.push(this.bezierCurves[0].startControlPoint);\n        for (var i = 1; i < this.bezierCurves.length; i++) {\n            arr.push(this.bezierCurves[i - 1].endControlPoint);\n            arr.push(this.bezierCurves[i - 1].endPoint);\n            arr.push(this.bezierCurves[i].startPoint);\n            arr.push(this.bezierCurves[i].startControlPoint);\n        }\n        arr.push(this.bezierCurves[0].endControlPoint);\n        arr.push(this.bezierCurves[0].endPoint);\n        return arr;\n    }\n    /**\n     * Create a JSON string representation of this bézier curve.\n     *\n     * @method toJSON\n     * @param {boolean} prettyFormat - If true then the function will add line breaks.\n     * @instance\n     * @memberof BezierPath\n     * @return {string} The JSON string.\n     **/\n    toJSON(prettyFormat) {\n        var buffer = [];\n        buffer.push(\"[\"); // array begin\n        for (var i = 0; i < this.bezierCurves.length; i++) {\n            if (i > 0)\n                buffer.push(\",\");\n            if (prettyFormat)\n                buffer.push(\"\\n\\t\");\n            else\n                buffer.push(\" \");\n            buffer.push(this.bezierCurves[i].toJSON(prettyFormat));\n        }\n        if (this.bezierCurves.length != 0)\n            buffer.push(\" \");\n        buffer.push(\"]\"); // array end\n        return buffer.join(\"\"); // Convert to string, with empty separator.\n    }\n    /**\n     * Parse a BezierPath from the given JSON string.\n     *\n     * @method fromJSON\n     * @param {string} jsonString - The string with the JSON data.\n     * @throw An error if the string is not JSON or does not contain a bezier path object.\n     * @static\n     * @memberof BezierPath\n     * @return {BezierPath} The parsed bezier path instance.\n     **/\n    static fromJSON(jsonString) {\n        var obj = JSON.parse(jsonString);\n        return BezierPath.fromArray(obj);\n    }\n    /**\n     * Construct a new path with a single curve. Adding more curves is always possible.\n     *\n     * @method fromCurve\n     * @param {CubicBezierCurve} curve - The curve to construct a new path from.\n     * @static\n     * @memberof BezierPath\n     * @return {BezierPath} The constructed bezier path instance.\n     */\n    static fromCurve(curve) {\n        const path = new BezierPath(); // []);\n        path.addCurve(curve);\n        return path;\n    }\n    /**\n     * Create a BezierPath instance from the given array.\n     *\n     * @method fromArray\n     * @param {Vertex[][]} arr - A two-dimensional array containing the bezier path vertices.\n     * @throw An error if the array does not contain proper bezier path data.\n     * @static\n     * @memberof BezierPath\n     * @return {BezierPath} The bezier path instance retrieved from the array data.\n     **/\n    static fromArray(obj) {\n        if (!Array.isArray(obj)) {\n            throw \"[BezierPath.fromArray] Passed object must be an array.\";\n        }\n        const arr = obj; // FORCE?\n        if (arr.length < 1) {\n            throw \"[BezierPath.fromArray] Passed array must contain at least one bezier curve (has \" + arr.length + \").\";\n        }\n        // Create an empty bezier path\n        var bPath = new BezierPath(); // undefined);\n        var lastCurve = null;\n        for (var i = 0; i < arr.length; i++) {\n            // Convert object (or array?) to bezier curve\n            var bCurve;\n            if (CubicBezierCurve.isInstance(arr[i])) {\n                bCurve = arr[i].clone();\n            }\n            else if (0 in arr[i] && 1 in arr[i] && 2 in arr[i] && 3 in arr[i]) {\n                if (!arr[i][0] || !arr[i][1] || !arr[i][2] || !arr[i][3])\n                    throw \"Cannot convert path data to BezierPath instance. At least one element is undefined (index=\" + i + \"): \" + arr[i];\n                bCurve = CubicBezierCurve.fromArray(arr[i]);\n            }\n            else {\n                bCurve = CubicBezierCurve.fromObject(arr[i]);\n            }\n            // Set curve start point?\n            // (avoid duplicate point instances!)\n            if (lastCurve)\n                bCurve.startPoint = lastCurve.endPoint;\n            // Add to path's internal list\n            bPath.bezierCurves.push(bCurve);\n            // bPath.totalArcLength += bCurve.getLength();\n            lastCurve = bCurve;\n        }\n        bPath.updateArcLengths();\n        // Bezier segments added. Done\n        return bPath;\n    }\n    /**\n     * This function converts the bezier path into a string containing\n     * integer values only.\n     * The points' float values are rounded to 1 digit after the comma.\n     *\n     * The returned string represents a JSON array (with leading '[' and\n     * trailing ']', the separator is ',').\n     *\n     * @method toReducedListRepresentation\n     * @param {number} digits - The number of digits to be used after the comma '.'.\n     * @instance\n     * @memberof BezierPath\n     * @return {string} The reduced list representation of this path.\n     **/\n    toReducedListRepresentation(digits) {\n        if (typeof digits == \"undefined\")\n            digits = 1;\n        var buffer = [];\n        buffer.push(\"[\"); // array begin\n        for (var i = 0; i < this.bezierCurves.length; i++) {\n            var curve = this.bezierCurves[i];\n            buffer.push(curve.getStartPoint().x.toFixed(digits));\n            buffer.push(\",\");\n            buffer.push(curve.getStartPoint().y.toFixed(digits));\n            buffer.push(\",\");\n            buffer.push(curve.getStartControlPoint().x.toFixed(digits));\n            buffer.push(\",\");\n            buffer.push(curve.getStartControlPoint().y.toFixed(digits));\n            buffer.push(\",\");\n            buffer.push(curve.getEndControlPoint().x.toFixed(digits));\n            buffer.push(\",\");\n            buffer.push(curve.getEndControlPoint().y.toFixed(digits));\n            buffer.push(\",\");\n        }\n        if (this.bezierCurves.length != 0) {\n            var curve = this.bezierCurves[this.bezierCurves.length - 1];\n            buffer.push(curve.getEndPoint().x.toFixed(digits));\n            buffer.push(\",\");\n            buffer.push(curve.getEndPoint().y.toFixed(digits));\n        }\n        buffer.push(\"]\"); // array end\n        return buffer.join(\"\"); // Convert to string, with empty separator.\n    }\n    /**\n     * Parse a BezierPath instance from the reduced list representation.<br>\n     * <br>\n     * The passed string must represent a JSON array containing numbers only.\n     *\n     * @method fromReducedListRepresentation\n     * @param {string} listJSON - The number of digits to be used after the floating point.\n     * @throw An error if the string is malformed.\n     * @instance\n     * @memberof BezierPath\n     * @return {BezierPath} The bezier path instance retrieved from the string.\n     **/\n    static fromReducedListRepresentation(listJSON, adjustCircular) {\n        // Parse the array\n        var pointArray = JSON.parse(listJSON);\n        if (!pointArray.length) {\n            console.log(\"Cannot parse bezier path from non-array object nor from empty point list.\");\n            throw \"Cannot parse bezier path from non-array object nor from empty point list.\";\n        }\n        if (pointArray.length < 8) {\n            console.log(\"Cannot build bezier path. The passed array must contain at least 8 elements (numbers).\");\n            throw \"Cannot build bezier path. The passed array must contain at least 8 elements (numbers).\";\n        }\n        return BezierPath.fromReducedList(pointArray, adjustCircular);\n    }\n    /**\n     * Convert a reduced list representation (array of numeric coordinates) to a BezierPath instance.\n     *\n     * The array's length must be 6*n + 2:\n     *  - [sx, sy,  scx, scy,  ecx, ecy, ... , ex,  ey ]\n     *     |                               |   |     |\n     *     +--- sequence of curves --------+   +-end-+\n     *\n     * @param {number[]} pointArray\n     * @returns BezierPath\n     */\n    static fromReducedList(pointArray, adjustCircular) {\n        // Convert to object\n        var bezierPath = new BezierPath(); // null); // No points yet\n        var startPoint = new Vertex();\n        var startControlPoint;\n        var endControlPoint;\n        var endPoint;\n        var i = 0;\n        do {\n            if (i == 0) {\n                // firstStartPoint =\n                startPoint = new Vertex(pointArray[i], pointArray[i + 1]);\n            }\n            startControlPoint = new Vertex(pointArray[i + 2], pointArray[i + 3]);\n            endControlPoint = new Vertex(pointArray[i + 4], pointArray[i + 5]);\n            // if (i + 8 >= pointArray.length) {\n            //   endPoint = firstStartPoint;\n            // } else {\n            endPoint = new Vertex(pointArray[i + 6], pointArray[i + 7]);\n            // }\n            var bCurve = new CubicBezierCurve(startPoint, endPoint, startControlPoint, endControlPoint);\n            bezierPath.bezierCurves.push(bCurve);\n            startPoint = endPoint;\n            i += 6;\n        } while (i + 2 < pointArray.length);\n        bezierPath.adjustCircular = adjustCircular !== null && adjustCircular !== void 0 ? adjustCircular : false;\n        if (adjustCircular) {\n            bezierPath.bezierCurves[bezierPath.bezierCurves.length - 1].endPoint = bezierPath.bezierCurves[0].startPoint;\n        }\n        bezierPath.updateArcLengths();\n        return bezierPath;\n    }\n}\n// +---------------------------------------------------------------------------------\n// | These constants equal the values from CubicBezierCurve.\n// +-------------------------------\n/** @constant {number} */\nBezierPath.START_POINT = 0;\n/** @constant {number} */\nBezierPath.START_CONTROL_POINT = 1;\n/** @constant {number} */\nBezierPath.END_CONTROL_POINT = 2;\n/** @constant {number} */\nBezierPath.END_POINT = 3;\n//# sourceMappingURL=BezierPath.js.map","/**\n * @author   Ikaros Kappler\n * @date     2020-12-17\n * @modified 2021-01-20 Added UID.\n * @modified 2021-02-26 Fixed an error in the svg-arc-calculation (case angle<90deg and anti-clockwise).\n * @modified 2024-01-30 Added a missing type in the `describeSVGArc` function.\n * @modified 2024-03-01 Added the `getStartPoint` and `getEndPoint` methods.\n * @modified 2024-03-08 Added the `containsAngle` method.\n * @modified 2024-03-09 Added the `circleSectorIntersection` method to find coherent sector intersections..\n * @modified 2024-03-09 Added the `angleAt` method to determine any angle at some ratio.\n * @modified 2025-04-02 Adding the `CircleSector.lineIntersections` and `CircleSector.lineIntersectionTangents` and implementing `Intersectable`.\n * @modified 2025-04-09 Adding the `CircleSector.move()` method.\n * @modified 2025-04-19 Tweaking the `CircleSector.containsAngle` method: all values (input angle, start- and end- angle) are wrapped into [0,2*PI) now.\n * @modified 2025-04-19 Class `CircleSector` implements interface `Bounded` now (method `getBounds` added).\n * @version  1.2.0\n **/\nimport { Bounds } from \"./Bounds\";\nimport { Circle } from \"./Circle\";\nimport { Line } from \"./Line\";\nimport { UIDGenerator } from \"./UIDGenerator\";\nimport { Vertex } from \"./Vertex\";\nimport { geomutils } from \"./geomutils\";\n/**\n * @classdesc A simple circle sector: circle, start- and end-angle.\n *\n * @requires Line\n * @requires SVGSerializale\n * @requires UID\n * @requires UIDGenerator\n * @requires XYCoords\n **/\nexport class CircleSector {\n    /**\n     * Create a new circle sector with given circle, start- and end-angle.\n     *\n     * @constructor\n     * @name CircleSector\n     * @param {Circle} circle - The circle.\n     * @param {number} startAngle - The start angle of the sector.\n     * @param {number} endAngle - The end angle of the sector.\n     */\n    constructor(circle, startAngle, endAngle) {\n        /**\n         * Required to generate proper CSS classes and other class related IDs.\n         **/\n        this.className = \"CircleSector\";\n        this.uid = UIDGenerator.next();\n        this.circle = circle;\n        this.startAngle = startAngle;\n        this.endAngle = endAngle;\n    }\n    //--- BEGIN --- Implement interface `IBounded`\n    /**\n     * Get the bounds of this ellipse.\n     *\n     * The bounds are approximated by the underlying segment buffer; the more segment there are,\n     * the more accurate will be the returned bounds.\n     *\n     * @method getBounds\n     * @instance\n     * @memberof VEllipse\n     * @return {Bounds} The bounds of this curve.\n     **/\n    getBounds() {\n        const _self = this;\n        const circleBounds = this.circle.getBounds();\n        // Calculage angles from east, west, north and south box points and check if they are inside\n        const candidates = [\n            circleBounds.getNorthPoint(),\n            circleBounds.getSouthPoint(),\n            circleBounds.getWestPoint(),\n            circleBounds.getEastPoint()\n        ].filter((point) => {\n            // Check for each candidate points if they are contained in this sector. Drop if not.\n            const angle = new Line(_self.circle.center, point).angle();\n            return _self.containsAngle(angle);\n        });\n        // Compute bounds and inlcude start end end point (they are definitely part of the bounds)\n        return Bounds.computeFromVertices(candidates.concat([this.getStartPoint(), this.getEndPoint()]));\n    }\n    //--- BEGIN --- Implement interface `IBounded`\n    /**\n     * Move the circle sector by the given amount.\n     *\n     * @method move\n     * @param {XYCoords} amount - The amount to move.\n     * @instance\n     * @memberof CircleSector\n     * @return {CircleSector} this for chaining\n     **/\n    move(amount) {\n        this.circle.move(amount);\n        return this;\n    }\n    /**\n     * Checks wether the given angle (must be inside 0 and PI*2) is contained inside this sector.\n     *\n     * @param {number} angle - The numeric angle to check.\n     * @method containsAngle\n     * @instance\n     * @memberof CircleSector\n     * @return {boolean} True if (and only if) this sector contains the given angle.\n     */\n    containsAngle(angle) {\n        var wrappedAngle = geomutils.mapAngleTo2PI(angle);\n        var wrappedStart = geomutils.mapAngleTo2PI(this.startAngle);\n        var wrappedEnd = geomutils.mapAngleTo2PI(this.endAngle);\n        // TODO: cleanup\n        // if (this.startAngle <= this.endAngle) {\n        //   return angle >= this.startAngle && angle < this.endAngle;\n        // } else {\n        //   // startAngle > endAngle\n        //   return angle >= this.startAngle || angle < this.endAngle;\n        // }\n        if (wrappedStart <= wrappedEnd) {\n            return wrappedAngle >= wrappedStart && wrappedAngle < wrappedEnd;\n        }\n        else {\n            // startAngle > endAngle\n            return wrappedAngle >= wrappedStart || wrappedAngle < wrappedEnd;\n        }\n    }\n    /**\n     * Get the angle inside this sector for a given ratio. 0.0 means startAngle, and 1.0 means endAngle.\n     *\n     * @param {number} t - The ratio inside [0..1].\n     * @method angleAt\n     * @instance\n     * @memberof CircleSector\n     * @return {number} The angle inside this sector at a given ratio.\n     */\n    angleAt(t) {\n        if (this.startAngle <= this.endAngle) {\n            const angleAtRatio = this.startAngle + (this.endAngle - this.startAngle) * t;\n            return angleAtRatio % (Math.PI * 2.0);\n        }\n        else {\n            // startAngle > endAngle\n            const angleAtRatio = this.startAngle + (Math.PI * 2 - this.startAngle + this.endAngle) * t;\n            return angleAtRatio % (Math.PI * 2.0);\n        }\n    }\n    /**\n     * Get the sectors starting point (on the underlying circle, located at the start angle).\n     *\n     * @method getStartPoint\n     * @instance\n     * @memberof CircleSector\n     * @return {Vertex} The sector's stating point.\n     */\n    getStartPoint() {\n        return this.circle.vertAt(this.startAngle);\n    }\n    /**\n     * Get the sectors ending point (on the underlying circle, located at the end angle).\n     *\n     * @method getEndPoint\n     * @instance\n     * @memberof CircleSector\n     * @return {Vertex} The sector's ending point.\n     */\n    getEndPoint() {\n        return this.circle.vertAt(this.endAngle);\n    }\n    /**\n     * Calculate the intersection of this circle sector and some other sector.\n     *\n     * If the two sectors do not corerently intersect (when not both points of the\n     * radical line are containted in both source sectors) then null is returned.\n     *\n     * See demo/53-circle-sector-intersections for a geometric visualisation.\n     *\n     * @method circleSectorIntersection\n     * @instance\n     * @memberof CircleSector\n     * @return {CircleSector | null} The intersecion of both sectors or null if they don't intersect.\n     */\n    circleSectorIntersection(sector) {\n        const radicalLine = this.circle.circleIntersection(sector.circle);\n        if (!radicalLine) {\n            // The circles to not intersect at all.\n            return null;\n        }\n        // Circles intersect. Check if this sector interval intersects, too.\n        const thisIntersectionAngleA = this.circle.center.angle(radicalLine.a);\n        const thisIntersectionAngleB = this.circle.center.angle(radicalLine.b);\n        // Is intersection inside this sector?\n        if (!this.containsAngle(thisIntersectionAngleA) || !this.containsAngle(thisIntersectionAngleB)) {\n            // At least one circle intersection point is not located in this sector.\n            //  -> no valid intersection at all\n            return null;\n        }\n        // Circles intersect. Check if the passed sector interval intersects, too.\n        const thatIntersectionAngleA = sector.circle.center.angle(radicalLine.a);\n        const thatIntersectionAngleB = sector.circle.center.angle(radicalLine.b);\n        // Is intersection inside this sector?\n        if (!sector.containsAngle(thatIntersectionAngleA) || !sector.containsAngle(thatIntersectionAngleB)) {\n            // At least one circle intersection point is not located in this sector.\n            //  -> no valid intersection at all\n            return null;\n        }\n        // The radical line has no direction. Thus the resulting sector _might_ be in reverse order.\n        // Make a quick logical check: the center of the gap must still be located inside the result sector.\n        // If not: reverse result.\n        var gapSector = new CircleSector(this.circle, this.endAngle, this.startAngle);\n        var centerOfOriginalGap = gapSector.angleAt(0.5);\n        const resultSector = new CircleSector(new Circle(this.circle.center.clone(), this.circle.radius), thisIntersectionAngleA, thisIntersectionAngleB);\n        if (resultSector.containsAngle(centerOfOriginalGap)) {\n            resultSector.startAngle = thisIntersectionAngleB;\n            resultSector.endAngle = thisIntersectionAngleA;\n        }\n        return resultSector;\n    }\n    //--- BEGIN --- Implement interface `Intersectable`\n    /**\n     * Get the line intersections as vectors with this ellipse.\n     *\n     * @method lineIntersections\n     * @instance\n     * @param {VertTuple<Vector> ray - The line/ray to intersect this ellipse with.\n     * @param {boolean} inVectorBoundsOnly - (default=false) Set to true if only intersections within the vector bounds are of interest.\n     * @returns\n     */\n    lineIntersections(ray, inVectorBoundsOnly = false) {\n        // First get all line intersections from underlying ellipse.\n        const ellipseIntersections = this.circle.lineIntersections(ray, inVectorBoundsOnly);\n        // Drop all intersection points that are not contained in the circle sectors bounds.\n        const tmpLine = new Line(this.circle.center, new Vertex());\n        return ellipseIntersections.filter((intersectionPoint) => {\n            tmpLine.b.set(intersectionPoint);\n            const lineAngle = tmpLine.angle();\n            return this.containsAngle(geomutils.wrapMinMax(lineAngle, 0, Math.PI * 2));\n        });\n    }\n    /**\n     * Get all line intersections of this polygon and their tangents along the shape.\n     *\n     * This method returns all intersection tangents (as vectors) with this shape. The returned array of vectors is in no specific order.\n     *\n     * @param line\n     * @param lineIntersectionTangents\n     * @returns\n     */\n    lineIntersectionTangents(line, inVectorBoundsOnly = false) {\n        // Find the intersections of all lines plus their tangents inside the circle bounds\n        const interSectionPoints = this.lineIntersections(line, inVectorBoundsOnly);\n        return interSectionPoints.map((vert) => {\n            // Calculate angle\n            const lineFromCenter = new Line(this.circle.center, vert);\n            const angle = lineFromCenter.angle();\n            // console.log(\"angle\", (angle / Math.PI) * 180.0);\n            // const angle = Math.random() * Math.PI * 2; // TODO\n            // Calculate tangent at angle\n            return this.circle.tangentAt(angle);\n        });\n    }\n    //--- END --- Implement interface `Intersectable`\n    describeSVGPath(options) {\n        // const buffer: SVGPathParams = [];\n        // const start = this.getStartPoint();\n        // const end = this.getEndPoint();\n        // //   describeSVGArc\n        // //   x: number,\n        // //   y: number,\n        // //   radius: number,\n        // //   startAngle: number,\n        // //   endAngle: number,\n        // //   options?: { moveToStart: boolean }\n        // // ): SVGPathParams => {\n        // var arcRotation = 0.0;\n        // var largeArcFlag = 1;\n        // var sweepFlag = 0;\n        // if (options && options.moveToStart) {\n        //   buffer.push(\"M\", start.x, start.y);\n        // }\n        // buffer.push(\"A\", cSector.circle.radius, cSector.circle.radius, arcRotation, largeArcFlag, sweepFlag, end.x, end.y);\n        // return buffer;\n        const arc = CircleSector.circleSectorUtils.describeSVGArc(this.circle.center.x, // end.x,\n        this.circle.center.y, // end.y,\n        this.circle.radius, this.startAngle, this.endAngle, options // options?: { moveToStart: boolean }\n        );\n        return arc;\n    }\n    /**\n     * This function should invalidate any installed listeners and invalidate this object.\n     * After calling this function the object might not hold valid data any more and\n     * should not be used.\n     *\n     * @method destroy\n     * @instance\n     * @memberof CircleSector\n     * @return {void}\n     */\n    destroy() {\n        this.circle.destroy();\n        this.isDestroyed = true;\n    }\n} // END class\nCircleSector.circleSectorUtils = {\n    /**\n     * Helper function to convert polar circle coordinates to cartesian coordinates.\n     *\n     * TODO: generalize for ellipses (two radii).\n     *\n     * @param {number} angle - The angle in radians.\n     */\n    polarToCartesian: (centerX, centerY, radius, angle) => {\n        return {\n            x: centerX + radius * Math.cos(angle),\n            y: centerY + radius * Math.sin(angle)\n        };\n    },\n    /**\n     * Helper function to convert a circle section as SVG arc params (for the `d` attribute).\n     * Found at: https://stackoverflow.com/questions/5736398/how-to-calculate-the-svg-path-for-an-arc-of-a-circle\n     *\n     * TODO: generalize for ellipses (two radii).\n     *\n     * @param {boolean} options.moveToStart - If false (default=true) the initial 'Move' command will not be used.\n     * @return [ 'A', radiusx, radiusy, rotation=0, largeArcFlag=1|0, sweepFlag=0, endx, endy ]\n     */\n    describeSVGArc: (x, y, radius, startAngle, endAngle, options) => {\n        if (typeof options === \"undefined\") {\n            options = { moveToStart: true };\n        }\n        const end = CircleSector.circleSectorUtils.polarToCartesian(x, y, radius, endAngle);\n        const start = CircleSector.circleSectorUtils.polarToCartesian(x, y, radius, startAngle);\n        // Split full circles into two halves.\n        // Some browsers have problems to render full circles (described by start==end).\n        if (Math.PI * 2 - Math.abs(startAngle - endAngle) < 0.001) {\n            const firstHalf = CircleSector.circleSectorUtils.describeSVGArc(x, y, radius, startAngle, startAngle + (endAngle - startAngle) / 2, options);\n            const secondHalf = CircleSector.circleSectorUtils.describeSVGArc(x, y, radius, startAngle + (endAngle - startAngle) / 2, endAngle, options);\n            return firstHalf.concat(secondHalf);\n        }\n        // Boolean stored as integers (0|1).\n        const diff = endAngle - startAngle;\n        var largeArcFlag;\n        var sweepFlag;\n        if (diff < 0) {\n            largeArcFlag = Math.abs(diff) < Math.PI ? 1 : 0;\n            sweepFlag = 1;\n        }\n        else {\n            largeArcFlag = Math.abs(diff) > Math.PI ? 1 : 0;\n            sweepFlag = 1;\n        }\n        const pathData = [];\n        if (options.moveToStart) {\n            pathData.push(\"M\", start.x, start.y);\n        }\n        pathData.push(\"A\", radius, radius, 0, largeArcFlag, sweepFlag, end.x, end.y);\n        return pathData;\n    }\n};\n//# sourceMappingURL=CircleSector.js.map","/**\n * Draws elements into an SVG node.\n *\n * Note that this library uses buffers and draw cycles. To draw onto an SVG canvas, do this:\n *   const drawLib = new drawutilssvg( svgNode, ... );\n *   const fillLib = drawLib.copyInstance(true);\n *   // Begin draw cycle\n *   drawLib.beginDrawCycle(time);\n *   // ... draw or fill your stuff ...\n *   drawLib.endDrawCycle(time); // Here the elements become visible\n *\n * @author   Ikaros Kappler\n * @date     2021-01-03\n * @modified 2021-01-24 Fixed the `fillShapes` attribute in the copyInstance function.\n * @modified 2021-01-26 Changed the `isPrimary` (default true) attribute to `isSecondary` (default false).\n * @modified 2021-02-03 Added the static `createSvg` function.\n * @modified 2021-02-03 Fixed the currentId='background' bug on the clear() function.\n * @modified 2021-02-03 Fixed CSSProperty `stroke-width` (was line-width before, which is wrong).\n * @modified 2021-02-03 Added the static `HEAD_XML` attribute.\n * @modified 2021-02-19 Added the static helper function `transformPathData(...)` for svg path transformations (scale and translate).\n * @modified 2021-02-22 Added the static helper function `copyPathData(...)`.\n * @modified 2021-02-22 Added the `path` drawing function to draw SVG path data.\n * @modified 2021-03-01 Fixed a bug in the `clear` function (curClassName was not cleared).\n * @modified 2021-03-29 Fixed a bug in the `text` function (second y param was wrong, used x here).\n * @modified 2021-03-29 Moved this file from `src/ts/utils/helpers/` to `src/ts/`.\n * @modified 2021-03-31 Added 'ellipseSector' the the class names.\n * @modified 2021-03-31 Implemented buffering using a buffer <g> node and the beginDrawCycle and endDrawCycle methods.\n * @modified 2021-05-31 Added the `setConfiguration` function from `DrawLib`.\n * @modified 2021-11-15 Adding more parameters tot the `text()` function: fontSize, textAlign, fontFamily, lineHeight.\n * @modified 2021-11-19 Fixing the `label(text,x,y)` position.\n * @modified 2021-11-19 Added the `color` param to the `label(...)` function.\n * @modified 2022-02-03 Added the `lineWidth` param to the `crosshair` function.\n * @modified 2022-02-03 Added the `cross(...)` function.\n * @modified 2022-03-26 Added the private `nodeDefs` and `bufferedNodeDefs` attributes.\n * @modified 2022-03-26 Added the `texturedPoly` function to draw textures polygons.\n * @modified 2022-07-26 Adding `alpha` to the `image(...)` function.\n * @modified 2022-11-10 Tweaking some type issues.\n * @modified 2023-02-04 Fixed a typo in the CSS classname for cubic Bézier paths: cubicBezier (was cubierBezier).\n * @modified 2023-02-10 The methods `setCurrentClassName` and `setCurrentId` also accept `null` now.\n * @modified 2023-09-29 Added initialization checks for null parameters.\n * @modified 2023-09-29 Added a missing implementation to the `drawurilssvg.do(XYCoords,string)` function. Didn't draw anything.\n * @modified 2023-09-29 Downgrading all `Vertex` param type to the more generic `XYCoords` type in these render functions: line, arrow, texturedPoly, cubicBezier, cubicBezierPath, handle, handleLine, dot, point, circle, circleArc, ellipse, grid, raster.\n * @modified 2023-09-29 Added the `headLength` parameter to the 'DrawLib.arrow()` function.\n * @modified 2023-09-29 Added the `arrowHead(...)` function to the 'DrawLib.arrow()` interface.\n * @modified 2023-09-29 Added the `cubicBezierArrow(...)` function to the 'DrawLib.arrow()` interface.\n * @modified 2023-10-04 Adding `strokeOptions` param to these draw function: line, arrow, cubicBezierArrow, cubicBezier, cubicBezierPath, circle, circleArc, ellipse, square, rect, polygon, polyline.\n * @modified 2024-01-30 Fixing an issue with immutable style sets; changes to the global draw config did not reflect here (do now).\n * @modified 2024-03-10 Fixing some types for Typescript 5 compatibility.\n * @modified 2024-07-24 Caching custom style defs in a private buffer variable.\n * @modified 2025-11-14 Fixing a bug in the CSS `mix-blend-mode` property handling (caused a runtime error).\n * @modified 2026-01-04 Adding `lineJoin` attribute to the methods' `StrokeOptions` param.\n * @modified 2026-01-04 Fixing missing `strokeOptions` param in the `drawutilssvg.polygon` method.\n * @modified 2026-03-18 Adding `isOpen` parameter to `cubicBezierPath` draw method.\n * @modified 2026-04-04 Added the method `bounds`.\n * @modified 2026-04-04 Handling the `stroke-linecap` option now from the `StrokeOptions` interface.\n * @modified 2026-04-04 Chaning the `copyPathData` method by usind `Array.slice()`.\n * @version  1.7.0\n **/\nimport { CircleSector } from \"./CircleSector\";\nimport { CubicBezierCurve } from \"./CubicBezierCurve\";\nimport { Vertex } from \"./Vertex\";\nimport { UIDGenerator } from \"./UIDGenerator\";\nimport { Vector } from \"./Vector\";\nconst RAD_TO_DEG = 180 / Math.PI;\n/**\n * @classdesc A helper class for basic SVG drawing operations. This class should\n * be compatible to the default 'draw' class.\n *\n * @requires CubicBzierCurvce\n * @requires Polygon\n * @requires Vertex\n * @requires XYCoords\n */\nexport class drawutilssvg {\n    /**\n     * Passed from primary to secondary instance.\n     */\n    //private nodeStyle: SVGStyleElement;\n    /**\n     * The constructor.\n     *\n     * @constructor\n     * @name drawutilssvg\n     * @param {SVGElement} svgNode - The SVG node to use.\n     * @param {XYCoords} offset - The draw offset to use.\n     * @param {XYCoords} scale - The scale factors to use.\n     * @param {XYDimension} canvasSize - The initial canvas size (use setSize to change).\n     * @param {boolean} fillShapes - Indicates if the constructed drawutils should fill all drawn shapes (if possible).\n     * @param {DrawConfig} drawConfig - The default draw config to use for CSS fallback styles.\n     * @param {boolean=} isSecondary - (optional) Indicates if this is the primary or secondary instance. Only primary instances manage child nodes.\n     * @param {SVGGElement=} gNode - (optional) Primary and seconday instances share the same &lt;g> node.\n     **/\n    constructor(svgNode, offset, scale, canvasSize, fillShapes, drawConfig, isSecondary, gNode, bufferGNode, nodeDefs, bufferNodeDefs, nodeStyle) {\n        this.svgNode = svgNode;\n        this.offset = new Vertex(0, 0).set(offset);\n        this.scale = new Vertex(1, 1).set(scale);\n        this.fillShapes = fillShapes;\n        this.isSecondary = Boolean(isSecondary);\n        this.drawConfig = drawConfig;\n        this.drawlibConfiguration = {};\n        this.cache = new Map();\n        this.setSize(canvasSize);\n        if (isSecondary) {\n            if (!gNode || !bufferGNode || !nodeDefs || !bufferNodeDefs) {\n                throw \"Cannot create secondary svg draw lib with undefinde gNode|bufferGNode|nodeDefs|bufferNodeDefs.\";\n            }\n            this.gNode = gNode;\n            this.bufferGNode = bufferGNode;\n            this.nodeDefs = nodeDefs;\n            this.bufferedNodeDefs = bufferNodeDefs;\n            if (nodeStyle) {\n                this.nodeStyle = nodeStyle;\n            }\n        }\n        else {\n            this.addStyleDefs(drawConfig);\n            this.addDefsNode();\n            this.gNode = this.createSVGNode(\"g\");\n            this.bufferGNode = this.createSVGNode(\"g\");\n            this.svgNode.appendChild(this.gNode);\n        }\n    }\n    /**\n     * Adds a default style defintion based on the passed DrawConfig.\n     * Twaek the draw config to change default colors or line thicknesses.\n     *\n     * @param {DrawConfig} drawConfig\n     */\n    addStyleDefs(drawConfig) {\n        this.nodeStyle = this.createSVGNode(\"style\");\n        this.svgNode.appendChild(this.nodeStyle);\n        this.rebuildStyleDefs(drawConfig);\n    }\n    /**\n     * This method is required to re-define the global style defs. It is needed\n     * if any value in the DrawConfig changed in the meantime.\n     * @param drawConfig\n     */\n    rebuildStyleDefs(drawConfig) {\n        // Which default styles to add? -> All from the DrawConfig.\n        // Compare with DrawConfig interface\n        const keys = {\n            \"bezier\": \"CubicBezierCurve\",\n            //\"bezierPath\": \"BezierPath\", // TODO: is this correct?\n            \"polygon\": \"Polygon\",\n            \"triangle\": \"Triangle\",\n            \"ellipse\": \"Ellipse\",\n            \"ellipseSector\": \"EllipseSector\",\n            \"circle\": \"Circle\",\n            \"circleSector\": \"CircleSector\",\n            \"vertex\": \"Vertex\",\n            \"line\": \"Line\",\n            \"vector\": \"Vector\",\n            \"image\": \"Image\",\n            \"text\": \"Text\"\n        };\n        // Question: why isn't this working if the svgNode is created dynamically? (nodeStyle.sheet is null)\n        const rules = [];\n        // console.log(\"drawConfig\", drawConfig);\n        for (var k in keys) {\n            const className = keys[k];\n            const drawSettings = drawConfig[k];\n            if (drawSettings) {\n                rules.push(`.${className} { fill : none; stroke: ${drawSettings.color}; stroke-width: ${drawSettings.lineWidth}px }`);\n            }\n            else {\n                console.warn(`Warning: your draw config is missing the key '${k}' which is required.`);\n            }\n        }\n        if (this.customStyleDefs) {\n            rules.push(\"\\n/* Custom styles */\\n\");\n            this.customStyleDefs.forEach((value, key) => {\n                rules.push(key + \" { \" + value + \" }\");\n            });\n            // this.nodeStyle.innerHTML += \"\\n/* Custom styles */\\n\" + rules.join(\"\\n\");\n        }\n        this.nodeStyle.innerHTML = rules.join(\"\\n\");\n    }\n    /**\n     * Adds the internal <defs> node.\n     */\n    addDefsNode() {\n        this.nodeDefs = this.createSVGNode(\"defs\");\n        // this.svgNode.appendChild(this.nodeDefs);\n        this.bufferedNodeDefs = this.createSVGNode(\"defs\");\n        this.svgNode.appendChild(this.nodeDefs);\n    }\n    /**\n     * This is a simple way to include custom CSS class mappings to the style defs of the generated SVG.\n     *\n     * The mapping should be of the form\n     *   [style-class] -> [style-def-string]\n     *\n     * Example:\n     *   \"rect.red\" -> \"fill: #ff0000; border: 1px solid red\"\n     *\n     * @param {Map<string,string>} defs\n     */\n    addCustomStyleDefs(defs) {\n        this.customStyleDefs = defs;\n    }\n    /**\n     * Retieve an old (cached) element.\n     * Only if both – key and nodeName – match, the element will be returned (null otherwise).\n     *\n     * @method findElement\n     * @private\n     * @memberof drawutilssvg\n     * @instance\n     * @param {UID} key - The key of the desired element (used when re-drawing).\n     * @param {string} nodeName - The expected node name.\n     */\n    findElement(key, nodeName) {\n        if (!key) {\n            return null;\n        }\n        var node = this.cache.get(key);\n        if (node && node.nodeName.toUpperCase() === nodeName.toUpperCase()) {\n            this.cache.delete(key);\n            return node;\n        }\n        return null;\n    }\n    /**\n     * Create a new DOM node &lt;svg&gt; in the SVG namespace.\n     *\n     * @method createSVGNode\n     * @private\n     * @memberof drawutilssvg\n     * @instance\n     * @param {string} nodeName - The node name (tag-name).\n     * @return {SVGElement} A new element in the SVG namespace with the given node name.\n     */\n    createSVGNode(nodeName) {\n        return document.createElementNS(\"http://www.w3.org/2000/svg\", nodeName);\n    }\n    /**\n     * Make a new SVG node (or recycle an old one) with the given node name (circle, path, line, rect, ...).\n     *\n     * This function is used in draw cycles to re-use old DOM nodes (in hope to boost performance).\n     *\n     * @method makeNode\n     * @private\n     * @instance\n     * @memberof drawutilssvg\n     * @param {string} nodeName - The node name.\n     * @return {SVGElement} The new node, which is not yet added to any document.\n     */\n    makeNode(nodeName) {\n        // Try to find node in current DOM cache.\n        // Unique node keys are strictly necessary.\n        // Try to recycle an old element from cache.\n        var node = this.findElement(this.curId, nodeName);\n        if (!node) {\n            // If no such old elements exists (key not found, tag name not matching),\n            // then create a new one.\n            node = this.createSVGNode(nodeName);\n        }\n        if (this.drawlibConfiguration.blendMode) {\n            const blendMode = node.style[\"mix-blend-mode\"];\n            if (typeof blendMode === \"function\") {\n                blendMode(this.drawlibConfiguration.blendMode);\n            }\n            else {\n                node.style[\"mix-blend-mode\"] = this.drawlibConfiguration.blendMode;\n            }\n        }\n        // if (this.lineDashEnabled && this.lineDash && this.lineDash.length > 0 && drawutilssvg.nodeSupportsLineDash(nodeName)) {\n        //   node.setAttribute(\"stroke-dasharray\", this.lineDash.join(\" \"));\n        // }\n        return node;\n    }\n    /**\n     * This is the final helper function for drawing and filling stuff and binding new\n     * nodes to the SVG document.\n     * It is not intended to be used from the outside.\n     *\n     * When in draw mode it draws the current shape.\n     * When in fill mode it fills the current shape.\n     *\n     * This function is usually only called internally.\n     *\n     * @method _bindFillDraw\n     * @private\n     * @instance\n     * @memberof drawutilssvg\n     * @param {SVGElement} node - The node to draw/fill and bind.\n     * @param {string} className - The class name(s) to use.\n     * @param {string} color - A stroke/fill color to use.\n     * @param {number=1} lineWidth - (optional) A line width to use for drawing (default is 1).\n     * @return {SVGElement} The node itself (for chaining).\n     */\n    _bindFillDraw(node, className, color, lineWidth, strokeOptions) {\n        this._configureNode(node, className, this.fillShapes, color, lineWidth, strokeOptions);\n        return this._bindNode(node, undefined);\n    }\n    /**\n     * Bind this given node to a parent. If no parent is passed then the global\n     * node buffer will be used.\n     *\n     * @method _bindNode\n     * @private\n     * @instance\n     * @memberof drawutilssvg\n     * @param {SVGElement} node - The SVG node to bind.\n     * @param {SVGElement=} bindingParent - (optional) You may pass node other than the glober buffer node.\n     * @returns {SVGElement} The passed node itself.\n     */\n    _bindNode(node, bindingParent) {\n        if (!node.parentNode) {\n            // Attach to DOM only if not already attached\n            (bindingParent !== null && bindingParent !== void 0 ? bindingParent : this.bufferGNode).appendChild(node);\n        }\n        return node;\n    }\n    /**\n     * Add custom CSS class names and the globally defined CSS classname to the\n     * given node.\n     *\n     * @method addCSSClasses\n     * @private\n     * @instance\n     * @memberof drawutilssvg\n     * @param {SVGElement} node - The SVG node to bind.\n     * @param {string} className - The additional custom classname to add.\n     * @returns {void}\n     */\n    _addCSSClasses(node, className) {\n        if (this.curClassName) {\n            node.setAttribute(\"class\", `${className} ${this.curClassName}`);\n        }\n        else {\n            node.setAttribute(\"class\", className);\n        }\n    }\n    _configureNode(node, className, fillMode, color, lineWidth, strokeOptions) {\n        this._addCSSClasses(node, className);\n        node.setAttribute(\"fill\", fillMode && color ? color : \"none\");\n        node.setAttribute(\"stroke\", fillMode ? \"none\" : color || \"none\");\n        node.setAttribute(\"stroke-width\", `${lineWidth || 1}`);\n        if (this.curId) {\n            node.setAttribute(\"id\", `${this.curId}`); // Maybe React-style 'key' would be better?\n        }\n        this.applyStrokeOpts(node, strokeOptions);\n        return node;\n    }\n    /**\n     * Sets the size and view box of the document. Call this if canvas size changes.\n     *\n     * @method setSize\n     * @instance\n     * @memberof drawutilssvg\n     * @param {XYDimension} canvasSize - The new canvas size.\n     */\n    setSize(canvasSize) {\n        this.canvasSize = canvasSize;\n        this.svgNode.setAttribute(\"viewBox\", `0 0 ${this.canvasSize.width} ${this.canvasSize.height}`);\n        this.svgNode.setAttribute(\"width\", `${this.canvasSize.width}`);\n        this.svgNode.setAttribute(\"height\", `${this.canvasSize.height}`);\n    }\n    /**\n     * Creates a 'shallow' (non deep) copy of this instance. This implies\n     * that under the hood the same gl context and gl program will be used.\n     */\n    copyInstance(fillShapes) {\n        var copy = new drawutilssvg(this.svgNode, this.offset, this.scale, this.canvasSize, fillShapes, this.drawConfig, // null as any as DrawConfig, // no DrawConfig – this will work as long as `isSecondary===true`\n        true, // isSecondary\n        this.gNode, this.bufferGNode, this.nodeDefs, this.bufferedNodeDefs, this.nodeStyle);\n        return copy;\n    }\n    /**\n     * Set the current drawlib configuration.\n     *\n     * @name setConfiguration\n     * @method\n     * @param {DrawLibConfiguration} configuration - The new configuration settings to use for the next render methods.\n     */\n    setConfiguration(configuration) {\n        this.drawlibConfiguration = configuration;\n    }\n    /**\n     * This method shouled be called each time the currently drawn `Drawable` changes.\n     * It is used by some libraries for identifying elemente on re-renders.\n     *\n     * @name setCurrentId\n     * @method\n     * @param {UID|null} uid - A UID identifying the currently drawn element(s).\n     * @instance\n     * @memberof drawutilssvg\n     **/\n    setCurrentId(uid) {\n        this.curId = uid;\n    }\n    /**\n     * This method shouled be called each time the currently drawn `Drawable` changes.\n     * Determine the class name for further usage here.\n     *\n     * @name setCurrentClassName\n     * @method\n     * @param {string|null} className - A class name for further custom use cases.\n     * @instance\n     * @memberof drawutilssvg\n     **/\n    setCurrentClassName(className) {\n        this.curClassName = className;\n    }\n    /**\n     * Called before each draw cycle.\n     * This is required for compatibility with other draw classes in the library.\n     *\n     * @name beginDrawCycle\n     * @method\n     * @param {UID=} uid - (optional) A UID identifying the currently drawn element(s).\n     * @instance\n     * @memberof drawutilssvg\n     **/\n    beginDrawCycle(renderTime) {\n        // Clear non-recycable elements from last draw cycle.\n        this.cache.clear();\n        // Clearing an SVG is equivalent to removing all its child elements.\n        for (var i = 0; i < this.bufferGNode.childNodes.length; i++) {\n            // Hide all nodes here. Don't throw them away.\n            // We can probably re-use them in the next draw cycle.\n            var child = this.bufferGNode.childNodes[i];\n            this.cache.set(child.getAttribute(\"id\"), child);\n        }\n        this.removeAllChildNodes();\n    }\n    /**\n     * Called after each draw cycle.\n     *\n     * This is required for compatibility with other draw classes in the library (like drawgl).\n     *\n     * @name endDrawCycle\n     * @method\n     * @param {number} renderTime\n     * @instance\n     **/\n    endDrawCycle(renderTime) {\n        this.rebuildStyleDefs(this.drawConfig);\n        if (!this.isSecondary) {\n            // All elements are drawn into the buffer; they are NOT yet visible, not did the browser perform any\n            // layout updates.\n            // Replace the old <g>-node with the buffer node.\n            //   https://stackoverflow.com/questions/27442464/how-to-update-a-svg-image-without-seeing-a-blinking\n            this.svgNode.replaceChild(this.bufferedNodeDefs, this.nodeDefs);\n            this.svgNode.replaceChild(this.bufferGNode, this.gNode);\n        }\n        const tmpGNode = this.gNode;\n        this.gNode = this.bufferGNode;\n        this.bufferGNode = tmpGNode;\n        const tmpDefsNode = this.nodeDefs;\n        this.nodeDefs = this.bufferedNodeDefs;\n        this.bufferedNodeDefs = tmpDefsNode;\n    }\n    /**\n     * A private helper method to apply stroke options to the current\n     * context.\n     * @param {StrokeOptions=} strokeOptions -\n     */\n    applyStrokeOpts(node, strokeOptions) {\n        // Set line dash options?\n        if (strokeOptions &&\n            strokeOptions.dashArray &&\n            strokeOptions.dashArray.length > 0 &&\n            drawutilssvg.nodeSupportsLineDash(node.tagName)) {\n            node.setAttribute(\"stroke-dasharray\", strokeOptions.dashArray\n                .map((dashArayElem) => {\n                return dashArayElem * this.scale.x;\n            })\n                .join(\" \"));\n            if (strokeOptions.dashOffset) {\n                node.setAttribute(\"stroke-dashoffset\", `${strokeOptions.dashOffset * this.scale.x}`);\n            }\n        }\n        // Set line join option?\n        if (strokeOptions && strokeOptions.lineJoin && drawutilssvg.nodeSupportsLineJoin(node.tagName)) {\n            node.setAttribute(\"stroke-linejoin\", strokeOptions.lineJoin);\n        }\n        // Set lineCap option?\n        if (strokeOptions && strokeOptions.lineCap && drawutilssvg.nodeSupportsLineCap(node.tagName)) {\n            node.setAttribute(\"stroke-linecap\", strokeOptions.lineCap);\n        }\n    }\n    _x(x) {\n        return this.offset.x + this.scale.x * x;\n    }\n    _y(y) {\n        return this.offset.y + this.scale.y * y;\n    }\n    /**\n     * Draw the line between the given two points with the specified (CSS-) color.\n     *\n     * @method line\n     * @param {XYCoords} zA - The start point of the line.\n     * @param {XYCoords} zB - The end point of the line.\n     * @param {string} color - Any valid CSS color string.\n     * @param {number=1} lineWidth? - [optional] The line's width.\n     * @param {StrokeOptions=} strokeOptions - (optional) Stroke settings to use.\n     *\n     * @return {void}\n     * @instance\n     * @memberof drawutilssvg\n     **/\n    line(zA, zB, color, lineWidth, strokeOptions) {\n        // const line: SVGElement = this.makeNode(\"line\");\n        // this.applyStrokeOpts(line, strokeOptions);\n        // line.setAttribute(\"x1\", `${this._x(zA.x)}`);\n        // line.setAttribute(\"y1\", `${this._y(zA.y)}`);\n        // line.setAttribute(\"x2\", `${this._x(zB.x)}`);\n        // line.setAttribute(\"y2\", `${this._y(zB.y)}`);\n        const line = this.makeLineNode(zA, zB, color, lineWidth, strokeOptions);\n        return this._bindFillDraw(line, \"line\", color, lineWidth || 1, strokeOptions);\n    }\n    /**\n     * Draw a line and an arrow at the end (zB) of the given line with the specified (CSS-) color.\n     *\n     * @method arrow\n     * @param {XYCoords} zA - The start point of the arrow-line.\n     * @param {XYCoords} zB - The end point of the arrow-line.\n     * @param {string} color - Any valid CSS color string.\n     * @param {number=} lineWidth - (optional) The line width to use; default is 1.\n     * @param {headLength=8} headLength - (optional) The length of the arrow head (default is 8 units).\n     * @param {StrokeOptions=} strokeOptions - (optional) Stroke settings to use.\n     *\n     * @return {void}\n     * @instance\n     * @memberof drawutilssvg\n     **/\n    arrow(zA, zB, color, lineWidth, headLength = 8, strokeOptions) {\n        const group = this.makeNode(\"g\");\n        const arrowHeadBasePosition = { x: 0, y: 0 };\n        // Just create the child nodes, don't bind them to the root node.\n        const arrowHead = this.makeArrowHeadNode(zA, zB, color, lineWidth, headLength, undefined, arrowHeadBasePosition);\n        const line = this.makeLineNode(zA, arrowHeadBasePosition, color, lineWidth, strokeOptions);\n        group.appendChild(line);\n        group.appendChild(arrowHead);\n        this._addCSSClasses(group, \"linear-arrow\");\n        this._bindNode(group, undefined);\n        return group;\n    }\n    /**\n     * Draw a cubic Bézier curve and and an arrow at the end (endControlPoint) of the given line width the specified (CSS-) color and arrow size.\n     *\n     * @method cubicBezierArrow\n     * @param {XYCoords} startPoint - The start point of the cubic Bézier curve\n     * @param {XYCoords} endPoint   - The end point the cubic Bézier curve.\n     * @param {XYCoords} startControlPoint - The start control point the cubic Bézier curve.\n     * @param {XYCoords} endControlPoint   - The end control point the cubic Bézier curve.\n     * @param {string} color - The CSS color to draw the curve with.\n     * @param {number} lineWidth - (optional) The line width to use.\n     * @param {headLength=8} headLength - (optional) The length of the arrow head (default is 8 units).\n     * @param {StrokeOptions=} strokeOptions - (optional) Stroke settings to use.\n     *\n     * @return {void}\n     * @instance\n     * @memberof DrawLib\n     */\n    cubicBezierArrow(startPoint, endPoint, startControlPoint, endControlPoint, color, lineWidth, headLength = 8, strokeOptions) {\n        const group = this.makeNode(\"g\");\n        // Just create the child nodes, don't bind them to the root node.\n        const arrowHeadBasePosition = new Vertex(0, 0);\n        const arrowHead = this.makeArrowHeadNode(endControlPoint, endPoint, color, lineWidth, headLength, undefined, arrowHeadBasePosition);\n        const diff = arrowHeadBasePosition.difference(endPoint);\n        const bezier = this.makeCubicBezierNode(startPoint, { x: endPoint.x - diff.x, y: endPoint.y - diff.y }, startControlPoint, { x: endControlPoint.x - diff.x, y: endControlPoint.y - diff.y }, color, lineWidth, strokeOptions);\n        group.appendChild(bezier);\n        group.appendChild(arrowHead);\n        this._addCSSClasses(group, \"cubicbezier-arrow\");\n        this._bindNode(group, undefined);\n        return group;\n    }\n    /**\n     * Draw just an arrow head a the end of an imaginary line (zB) of the given line width the specified (CSS-) color and size.\n     *\n     * @method arrow\n     * @param {XYCoords} zA - The start point of the arrow-line.\n     * @param {XYCoords} zB - The end point of the arrow-line.\n     * @param {string} color - Any valid CSS color string.\n     * @param {number=1} lineWidth - (optional) The line width to use; default is 1.\n     * @param {number=8} headLength - (optional) The length of the arrow head (default is 8 pixels).\n     * @param {StrokeOptions=} strokeOptions - (optional) Stroke settings to use.\n     *\n     * @return {void}\n     * @instance\n     * @memberof DrawLib\n     **/\n    arrowHead(zA, zB, color, lineWidth, headLength = 8, strokeOptions) {\n        const node = this.makeArrowHeadNode(zA, zB, color, lineWidth, headLength, strokeOptions);\n        return this._bindFillDraw(node, \"arrowhead\", color, lineWidth || 1, strokeOptions);\n    }\n    /**\n     * Draw an image at the given position with the given size.<br>\n     * <br>\n     * Note: SVG images may have resizing issues at the moment.Draw a line and an arrow at the end (zB) of the given line with the specified (CSS-) color.\n     *\n     * @method image\n     * @param {Image} image - The image object to draw.\n     * @param {XYCoords} position - The position to draw the the upper left corner at.\n     * @param {XYCoords} size - The x/y-size to draw the image with.\n     * @param {number=0.0} alpha - (optional, default=0.0) The transparency (1.0=opaque, 0.0=transparent).\n     * @return {void}\n     * @instance\n     * @memberof drawutilssvg\n     **/\n    image(image, position, size, alpha = 1.0) {\n        const node = this.makeNode(\"image\");\n        // We need to re-adjust the image if it was not yet fully loaded before.\n        const setImageSize = (image) => {\n            if (image.naturalWidth) {\n                const ratioX = size.x / image.naturalWidth;\n                const ratioY = size.y / image.naturalHeight;\n                node.setAttribute(\"width\", `${image.naturalWidth * this.scale.x}`);\n                node.setAttribute(\"height\", `${image.naturalHeight * this.scale.y}`);\n                node.setAttribute(\"display\", null); // Dislay when loaded\n                // if (alpha) {\n                node.setAttribute(\"opacity\", `${alpha}`);\n                // }\n                node.setAttribute(\"transform\", `translate(${this._x(position.x)} ${this._y(position.y)}) scale(${ratioX} ${ratioY})`);\n            }\n        };\n        image.addEventListener(\"load\", event => {\n            setImageSize(image);\n        });\n        // Safari has a transform-origin bug.\n        // Use x=0, y=0 and translate/scale instead (see above)\n        node.setAttribute(\"x\", `${0}`);\n        node.setAttribute(\"y\", `${0}`);\n        node.setAttribute(\"display\", \"none\"); // Hide before loaded\n        setImageSize(image);\n        node.setAttribute(\"href\", image.src);\n        return this._bindFillDraw(node, \"image\", null, null);\n    }\n    /**\n     * Draw an image at the given position with the given size.<br>\n     * <br>\n     * Note: SVG images may have resizing issues at the moment.Draw a line and an arrow at the end (zB) of the given line with the specified (CSS-) color.\n     *\n     * @method texturedPoly\n     * @param {Image} textureImage - The image object to draw.\n     * @param {Bounds} textureSize - The texture size to use; these are the original bounds to map the polygon vertices to.\n     * @param {Polygon} polygon - The polygon to use as clip path.\n     * @param {XYCoords} polygonPosition - The polygon's position (relative), measured at the bounding box's center.\n     * @param {number} rotation - The rotation to use for the polygon (and for the texture).\n     * @return {void}\n     * @instance\n     * @memberof drawutilssvg\n     **/\n    texturedPoly(textureImage, textureSize, polygon, polygonPosition, rotation) {\n        // const basePolygonBounds: Bounds = polygon.getBounds();\n        const rotatedScalingOrigin = new Vertex(textureSize.min).clone().rotate(rotation, polygonPosition);\n        // const rotationCenter = polygonPosition.clone().add(rotatedScalingOrigin.difference(textureSize.min).inv());\n        // Create something like this\n        // ...\n        //    <defs>\n        //       <clipPath id=\"shape\">\n        //         <path fill=\"none\" d=\"...\"/>\n        //       </clipPath>\n        //    </defs>\n        //    ...\n        //    <g clip-path=\"url(#shape)\">\n        //       <g transform=\"scale(...)\">\n        //          <image width=\"643\" height=\"643\" transform=\"rotate(...)\" xlink:href=\"https://s3-us-west-2.amazonaws.com/s.cdpn.io/222579/beagle400.jpg\" >\n        //       </g>\n        //    </g>\n        //    </image>\n        // ...\n        const clipPathNode = this.makeNode(\"clipPath\");\n        const clipPathId = `clippath_${UIDGenerator.next()}`; // TODO: use a better UUID generator here?\n        clipPathNode.setAttribute(\"id\", clipPathId);\n        const gNode = this.makeNode(\"g\");\n        const imageNode = this.makeNode(\"image\");\n        imageNode.setAttribute(\"x\", `${this._x(rotatedScalingOrigin.x)}`);\n        imageNode.setAttribute(\"y\", `${this._y(rotatedScalingOrigin.y)}`);\n        imageNode.setAttribute(\"width\", `${textureSize.width}`);\n        imageNode.setAttribute(\"height\", `${textureSize.height}`);\n        imageNode.setAttribute(\"href\", textureImage.src);\n        // imageNode.setAttribute(\"opacity\", \"0.5\");\n        // SVG rotations in degrees\n        imageNode.setAttribute(\"transform\", `rotate(${rotation * RAD_TO_DEG}, ${this._x(rotatedScalingOrigin.x)}, ${this._y(rotatedScalingOrigin.y)})`);\n        const pathNode = this.makeNode(\"path\");\n        const pathData = [];\n        if (polygon.vertices.length > 0) {\n            const self = this;\n            pathData.push(\"M\", `${this._x(polygon.vertices[0].x)}`, `${this._y(polygon.vertices[0].y)}`);\n            for (var i = 1; i < polygon.vertices.length; i++) {\n                pathData.push(\"L\", `${this._x(polygon.vertices[i].x)}`, `${this._y(polygon.vertices[i].y)}`);\n            }\n        }\n        pathNode.setAttribute(\"d\", pathData.join(\" \"));\n        clipPathNode.appendChild(pathNode);\n        this.bufferedNodeDefs.appendChild(clipPathNode);\n        gNode.appendChild(imageNode);\n        gNode.setAttribute(\"transform-origin\", `${this._x(rotatedScalingOrigin.x)} ${this._y(rotatedScalingOrigin.y)}`);\n        gNode.setAttribute(\"transform\", `scale(${this.scale.x}, ${this.scale.y})`);\n        const clipNode = this.makeNode(\"g\");\n        clipNode.appendChild(gNode);\n        clipNode.setAttribute(\"clip-path\", `url(#${clipPathId})`);\n        // TODO: check if the image class is correct here or if we should use a 'clippedImage' class here\n        this._bindFillDraw(clipNode, \"image\", null, null); // No color, no lineWidth\n        return clipNode;\n    }\n    /**\n     * Draw the given (cubic) bézier curve.\n     *\n     * @method cubicBezier\n     * @param {XYCoords} startPoint - The start point of the cubic Bézier curve\n     * @param {XYCoords} endPoint   - The end point the cubic Bézier curve.\n     * @param {XYCoords} startControlPoint - The start control point the cubic Bézier curve.\n     * @param {XYCoords} endControlPoint   - The end control point the cubic Bézier curve.\n     * @param {string} color - The CSS color to draw the curve with.\n     * @param {number} lineWidth - (optional) The line width to use.\n     * @param {StrokeOptions=} strokeOptions - (optional) Stroke settings to use.\n     *\n     * @return {void}\n     * @instance\n     * @memberof drawutilssvg\n     */\n    cubicBezier(startPoint, endPoint, startControlPoint, endControlPoint, color, lineWidth, strokeOptions) {\n        const node = this.makeCubicBezierNode(startPoint, endPoint, startControlPoint, endControlPoint, color, lineWidth, strokeOptions);\n        return this._bindNode(node, undefined);\n    }\n    /**\n     * Draw the given (cubic) Bézier path.\n     *\n     * The given path must be an array with n*3+1 vertices, where n is the number of\n     * curves in the path:\n     * <pre> [ point1, point1_startControl, point2_endControl, point2, point2_startControl, point3_endControl, point3, ... pointN_endControl, pointN ]</pre>\n     *\n     * @method cubicBezierPath\n     * @param {XYCoords[]} path - The cubic bezier path as described above.\n     * @param {string} color - The CSS colot to draw the path with.\n     * @param {number=1} lineWidth - (optional) The line width to use.\n     * @param {StrokeOptions=} strokeOptions - (optional) Stroke settings to use.\n     * @param {boolean} isOpen - (optional) Set to tur if the path should not be closed.\n     * @return {void}\n     * @instance\n     * @memberof drawutilssvg\n     */\n    cubicBezierPath(path, color, lineWidth, strokeOptions, isOpen) {\n        const node = this.makeNode(\"path\");\n        this.applyStrokeOpts(node, strokeOptions);\n        if (!path || path.length == 0) {\n            return node;\n        }\n        // Draw curve\n        const d = [\"M\", this._x(path[0].x), this._y(path[0].y)];\n        // Draw curve path\n        var endPoint;\n        var startControlPoint;\n        var endControlPoint;\n        for (var i = 1; i < path.length; i += 3) {\n            startControlPoint = path[i];\n            endControlPoint = path[i + 1];\n            endPoint = path[i + 2];\n            d.push(\"C\", this._x(startControlPoint.x), this._y(startControlPoint.y), this._x(endControlPoint.x), this._y(endControlPoint.y), this._x(endPoint.x), this._y(endPoint.y));\n        }\n        if (!isOpen) {\n            d.push(\"Z\");\n        }\n        node.setAttribute(\"d\", d.join(\" \"));\n        return this._bindFillDraw(node, \"cubicBezierPath\", color, lineWidth || 1);\n    }\n    /**\n     * Draw the given handle and handle point (used to draw interactive Bézier curves).\n     *\n     * The colors for this are fixed and cannot be specified.\n     *\n     * @method handle\n     * @param {Vertex} startPoint - The start of the handle.\n     * @param {Vertex} endPoint - The end point of the handle.\n     * @return {void}\n     * @instance\n     * @memberof drawutilssvg\n     */\n    handle(startPoint, endPoint) {\n        // TODO: redefine methods like these into an abstract class?\n        this.point(startPoint, \"rgb(0,32,192)\");\n        this.square(endPoint, 5, \"rgba(0,128,192,0.5)\");\n    }\n    /**\n     * Draw a handle line (with a light grey).\n     *\n     * @method handleLine\n     * @param {XYCoords} startPoint - The start point to draw the handle at.\n     * @param {XYCoords} endPoint - The end point to draw the handle at.\n     * @return {void}\n     * @instance\n     * @memberof drawutilssvg\n     */\n    handleLine(startPoint, endPoint) {\n        this.line(startPoint, endPoint, \"rgb(128,128,128,0.5)\");\n    }\n    /**\n     * Draw a 1x1 dot with the specified (CSS-) color.\n     *\n     * @method dot\n     * @param {XYCoords} p - The position to draw the dot at.\n     * @param {string} color - The CSS color to draw the dot with.\n     * @return {void}\n     * @instance\n     * @memberof drawutilssvg\n     */\n    dot(p, color) {\n        const node = this.makeNode(\"line\");\n        node.setAttribute(\"x1\", `${this._x(p.x)}`);\n        node.setAttribute(\"y1\", `${this._y(p.y)}`);\n        node.setAttribute(\"x2\", `${this._x(p.x)}`);\n        node.setAttribute(\"y2\", `${this._y(p.y)}`);\n        return this._bindFillDraw(node, \"dot\", color, 1);\n    }\n    /**\n     * Draw the given point with the specified (CSS-) color and radius 3.\n     *\n     * @method point\n     * @param {XYCoords} p - The position to draw the point at.\n     * @param {string} color - The CSS color to draw the point with.\n     * @return {void}\n     * @instance\n     * @memberof drawutilssvg\n     */\n    point(p, color) {\n        var radius = 3;\n        const node = this.makeNode(\"circle\");\n        node.setAttribute(\"cx\", `${this._x(p.x)}`);\n        node.setAttribute(\"cy\", `${this._y(p.y)}`);\n        node.setAttribute(\"r\", `${radius}`);\n        return this._bindFillDraw(node, \"point\", color, 1);\n    }\n    /**\n     * Draw a circle with the specified (CSS-) color and radius.<br>\n     * <br>\n     * Note that if the x- and y- scales are different the result will be an ellipse rather than a circle.\n     *\n     * @method circle\n     * @param {XYCoords} center - The center of the circle.\n     * @param {number} radius - The radius of the circle.\n     * @param {string} color - The CSS color to draw the circle with.\n     * @param {number=} lineWidth - (optional) The line width to use; default is 1.\n     * @param {StrokeOptions=} strokeOptions - (optional) Stroke settings to use.\n     *\n     * @return {void}\n     * @instance\n     * @memberof drawutilssvg\n     */\n    circle(center, radius, color, lineWidth, strokeOptions) {\n        // Todo: draw ellipse when scalex!=scaley\n        const node = this.makeNode(\"circle\");\n        this.applyStrokeOpts(node, strokeOptions);\n        node.setAttribute(\"cx\", `${this._x(center.x)}`);\n        node.setAttribute(\"cy\", `${this._y(center.y)}`);\n        node.setAttribute(\"r\", `${radius * this.scale.x}`); // y?\n        return this._bindFillDraw(node, \"circle\", color, lineWidth || 1);\n    }\n    /**\n     * Draw a circular arc (section of a circle) with the given CSS color.\n     *\n     * @method circleArc\n     * @param {XYCoords} center - The center of the circle.\n     * @param {number} radius - The radius of the circle.\n     * @param {number} startAngle - The angle to start at.\n     * @param {number} endAngle - The angle to end at.\n     * @param {string} color - The CSS color to draw the circle with.\n     * @param {StrokeOptions=} strokeOptions - (optional) Stroke settings to use.\n     *\n     * @return {void}\n     * @instance\n     * @memberof drawutilssvg\n     */\n    circleArc(center, radius, startAngle, endAngle, color, lineWidth, strokeOptions) {\n        const node = this.makeNode(\"path\");\n        this.applyStrokeOpts(node, strokeOptions);\n        const arcData = CircleSector.circleSectorUtils.describeSVGArc(this._x(center.x), this._y(center.y), radius * this.scale.x, // y?\n        startAngle, endAngle);\n        node.setAttribute(\"d\", arcData.join(\" \"));\n        return this._bindFillDraw(node, \"circleArc\", color, lineWidth || 1);\n    }\n    /**\n     * Draw an ellipse with the specified (CSS-) color and thw two radii.\n     *\n     * @method ellipse\n     * @param {XYCoords} center - The center of the ellipse.\n     * @param {number} radiusX - The radius of the ellipse.\n     * @param {number} radiusY - The radius of the ellipse.\n     * @param {string} color - The CSS color to draw the ellipse with.\n     * @param {number=} lineWidth - (optional) The line width to use; default is 1.\n     * @param {number=} rotation - (optional, default=0) The rotation of the ellipse.\n     * @param {StrokeOptions=} strokeOptions - (optional) Stroke settings to use.\n     *\n     * @return {void}\n     * @instance\n     * @memberof drawutilssvg\n     */\n    ellipse(center, radiusX, radiusY, color, lineWidth, rotation, strokeOptions) {\n        if (typeof rotation === \"undefined\") {\n            rotation = 0.0;\n        }\n        const node = this.makeNode(\"ellipse\");\n        this.applyStrokeOpts(node, strokeOptions);\n        node.setAttribute(\"cx\", `${this._x(center.x)}`);\n        node.setAttribute(\"cy\", `${this._y(center.y)}`);\n        node.setAttribute(\"rx\", `${radiusX * this.scale.x}`);\n        node.setAttribute(\"ry\", `${radiusY * this.scale.y}`);\n        // node.setAttribute( 'style', `transform: rotate(${rotation} ${center.x} ${center.y})` );\n        node.setAttribute(\"transform\", `rotate(${(rotation * 180) / Math.PI} ${this._x(center.x)} ${this._y(center.y)})`);\n        return this._bindFillDraw(node, \"ellipse\", color, lineWidth || 1);\n    }\n    /**\n     * Draw square at the given center, size and with the specified (CSS-) color.<br>\n     * <br>\n     * Note that if the x-scale and the y-scale are different the result will be a rectangle rather than a square.\n     *\n     * @method square\n     * @param {XYCoords} center - The center of the square.\n     * @param {number} size - The size of the square.\n     * @param {string} color - The CSS color to draw the square with.\n     * @param {number=} lineWidth - (optional) The line width to use; default is 1.\n     * @param {StrokeOptions=} strokeOptions - (optional) Stroke settings to use.\n     *\n     * @return {SVGElement}\n     * @instance\n     * @memberof drawutilssvg\n     */\n    square(center, size, color, lineWidth, strokeOptions) {\n        const node = this.makeNode(\"rectangle\");\n        this.applyStrokeOpts(node, strokeOptions);\n        node.setAttribute(\"x\", `${this._x(center.x - size / 2.0)}`);\n        node.setAttribute(\"y\", `${this._y(center.y - size / 2.0)}`);\n        node.setAttribute(\"width\", `${size * this.scale.x}`);\n        node.setAttribute(\"height\", `${size * this.scale.y}`);\n        return this._bindFillDraw(node, \"square\", color, lineWidth || 1);\n    }\n    /**\n     * Draw a rectangle.\n     *\n     * @param {XYCoords} position - The upper left corner of the rectangle.\n     * @param {number} width - The width of the rectangle.\n     * @param {number} height - The height of the rectangle.\n     * @param {string} color - The color to use.\n     * @param {number=1} lineWidth - (optional) The line with to use (default is 1).\n     * @param {StrokeOptions=} strokeOptions - (optional) Stroke settings to use.\n     *\n     * @return {SVGElement}\n     * @instance\n     * @memberof drawutilssvg\n     **/\n    rect(position, width, height, color, lineWidth, strokeOptions) {\n        const node = this.makeNode(\"rect\");\n        this.applyStrokeOpts(node, strokeOptions);\n        node.setAttribute(\"x\", `${this._x(position.x)}`);\n        node.setAttribute(\"y\", `${this._y(position.y)}`);\n        node.setAttribute(\"width\", `${width * this.scale.x}`);\n        node.setAttribute(\"height\", `${height * this.scale.y}`);\n        return this._bindFillDraw(node, \"rect\", color, lineWidth || 1);\n    }\n    /**\n     * Draw a rectangle at the given bounds; and with the specified line width and (CSS-) color.<br>\n     *\n     * @method bounds\n     * @param {IBounds} bounds - The bounds rectangle to be drawn.\n     * @param {string} color - The CSS color to draw the rectangle with.\n     * @param {number=} lineWidth - (optional) The line width to use; default is 1.\n     * @param {StrokeOptions=} strokeOptions - (optional) Stroke settings to use.\n     *\n     * @return {R}\n     * @instance\n     * @memberof DrawLib\n     */\n    bounds(bounds, color, lineWidth, strokeOptions) {\n        this.rect(bounds.min, bounds.max.x - bounds.min.x, bounds.max.y - bounds.min.y, color, lineWidth, strokeOptions);\n    }\n    /**\n     * Draw a grid of horizontal and vertical lines with the given (CSS-) color.\n     *\n     * @method grid\n     * @param {XYCoords} center - The center of the grid.\n     * @param {number} width - The total width of the grid (width/2 each to the left and to the right).\n     * @param {number} height - The total height of the grid (height/2 each to the top and to the bottom).\n     * @param {number} sizeX - The horizontal grid size.\n     * @param {number} sizeY - The vertical grid size.\n     * @param {string} color - The CSS color to draw the grid with.\n     * @return {void}\n     * @instance\n     * @memberof drawutilssvg\n     */\n    grid(center, width, height, sizeX, sizeY, color) {\n        // console.log(\"grid\");\n        // const node: SVGElement = this.makeNode(\"pattern\");\n        // var patternId = \"pattern_id_\" + Math.floor(Math.random() * 65365);\n        // node.setAttribute(\"id\", patternId);\n        // node.setAttribute(\"viewBox\", `0,0,${sizeX},${sizeY}`);\n        // node.setAttribute(\"width\", `${sizeX}`);\n        // node.setAttribute(\"height\", `${sizeX}`);\n        // var pattern: SVGElement = this.makeNode(\"path\");\n        // const d: SVGPathParams = [];\n        // d.push(\"M\", sizeX / 2.0, 0);\n        // d.push(\"L\", sizeX / 2.0, sizeY);\n        // d.push(\"M\", 0, sizeY / 2.0);\n        // d.push(\"L\", sizeX, sizeY / 2.0);\n        // node.setAttribute(\"d\", d.join(\" \"));\n        // this.bufferedNodeDefs.append(pattern);\n        // const fillNode: SVGElement = this.makeNode(\"rect\");\n        // // For some strange reason SVG rotation transforms use degrees instead of radians\n        // // Note that the background does not scale with the zoom level (always covers full element)\n        // fillNode.setAttribute(\"x\", \"0\");\n        // fillNode.setAttribute(\"y\", \"0\");\n        // fillNode.setAttribute(\"width\", `${this.canvasSize.width}`);\n        // fillNode.setAttribute(\"height\", `${this.canvasSize.height}`);\n        // fillNode.setAttribute(\"fill\", `url(#${patternId})`);\n        // return this._bindFillDraw(fillNode, \"grid\", \"red\", 1);\n        const node = this.makeNode(\"path\");\n        const d = [];\n        var yMin = -Math.ceil((height * 0.5) / sizeY) * sizeY;\n        var yMax = height / 2;\n        for (var x = -Math.ceil((width * 0.5) / sizeX) * sizeX; x < width / 2; x += sizeX) {\n            d.push(\"M\", this._x(center.x + x), this._y(center.y + yMin));\n            d.push(\"L\", this._x(center.x + x), this._y(center.y + yMax));\n        }\n        var xMin = -Math.ceil((width * 0.5) / sizeX) * sizeX;\n        var xMax = width / 2;\n        for (var y = -Math.ceil((height * 0.5) / sizeY) * sizeY; y < height / 2; y += sizeY) {\n            d.push(\"M\", this._x(center.x + xMin), this._y(center.y + y));\n            d.push(\"L\", this._x(center.x + xMax), this._y(center.y + y));\n        }\n        node.setAttribute(\"d\", d.join(\" \"));\n        return this._bindFillDraw(node, \"grid\", color, 1);\n    }\n    /**\n     * Draw a raster of crosshairs in the given grid.<br>\n     *\n     * This works analogue to the grid() function\n     *\n     * @method raster\n     * @param {XYCoords} center - The center of the raster.\n     * @param {number} width - The total width of the raster (width/2 each to the left and to the right).\n     * @param {number} height - The total height of the raster (height/2 each to the top and to the bottom).\n     * @param {number} sizeX - The horizontal raster size.\n     * @param {number} sizeY - The vertical raster size.\n     * @param {string} color - The CSS color to draw the raster with.\n     * @return {void}\n     * @instance\n     * @memberof drawutilssvg\n     */\n    raster(center, width, height, sizeX, sizeY, color) {\n        const node = this.makeNode(\"path\");\n        const d = [];\n        for (var x = -Math.ceil((width * 0.5) / sizeX) * sizeX; x < width / 2; x += sizeX) {\n            for (var y = -Math.ceil((height * 0.5) / sizeY) * sizeY; y < height / 2; y += sizeY) {\n                // Draw a crosshair\n                d.push(\"M\", this._x(center.x + x) - 4, this._y(center.y + y));\n                d.push(\"L\", this._x(center.x + x) + 4, this._y(center.y + y));\n                d.push(\"M\", this._x(center.x + x), this._y(center.y + y) - 4);\n                d.push(\"L\", this._x(center.x + x), this._y(center.y + y) + 4);\n            }\n        }\n        node.setAttribute(\"d\", d.join(\" \"));\n        return this._bindFillDraw(node, \"raster\", color, 1);\n    }\n    /**\n     * Draw a diamond handle (square rotated by 45°) with the given CSS color.\n     *\n     * It is an inherent featur of the handle functions that the drawn elements are not scaled and not\n     * distorted. So even if the user zooms in or changes the aspect ratio, the handles will be drawn\n     * as even shaped diamonds.\n     *\n     * @method diamondHandle\n     * @param {XYCoords} center - The center of the diamond.\n     * @param {number} size - The x/y-size of the diamond.\n     * @param {string} color - The CSS color to draw the diamond with.\n     * @return {void}\n     * @instance\n     * @memberof drawutilssvg\n     */\n    diamondHandle(center, size, color) {\n        const node = this.makeNode(\"path\");\n        const d = [\n            \"M\",\n            this._x(center.x) - size / 2.0,\n            this._y(center.y),\n            \"L\",\n            this._x(center.x),\n            this._y(center.y) - size / 2.0,\n            \"L\",\n            this._x(center.x) + size / 2.0,\n            this._y(center.y),\n            \"L\",\n            this._x(center.x),\n            this._y(center.y) + size / 2.0,\n            \"Z\"\n        ];\n        node.setAttribute(\"d\", d.join(\" \"));\n        return this._bindFillDraw(node, \"diamondHandle\", color, 1);\n    }\n    /**\n     * Draw a square handle with the given CSS color.<br>\n     * <br>\n     * It is an inherent featur of the handle functions that the drawn elements are not scaled and not\n     * distorted. So even if the user zooms in or changes the aspect ratio, the handles will be drawn\n     * as even shaped squares.\n     *\n     * @method squareHandle\n     * @param {XYCoords} center - The center of the square.\n     * @param {XYCoords} size - The x/y-size of the square.\n     * @param {string} color - The CSS color to draw the square with.\n     * @return {void}\n     * @instance\n     * @memberof drawutilssvg\n     */\n    squareHandle(center, size, color) {\n        const node = this.makeNode(\"rect\");\n        node.setAttribute(\"x\", `${this._x(center.x) - size / 2.0}`);\n        node.setAttribute(\"y\", `${this._y(center.y) - size / 2.0}`);\n        node.setAttribute(\"width\", `${size}`);\n        node.setAttribute(\"height\", `${size}`);\n        return this._bindFillDraw(node, \"squareHandle\", color, 1);\n    }\n    /**\n     * Draw a circle handle with the given CSS color.<br>\n     * <br>\n     * It is an inherent featur of the handle functions that the drawn elements are not scaled and not\n     * distorted. So even if the user zooms in or changes the aspect ratio, the handles will be drawn\n     * as even shaped circles.\n     *\n     * @method circleHandle\n     * @param {XYCoords} center - The center of the circle.\n     * @param {number} radius - The radius of the circle.\n     * @param {string} color - The CSS color to draw the circle with.\n     * @return {void}\n     * @instance\n     * @memberof drawutilssvg\n     */\n    circleHandle(center, radius, color) {\n        radius = radius || 3;\n        const node = this.makeNode(\"circle\");\n        node.setAttribute(\"cx\", `${this._x(center.x)}`);\n        node.setAttribute(\"cy\", `${this._y(center.y)}`);\n        node.setAttribute(\"r\", `${radius}`);\n        return this._bindFillDraw(node, \"circleHandle\", color, 1);\n    }\n    /**\n     * Draw a crosshair with given radius and color at the given position.<br>\n     * <br>\n     * Note that the crosshair radius will not be affected by scaling.\n     *\n     * @method crosshair\n     * @param {XYCoords} center - The center of the crosshair.\n     * @param {number} radius - The radius of the crosshair.\n     * @param {string} color - The CSS color to draw the crosshair with.\n     * @param {number=0.5} lineWidth - (optional, default=0.5) The line width to use.\n     * @return {void}\n     * @instance\n     * @memberof drawutilssvg\n     */\n    crosshair(center, radius, color, lineWidth) {\n        const node = this.makeNode(\"path\");\n        const d = [\n            \"M\",\n            this._x(center.x) - radius,\n            this._y(center.y),\n            \"L\",\n            this._x(center.x) + radius,\n            this._y(center.y),\n            \"M\",\n            this._x(center.x),\n            this._y(center.y) - radius,\n            \"L\",\n            this._x(center.x),\n            this._y(center.y) + radius\n        ];\n        node.setAttribute(\"d\", d.join(\" \"));\n        return this._bindFillDraw(node, \"crosshair\", color, lineWidth || 0.5);\n    }\n    /**\n     * Draw a cross with diagonal axes with given radius, color and lineWidth at the given position.<br>\n     * <br>\n     * Note that the x's radius will not be affected by scaling.\n     *\n     * @method crosshair\n     * @param {XYCoords} center - The center of the crosshair.\n     * @param {number} radius - The radius of the crosshair.\n     * @param {string} color - The CSS color to draw the crosshair with.\n     * @param {number=1} lineWidth - (optional, default=1.0) The line width to use.\n     * @return {void}\n     * @instance\n     * @memberof drawutils\n     */\n    cross(center, radius, color, lineWidth) {\n        const node = this.makeNode(\"path\");\n        const d = [\n            \"M\",\n            this._x(center.x) - radius,\n            this._y(center.y) - radius,\n            \"L\",\n            this._x(center.x) + radius,\n            this._y(center.y) + radius,\n            \"M\",\n            this._x(center.x) - radius,\n            this._y(center.y) + radius,\n            \"L\",\n            this._x(center.x) + radius,\n            this._y(center.y) - radius\n        ];\n        node.setAttribute(\"d\", d.join(\" \"));\n        return this._bindFillDraw(node, \"cross\", color, lineWidth || 1.0);\n    }\n    /**\n     * Draw a polygon.\n     *\n     * @method polygon\n     * @param {Polygon} polygon - The polygon to draw.\n     * @param {string} color - The CSS color to draw the polygon with.\n     * @param {number=} lineWidth - (optional) The line width to use; default is 1.\n     * @param {StrokeOptions=} strokeOptions - (optional) Stroke settings to use.\n     * @return {void}\n     * @instance\n     * @memberof drawutilssvg\n     */\n    polygon(polygon, color, lineWidth, strokeOptions) {\n        return this.polyline(polygon.vertices, polygon.isOpen, color, lineWidth, strokeOptions);\n    }\n    /**\n     * Draw a polygon line (alternative function to the polygon).\n     *\n     * @method polyline\n     * @param {XYCoords[]} vertices - The polygon vertices to draw.\n     * @param {boolan}   isOpen   - If true the polyline will not be closed at its end.\n     * @param {string}   color    - The CSS color to draw the polygon with.\n     * @param {number=} lineWidth - (optional) The line width to use; default is 1.\n     * @param {StrokeOptions=} strokeOptions - (optional) Stroke settings to use.\n     *\n     * @return {void}\n     * @instance\n     * @memberof drawutilssvg\n     */\n    polyline(vertices, isOpen, color, lineWidth, strokeOptions) {\n        const node = this.makeNode(\"path\");\n        this.applyStrokeOpts(node, strokeOptions);\n        if (vertices.length == 0) {\n            return node;\n        }\n        // Draw curve\n        const d = [\"M\", this._x(vertices[0].x), this._y(vertices[0].y)];\n        var n = vertices.length;\n        for (var i = 1; i < n; i++) {\n            d.push(\"L\", this._x(vertices[i].x), this._y(vertices[i].y));\n        }\n        if (!isOpen)\n            d.push(\"Z\");\n        node.setAttribute(\"d\", d.join(\" \"));\n        return this._bindFillDraw(node, \"polygon\", color, lineWidth || 1);\n    }\n    /**\n     * Draw a text at the given relative position.\n     *\n     * @method text\n     * @param {string} text - The text to draw.\n     * @param {number} x - The x-position to draw the text at.\n     * @param {number} y - The y-position to draw the text at.\n     * @param {string=} options.color - The Color to use.\n     * @param {string=} options.fontFamily - The font family to use.\n     * @param {number=} options.fontSize - The font size (in pixels) to use.\n     * @param {FontStyle=} options.fontStyle - The font style to use.\n     * @param {FontWeight=} options.fontWeight - The font weight to use.\n     * @param {number=} options.lineHeight - The line height (in pixels) to use.\n     * @param {number=} options.rotation - The (optional) rotation in radians.\n     * @param {string=} options.textAlign - The text align to use. According to the specifiactions (https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/textAlign) valid values are `\"left\" || \"right\" || \"center\" || \"start\" || \"end\"`.\n     * @return {void}\n     * @instance\n     * @memberof drawutils\n     */\n    text(text, x, y, options) {\n        var _a, _b, _c;\n        options = options || {};\n        const color = options.color || \"black\";\n        const lineHeight = ((_b = (_a = options.lineHeight) !== null && _a !== void 0 ? _a : options.fontSize) !== null && _b !== void 0 ? _b : 0) * this.scale.x;\n        // https://www.w3.org/TR/SVG/text.html#TextAnchorProperty\n        //    start | middle | end\n        const textAlign = options.textAlign === \"left\" || options.textAlign === \"start\"\n            ? \"start\"\n            : options.textAlign === \"center\"\n                ? \"middle\"\n                : options.textAlign === \"right\" || options.textAlign === \"end\"\n                    ? \"end\"\n                    : \"start\";\n        const transformOrigin = `${this._x(x)}px ${this._y(y)}px`;\n        const translate = `translate(${this._x(x)} ${this._y(y) + lineHeight / 2})`;\n        // Safari has a transform-origin/rotation bug.\n        // It's essential to use rotate(r,x,y) here. \"rotate(r)\"\" with transform-origin(x,y) won't do the job.\n        // And rotate and translate cannot be used is combination on a text object.\n        // So wrap the text inside a <g>, translate the <g>, and rotate the text inside.\n        const rotate = options.rotation ? `rotate(${options.rotation * RAD_TO_DEG} 0 0)` : ``;\n        const node = this.makeNode(\"g\");\n        const curId = this.curId;\n        this.curId = curId + \"_text\";\n        const textNode = this.makeNode(\"text\");\n        node.appendChild(textNode);\n        textNode.setAttribute(\"font-family\", (_c = options.fontFamily) !== null && _c !== void 0 ? _c : \"\"); // May be undefined\n        textNode.setAttribute(\"font-size\", options.fontSize ? `${options.fontSize * this.scale.x}` : \"\");\n        textNode.setAttribute(\"font-style\", options.fontStyle ? `${options.fontStyle}` : \"\");\n        textNode.setAttribute(\"font-weight\", options.fontWeight ? `${options.fontWeight}` : \"\");\n        textNode.setAttribute(\"text-anchor\", textAlign);\n        textNode.setAttribute(\"transform-origin\", \"0 0\");\n        textNode.setAttribute(\"transform\", rotate);\n        node.setAttribute(\"transform-origin\", transformOrigin);\n        node.setAttribute(\"transform\", translate);\n        textNode.innerHTML = text;\n        // Restore old ID\n        this.curId = curId;\n        return this._bindFillDraw(node, \"text\", color, 1);\n    }\n    /**\n     * Draw a non-scaling text label at the given position.\n     *\n     * @method label\n     * @param {string} text - The text to draw.\n     * @param {number} x - The x-position to draw the text at.\n     * @param {number} y - The y-position to draw the text at.\n     * @param {number=} rotation - The (optional) rotation in radians.\n     * @param {string=\"black\"} color - The color to use (default is black).\n     * @return {void}\n     * @instance\n     * @memberof drawutilssvg\n     */\n    label(text, x, y, rotation, color) {\n        const node = this.makeNode(\"text\");\n        // For some strange reason SVG rotation transforms use degrees instead of radians\n        node.setAttribute(\"transform\", `translate(${x},${y}), rotate(${((rotation || 0) / Math.PI) * 180})`);\n        node.setAttribute(\"font-family\", \"Arial\");\n        node.setAttribute(\"font-size\", \"9pt\");\n        node.setAttribute(\"font-style\", \"normal\");\n        node.setAttribute(\"font-weight\", \"lighter\");\n        node.innerHTML = text;\n        return this._bindFillDraw(node, \"label\", color || \"black\", null);\n    }\n    /**\n     * Draw an SVG-like path given by the specified path data.\n     *\n     * @method path\n     * @param {SVGPathData} pathData - An array of path commands and params.\n     * @param {string=null} color - (optional) The color to draw this path with (default is null).\n     * @param {number=1} lineWidth - (optional) the line width to use (default is 1).\n     * @param {boolean=false} options.inplace - (optional) If set to true then path transforamtions (scale and translate) will be done in-place in the array. This can boost the performance.\n     * @param {number=} options.dashOffset - (optional) `See StrokeOptions`.\n     * @param {number=[]} options.dashArray - (optional) `See StrokeOptions`.\n     *\n     * @instance\n     * @memberof drawutils\n     * @return {R} An instance representing the drawn path.\n     */\n    path(pathData, color, lineWidth, options) {\n        const node = this.makeNode(\"path\");\n        this.applyStrokeOpts(node, options);\n        // Transform the path: in-place (fast) or copy (slower)\n        const d = options && options.inplace ? pathData : drawutilssvg.copyPathData(pathData);\n        drawutilssvg.transformPathData(d, this.offset, this.scale);\n        node.setAttribute(\"d\", d.join(\" \"));\n        return this._bindFillDraw(node, \"path\", color, lineWidth);\n    }\n    /**\n     * Due to gl compatibility there is a generic 'clear' function required\n     * to avoid accessing the context object itself directly.\n     *\n     * This function just fills the whole canvas with a single color.\n     *\n     * @param {string} color - The color to clear with.\n     * @return {void}\n     * @instance\n     * @memberof drawutilssvg\n     **/\n    clear(color) {\n        // If this isn't the primary handler then do not remove anything here.\n        // The primary handler will do that (no double work).\n        if (this.isSecondary) {\n            return;\n        }\n        // Add a covering rect with the given background color\n        this.curId = \"background\";\n        this.curClassName = null; // undefined;\n        const node = this.makeNode(\"rect\");\n        // For some strange reason SVG rotation transforms use degrees instead of radians\n        // Note that the background does not scale with the zoom level (always covers full element)\n        node.setAttribute(\"x\", \"0\");\n        node.setAttribute(\"y\", \"0\");\n        node.setAttribute(\"width\", `${this.canvasSize.width}`);\n        node.setAttribute(\"height\", `${this.canvasSize.height}`);\n        // Bind this special element into the document\n        this._bindFillDraw(node, this.curId, null, null);\n        node.setAttribute(\"fill\", typeof color === \"undefined\" ? \"none\" : color);\n        // Clear the current ID again\n        this.curId = null; // undefined;\n    }\n    /**\n     * A private helper function to clear all SVG nodes from the &gt;g> node.\n     *\n     * @private\n     */\n    removeAllChildNodes() {\n        while (this.bufferGNode.lastChild) {\n            this.bufferGNode.removeChild(this.bufferGNode.lastChild);\n        }\n        while (this.bufferedNodeDefs.lastChild) {\n            this.bufferedNodeDefs.removeChild(this.bufferedNodeDefs.lastChild);\n        }\n    }\n    /**\n     * Create a new and empty `SVGElement` &lt;svg&gt; in the svg-namespace.\n     *\n     * @name createSvg\n     * @static\n     * @memberof drawutilssvg\n     * @return SVGElement\n     */\n    static createSvg() {\n        return document.createElementNS(\"http://www.w3.org/2000/svg\", \"svg\");\n    }\n    /**\n     * Create a copy of the given path data. As path data only consists of strings and numbers,\n     * the copy will be shallow by definition.\n     *\n     * @name copyPathData\n     * @static\n     * @memberof drawutilssvg\n     */\n    static copyPathData(data) {\n        // To create a shallow copy we can just use the `slice` method.\n        return data.slice();\n    }\n    /**\n     * Transform the given path data (translate and scale. rotating is not intended here).\n     *\n     * @name transformPathData\n     * @static\n     * @memberof drawutilssvg\n     * @param {SVGPathParams} data - The data to transform.\n     * @param {XYCoords} offset - The translation offset (neutral is x=0, y=0).\n     * @param {XYCoords} scale - The scale factors (neutral is x=1, y=1).\n     */\n    static transformPathData(data, offset, scale) {\n        // Scale and translate {x,y}\n        const _stx = (index) => {\n            data[index] = offset.x + scale.x * Number(data[index]);\n        };\n        const _sty = (index) => {\n            data[index] = offset.y + scale.y * Number(data[index]);\n        };\n        // scale only {x,y}\n        const _sx = (index) => {\n            data[index] = scale.x * Number(data[index]);\n        };\n        const _sy = (index) => {\n            data[index] = scale.y * Number(data[index]);\n        };\n        var i = 0;\n        var lastPoint = { x: NaN, y: NaN };\n        // \"save last point\"\n        var _slp = (index) => {\n            lastPoint.x = Number(data[index]);\n            lastPoint.y = Number(data[index + 1]);\n        };\n        while (i < data.length) {\n            const cmd = data[i];\n            switch (cmd) {\n                case \"M\":\n                // MoveTo: M|m x y\n                case \"L\":\n                // LineTo L|l x y\n                case \"T\":\n                    // Shorthand/smooth quadratic Bézier curveto: T|t x y\n                    _stx(i + 1);\n                    _sty(i + 2);\n                    _slp(i + 1);\n                    i += 3;\n                    break;\n                case \"m\":\n                // MoveTo: M|m x y\n                case \"l\":\n                // LineTo L|l x y\n                case \"t\":\n                    // Shorthand/smooth quadratic Bézier curveto: T|t x y\n                    _sx(i + 1);\n                    _sy(i + 2);\n                    _slp(i + 1);\n                    i += 3;\n                    break;\n                case \"H\":\n                    // HorizontalLineTo: H|h x\n                    _stx(i + 1);\n                    lastPoint.x = Number(data[i + 1]);\n                    i += 2;\n                    break;\n                case \"h\":\n                    // HorizontalLineTo: H|h x\n                    _sx(i + 1);\n                    lastPoint.x = Number(data[i + 1]);\n                    i += 2;\n                    break;\n                case \"V\":\n                    // VerticalLineTo: V|v y\n                    _sty(i + 1);\n                    lastPoint.y = Number(data[i + 1]);\n                    i += 2;\n                    break;\n                case \"v\":\n                    // VerticalLineTo: V|v y\n                    _sy(i + 1);\n                    lastPoint.y = Number(data[i + 1]);\n                    i += 2;\n                    break;\n                case \"C\":\n                    // CurveTo: C|c x1 y1 x2 y2 x y\n                    _stx(i + 1);\n                    _sty(i + 2);\n                    _stx(i + 3);\n                    _sty(i + 4);\n                    _stx(i + 5);\n                    _sty(i + 6);\n                    _slp(i + 5);\n                    i += 7;\n                    break;\n                case \"c\":\n                    // CurveTo: C|c x1 y1 x2 y2 x y\n                    _sx(i + 1);\n                    _sy(i + 2);\n                    _sx(i + 3);\n                    _sy(i + 4);\n                    _sx(i + 5);\n                    _sy(i + 6);\n                    _slp(i + 5);\n                    i += 7;\n                    break;\n                case \"S\":\n                case \"Q\":\n                    // Shorthand-/SmoothCurveTo: S|s x2 y2 x y\n                    // QuadraticCurveTo: Q|q x1 y1 x y\n                    _stx(i + 1);\n                    _sty(i + 2);\n                    _stx(i + 3);\n                    _sty(i + 4);\n                    _slp(i + 3);\n                    i += 5;\n                    break;\n                case \"s\":\n                case \"q\":\n                    // Shorthand-/SmoothCurveTo: S|s x2 y2 x y\n                    // QuadraticCurveTo: Q|q x1 y1 x y\n                    _sx(i + 1);\n                    _sy(i + 2);\n                    _sx(i + 3);\n                    _sy(i + 4);\n                    _slp(i + 3);\n                    i += 5;\n                    break;\n                case \"A\":\n                    // EllipticalArcTo: A|a rx ry x-axis-rotation large-arc-flag sweep-flag x y\n                    // Uniform scale: just scale\n                    // NOTE: here is something TODO\n                    //  * if scalex!=scaleY this won't work\n                    //  * Arcs have to be converted to Bézier curves here in that case\n                    _sx(i + 1);\n                    _sy(i + 2);\n                    _stx(i + 6);\n                    _sty(i + 7);\n                    _slp(i + 6);\n                    // Update the arc flag when x _or_ y scale is negative\n                    if ((scale.x < 0 && scale.y >= 0) || (scale.x >= 0 && scale.y < 0)) {\n                        data[i + 5] = data[i + 5] ? 0 : 1;\n                    }\n                    i += 8;\n                    break;\n                case \"a\":\n                    // EllipticalArcTo: A|a rx ry x-axis-rotation large-arc-flag sweep-flag x y\n                    _sx(i + 1);\n                    _sy(i + 2);\n                    _sx(i + 6);\n                    _sy(i + 7);\n                    _slp(i + 6);\n                    i += 8;\n                    break;\n                case \"z\":\n                case \"Z\":\n                    // ClosePath: Z|z (no arguments)\n                    // lastPoint.x = firstPoint.x;\n                    // lastPoint.y = firstPoint.y;\n                    i++;\n                    break;\n                // Safepoint: continue reading token by token until something is recognized again\n                default:\n                    i++;\n            }\n        } // END while\n    } // END transformPathData\n    static nodeSupportsLineDash(nodeName) {\n        return [\"line\", \"path\", \"circle\", \"ellipse\", \"rectangle\", \"rect\"].includes(nodeName);\n    }\n    static nodeSupportsLineJoin(nodeName) {\n        return [\"line\", \"path\", \"circle\", \"ellipse\", \"rectangle\", \"rect\"].includes(nodeName);\n    }\n    static nodeSupportsLineCap(nodeName) {\n        return [\"line\", \"path\", \"circle\", \"ellipse\", \"rectangle\", \"rect\"].includes(nodeName);\n    }\n    /**\n     * Creates a basic <line> node with start and end coordinates. The created node will not\n     * be bound to any root node.\n     *\n     * @private\n     * @method makeLineNode\n     * @param {XYCoords} zA - The line's start position.\n     * @param {XYCoords} zB - The line's start position.\n     * @param {string} color - The CSS color to draw the point with.\n     * @param {number=1} lineWidth - (optional) The line width to use.\n     * @param {StrokeOptions=} strokeOptions - (optional) Additional stroke options to use.\n     * @param {string=} classNameOverride - (optional) If nothing is passed the default classname 'path' will be used.\n     * @return {SVGLineElement}\n     * @instance\n     * @memberof drawutilssvg\n     */\n    makeLineNode(zA, zB, color, lineWidth, strokeOptions, classNameOverride) {\n        const line = this.makeNode(\"line\");\n        line.setAttribute(\"x1\", `${this._x(zA.x)}`);\n        line.setAttribute(\"y1\", `${this._y(zA.y)}`);\n        line.setAttribute(\"x2\", `${this._x(zB.x)}`);\n        line.setAttribute(\"y2\", `${this._y(zB.y)}`);\n        this._configureNode(line, classNameOverride !== null && classNameOverride !== void 0 ? classNameOverride : \"line\", this.fillShapes, color, lineWidth || 1, strokeOptions);\n        return line;\n    }\n    /**\n     * Creates a basic <path> node with given path string data. The created node will not\n     * be bound to any root node.\n     *\n     * @private\n     * @method makePathNode\n     * @param {string} pathString - The path data (must be a valid path data string).\n     * @param {string} color - The CSS color to draw the point with.\n     * @param {number=1} lineWidth - (optional) The line width to use.\n     * @param {StrokeOptions=} strokeOptions - (optional) Additional stroke options to use.\n     * @param {string=} classNameOverride - (optional) If nothing is passed the default classname 'path' will be used.\n     * @return {SVGPathElement}\n     * @instance\n     * @memberof drawutilssvg\n     */\n    makePathNode(pathString, color, lineWidth, strokeOptions, classNameOverride) {\n        const path = this.makeNode(\"path\");\n        path.setAttribute(\"d\", pathString);\n        this._configureNode(path, classNameOverride !== null && classNameOverride !== void 0 ? classNameOverride : \"path\", this.fillShapes, color, lineWidth || 1, strokeOptions);\n        return path;\n    }\n    /**\n     * Creates a basic arrow head node (<path> node) at the end of the given line coordinates. The created node will not\n     * be bound to any root node.\n     *\n     * @private\n     * @method makeArrowHeadNode\n     * @param {string} pathString - The path data (must be a valid path data string).\n     * @param {string} color - The CSS color to draw the point with.\n     * @param {number=1} lineWidth - (optional) The line width to use.\n     * @param {number=8} headLength - (optional) The length of the arrow head; if none is specified then the head will be 8 absolute units long.\n     * @param {StrokeOptions=} strokeOptions - (optional) Additional stroke options to use.\n     * @param {XYCoords=} arrowHeadBasePositionBuffer - (optional) If not null, then this position will contain the arrow head's start point (after execution). Some sort of OUT variable.\n     * @return {SVGPathElement}\n     * @instance\n     * @memberof drawutilssvg\n     */\n    makeArrowHeadNode(zA, zB, color, lineWidth, headLength = 8, strokeOptions, arrowHeadBasePositionBuffer) {\n        var vertices = Vector.utils.buildArrowHead(zA, zB, headLength, this.scale.x, this.scale.y);\n        const d = [\"M\", this.offset.x + vertices[0].x, this.offset.y + vertices[0].y];\n        if (arrowHeadBasePositionBuffer) {\n            arrowHeadBasePositionBuffer.x = vertices[0].x / this.scale.x;\n            arrowHeadBasePositionBuffer.y = vertices[0].y / this.scale.y;\n        }\n        for (var i = 1; i <= vertices.length; i++) {\n            d.push(\"L\");\n            // Note: only use offset here (the vertices are already scaled)\n            d.push(this.offset.x + vertices[i % vertices.length].x);\n            d.push(this.offset.y + vertices[i % vertices.length].y);\n        }\n        const node = this.makePathNode(d.join(\" \"), color, lineWidth, strokeOptions, \"arrowhead\");\n        return node;\n    }\n    /**\n     * Creates a basic cubic Bézier path node (<path> node) with the given cubic Bézier data. The created node will not\n     * be bound to any root node.\n     *\n     * @private\n     * @method makeCubicBezierNode\n     * @param {XYCoords} startPoint - The start point of the cubic Bézier curve\n     * @param {XYCoords} endPoint   - The end point the cubic Bézier curve.\n     * @param {XYCoords} startControlPoint - The start control point the cubic Bézier curve.\n     * @param {XYCoords} endControlPoint   - The end control point the cubic Bézier curve.\n     * @param {string} color - The CSS color to draw the point with.\n     * @param {number=1} lineWidth - (optional) The line width to use.\n     * @param {StrokeOptions=} strokeOptions - (optional) Additional stroke options to use.\n     * @param {string=} classNameOverride - (optional) If nothing is passed the default classname 'path' will be used.\n     * @param {XYCoords=} arrowHeadBasePositionBuffer - (optional) If not null, then this position will contain the arrow head's start point (after execution). Some sort of OUT variable.\n     * @return {SVGPathElement}\n     * @instance\n     * @memberof drawutilssvg\n     */\n    makeCubicBezierNode(startPoint, endPoint, startControlPoint, endControlPoint, color, lineWidth, strokeOptions) {\n        if (startPoint instanceof CubicBezierCurve) {\n            return this.cubicBezier(startPoint.startPoint, startPoint.endPoint, startPoint.startControlPoint, startPoint.endControlPoint, color, lineWidth);\n        }\n        // Draw curve\n        const d = [\n            \"M\",\n            this._x(startPoint.x),\n            this._y(startPoint.y),\n            \"C\",\n            this._x(startControlPoint.x),\n            this._y(startControlPoint.y),\n            this._x(endControlPoint.x),\n            this._y(endControlPoint.y),\n            this._x(endPoint.x),\n            this._y(endPoint.y)\n        ];\n        const node = this.makePathNode(d.join(\" \"), color, lineWidth, strokeOptions, \"cubicBezier\");\n        return node;\n    }\n}\ndrawutilssvg.HEAD_XML = [\n    '<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\"?>',\n    '<!DOCTYPE svg PUBLIC \"-//W3C//DTD SVG 1.0//EN\" ',\n    '         \"http://www.w3.org/TR/2001/REC-SVG-20010904/DTD/svg10.dtd\">',\n    \"\"\n].join(\"\\n\");\n//# sourceMappingURL=drawutilssvg.js.map","/**\n * @author   Ikaros Kappler\n * @date     2018-04-22\n * @modified 2018-08-16 Added the curve() function to draw cubic bézier curves.\n * @modified 2018-10-23 Recognizing the offset param in the circle() function.\n * @modified 2018-11-27 Added the diamondHandle() function.\n * @modified 2018-11-28 Added the grid() function and the ellipse() function.\n * @modified 2018-11-30 Renamed the text() function to label() as it is not scaling.\n * @modified 2018-12-06 Added a test function for drawing arc in SVG style.\n * @modified 2018-12-09 Added the dot(Vertex,color) function (copied from Feigenbaum-plot-script).\n * @modified 2019-01-30 Added the arrow(Vertex,Vertex,color) function for drawing arrow heads.\n * @modified 2019-01-30 Added the image(Image,Vertex,Vertex) function for drawing images.\n * @modified 2019-04-27 Fixed a severe drawing bug in the arrow(...) function. Scaling arrows did not work properly.\n * @modified 2019-04-28 Added Math.round to the dot() drawing parameters to really draw a singlt dot.\n * @modified 2019-06-07 Fixed an issue in the cubicBezier() function. Paths were always closed.\n * @modified 2019-10-03 Added the beginDrawCycle hook.\n * @modified 2019-10-25 Polygons are no longer drawn with dashed lines (solid lines instead).\n * @modified 2019-11-18 Added the polyline function.\n * @modified 2019-11-22 Added a second workaround for th drawImage bug in Safari.\n * @modified 2019-12-07 Added the 'lineWidth' param to the line(...) function.\n * @modified 2019-12-07 Added the 'lineWidth' param to the cubicBezier(...) function.\n * @modified 2019-12-11 Added the 'color' param to the label(...) function.\n * @modified 2019-12-18 Added the quadraticBezier(...) function (for the sake of approximating Lissajous curves).\n * @modified 2019-12-20 Added the 'lineWidth' param to the polyline(...) function.\n * @modified 2020-01-09 Added the 'lineWidth' param to the ellipse(...) function.\n * @modified 2020-03-25 Ported this class from vanilla-JS to Typescript.\n * @modified 2020-05-05 Added the 'lineWidth' param to the circle(...) function.\n * @modified 2020-05-12 Drawing any handles (square, circle, diamond) with lineWidth 1 now; this was not reset before.\n * @modified 2020-06-22 Added a context.clearRect() call to the clear() function; clearing with alpha channel did not work as expected.\n * @modified 2020-09-07 Added the circleArc(...) function to draw sections of circles.\n * @modified 2020-10-06 Removed the .closePath() instruction from the circleArc function.\n * @modified 2020-10-15 Re-added the text() function.\n * @modified 2020-10-28 Added the path(Path2D) function.\n * @modified 2020-12-28 Added the `singleSegment` mode (test).\n * @modified 2021-01-05 Added the image-loaded/broken check.\n * @modified 2021-01-24 Added the `setCurrentId` function from the `DrawLib` interface.\n * @modified 2021-02-22 Added the `path` drawing function to draw SVG path data.\n * @modified 2021-03-31 Added the `endDrawCycle` function from `DrawLib`.\n * @modified 2021-05-31 Added the `setConfiguration` function from `DrawLib`.\n * @modified 2021-11-12 Adding more parameters tot the `text()` function: fontSize, textAlign, fontFamily, lineHeight.\n * @modified 2021-11-19 Added the `color` param to the `label(...)` function.\n * @modified 2022-02-03 Added the `lineWidth` param to the `crosshair` function.\n * @modified 2022-02-03 Added the `cross(...)` function.\n * @modified 2022-03-27 Added the `texturedPoly` function.\n * @modified 2022-06-01 Tweaked the `polyline` function; lineWidth now scales with scale.x.\n * @modified 2022-07-26 Adding `alpha` to the `image(...)` function.\n * @modified 2022-08-23 Fixed a type issue in the `polyline` function.\n * @modified 2022-08-23 Fixed a type issue in the `setConfiguration` function.\n * @modified 2022-08-23 Fixed a type issue in the `path` function.\n * @modified 2023-02-10 The methods `setCurrentClassName` and `setCurrentId` also accept `null` now.\n * @modified 2023-09-29 Removed unused method stub for texturedPoly helper function (cleanup).\n * @modified 2023-09-29 Downgrading all `Vertex` param type to the more generic `XYCoords` type in these render functions: line, arrow, texturedPoly, cubicBezier, cubicBezierPath, handle, handleLine, dot, point, circle, circleArc, ellipse, grid, raster.\n * @modified 2023-09-29 Added the `headLength` parameter to the 'DrawLib.arrow()` function.\n * @modified 2023-09-29 Added the `arrowHead(...)` function to the 'DrawLib.arrow()` interface.\n * @modified 2023-09-29 Added the `cubicBezierArrow(...)` function to the 'DrawLib.arrow()` interface.\n * @modified 2023-09-29 Added the `lineDashes` attribute.\n * @modified 2023-09-30 Adding `strokeOptions` param to these draw function: line, arrow, cubicBezierArrow, cubicBezier, cubicBezierPath, circle, circleArc, ellipse, square, rect, polygon, polyline.\n * @modified 2023-10-07 Adding the optional `arrowHeadBasePositionBuffer` param to the arrowHead(...) method.\n * @modified 2024-09-13 Remoed the scaling of `lineWidth` in the `polygon` and `polyline` methods. This makes no sense here and doesn't match up with the behavior of other line functions.\n * @modified 2026-01-04 Adding `lineJoin` attribute to the `StrokeOptions`.\n * @modified 2026-03-18 Adding `isOpen` parameter to `cubicBezierPath` draw method.\n * @modified 2026-04-04 Added the method `bounds`.\n * @modified 2026-04-04 Handling the `lineCap` attribute in the `StrokeOptions`.\n * @version  1.15.0\n **/\nimport { CubicBezierCurve } from \"./CubicBezierCurve\";\nimport { Vertex } from \"./Vertex\";\nimport { drawutilssvg } from \"./drawutilssvg\";\nimport { Vector } from \"./Vector\";\n// Todo: rename this class to Drawutils?\n/**\n * @classdesc A wrapper class for basic drawing operations.\n *\n * @requires CubicBzierCurvce\n * @requires Polygon\n * @requires Vertex\n * @requires XYCoords\n */\nexport class drawutils {\n    /**\n     * The constructor.\n     *\n     * @constructor\n     * @name drawutils\n     * @param {anvasRenderingContext2D} context - The drawing context.\n     * @param {boolean} fillShaped - Indicates if the constructed drawutils should fill all drawn shapes (if possible).\n     **/\n    constructor(context, fillShapes) {\n        this.ctx = context;\n        // this.lineDash = [];\n        this.offset = new Vertex(0, 0);\n        this.scale = new Vertex(1, 1);\n        this.fillShapes = fillShapes;\n    }\n    /**\n     * A private helper method to apply stroke options to the current\n     * context.\n     * @param {StrokeOptions=} strokeOptions -\n     */\n    applyStrokeOpts(strokeOptions) {\n        var _a, _b, _c, _d;\n        this.ctx.setLineDash(((_a = strokeOptions === null || strokeOptions === void 0 ? void 0 : strokeOptions.dashArray) !== null && _a !== void 0 ? _a : []).map((dashArrayElem) => {\n            // Note assume scale.x === scale.y\n            // Invariant scale makes funny stuff anyway.\n            return dashArrayElem * this.scale.x;\n        }));\n        this.ctx.lineDashOffset = ((_b = strokeOptions === null || strokeOptions === void 0 ? void 0 : strokeOptions.dashOffset) !== null && _b !== void 0 ? _b : 0) * this.scale.x;\n        this.ctx.lineJoin = (_c = strokeOptions === null || strokeOptions === void 0 ? void 0 : strokeOptions.lineJoin) !== null && _c !== void 0 ? _c : null;\n        this.ctx.lineCap = (_d = strokeOptions === null || strokeOptions === void 0 ? void 0 : strokeOptions.lineCap) !== null && _d !== void 0 ? _d : null;\n    }\n    // +---------------------------------------------------------------------------------\n    // | This is the final helper function for drawing and filling stuff. It is not\n    // | intended to be used from the outside.\n    // |\n    // | When in draw mode it draws the current shape.\n    // | When in fill mode it fills the current shape.\n    // |\n    // | This function is usually only called internally.\n    // |\n    // | @param color A stroke/fill color to use.\n    // +-------------------------------\n    // TODO: convert this to a STATIC function.\n    _fillOrDraw(color) {\n        if (this.fillShapes) {\n            this.ctx.fillStyle = color;\n            this.ctx.fill();\n        }\n        else {\n            this.ctx.strokeStyle = color;\n            this.ctx.stroke();\n        }\n    }\n    /**\n     * Called before each draw cycle.\n     * @param {UID=} uid - (optional) A UID identifying the currently drawn element(s).\n     **/\n    beginDrawCycle(renderTime) {\n        // NOOP\n    }\n    /**\n     * Called after each draw cycle.\n     *\n     * This is required for compatibility with other draw classes in the library (like drawgl).\n     *\n     * @name endDrawCycle\n     * @method\n     * @param {number} renderTime\n     * @instance\n     **/\n    endDrawCycle(renderTime) {\n        // NOOP\n    }\n    /**\n     * Set the current drawlib configuration.\n     *\n     * @name setConfiguration\n     * @method\n     * @param {DrawLibConfiguration} configuration - The new configuration settings to use for the next render methods.\n     */\n    setConfiguration(configuration) {\n        this.ctx.globalCompositeOperation = configuration.blendMode || \"source-over\";\n    }\n    // /**\n    //  * Set or clear the line-dash configuration. Pass `null` for un-dashed lines.\n    //  *\n    //  * See https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/stroke-dasharray\n    //  * and https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/setLineDash\n    //  * for how line dashes work.\n    //  *\n    //  * @method\n    //  * @param {Array<number> lineDashes - The line-dash array configuration.\n    //  * @returns {void}\n    //  */\n    // setLineDash(lineDash: Array<number>) {\n    //   this.lineDash = lineDash;\n    // }\n    /**\n     * This method shouled be called each time the currently drawn `Drawable` changes.\n     * It is used by some libraries for identifying elemente on re-renders.\n     *\n     * @name setCurrentId\n     * @method\n     * @param {UID|null} uid - A UID identifying the currently drawn element(s).\n     **/\n    setCurrentId(uid) {\n        // NOOP\n    }\n    /**\n     * This method shouled be called each time the currently drawn `Drawable` changes.\n     * Determine the class name for further usage here.\n     *\n     * @name setCurrentClassName\n     * @method\n     * @param {string|null} className - A class name for further custom use cases.\n     **/\n    setCurrentClassName(className) {\n        // NOOP\n    }\n    /**\n     * Draw the line between the given two points with the specified (CSS-) color.\n     *\n     * @method line\n     * @param {XYCoords} zA - The start point of the line.\n     * @param {XYCoords} zB - The end point of the line.\n     * @param {string} color - Any valid CSS color string.\n     * @param {number} lineWidth? - [optional] The line's width.\n     * @param {StrokeOptions=} strokeOptions - (optional) Stroke settings to use.\n     *\n     * @return {void}\n     * @instance\n     * @memberof drawutils\n     **/\n    line(zA, zB, color, lineWidth, strokeOptions) {\n        this.ctx.save();\n        this.ctx.beginPath();\n        this.applyStrokeOpts(strokeOptions);\n        this.ctx.moveTo(this.offset.x + zA.x * this.scale.x, this.offset.y + zA.y * this.scale.y);\n        this.ctx.lineTo(this.offset.x + zB.x * this.scale.x, this.offset.y + zB.y * this.scale.y);\n        this.ctx.strokeStyle = color;\n        this.ctx.lineWidth = lineWidth || 1;\n        this.ctx.stroke();\n        this.ctx.restore();\n    }\n    /**\n     * Draw a line and an arrow at the end (zB) of the given line with the specified (CSS-) color.\n     *\n     * @method arrow\n     * @param {XYCoords} zA - The start point of the arrow-line.\n     * @param {XYCoords} zB - The end point of the arrow-line.\n     * @param {string} color - Any valid CSS color string.\n     * @param {number=} lineWidth - (optional) The line width to use; default is 1.\n     * @param {headLength=8} headLength - (optional) The length of the arrow head (default is 8 units).\n     * @param {StrokeOptions=} strokeOptions - (optional) Stroke settings to use.\n     *\n     * @return {void}\n     * @instance\n     * @memberof drawutils\n     **/\n    arrow(zA, zB, color, lineWidth, headLength = 8, strokeOptions) {\n        const arrowHeadBasePosition = new Vertex(0, 0);\n        this.arrowHead(zA, zB, color, lineWidth, headLength, undefined, arrowHeadBasePosition); // Will NOT use dash configuration\n        this.line(zA, arrowHeadBasePosition, color, lineWidth, strokeOptions); // Will use dash configuration\n    }\n    /**\n     * Draw a cubic Bézier curve and and an arrow at the end (endControlPoint) of the given line width the specified (CSS-) color and arrow size.\n     *\n     * @method cubicBezierArrow\n     * @param {XYCoords} startPoint - The start point of the cubic Bézier curve\n     * @param {XYCoords} endPoint   - The end point the cubic Bézier curve.\n     * @param {XYCoords} startControlPoint - The start control point the cubic Bézier curve.\n     * @param {XYCoords} endControlPoint   - The end control point the cubic Bézier curve.\n     * @param {string} color - The CSS color to draw the curve with.\n     * @param {number} lineWidth - (optional) The line width to use.\n     * @param {headLength=8} headLength - (optional) The length of the arrow head (default is 8 units).\n     * @param {StrokeOptions=} strokeOptions - (optional) Stroke settings to use.\n     *\n     * @return {void}\n     * @instance\n     * @memberof DrawLib\n     */\n    cubicBezierArrow(startPoint, endPoint, startControlPoint, endControlPoint, color, lineWidth, headLength, strokeOptions) {\n        const arrowHeadBasePosition = new Vertex(0, 0);\n        // Will NOT use dash configuration\n        this.arrowHead(endControlPoint, endPoint, color, lineWidth, headLength, undefined, arrowHeadBasePosition);\n        const diff = arrowHeadBasePosition.difference(endPoint);\n        // Will use dash configuration\n        this.cubicBezier(startPoint, { x: endPoint.x - diff.x, y: endPoint.y - diff.y }, startControlPoint, { x: endControlPoint.x - diff.x, y: endControlPoint.y - diff.y }, color, lineWidth, strokeOptions);\n    }\n    /**\n     * Draw just an arrow head a the end of an imaginary line (zB) of the given line width the specified (CSS-) color and size.\n     *\n     * @method arrow\n     * @param {XYCoords} zA - The start point of the arrow-line.\n     * @param {XYCoords} zB - The end point of the arrow-line.\n     * @param {string} color - Any valid CSS color string.\n     * @param {number=1} lineWidth - (optional) The line width to use; default is 1.\n     * @param {number=8} headLength - (optional) The length of the arrow head (default is 8 pixels).\n     * @param {StrokeOptions=} strokeOptions - (optional) Stroke settings to use.\n     * @param {XYCoords=} arrowHeadBasePositionBuffer - (optional) If not null, then this position will contain the arrow head's start point (after execution). Some sort of OUT variable.\n     *\n     * @return {void}\n     * @instance\n     * @memberof DrawLib\n     **/\n    arrowHead(zA, zB, color, lineWidth, headLength = 8, strokeOptions, arrowHeadBasePositionBuffer) {\n        // var headLength: number = 8; // length of head in pixels\n        this.ctx.save();\n        this.ctx.beginPath();\n        this.applyStrokeOpts(strokeOptions);\n        var vertices = Vector.utils.buildArrowHead(zA, zB, headLength, this.scale.x, this.scale.y);\n        if (arrowHeadBasePositionBuffer) {\n            arrowHeadBasePositionBuffer.x = vertices[0].x / this.scale.x;\n            arrowHeadBasePositionBuffer.y = vertices[0].y / this.scale.y;\n        }\n        this.ctx.moveTo(this.offset.x + vertices[0].x, this.offset.y + vertices[0].y);\n        for (var i = 0; i < vertices.length; i++) {\n            this.ctx.lineTo(this.offset.x + vertices[i].x, this.offset.y + vertices[i].y);\n        }\n        this.ctx.lineTo(this.offset.x + vertices[0].x, this.offset.y + vertices[0].y);\n        this.ctx.lineWidth = lineWidth || 1;\n        this._fillOrDraw(color);\n        this.ctx.restore();\n    }\n    /**\n     * Draw an image at the given position with the given size.<br>\n     * <br>\n     * Note: SVG images may have resizing issues at the moment.Draw a line and an arrow at the end (zB) of the given line with the specified (CSS-) color.\n     *\n     * @method image\n     * @param {Image} image - The image object to draw.\n     * @param {XYCoords} position - The position to draw the the upper left corner at.\n     * @param {XYCoords} size - The x/y-size to draw the image with.\n     * @param {number=0.0} alpha - (optional, default=0.0) The transparency (1.0=opaque, 0.0=transparent).\n     * @return {void}\n     * @instance\n     * @memberof drawutils\n     **/\n    image(image, position, size, alpha = 1.0) {\n        if (!image.complete || !image.naturalWidth) {\n            // Avoid drawing un-unloaded or broken images\n            return;\n        }\n        this.ctx.save();\n        this.ctx.globalAlpha = alpha;\n        // Note that there is a Safari bug with the 3 or 5 params variant.\n        // Only the 9-param varaint works.\n        this.ctx.drawImage(image, 0, 0, image.naturalWidth - 1, // There is this horrible Safari bug (fixed in newer versions)\n        image.naturalHeight - 1, // To avoid errors substract 1 here.\n        this.offset.x + position.x * this.scale.x, this.offset.y + position.y * this.scale.y, size.x * this.scale.x, size.y * this.scale.y);\n        this.ctx.restore();\n    }\n    /**\n     * Draw an image at the given position with the given size.<br>\n     * <br>\n     * Note: SVG images may have resizing issues at the moment.Draw a line and an arrow at the end (zB) of the given line with the specified (CSS-) color.\n     *\n     * @method texturedPoly\n     * @param {Image} textureImage - The image object to draw.\n     * @param {Bounds} textureSize - The texture size to use; these are the original bounds to map the polygon vertices to.\n     * @param {Polygon} polygon - The polygon to use as clip path.\n     * @param {XYCoords} polygonPosition - The polygon's position (relative), measured at the bounding box's center.\n     * @param {number} rotation - The rotation to use for the polygon (and for the texture).\n     * @param {XYCoords={x:0,y:0}} rotationCenter - (optional) The rotational center; default is center of bounding box.\n     * @return {void}\n     * @instance\n     * @memberof drawutils\n     **/\n    texturedPoly(textureImage, textureSize, polygon, polygonPosition, rotation) {\n        var basePolygonBounds = polygon.getBounds();\n        // var targetCenterDifference = polygonPosition.clone().difference(basePolygonBounds.getCenter());\n        var targetCenterDifference = new Vertex(polygonPosition.x, polygonPosition.y).difference(basePolygonBounds.getCenter());\n        // var tileCenter = basePolygonBounds.getCenter().sub(targetCenterDifference);\n        // Get the position offset of the polygon\n        var targetTextureSize = new Vertex(textureSize.width, textureSize.height);\n        // var targetTextureOffset = new Vertex(-textureSize.width / 2, -textureSize.height / 2).sub(targetCenterDifference);\n        var targetTextureOffset = new Vertex(textureSize.min.x, textureSize.min.y).sub(polygonPosition);\n        this.ctx.save();\n        // this.ctx.translate(this.offset.x + rotationCenter.x * this.scale.x, this.offset.y + rotationCenter.y * this.scale.y);\n        this.ctx.translate(this.offset.x + polygonPosition.x * this.scale.x, this.offset.y + polygonPosition.y * this.scale.y);\n        drawutils.helpers.clipPoly(this.ctx, {\n            x: -polygonPosition.x * this.scale.x,\n            y: -polygonPosition.y * this.scale.y\n        }, this.scale, polygon.vertices);\n        this.ctx.scale(this.scale.x, this.scale.y);\n        this.ctx.rotate(rotation);\n        this.ctx.drawImage(textureImage, 0, 0, textureImage.naturalWidth - 1, // There is this horrible Safari bug (fixed in newer versions)\n        textureImage.naturalHeight - 1, // To avoid errors substract 1 here.\n        targetTextureOffset.x, // * this.scale.x,\n        targetTextureOffset.y, // * this.scale.y,\n        targetTextureSize.x, //  * this.scale.x,\n        targetTextureSize.y // * this.scale.y\n        );\n        this.ctx.restore();\n    }\n    /*\n    _texturedPoly(\n      textureImage: HTMLImageElement,\n      textureSize: Bounds,\n      polygon: Polygon,\n      polygonPosition: XYCoords,\n      rotation: number,\n      rotationCenter: XYCoords = { x: 0, y: 0 }\n    ): void {\n      var basePolygonBounds = polygon.getBounds();\n      var targetCenterDifference = polygonPosition.clone().difference(basePolygonBounds.getCenter());\n      var rotationalOffset = rotationCenter ? polygonPosition.difference(rotationCenter) : { x: 0, y: 0 };\n      // var rotationalOffset = { x: 0, y: 0 };\n      var tileCenter = basePolygonBounds.getCenter().sub(targetCenterDifference);\n  \n      // Get the position offset of the polygon\n      var targetTextureSize = new Vertex(textureSize.width, textureSize.height);\n      var targetTextureOffset = new Vertex(-textureSize.width / 2, -textureSize.height / 2).sub(targetCenterDifference);\n  \n      this.ctx.save();\n  \n      // this.ctx.translate(\n      //   this.offset.x + (tileCenter.x - rotationalOffset.x * 0 + targetTextureOffset.x * 0.0) * this.scale.x,\n      //   this.offset.y + (tileCenter.y - rotationalOffset.y * 0 + targetTextureOffset.y * 0.0) * this.scale.y\n      // );\n      this.ctx.translate(\n        this.offset.x + (tileCenter.x - rotationalOffset.x * 0 + targetTextureOffset.x * 0.0) * this.scale.x,\n        this.offset.y + (tileCenter.y - rotationalOffset.y * 0 + targetTextureOffset.y * 0.0) * this.scale.y\n      );\n      this.ctx.rotate(rotation);\n  \n      drawutils.helpers.clipPoly(\n        this.ctx,\n        {\n          x: (-targetCenterDifference.x * 1 - tileCenter.x - rotationalOffset.x) * this.scale.x,\n          y: (-targetCenterDifference.y * 1 - tileCenter.y - rotationalOffset.y) * this.scale.y\n        },\n        this.scale,\n        polygon.vertices\n      );\n      this.ctx.drawImage(\n        textureImage,\n        0,\n        0,\n        textureImage.naturalWidth - 1, // There is this horrible Safari bug (fixed in newer versions)\n        textureImage.naturalHeight - 1, // To avoid errors substract 1 here.\n        (-polygonPosition.x + targetTextureOffset.x * 1 - rotationalOffset.x * 1) * this.scale.x,\n        (-polygonPosition.y + targetTextureOffset.y * 1 - rotationalOffset.y * 1) * this.scale.y,\n        targetTextureSize.x * this.scale.x,\n        targetTextureSize.y * this.scale.y\n      );\n  \n      // const scaledTextureSize = new Bounds(\n      //   new Vertex(\n      //     -polygonPosition.x + targetTextureOffset.x - rotationalOffset.x,\n      //     -polygonPosition.y + targetTextureOffset.y - rotationalOffset.y\n      //   ).scaleXY(this.scale, rotationCenter),\n      //   new Vertex(\n      //     -polygonPosition.x + targetTextureOffset.x - rotationalOffset.x + targetTextureSize.x,\n      //     -polygonPosition.y + targetTextureOffset.y - rotationalOffset.y + targetTextureSize.y\n      //   ).scaleXY(this.scale, rotationCenter)\n      // );\n      // this.ctx.drawImage(\n      //   textureImage,\n      //   0,\n      //   0,\n      //   textureImage.naturalWidth - 1, // There is this horrible Safari bug (fixed in newer versions)\n      //   textureImage.naturalHeight - 1, // To avoid errors substract 1 here.\n      //   scaledTextureSize.min.x,\n      //   scaledTextureSize.min.y,\n      //   scaledTextureSize.width,\n      //   scaledTextureSize.height\n      // );\n  \n      this.ctx.restore();\n    }\n    */\n    /**\n     * Draw a rectangle.\n     *\n     * @param {XYCoords} position - The upper left corner of the rectangle.\n     * @param {number} width - The width of the rectangle.\n     * @param {number} height - The height of the rectangle.\n     * @param {string} color - The color to use.\n     * @param {number=1} lineWidth - (optional) The line with to use (default is 1).\n     * @param {StrokeOptions=} strokeOptions - (optional) Stroke settings to use.\n     *\n     * @return {void}\n     * @instance\n     * @memberof drawutils\n     **/\n    rect(position, width, height, color, lineWidth, strokeOptions) {\n        this.ctx.save();\n        this.ctx.beginPath();\n        this.applyStrokeOpts(strokeOptions);\n        this.ctx.moveTo(this.offset.x + position.x * this.scale.x, this.offset.y + position.y * this.scale.y);\n        this.ctx.lineTo(this.offset.x + (position.x + width) * this.scale.x, this.offset.y + position.y * this.scale.y);\n        this.ctx.lineTo(this.offset.x + (position.x + width) * this.scale.x, this.offset.y + (position.y + height) * this.scale.y);\n        this.ctx.lineTo(this.offset.x + position.x * this.scale.x, this.offset.y + (position.y + height) * this.scale.y);\n        // this.ctx.lineTo( this.offset.x+position.x*this.scale.x, this.offset.y+position.y*this.scale.y );\n        this.ctx.closePath();\n        this.ctx.lineWidth = lineWidth || 1;\n        this._fillOrDraw(color);\n        this.ctx.restore();\n    }\n    /**\n     * Draw a rectangle at the given bounds; and with the specified line width and (CSS-) color.<br>\n     *\n     * @method bounds\n     * @param {IBounds} bounds - The bounds rectangle to be drawn.\n     * @param {string} color - The CSS color to draw the rectangle with.\n     * @param {number=} lineWidth - (optional) The line width to use; default is 1.\n     * @param {StrokeOptions=} strokeOptions - (optional) Stroke settings to use.\n     *\n     * @return {R}\n     * @instance\n     * @memberof DrawLib\n     */\n    bounds(bounds, color, lineWidth, strokeOptions) {\n        this.rect(bounds.min, bounds.max.x - bounds.min.x, bounds.max.y - bounds.min.y, color, lineWidth, strokeOptions);\n    }\n    /**\n     * Draw the given (cubic) bézier curve.\n     *\n     * @method cubicBezier\n     * @param {XYCoords} startPoint - The start point of the cubic Bézier curve\n     * @param {XYCoords} endPoint   - The end point the cubic Bézier curve.\n     * @param {XYCoords} startControlPoint - The start control point the cubic Bézier curve.\n     * @param {XYCoords} endControlPoint   - The end control point the cubic Bézier curve.\n     * @param {string} color - The CSS color to draw the curve with.\n     * @param {number} lineWidth - (optional) The line width to use.\n     * @param {StrokeOptions=} strokeOptions - (optional) Stroke settings to use.\n     *\n     * @return {void}\n     * @instance\n     * @memberof drawutils\n     */\n    cubicBezier(startPoint, endPoint, startControlPoint, endControlPoint, color, lineWidth, strokeOptions) {\n        if (startPoint instanceof CubicBezierCurve) {\n            this.cubicBezier(startPoint.startPoint, startPoint.endPoint, startPoint.startControlPoint, startPoint.endControlPoint, color, lineWidth);\n            return;\n        }\n        // Draw curve\n        this.ctx.save();\n        this.ctx.beginPath();\n        this.applyStrokeOpts(strokeOptions);\n        this.ctx.moveTo(this.offset.x + startPoint.x * this.scale.x, this.offset.y + startPoint.y * this.scale.y);\n        this.ctx.bezierCurveTo(this.offset.x + startControlPoint.x * this.scale.x, this.offset.y + startControlPoint.y * this.scale.y, this.offset.x + endControlPoint.x * this.scale.x, this.offset.y + endControlPoint.y * this.scale.y, this.offset.x + endPoint.x * this.scale.x, this.offset.y + endPoint.y * this.scale.y);\n        //this.ctx.closePath();\n        this.ctx.lineWidth = lineWidth || 2;\n        this._fillOrDraw(color);\n        this.ctx.restore();\n    }\n    /**\n     * Draw the given (quadratic) bézier curve.\n     *\n     * @method quadraticBezier\n     * @param {XYCoords} startPoint   - The start point of the cubic Bézier curve\n     * @param {XYCoords} controlPoint - The control point the cubic Bézier curve.\n     * @param {XYCoords} endPoint     - The end control point the cubic Bézier curve.\n     * @param {string} color        - The CSS color to draw the curve with.\n     * @param {number|string} lineWidth - (optional) The line width to use.\n     * @param {StrokeOptions=} strokeOptions - (optional) Stroke settings to use.\n     *\n     * @return {void}\n     * @instance\n     * @memberof drawutils\n     */\n    quadraticBezier(startPoint, controlPoint, endPoint, color, lineWidth, strokeOptions) {\n        // Draw curve\n        this.ctx.save();\n        this.ctx.beginPath();\n        this.applyStrokeOpts(strokeOptions);\n        this.ctx.moveTo(this.offset.x + startPoint.x * this.scale.x, this.offset.y + startPoint.y * this.scale.y);\n        this.ctx.quadraticCurveTo(this.offset.x + controlPoint.x * this.scale.x, this.offset.y + controlPoint.y * this.scale.y, this.offset.x + endPoint.x * this.scale.x, this.offset.y + endPoint.y * this.scale.y);\n        this.ctx.lineWidth = lineWidth || 2;\n        this._fillOrDraw(color);\n        this.ctx.restore();\n    }\n    /**\n     * Draw the given (cubic) Bézier path.\n     *\n     * The given path must be an array with n*3+1 vertices, where n is the number of\n     * curves in the path:\n     * <pre> [ point1, point1_startControl, point2_endControl, point2, point2_startControl, point3_endControl, point3, ... pointN_endControl, pointN ]</pre>\n     *\n     * @method cubicBezierPath\n     * @param {XYCoords[]} path - The cubic bezier path as described above.\n     * @param {string} color - The CSS colot to draw the path with.\n     * @param {number=1} lineWidth - (optional) The line width to use.\n     * @param {StrokeOptions=} strokeOptions - (optional) Stroke settings to use.\n     *\n     * @return {void}\n     * @instance\n     * @memberof drawutils\n     */\n    cubicBezierPath(path, color, lineWidth, strokeOptions, isOpen) {\n        if (!path || path.length == 0) {\n            return;\n        }\n        // Draw curve\n        this.ctx.save();\n        this.ctx.beginPath();\n        var endPoint;\n        var startControlPoint;\n        var endControlPoint;\n        this.applyStrokeOpts(strokeOptions);\n        this.ctx.moveTo(this.offset.x + path[0].x * this.scale.x, this.offset.y + path[0].y * this.scale.y);\n        for (var i = 1; i < path.length; i += 3) {\n            startControlPoint = path[i];\n            endControlPoint = path[i + 1];\n            endPoint = path[i + 2];\n            this.ctx.bezierCurveTo(this.offset.x + startControlPoint.x * this.scale.x, this.offset.y + startControlPoint.y * this.scale.y, this.offset.x + endControlPoint.x * this.scale.x, this.offset.y + endControlPoint.y * this.scale.y, this.offset.x + endPoint.x * this.scale.x, this.offset.y + endPoint.y * this.scale.y);\n        }\n        if (!isOpen) {\n            this.ctx.closePath();\n        }\n        this.ctx.lineWidth = lineWidth || 1;\n        this._fillOrDraw(color);\n        this.ctx.restore();\n    }\n    /**\n     * Draw the given handle and handle point (used to draw interactive Bézier curves).\n     *\n     * The colors for this are fixed and cannot be specified.\n     *\n     * @method handle\n     * @param {XYCoords} startPoint - The start of the handle.\n     * @param {XYCoords} endPoint - The end point of the handle.\n     * @return {void}\n     * @instance\n     * @memberof drawutils\n     */\n    handle(startPoint, endPoint) {\n        // Draw handles\n        // (No need to save and restore here)\n        this.point(startPoint, \"rgb(0,32,192)\");\n        this.square(endPoint, 5, \"rgba(0,128,192,0.5)\");\n    }\n    /**\n     * Draw a handle line (with a light grey).\n     *\n     * @method handleLine\n     * @param {XYCoords} startPoint - The start point to draw the handle at.\n     * @param {XYCoords} endPoint - The end point to draw the handle at.\n     * @return {void}\n     * @instance\n     * @memberof drawutils\n     */\n    handleLine(startPoint, endPoint) {\n        // Draw handle lines\n        this.line(startPoint, endPoint, \"rgba(128,128,128, 0.5)\", undefined);\n    }\n    /**\n     * Draw a 1x1 dot with the specified (CSS-) color.\n     *\n     * @method dot\n     * @param {XYCoords} p - The position to draw the dot at.\n     * @param {string} color - The CSS color to draw the dot with.\n     * @return {void}\n     * @instance\n     * @memberof drawutils\n     */\n    dot(p, color) {\n        this.ctx.save();\n        this.ctx.beginPath();\n        this.ctx.setLineDash([]); // Clear line-dash settings\n        this.ctx.moveTo(Math.round(this.offset.x + this.scale.x * p.x), Math.round(this.offset.y + this.scale.y * p.y));\n        this.ctx.lineTo(Math.round(this.offset.x + this.scale.x * p.x + 1), Math.round(this.offset.y + this.scale.y * p.y + 1));\n        this.ctx.closePath();\n        this.ctx.lineWidth = 1;\n        this._fillOrDraw(color);\n        this.ctx.restore();\n    }\n    /**\n     * Draw the given point with the specified (CSS-) color and radius 3.\n     *\n     * @method point\n     * @param {XYCoords} p - The position to draw the point at.\n     * @param {string} color - The CSS color to draw the point with.\n     * @return {void}\n     * @instance\n     * @memberof drawutils\n     */\n    point(p, color) {\n        var radius = 3;\n        this.ctx.setLineDash([]); // Clear line-dash settings\n        this.ctx.beginPath();\n        this.ctx.arc(this.offset.x + p.x * this.scale.x, this.offset.y + p.y * this.scale.y, radius, 0, 2 * Math.PI, false);\n        this.ctx.closePath();\n        this.ctx.lineWidth = 1;\n        this._fillOrDraw(color);\n    }\n    /**\n     * Draw a circle with the specified (CSS-) color and radius.<br>\n     * <br>\n     * Note that if the x- and y- scales are different the result will be an ellipse rather than a circle.\n     *\n     * @method circle\n     * @param {XYCoords} center - The center of the circle.\n     * @param {number} radius - The radius of the circle.\n     * @param {string} color - The CSS color to draw the circle with.\n     * @param {number} lineWidth - The line width (optional, default=1).\n     * @param {StrokeOptions=} strokeOptions - (optional) Stroke settings to use.\n     *\n     * @return {void}\n     * @instance\n     * @memberof drawutils\n     */\n    circle(center, radius, color, lineWidth, strokeOptions) {\n        this.applyStrokeOpts(strokeOptions);\n        this.ctx.beginPath();\n        this.ctx.ellipse(this.offset.x + center.x * this.scale.x, this.offset.y + center.y * this.scale.y, radius * this.scale.x, radius * this.scale.y, 0.0, 0.0, Math.PI * 2);\n        this.ctx.closePath();\n        this.ctx.lineWidth = lineWidth || 1;\n        this._fillOrDraw(color);\n    }\n    /**\n     * Draw a circular arc (section of a circle) with the given CSS color.\n     *\n     * @method circleArc\n     * @param {XYCoords} center - The center of the circle.\n     * @param {number} radius - The radius of the circle.\n     * @param {number} startAngle - The angle to start at.\n     * @param {number} endAngle - The angle to end at.\n     * @param {string=#000000} color - The CSS color to draw the circle with.\n     * @param {number=1} lineWidth - The line width to use\n     * @param {boolean=false} options.asSegment - If `true` then no beginPath and no draw will be applied (as part of larger path).\n     * @param {number=} options.dashOffset - (optional) `See StrokeOptions`.\n     * @param {number=[]} options.dashArray - (optional) `See StrokeOptions`.\n     *\n     * @return {void}\n     * @instance\n     * @memberof drawutils\n     */\n    circleArc(center, radius, startAngle, endAngle, color, lineWidth, options) {\n        if (!options || !options.asSegment) {\n            this.ctx.beginPath();\n        }\n        this.applyStrokeOpts(options);\n        this.ctx.ellipse(this.offset.x + center.x * this.scale.x, this.offset.y + center.y * this.scale.y, radius * this.scale.x, radius * this.scale.y, 0.0, startAngle, endAngle, false);\n        if (!options || !options.asSegment) {\n            // this.ctx.closePath();\n            this.ctx.lineWidth = lineWidth || 1;\n            this._fillOrDraw(color || \"#000000\");\n        }\n    }\n    /**\n     * Draw an ellipse with the specified (CSS-) color and thw two radii.\n     *\n     * @method ellipse\n     * @param {XYCoords} center - The center of the ellipse.\n     * @param {number} radiusX - The radius of the ellipse.\n     * @param {number} radiusY - The radius of the ellipse.\n     * @param {string} color - The CSS color to draw the ellipse with.\n     * @param {number} lineWidth=1 - An optional line width param (default is 1).\n     * @param {number=} rotation - (optional, default=0) The rotation of the ellipse.\n     * @param {StrokeOptions=} strokeOptions - (optional) Stroke settings to use.\n     *\n     * @return {void}\n     * @instance\n     * @memberof drawutils\n     */\n    ellipse(center, radiusX, radiusY, color, lineWidth, rotation, strokeOptions) {\n        if (typeof rotation === \"undefined\") {\n            rotation = 0.0;\n        }\n        this.applyStrokeOpts(strokeOptions);\n        this.ctx.beginPath();\n        this.ctx.ellipse(this.offset.x + center.x * this.scale.x, this.offset.y + center.y * this.scale.y, radiusX * this.scale.x, radiusY * this.scale.y, rotation, 0.0, Math.PI * 2);\n        this.ctx.closePath();\n        this.ctx.lineWidth = lineWidth || 1;\n        this._fillOrDraw(color);\n    }\n    /**\n     * Draw square at the given center, size and with the specified (CSS-) color.<br>\n     * <br>\n     * Note that if the x-scale and the y-scale are different the result will be a rectangle rather than a square.\n     *\n     * @method square\n     * @param {XYCoords} center - The center of the square.\n     * @param {number} size - The size of the square.\n     * @param {string} color - The CSS color to draw the square with.\n     * @param {number} lineWidth - The line with to use (optional, default is 1).\n     * @param {StrokeOptions=} strokeOptions - (optional) Stroke settings to use.\n     *\n     * @return {void}\n     * @instance\n     * @memberof drawutils\n     */\n    square(center, size, color, lineWidth, strokeOptions) {\n        this.applyStrokeOpts(strokeOptions);\n        this.ctx.beginPath();\n        this.ctx.rect(this.offset.x + (center.x - size / 2.0) * this.scale.x, this.offset.y + (center.y - size / 2.0) * this.scale.y, size * this.scale.x, size * this.scale.y);\n        this.ctx.closePath();\n        this.ctx.lineWidth = lineWidth || 1;\n        this._fillOrDraw(color);\n    }\n    /**\n     * Draw a grid of horizontal and vertical lines with the given (CSS-) color.\n     *\n     * @method grid\n     * @param {XYCoords} center - The center of the grid.\n     * @param {number} width - The total width of the grid (width/2 each to the left and to the right).\n     * @param {number} height - The total height of the grid (height/2 each to the top and to the bottom).\n     * @param {number} sizeX - The horizontal grid size.\n     * @param {number} sizeY - The vertical grid size.\n     * @param {string} color - The CSS color to draw the grid with.\n     * @return {void}\n     * @instance\n     * @memberof drawutils\n     */\n    grid(center, width, height, sizeX, sizeY, color) {\n        this.ctx.setLineDash([]); // Clear line-dash settings\n        this.ctx.beginPath();\n        var yMin = -Math.ceil((height * 0.5) / sizeY) * sizeY;\n        var yMax = height / 2;\n        for (var x = -Math.ceil((width * 0.5) / sizeX) * sizeX; x < width / 2; x += sizeX) {\n            this.ctx.moveTo(this.offset.x + (center.x + x) * this.scale.x, this.offset.y + (center.y + yMin) * this.scale.y);\n            this.ctx.lineTo(this.offset.x + (center.x + x) * this.scale.x, this.offset.y + (center.y + yMax) * this.scale.y);\n        }\n        var xMin = -Math.ceil((width * 0.5) / sizeX) * sizeX; // -Math.ceil((height*0.5)/sizeY)*sizeY;\n        var xMax = width / 2; // height/2;\n        for (var y = -Math.ceil((height * 0.5) / sizeY) * sizeY; y < height / 2; y += sizeY) {\n            this.ctx.moveTo(this.offset.x + (center.x + xMin) * this.scale.x - 4, this.offset.y + (center.y + y) * this.scale.y);\n            this.ctx.lineTo(this.offset.x + (center.x + xMax) * this.scale.x + 4, this.offset.y + (center.y + y) * this.scale.y);\n        }\n        this.ctx.strokeStyle = color;\n        this.ctx.lineWidth = 1.0;\n        this.ctx.stroke();\n        this.ctx.closePath();\n    }\n    /**\n     * Draw a raster of crosshairs in the given grid.<br>\n     *\n     * This works analogue to the grid() function\n     *\n     * @method raster\n     * @param {XYCoords} center - The center of the raster.\n     * @param {number} width - The total width of the raster (width/2 each to the left and to the right).\n     * @param {number} height - The total height of the raster (height/2 each to the top and to the bottom).\n     * @param {number} sizeX - The horizontal raster size.\n     * @param {number} sizeY - The vertical raster size.\n     * @param {string} color - The CSS color to draw the raster with.\n     * @return {void}\n     * @instance\n     * @memberof drawutils\n     */\n    raster(center, width, height, sizeX, sizeY, color) {\n        this.ctx.save();\n        this.ctx.setLineDash([]); // Clear line-dash settings\n        this.ctx.beginPath();\n        for (var x = -Math.ceil((width * 0.5) / sizeX) * sizeX; x < width / 2; x += sizeX) {\n            for (var y = -Math.ceil((height * 0.5) / sizeY) * sizeY; y < height / 2; y += sizeY) {\n                // Draw a crosshair\n                this.ctx.moveTo(this.offset.x + (center.x + x) * this.scale.x - 4, this.offset.y + (center.y + y) * this.scale.y);\n                this.ctx.lineTo(this.offset.x + (center.x + x) * this.scale.x + 4, this.offset.y + (center.y + y) * this.scale.y);\n                this.ctx.moveTo(this.offset.x + (center.x + x) * this.scale.x, this.offset.y + (center.y + y) * this.scale.y - 4);\n                this.ctx.lineTo(this.offset.x + (center.x + x) * this.scale.x, this.offset.y + (center.y + y) * this.scale.y + 4);\n            }\n        }\n        this.ctx.strokeStyle = color;\n        this.ctx.lineWidth = 1.0;\n        this.ctx.stroke();\n        this.ctx.closePath();\n        this.ctx.restore();\n    }\n    /**\n     * Draw a diamond handle (square rotated by 45°) with the given CSS color.\n     *\n     * It is an inherent feature of the handle functions that the drawn elements are not scaled and not\n     * distorted. So even if the user zooms in or changes the aspect ratio, the handles will be drawn\n     * as even shaped diamonds.\n     *\n     * @method diamondHandle\n     * @param {XYCoords} center - The center of the diamond.\n     * @param {number} size - The x/y-size of the diamond.\n     * @param {string} color - The CSS color to draw the diamond with.\n     * @return {void}\n     * @instance\n     * @memberof drawutils\n     */\n    diamondHandle(center, size, color) {\n        this.ctx.setLineDash([]); // Clear line-dash settings\n        this.ctx.beginPath();\n        this.ctx.moveTo(this.offset.x + center.x * this.scale.x - size / 2.0, this.offset.y + center.y * this.scale.y);\n        this.ctx.lineTo(this.offset.x + center.x * this.scale.x, this.offset.y + center.y * this.scale.y - size / 2.0);\n        this.ctx.lineTo(this.offset.x + center.x * this.scale.x + size / 2.0, this.offset.y + center.y * this.scale.y);\n        this.ctx.lineTo(this.offset.x + center.x * this.scale.x, this.offset.y + center.y * this.scale.y + size / 2.0);\n        this.ctx.closePath();\n        this.ctx.lineWidth = 1;\n        this._fillOrDraw(color);\n    }\n    /**\n     * Draw a square handle with the given CSS color.<br>\n     * <br>\n     * It is an inherent feature of the handle functions that the drawn elements are not scaled and not\n     * distorted. So even if the user zooms in or changes the aspect ratio, the handles will be drawn\n     * as even shaped squares.\n     *\n     * @method squareHandle\n     * @param {XYCoords} center - The center of the square.\n     * @param {number} size - The x/y-size of the square.\n     * @param {string} color - The CSS color to draw the square with.\n     * @return {void}\n     * @instance\n     * @memberof drawutils\n     */\n    squareHandle(center, size, color) {\n        this.ctx.setLineDash([]); // Clear line-dash settings\n        this.ctx.beginPath();\n        this.ctx.rect(this.offset.x + center.x * this.scale.x - size / 2.0, this.offset.y + center.y * this.scale.y - size / 2.0, size, size);\n        this.ctx.closePath();\n        this.ctx.lineWidth = 1;\n        this._fillOrDraw(color);\n    }\n    /**\n     * Draw a circle handle with the given CSS color.<br>\n     * <br>\n     * It is an inherent feature of the handle functions that the drawn elements are not scaled and not\n     * distorted. So even if the user zooms in or changes the aspect ratio, the handles will be drawn\n     * as even shaped circles.\n     *\n     * @method circleHandle\n     * @param {XYCoords} center - The center of the circle.\n     * @param {number} radius - The radius of the circle.\n     * @param {string} color - The CSS color to draw the circle with.\n     * @return {void}\n     * @instance\n     * @memberof drawutils\n     */\n    circleHandle(center, radius, color) {\n        radius = radius || 3;\n        this.ctx.setLineDash([]); // Clear line-dash settings\n        this.ctx.beginPath();\n        this.ctx.arc(this.offset.x + center.x * this.scale.x, this.offset.y + center.y * this.scale.y, radius, 0, 2 * Math.PI, false);\n        this.ctx.closePath();\n        this.ctx.lineWidth = 1;\n        this._fillOrDraw(color);\n    }\n    /**\n     * Draw a crosshair with given radius and color at the given position.<br>\n     * <br>\n     * Note that the crosshair radius will not be affected by scaling.\n     *\n     * @method crosshair\n     * @param {XYCoords} center - The center of the crosshair.\n     * @param {number} radius - The radius of the crosshair.\n     * @param {string} color - The CSS color to draw the crosshair with.\n     * @param {number=0.5} lineWidth - (optional, default=0.5) The line width to use.\n     * @return {void}\n     * @instance\n     * @memberof drawutils\n     */\n    crosshair(center, radius, color, lineWidth) {\n        this.ctx.save();\n        this.ctx.setLineDash([]); // Clear line-dash settings\n        this.ctx.beginPath();\n        this.ctx.moveTo(this.offset.x + center.x * this.scale.x - radius, this.offset.y + center.y * this.scale.y);\n        this.ctx.lineTo(this.offset.x + center.x * this.scale.x + radius, this.offset.y + center.y * this.scale.y);\n        this.ctx.moveTo(this.offset.x + center.x * this.scale.x, this.offset.y + center.y * this.scale.y - radius);\n        this.ctx.lineTo(this.offset.x + center.x * this.scale.x, this.offset.y + center.y * this.scale.y + radius);\n        this.ctx.strokeStyle = color;\n        this.ctx.lineWidth = lineWidth || 0.5;\n        this.ctx.stroke();\n        this.ctx.closePath();\n        this.ctx.restore();\n    }\n    /**\n     * Draw a cross with diagonal axes with given radius, color and lineWidth at the given position.<br>\n     * <br>\n     * Note that the x's radius will not be affected by scaling.\n     *\n     * @method crosshair\n     * @param {XYCoords} center - The center of the crosshair.\n     * @param {number} radius - The radius of the crosshair.\n     * @param {string} color - The CSS color to draw the crosshair with.\n     * @param {number=1} lineWidth - (optional, default=1.0) The line width to use.\n     * @return {void}\n     * @instance\n     * @memberof drawutils\n     */\n    cross(center, radius, color, lineWidth) {\n        this.ctx.save();\n        this.ctx.setLineDash([]); // Clear line-dash settings\n        this.ctx.beginPath();\n        this.ctx.moveTo(this.offset.x + center.x * this.scale.x - radius, this.offset.y + center.y * this.scale.y - radius);\n        this.ctx.lineTo(this.offset.x + center.x * this.scale.x + radius, this.offset.y + center.y * this.scale.y + radius);\n        this.ctx.moveTo(this.offset.x + center.x * this.scale.x - radius, this.offset.y + center.y * this.scale.y + radius);\n        this.ctx.lineTo(this.offset.x + center.x * this.scale.x + radius, this.offset.y + center.y * this.scale.y - radius);\n        this.ctx.strokeStyle = color;\n        this.ctx.lineWidth = lineWidth || 1.0;\n        this.ctx.stroke();\n        this.ctx.closePath();\n        this.ctx.restore();\n    }\n    /**\n     * Draw a polygon.\n     *\n     * @method polygon\n     * @param {Polygon}  polygon - The polygon to draw.\n     * @param {string}   color - The CSS color to draw the polygon with.\n     * @param {string}   lineWidth - The line width to use.\n     * @param {StrokeOptions=} strokeOptions - (optional) Stroke settings to use.\n     *\n     * @return {void}\n     * @instance\n     * @memberof drawutils\n     */\n    polygon(polygon, color, lineWidth, strokeOptions) {\n        this.polyline(polygon.vertices, polygon.isOpen, color, lineWidth, strokeOptions);\n    }\n    /**\n     * Draw a polygon line (alternative function to the polygon).\n     *\n     * @method polyline\n     * @param {XYCoords[]} vertices - The polygon vertices to draw.\n     * @param {boolan}   isOpen     - If true the polyline will not be closed at its end.\n     * @param {string}   color      - The CSS color to draw the polygon with.\n     * @param {number}   lineWidth  - The line width (default is 1.0);\n     * @param {StrokeOptions=} strokeOptions - (optional) Stroke settings to use.\n     *\n     * @return {void}\n     * @instance\n     * @memberof drawutils\n     */\n    polyline(vertices, isOpen, color, lineWidth, strokeOptions) {\n        if (vertices.length <= 1) {\n            return;\n        }\n        this.ctx.save();\n        this.applyStrokeOpts(strokeOptions);\n        this.ctx.beginPath();\n        this.ctx.lineWidth = lineWidth || 1.0;\n        this.ctx.moveTo(this.offset.x + vertices[0].x * this.scale.x, this.offset.y + vertices[0].y * this.scale.y);\n        for (var i = 0; i < vertices.length; i++) {\n            this.ctx.lineTo(this.offset.x + vertices[i].x * this.scale.x, this.offset.y + vertices[i].y * this.scale.y);\n        }\n        if (!isOpen)\n            // && vertices.length > 2 )\n            this.ctx.closePath();\n        this._fillOrDraw(color);\n        this.ctx.closePath();\n        this.ctx.setLineDash([]);\n        this.ctx.restore();\n    }\n    /**\n     * Draw a text at the given relative position.\n     *\n     * @method text\n     * @param {string} text - The text to draw.\n     * @param {number} x - The x-position to draw the text at.\n     * @param {number} y - The y-position to draw the text at.\n     * @param {string=} options.color - The Color to use.\n     * @param {string=} options.fontFamily - The font family to use.\n     * @param {number=} options.fontSize - The font size (in pixels) to use.\n     * @param {FontStyle=} options.fontStyle - The font style to use.\n     * @param {FontWeight=} options.fontWeight - The font weight to use.\n     * @param {number=} options.lineHeight - The line height (in pixels) to use.\n     * @param {number=} options.rotation - The (optional) rotation in radians.\n     * @param {string=} options.textAlign - The text align to use. According to the specifiactions (https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/textAlign) valid values are `\"left\" || \"right\" || \"center\" || \"start\" || \"end\"`.\n     * @return {void}\n     * @instance\n     * @memberof drawutils\n     */\n    text(text, x, y, options) {\n        // See https://stackoverflow.com/a/23523697\n        var _a, _b, _c;\n        options = options || {};\n        this.ctx.save();\n        let relX = this.offset.x + x * this.scale.x;\n        let relY = this.offset.y + y * this.scale.y;\n        const color = options.color || \"black\";\n        if (options.fontSize || options.fontFamily) {\n            // Scaling of text only works in uniform mode\n            this.ctx.font =\n                (options.fontWeight ? options.fontWeight + \" \" : \"\") +\n                    (options.fontStyle ? options.fontStyle + \" \" : \"\") +\n                    (options.fontSize ? options.fontSize * this.scale.x + \"px \" : \" \") +\n                    (options.fontFamily\n                        ? options.fontFamily.indexOf(\" \") === -1\n                            ? options.fontFamily\n                            : `\"${options.fontFamily}\"`\n                        : \"Arial\");\n        }\n        if (options.textAlign) {\n            this.ctx.textAlign = options.textAlign;\n        }\n        const rotation = (_a = options.rotation) !== null && _a !== void 0 ? _a : 0.0;\n        const lineHeight = ((_c = (_b = options.lineHeight) !== null && _b !== void 0 ? _b : options.fontSize) !== null && _c !== void 0 ? _c : 0) * this.scale.x;\n        this.ctx.translate(relX, relY);\n        this.ctx.rotate(rotation);\n        if (this.fillShapes) {\n            this.ctx.fillStyle = color;\n            this.ctx.fillText(text, 0, lineHeight / 2);\n        }\n        else {\n            this.ctx.strokeStyle = color;\n            this.ctx.strokeText(text, 0, lineHeight / 2);\n        }\n        // this.ctx.translate(-relX, -relY);\n        // this.ctx.rotate(-rotation); // is this necessary before 'restore()'?\n        this.ctx.restore();\n    }\n    /**\n     * Draw a non-scaling text label at the given position.\n     *\n     * Note that these are absolute label positions, they are not affected by offset or scale.\n     *\n     * @method label\n     * @param {string} text - The text to draw.\n     * @param {number} x - The x-position to draw the text at.\n     * @param {number} y - The y-position to draw the text at.\n     * @param {number=} rotation - The (optional) rotation in radians (default=0).\n     * @param {string=} color - The color to render the text with (default=black).\n     * @return {void}\n     * @instance\n     * @memberof drawutils\n     */\n    label(text, x, y, rotation, color) {\n        this.ctx.save();\n        this.ctx.font = \"lighter 9pt Arial\";\n        this.ctx.translate(x, y);\n        if (typeof rotation !== \"undefined\")\n            this.ctx.rotate(rotation);\n        this.ctx.fillStyle = color || \"black\";\n        if (this.fillShapes) {\n            this.ctx.fillText(text, 0, 0);\n        }\n        else {\n            this.ctx.strokeText(text, 0, 0);\n        }\n        this.ctx.restore();\n    }\n    /**\n     * Draw an SVG-like path given by the specified path data.\n     *\n     *\n     * @method path\n     * @param {SVGPathData} pathData - An array of path commands and params.\n     * @param {string=null} color - (optional) The color to draw this path with (default is null).\n     * @param {number=1} lineWidth - (optional) the line width to use (default is 1).\n     * @param {boolean=false} options.inplace - (optional) If set to true then path transforamtions (scale and translate) will be done in-place in the array. This can boost the performance.\n     * @param {number=} options.dashOffset - (optional) `See StrokeOptions`.\n     * @param {number=[]} options.dashArray - (optional) `See StrokeOptions`.\n     * @instance\n     * @memberof drawutils\n     * @return {R} An instance representing the drawn path.\n     */\n    path(pathData, color, lineWidth, options) {\n        const d = options && options.inplace ? pathData : drawutilssvg.copyPathData(pathData);\n        drawutilssvg.transformPathData(d, this.offset, this.scale);\n        if (color) {\n            this.ctx.strokeStyle = color;\n        }\n        this.ctx.lineWidth = lineWidth || 1;\n        this.applyStrokeOpts(options);\n        if (this.fillShapes) {\n            if (color) {\n                this.ctx.fillStyle = color;\n            }\n            this.ctx.fill(new Path2D(d.join(\" \")));\n        }\n        else {\n            if (color) {\n                this.ctx.strokeStyle = color;\n            }\n            this.ctx.stroke(new Path2D(d.join(\" \")));\n        }\n    }\n    /**\n     * Due to gl compatibility there is a generic 'clear' function required\n     * to avoid accessing the context object itself directly.\n     *\n     * This function just fills the whole canvas with a single color.\n     *\n     * @param {string} color - The color to clear with.\n     **/\n    clear(color) {\n        this.ctx.clearRect(0, 0, this.ctx.canvas.width, this.ctx.canvas.height);\n        this.ctx.fillStyle = color;\n        this.ctx.fillRect(0, 0, this.ctx.canvas.width, this.ctx.canvas.height);\n    }\n}\ndrawutils.helpers = {\n    // A helper function to define the clipping path.\n    // This could be a candidate for the draw library.\n    clipPoly: (ctx, offset, scale, vertices) => {\n        ctx.beginPath();\n        // Set clip mask\n        ctx.moveTo(offset.x + vertices[0].x * scale.x, offset.y + vertices[0].y * scale.y);\n        for (var i = 1; i < vertices.length; i++) {\n            const vert = vertices[i];\n            ctx.lineTo(offset.x + vert.x * scale.x, offset.y + vert.y * scale.y);\n        }\n        ctx.closePath();\n        ctx.clip();\n    }\n};\n//# sourceMappingURL=draw.js.map","/**\n * @author   Ikaros Kappler\n * @date     2019-09-18\n * @modified 2019-10-03 Added the beginDrawCycle hook.\n * @modified 2020-03-25 Ported stub to Typescript.\n * @modified 2020-10-15 Re-added the text() function.\n * @modified 2021-01-24 Added the `setCurrentId` function.\n * @modified 2021-05-31 Added the `setConfiguration` function from `DrawLib`.\n * @modified 2022-02-03 Added the `lineWidth` param to the `crosshair` function.\n * @modified 2022-02-03 Added the `cross(...)` function.\n * @modified 2022-03-27 Added the `texturedPoly` function.\n * @modified 2022-07-26 Adding `alpha` to the `image(...)` function.\n * @modified 2023-02-10 The methods `setCurrentClassName` and `setCurrentId` also accept `null` now.\n * @modified 2023-09-29 Downgrading all `Vertex` param type to the more generic `XYCoords` type in these render functions: line, arrow, texturedPoly, cubicBezier, cubicBezierPath, handle, handleLine, dot, point, circle, circleArc, ellipse, grid, raster.\n * @modified 2023-09-29 Added the `headLength` parameter to the 'DrawLib.arrow()` function.\n * @modified 2023-09-29 Added the `arrowHead(...)` function to the 'DrawLib.arrow()` interface.\n * @modified 2023-09-29 Added the `cubicBezierArrow(...)` function to the 'DrawLib.arrow()` interface.\n * @modified 2023-09-29 Added the `lineDashes` attribute.\n * @modified 2026-03-18 Adding `isOpen` parameter to `cubicBezierPath` draw method.\n * @modified 2026-04-04 Added the method `bounds`.\n * @version  0.0.11\n **/\nimport { Vertex } from \"./Vertex\";\n/**\n * @classdesc A wrapper class for basic drawing operations. This is the WebGL\n * implementation whih sould work with shaders.\n *\n * @requires CubicBzierCurvce\n * @requires Polygon\n * @requires SVGSerializable\n * @requires Vertex\n * @requires XYCoords\n */\nexport class drawutilsgl {\n    /**\n     * The constructor.\n     *\n     * @constructor\n     * @name drawutils\n     * @param {WebGLRenderingContext|null} context - The drawing context.\n     * @param {boolean} fillShaped - Indicates if the constructed drawutils should fill all drawn shapes (if possible).\n     **/\n    constructor(context, fillShapes) {\n        this.gl = context;\n        this.offset = new Vertex(0, 0);\n        this.scale = new Vertex(1, 1);\n        this.fillShapes = fillShapes;\n        this._zindex = 0.0;\n        if (context == null || typeof context === \"undefined\")\n            return;\n        this.glutils = new GLU(context);\n        // PROBLEM: CANNOT USE MULTIPLE SHADER PROGRAM INSTANCES ON THE SAME CONTEXT!\n        // SOLUTION: USE SHARED SHADER PROGRAM!!! ... somehow ...\n        // This needs to be considered in the overlying component; both draw-instances need to\n        // share their gl context.\n        // That's what the copyInstace(boolean) method is good for.\n        this._vertShader = this.glutils.compileShader(drawutilsgl.vertCode, this.gl.VERTEX_SHADER);\n        this._fragShader = this.glutils.compileShader(drawutilsgl.fragCode, this.gl.FRAGMENT_SHADER);\n        this._program = this.glutils.makeProgram(this._vertShader, this._fragShader);\n        // Create an empty buffer object\n        this.vertex_buffer = this.gl.createBuffer();\n        // Bind appropriate array buffer to it\n        // this.gl.bindBuffer(this.gl.ARRAY_BUFFER, this.vertex_buffer);\n        console.log(\"gl initialized\");\n    }\n    _x2rel(x) {\n        return ((this.scale.x * x + this.offset.x) / this.gl.canvas.width) * 2.0 - 1.0;\n    }\n    _y2rel(y) {\n        return ((this.offset.y - this.scale.y * y) / this.gl.canvas.height) * 2.0 - 1.0;\n    }\n    /**\n     * Creates a 'shallow' (non deep) copy of this instance. This implies\n     * that under the hood the same gl context and gl program will be used.\n     */\n    copyInstance(fillShapes) {\n        var copy = new drawutilsgl(null, fillShapes);\n        copy.gl = this.gl;\n        copy.glutils = this.glutils;\n        copy._vertShader = this._vertShader;\n        copy._fragShader = this._fragShader;\n        copy._program = this._program;\n        return copy;\n    }\n    /**\n     * Called before each draw cycle.\n     * @param {number} renderTime\n     **/\n    beginDrawCycle(renderTime) {\n        this._zindex = 0.0;\n        this.renderTime = renderTime;\n    }\n    /**\n     * Called after each draw cycle.\n     *\n     * This is required for compatibility with other draw classes in the library (like drawgl).\n     *\n     * @name endDrawCycle\n     * @method\n     * @param {number} renderTime\n     * @instance\n     **/\n    endDrawCycle(renderTime) {\n        // NOOP\n    }\n    /**\n     * Set the current drawlib configuration.\n     *\n     * @name setConfiguration\n     * @method\n     * @param {DrawLibConfiguration} configuration - The new configuration settings to use for the next render methods.\n     */\n    setConfiguration(configuration) {\n        // TODO\n    }\n    // /**\n    //  * Set or clear the line-dash configuration. Pass `null` for un-dashed lines.\n    //  *\n    //  * See https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/stroke-dasharray\n    //  * and https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/setLineDash\n    //  * for how line dashes work.\n    //  *\n    //  * @method\n    //  * @param {Array<number> lineDashes - The line-dash array configuration.\n    //  * @returns {void}\n    //  */\n    // setLineDash(lineDashes: Array<number>) {\n    //   // TODO\n    // }\n    /**\n     * This method shouled be called each time the currently drawn `Drawable` changes.\n     * It is used by some libraries for identifying elemente on re-renders.\n     *\n     * @name setCurrentId\n     * @method\n     * @param {UID|null} uid - A UID identifying the currently drawn element(s).es.\n     **/\n    setCurrentId(uid) {\n        // NOOP\n        this.curId = uid;\n    }\n    /**\n     * This method shouled be called each time the currently drawn `Drawable` changes.\n     * Determine the class name for further usage here.\n     *\n     * @name setCurrentClassName\n     * @method\n     * @param {string|null} className - A class name for further custom use cases.\n     **/\n    setCurrentClassName(className) {\n        // NOOP\n    }\n    /**\n     * Draw the line between the given two points with the specified (CSS-) color.\n     *\n     * @method line\n     * @param {XYCoords} zA - The start point of the line.\n     * @param {XYCoords} zB - The end point of the line.\n     * @param {string} color - Any valid CSS color string.\n     * @return {void}\n     * @instance\n     * @memberof drawutils\n     **/\n    line(zA, zB, color) {\n        const vertices = new Float32Array(6);\n        vertices[0] = this._x2rel(zA.x);\n        vertices[1] = this._y2rel(zA.y);\n        vertices[2] = this._zindex;\n        vertices[3] = this._x2rel(zB.x);\n        vertices[4] = this._y2rel(zB.y);\n        vertices[5] = this._zindex;\n        this._zindex += 0.001;\n        // Create an empty buffer object\n        // const vertex_buffer = this.gl.createBuffer();\n        // Bind appropriate array buffer to it\n        this.gl.bindBuffer(this.gl.ARRAY_BUFFER, this.vertex_buffer);\n        // Pass the vertex data to the buffer\n        this.gl.bufferData(this.gl.ARRAY_BUFFER, vertices, this.gl.STATIC_DRAW);\n        // Bind vertex buffer object\n        // this.gl.bindBuffer(this.gl.ARRAY_BUFFER, vertex_buffer);\n        // Get the attribute location\n        var coord = this.gl.getAttribLocation(this._program, \"position\");\n        // Point an attribute to the currently bound VBO\n        this.gl.vertexAttribPointer(coord, 3, this.gl.FLOAT, false, 0, 0);\n        // Enable the attribute\n        this.gl.enableVertexAttribArray(coord);\n        // Unbind the buffer?\n        //this.gl.bindBuffer(this.gl.ARRAY_BUFFER, null);\n        // Set the view port\n        this.gl.viewport(0, 0, this.gl.canvas.width, this.gl.canvas.height);\n        let uRotationVector = this.gl.getUniformLocation(this._program, \"uRotationVector\");\n        // let radians = currentAngle * Math.PI / 180.0;\n        let currentRotation = [0.0, 1.0];\n        //currentRotation[0] = Math.sin(radians);\n        //currentRotation[1] = Math.cos(radians);\n        this.gl.uniform2fv(uRotationVector, currentRotation);\n        this.gl.lineWidth(5);\n        // Draw the line\n        this.gl.drawArrays(this.gl.LINES, 0, vertices.length / 3);\n        // POINTS, LINE_STRIP, LINE_LOOP, LINES,\n        // TRIANGLE_STRIP,TRIANGLE_FAN, TRIANGLES\n    }\n    /**\n     * Draw a line and an arrow at the end (zB) of the given line with the specified (CSS-) color.\n     *\n     * @method arrow\n     * @param {XYCoords} zA - The start point of the arrow-line.\n     * @param {XYCoords} zB - The end point of the arrow-line.\n     * @param {string} color - Any valid CSS color string.\n     * @param {headLength=8} headLength - (optional) The length of the arrow head (default is 8 units).\n     * @return {void}\n     * @instance\n     * @memberof drawutils\n     **/\n    arrow(zA, zB, color) {\n        // NOT YET IMPLEMENTED\n    }\n    /**\n     * Draw a cubic Bézier curve and and an arrow at the end (endControlPoint) of the given line width the specified (CSS-) color and arrow size.\n     *\n     * @method cubicBezierArrow\n     * @param {XYCoords} startPoint - The start point of the cubic Bézier curve\n     * @param {XYCoords} endPoint   - The end point the cubic Bézier curve.\n     * @param {XYCoords} startControlPoint - The start control point the cubic Bézier curve.\n     * @param {XYCoords} endControlPoint   - The end control point the cubic Bézier curve.\n     * @param {string} color - The CSS color to draw the curve with.\n     * @param {number} lineWidth - (optional) The line width to use.\n     * @param {headLength=8} headLength - (optional) The length of the arrow head (default is 8 units).\n     *\n     * @return {void}\n     * @instance\n     * @memberof DrawLib\n     */\n    cubicBezierArrow(startPoint, endPoint, startControlPoint, endControlPoint, color, lineWidth, headLength) {\n        // NOT YET IMPLEMENTED\n    }\n    /**\n     * Draw just an arrow head a the end of an imaginary line (zB) of the given line width the specified (CSS-) color and size.\n     *\n     * @method arrow\n     * @param {XYCoords} zA - The start point of the arrow-line.\n     * @param {XYCoords} zB - The end point of the arrow-line.\n     * @param {string} color - Any valid CSS color string.\n     * @param {number=1} lineWidth - (optional) The line width to use; default is 1.\n     * @param {number=8} headLength - (optional) The length of the arrow head (default is 8 pixels).\n     * @return {void}\n     * @instance\n     * @memberof DrawLib\n     **/\n    arrowHead(zA, zB, color, lineWidth, headLength) {\n        // NOT YET IMPLEMENTED\n    }\n    /**\n     * Draw an image at the given position with the given size.<br>\n     * <br>\n     * Note: SVG images may have resizing issues at the moment.Draw a line and an arrow at the end (zB) of the given line with the specified (CSS-) color.\n     *\n     * @method image\n     * @param {Image} image - The image object to draw.\n     * @param {XYCoords} position - The position to draw the the upper left corner at.\n     * @param {XYCoords} size - The x/y-size to draw the image with.\n     * @param {number=0.0} alpha - (optional, default=0.0) The transparency (0.0=opaque, 1.0=transparent).\n     * @return {void}\n     * @instance\n     * @memberof drawutils\n     **/\n    image(image, position, size, alpha = 0.0) {\n        // NOT YET IMPLEMENTED\n    }\n    /**\n     * Draw an image at the given position with the given size.<br>\n     * <br>\n     * Note: SVG images may have resizing issues at the moment.Draw a line and an arrow at the end (zB) of the given line with the specified (CSS-) color.\n     *\n     * @method texturedPoly\n     * @param {Image} textureImage - The image object to draw.\n     * @param {Bounds} textureSize - The texture size to use; these are the original bounds to map the polygon vertices to.\n     * @param {Polygon} polygon - The polygon to use as clip path.\n     * @param {XYCoords} polygonPosition - The polygon's position (relative), measured at the bounding box's center.\n     * @param {number} rotation - The rotation to use for the polygon (and for the texture).\n     * @return {void}\n     * @instance\n     * @memberof drawutilsgl\n     **/\n    texturedPoly(textureImage, textureSize, polygon, polygonPosition, rotation) {\n        // NOT YET IMPLEMENTED\n    }\n    // +---------------------------------------------------------------------------------\n    // | This is the final helper function for drawing and filling stuff. It is not\n    // | intended to be used from the outside.\n    // |\n    // | When in draw mode it draws the current shape.\n    // | When in fill mode it fills the current shape.\n    // |\n    // | This function is usually only called internally.\n    // |\n    // | @param color A stroke/fill color to use.\n    // +-------------------------------\n    _fillOrDraw(color) {\n        // NOT YET IMPLEMENTED\n    }\n    /**\n     * Draw the given (cubic) bézier curve.\n     *\n     * @method cubicBezier\n     * @param {XYCoords} startPoint - The start point of the cubic Bézier curve\n     * @param {XYCoords} endPoint   - The end point the cubic Bézier curve.\n     * @param {XYCoords} startControlPoint - The start control point the cubic Bézier curve.\n     * @param {VertXYCoordsex} endControlPoint   - The end control point the cubic Bézier curve.\n     * @param {string} color - The CSS color to draw the curve with.\n     * @param {number=} lineWidth - (optional) The line width to use; default is 1.\n     * @return {void}\n     * @instance\n     * @memberof drawutils\n     */\n    cubicBezier(startPoint, endPoint, startControlPoint, endControlPoint, color, lineWidth) {\n        // NOT YET IMPLEMENTED\n    }\n    /**\n     * Draw the given (cubic) Bézier path.\n     *\n     * The given path must be an array with n*3+1 vertices, where n is the number of\n     * curves in the path:\n     * <pre> [ point1, point1_startControl, point2_endControl, point2, point2_startControl, point3_endControl, point3, ... pointN_endControl, pointN ]</pre>\n     *\n     * @method cubicBezierPath\n     * @param {XYCoords[]} path - The cubic bezier path as described above.\n     * @param {string} color - The CSS colot to draw the path with.\n     * @param {number=} lineWidth - (optional) The line width to use; default is 1.\n     * @return {void}\n     * @instance\n     * @memberof drawutils\n     */\n    cubicBezierPath(path, color, lineWidth, strokeOptions, isOpen) {\n        // NOT YET IMPLEMENTED\n    }\n    /**\n     * Draw the given handle and handle point (used to draw interactive Bézier curves).\n     *\n     * The colors for this are fixed and cannot be specified.\n     *\n     * @method handle\n     * @param {XYCoords} startPoint - The start of the handle.\n     * @param {XYCoords} endPoint - The end point of the handle.\n     * @return {void}\n     * @instance\n     * @memberof drawutils\n     */\n    handle(startPoint, endPoint) {\n        // NOT YET IMPLEMENTED\n    }\n    /**\n     * Draw a handle line (with a light grey).\n     *\n     * @method handleLine\n     * @param {XYCoords} startPoint - The start point to draw the handle at.\n     * @param {XYCoords} endPoint - The end point to draw the handle at.\n     * @return {void}\n     * @instance\n     * @memberof drawutils\n     */\n    handleLine(startPoint, endPoint) {\n        // NOT YET IMPLEMENTED\n    }\n    /**\n     * Draw a 1x1 dot with the specified (CSS-) color.\n     *\n     * @method dot\n     * @param {XYCoords} p - The position to draw the dot at.\n     * @param {string} color - The CSS color to draw the dot with.\n     * @return {void}\n     * @instance\n     * @memberof drawutils\n     */\n    dot(p, color) {\n        // NOT YET IMPLEMENTED\n    }\n    /**\n     * Draw the given point with the specified (CSS-) color and radius 3.\n     *\n     * @method point\n     * @param {XYCoords} p - The position to draw the point at.\n     * @param {string} color - The CSS color to draw the point with.\n     * @return {void}\n     * @instance\n     * @memberof drawutils\n     */\n    point(p, color) {\n        // NOT YET IMPLEMENTED\n    }\n    /**\n     * Draw a circle with the specified (CSS-) color and radius.<br>\n     * <br>\n     * Note that if the x- and y- scales are different the result will be an ellipse rather than a circle.\n     *\n     * @method circle\n     * @param {XYCoords} center - The center of the circle.\n     * @param {number} radius - The radius of the circle.\n     * @param {string} color - The CSS color to draw the circle with.\n     * @param {number=} lineWidth - (optional) The line width to use; default is 1.\n     * @return {void}\n     * @instance\n     * @memberof drawutils\n     */\n    circle(center, radius, color, lineWidth) {\n        // NOT YET IMPLEMENTED\n    }\n    /**\n     * Draw a circular arc (section of a circle) with the given CSS color.\n     *\n     * @method circleArc\n     * @param {XYCoords} center - The center of the circle.\n     * @param {number} radius - The radius of the circle.\n     * @param {number} startAngle - The angle to start at.\n     * @param {number} endAngle - The angle to end at.\n     * @param {string} color - The CSS color to draw the circle with.\n     * @return {void}\n     * @instance\n     * @memberof drawutils\n     */\n    circleArc(center, radius, startAngle, endAngle, color, lineWidth) {\n        // NOT YET IMPLEMENTED\n    }\n    /**\n     * Draw an ellipse with the specified (CSS-) color and thw two radii.\n     *\n     * @method ellipse\n     * @param {XYCoords} center - The center of the ellipse.\n     * @param {number} radiusX - The radius of the ellipse.\n     * @param {number} radiusY - The radius of the ellipse.\n     * @param {string} color - The CSS color to draw the ellipse with.\n     * @param {number=} lineWidth - (optional) The line width to use; default is 1.\n     * @param {number=} rotation - (optional, default=0) The rotation of the ellipse.\n     * @return {void}\n     * @instance\n     * @memberof drawutils\n     */\n    ellipse(center, radiusX, radiusY, color, lineWidth, rotation) {\n        // NOT YET IMPLEMENTED\n    }\n    /**\n     * Draw square at the given center, size and with the specified (CSS-) color.<br>\n     * <br>\n     * Note that if the x-scale and the y-scale are different the result will be a rectangle rather than a square.\n     *\n     * @method square\n     * @param {XYCords} center - The center of the square.\n     * @param {number} size - The size of the square.\n     * @param {string} color - The CSS color to draw the square with.\n     * @param {number=} lineWidth - (optional) The line width to use; default is 1.\n     * @return {void}\n     * @instance\n     * @memberof drawutils\n     */\n    square(center, size, color, lineWidth) {\n        // NOT YET IMPLEMENTED\n    }\n    /**\n     * Draw a rectangle.\n     *\n     * @param {XYCoords} position - The upper left corner of the rectangle.\n     * @param {number} width - The width of the rectangle.\n     * @param {number} height - The height of the rectangle.\n     * @param {string} color - The color to use.\n     * @param {number=1} lineWidth - (optional) The line with to use (default is 1).\n     **/\n    rect(position, width, height, color, lineWidth, strokeOptions) {\n        // NOT YET IMPLEMENTED\n    }\n    /**\n     * Draw a rectangle at the given bounds; and with the specified line width and (CSS-) color.<br>\n     *\n     * @method bounds\n     * @param {IBounds} bounds - The bounds rectangle to be drawn.\n     * @param {string} color - The CSS color to draw the rectangle with.\n     * @param {number=} lineWidth - (optional) The line width to use; default is 1.\n     * @param {StrokeOptions=} strokeOptions - (optional) Stroke settings to use.\n     *\n     * @return {R}\n     * @instance\n     * @memberof DrawLib\n     */\n    bounds(bounds, color, lineWidth, strokeOptions) {\n        this.rect(bounds.min, bounds.max.x - bounds.min.x, bounds.max.y - bounds.min.y, color, lineWidth, strokeOptions);\n    }\n    /**\n     * Draw a grid of horizontal and vertical lines with the given (CSS-) color.\n     *\n     * @method grid\n     * @param {XYCoords} center - The center of the grid.\n     * @param {number} width - The total width of the grid (width/2 each to the left and to the right).\n     * @param {number} height - The total height of the grid (height/2 each to the top and to the bottom).\n     * @param {number} sizeX - The horizontal grid size.\n     * @param {number} sizeY - The vertical grid size.\n     * @param {string} color - The CSS color to draw the grid with.\n     * @return {void}\n     * @instance\n     * @memberof drawutils\n     */\n    grid(center, width, height, sizeX, sizeY, color) {\n        // NOT YET IMPLEMENTED\n    }\n    /**\n     * Draw a raster of crosshairs in the given grid.<br>\n     *\n     * This works analogue to the grid() function\n     *\n     * @method raster\n     * @param {XYCoords} center - The center of the raster.\n     * @param {number} width - The total width of the raster (width/2 each to the left and to the right).\n     * @param {number} height - The total height of the raster (height/2 each to the top and to the bottom).\n     * @param {number} sizeX - The horizontal raster size.\n     * @param {number} sizeY - The vertical raster size.\n     * @param {string} color - The CSS color to draw the raster with.\n     * @return {void}\n     * @instance\n     * @memberof drawutils\n     */\n    raster(center, width, height, sizeX, sizeY, color) {\n        // NOT YET IMPLEMENTED\n    }\n    /**\n     * Draw a diamond handle (square rotated by 45°) with the given CSS color.\n     *\n     * It is an inherent featur of the handle functions that the drawn elements are not scaled and not\n     * distorted. So even if the user zooms in or changes the aspect ratio, the handles will be drawn\n     * as even shaped diamonds.\n     *\n     * @method diamondHandle\n     * @param {XYCoords} center - The center of the diamond.\n     * @param {number} size - The x/y-size of the diamond.\n     * @param {string} color - The CSS color to draw the diamond with.\n     * @return {void}\n     * @instance\n     * @memberof drawutils\n     */\n    diamondHandle(center, size, color) {\n        // NOT YET IMPLEMENTED\n    }\n    /**\n     * Draw a square handle with the given CSS color.<br>\n     * <br>\n     * It is an inherent featur of the handle functions that the drawn elements are not scaled and not\n     * distorted. So even if the user zooms in or changes the aspect ratio, the handles will be drawn\n     * as even shaped squares.\n     *\n     * @method squareHandle\n     * @param {XYCoords} center - The center of the square.\n     * @param {number} size - The x/y-size of the square.\n     * @param {string} color - The CSS color to draw the square with.\n     * @return {void}\n     * @instance\n     * @memberof drawutils\n     */\n    squareHandle(center, size, color) {\n        // NOT YET IMPLEMENTED\n    }\n    /**\n     * Draw a circle handle with the given CSS color.<br>\n     * <br>\n     * It is an inherent featur of the handle functions that the drawn elements are not scaled and not\n     * distorted. So even if the user zooms in or changes the aspect ratio, the handles will be drawn\n     * as even shaped circles.\n     *\n     * @method circleHandle\n     * @param {XYCoords} center - The center of the circle.\n     * @param {number} radius - The radius of the circle.\n     * @param {string} color - The CSS color to draw the circle with.\n     * @return {void}\n     * @instance\n     * @memberof drawutils\n     */\n    circleHandle(center, size, color) {\n        // NOT YET IMPLEMENTED\n    }\n    /**\n     * Draw a crosshair with given radius and color at the given position.<br>\n     * <br>\n     * Note that the crosshair radius will not be affected by scaling.\n     *\n     * @method crosshair\n     * @param {XYCoords} center - The center of the crosshair.\n     * @param {number} radius - The radius of the crosshair.\n     * @param {string} color - The CSS color to draw the crosshair with.\n     * @param {number=0.5} lineWidth - (optional, default=0.5) The line width to use.\n     * @return {void}\n     * @instance\n     * @memberof drawutils\n     */\n    crosshair(center, radius, color, lineWidth) {\n        // NOT YET IMPLEMENTED\n    }\n    /**\n     * Draw a cross with diagonal axes with given radius, color and lineWidth at the given position.<br>\n     * <br>\n     * Note that the x's radius will not be affected by scaling.\n     *\n     * @method crosshair\n     * @param {XYCoords} center - The center of the crosshair.\n     * @param {number} radius - The radius of the crosshair.\n     * @param {string} color - The CSS color to draw the crosshair with.\n     * @param {number=1} lineWidth - (optional, default=1.0) The line width to use.\n     * @return {void}\n     * @instance\n     * @memberof drawutils\n     */\n    cross(center, radius, color, lineWidth) {\n        // NOT YET IMPLEMENTED\n    }\n    /**\n     * Draw a polygon.\n     *\n     * @method polygon\n     * @param {Polygon} polygon - The polygon to draw.\n     * @param {string} color - The CSS color to draw the polygon with.\n     * @return {void}\n     * @instance\n     * @memberof drawutils\n     */\n    polygon(polygon, color, lineWidth) {\n        const vertices = new Float32Array(polygon.vertices.length * 3);\n        for (var i = 0; i < polygon.vertices.length; i++) {\n            vertices[i * 3 + 0] = this._x2rel(polygon.vertices[i].x);\n            vertices[i * 3 + 1] = this._y2rel(polygon.vertices[i].y);\n            vertices[i * 3 + 2] = this._zindex;\n        }\n        this._zindex += 0.001;\n        //console.log( vertices );\n        // Create an empty buffer object\n        // const vertex_buffer = this.gl.createBuffer();\n        // Bind appropriate array buffer to it\n        this.gl.bindBuffer(this.gl.ARRAY_BUFFER, this.vertex_buffer);\n        // Pass the vertex data to the buffer\n        this.gl.bufferData(this.gl.ARRAY_BUFFER, vertices, this.gl.STATIC_DRAW);\n        // Bind vertex buffer object\n        // this.gl.bindBuffer(this.gl.ARRAY_BUFFER, vertex_buffer);\n        // Get the attribute location\n        var coord = this.gl.getAttribLocation(this._program, \"position\");\n        // Point an attribute to the currently bound VBO\n        this.gl.vertexAttribPointer(coord, 3, this.gl.FLOAT, false, 0, 0);\n        // Enable the attribute\n        this.gl.enableVertexAttribArray(coord);\n        // Unbind the buffer?\n        this.gl.bindBuffer(this.gl.ARRAY_BUFFER, null);\n        // Set the view port\n        this.gl.viewport(0, 0, this.gl.canvas.width, this.gl.canvas.height);\n        let uRotationVector = this.gl.getUniformLocation(this._program, \"uRotationVector\");\n        // let radians = currentAngle * Math.PI / 180.0;\n        let currentRotation = [0.0, 1.0];\n        //currentRotation[0] = Math.sin(radians);\n        //currentRotation[1] = Math.cos(radians);\n        this.gl.uniform2fv(uRotationVector, currentRotation);\n        // Draw the polygon\n        this.gl.drawArrays(this.gl.TRIANGLE_FAN, 0, vertices.length / 3);\n        // POINTS, LINE_STRIP, LINE_LOOP, LINES,\n        // TRIANGLE_STRIP,TRIANGLE_FAN, TRIANGLES\n    }\n    /**\n     * Draw a polygon line (alternative function to the polygon).\n     *\n     * @method polyline\n     * @param {XYCoords[]} vertices - The polygon vertices to draw.\n     * @param {boolan}   isOpen   - If true the polyline will not be closed at its end.\n     * @param {string}   color    - The CSS color to draw the polygon with.\n     * @param {number=}  lineWidth - (optional) The line width to use; default is 1.\n     * @return {void}\n     * @instance\n     * @memberof drawutils\n     */\n    polyline(vertices, isOpen, color, lineWidth) {\n        // NOT YET IMPLEMENTED\n    }\n    /**\n     * Draw a text at the given relative position.\n     *\n     * @method text\n     * @param {string} text - The text to draw.\n     * @param {number} x - The x-position to draw the text at.\n     * @param {number} y - The y-position to draw the text at.\n     * @param {string=} options.color - The Color to use.\n     * @param {string=} options.fontFamily - The font family to use.\n     * @param {number=} options.fontSize - The font size (in pixels) to use.\n     * @param {FontStyle=} options.fontStyle - The font style to use.\n     * @param {FontWeight=} options.fontWeight - The font weight to use.\n     * @param {number=} options.lineHeight - The line height (in pixels) to use.\n     * @param {number=} options.rotation - The (optional) rotation in radians.\n     * @param {string=} options.textAlign - The text align to use. According to the specifiactions (https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/textAlign) valid values are `\"left\" || \"right\" || \"center\" || \"start\" || \"end\"`.\n     * @return {void}\n     * @instance\n     * @memberof drawutils\n     */\n    text(text, x, y, options) {\n        // NOT YET IMPLEMENTED\n    }\n    /**\n     * Draw a non-scaling text label at the given position.\n     *\n     * @method label\n     * @param {string} text - The text to draw.\n     * @param {number} x - The x-position to draw the text at.\n     * @param {number} y - The y-position to draw the text at.\n     * @param {number=} rotation - The (aoptional) rotation in radians.\n     * @param {string=\"black\"} color - The color to use (default is black).\n     * @return {void}\n     * @instance\n     * @memberof drawutils\n     */\n    label(text, x, y, rotation, color) {\n        // NOT YET IMPLEMENTED\n    }\n    /**\n     * Draw an SVG-like path given by the specified path data.\n     *\n     * @method path\n     * @param {SVGPathData} pathData - An array of path commands and params.\n     * @param {string=null} color - (optional) The color to draw this path with (default is null).\n     * @param {number=1} lineWidth - (optional) the line width to use (default is 1).\n     * @param {boolean=false} options.inplace - (optional) If set to true then path transforamtions (scale and translate) will be done in-place in the array. This can boost the performance.\n     * @instance\n     * @memberof drawutils\n     * @return {R} An instance representing the drawn path.\n     */\n    path(pathData, color, lineWidth, options) {\n        // NOT YET IMPLEMENTED\n    }\n    /**\n     * Due to gl compatibility there is a generic 'clear' function required\n     * to avoid accessing the context object itself directly.\n     *\n     * This function just fills the whole canvas with a single color.\n     *\n     * @param {string} color - The color to clear with.\n     **/\n    clear(color) {\n        // NOT YET IMPLEMENTED\n        // if( typeof color == 'string' )\n        // color = Color.parse(color); // Color class does not yet exist in TS\n        // Clear the canvas\n        this.gl.clearColor(1.0, 1.0, 1.0, 1.0);\n        // Enable the depth test\n        this.gl.enable(this.gl.DEPTH_TEST);\n        // Clear the color and depth buffer\n        this.gl.clear(this.gl.COLOR_BUFFER_BIT | this.gl.DEPTH_BUFFER_BIT);\n    }\n}\n// Vertex shader source code\ndrawutilsgl.vertCode = `\n    precision mediump float;\n\n    attribute vec3 position;\n\n    uniform vec2 uRotationVector;\n\n    void main(void) {\n\tvec2 rotatedPosition = vec2(\n\t    position.x * uRotationVector.y +\n\t\tposition.y * uRotationVector.x,\n\t    position.y * uRotationVector.y -\n\t\tposition.x * uRotationVector.x\n\t);\n\n\tgl_Position = vec4(rotatedPosition, position.z, 1.0);\n    }`;\n// Fragment shader source code\ndrawutilsgl.fragCode = `\n    precision highp float;\n\n    void main(void) {\n\tgl_FragColor = vec4(0.0,0.75,1.0,1.0);\n    }`;\n/**\n * Some GL helper utils.\n **/\nclass GLU {\n    constructor(gl) {\n        this.gl = gl;\n    }\n    bufferData(verts) {\n        // Create an empty buffer object\n        var vbuffer = this.gl.createBuffer();\n        // Bind appropriate array buffer to it\n        this.gl.bindBuffer(this.gl.ARRAY_BUFFER, vbuffer);\n        // Pass the vertex data to the buffer\n        this.gl.bufferData(this.gl.ARRAY_BUFFER, verts, this.gl.STATIC_DRAW);\n        // Unbind the buffer\n        this.gl.bindBuffer(this.gl.ARRAY_BUFFER, null);\n        return vbuffer;\n    }\n    /*=================== Shaders ====================*/\n    compileShader(shaderCode, shaderType) {\n        // Create a vertex shader object\n        var shader = this.gl.createShader(shaderType);\n        // Attach vertex shader source code\n        this.gl.shaderSource(shader, shaderCode);\n        // Compile the vertex shader\n        this.gl.compileShader(shader);\n        const vertStatus = this.gl.getShaderParameter(shader, this.gl.COMPILE_STATUS);\n        if (!vertStatus) {\n            console.warn(\"Error in shader:\" + this.gl.getShaderInfoLog(shader));\n            this.gl.deleteShader(shader);\n            return null;\n        }\n        return shader;\n    }\n    makeProgram(vertShader, fragShader) {\n        // Create a shader program object to store\n        // the combined shader program\n        var program = this.gl.createProgram();\n        // Attach a vertex shader\n        this.gl.attachShader(program, vertShader);\n        // Attach a fragment shader\n        this.gl.attachShader(program, fragShader);\n        // Link both the programs\n        this.gl.linkProgram(program);\n        // Use the combined shader program object\n        this.gl.useProgram(program);\n        /*======= Do some cleanup ======*/\n        this.gl.detachShader(program, vertShader);\n        this.gl.detachShader(program, fragShader);\n        this.gl.deleteShader(vertShader);\n        this.gl.deleteShader(fragShader);\n        return program;\n    }\n}\n//# sourceMappingURL=drawgl.js.map","/**\n * @author   Ikaros Kappler\n * @date     2018-11-28\n * @modified 2018-12-09 Added the utils: baseLog(Number,Number) and mapRasterScale(Number,Number).\n * @version  1.0.1\n *\n * @file Grid\n * @fileoverview Note that the PlotBoilerplate already has a Grid instance member. The Grid is not meant\n *               to be added to the canvas as a drawable as it encapsulates more an abstract concept of the canvas\n *               rather than a drawable object.\n * @public\n **/\n/**\n * @classdesc A grid class with vertical and horizontal lines (or a raster).\n *\n * Note that the PlotBoilerplate already has a Grid instance member. The Grid is not meant\n * to be added to the canvas as a drawable as it encapsulates more an abstract concept of the canvas\n * rather than a drawable object.\n *\n * @requires Vertex\n */\nexport class Grid {\n    /**\n     * The constructor.\n     *\n     * @constructor\n     * @name Grid\n     * @param {Vertex} center - The offset of the grid (default is [0,0]).\n     * @param {Vertex} size   - The x- and y-size of the grid.\n     **/\n    constructor(center, size) {\n        this.center = center;\n        this.size = size;\n    }\n    ;\n}\n/**\n * @memberof Grid\n **/\nGrid.utils = {\n    /**\n     * Calculate the logarithm of the given number (num) to a given base.<br>\n     * <br>\n     * This function returns the number l with<br>\n     *  <pre>num == Math.pow(base,l)</pre>\n     *\n     * @member baseLog\n     * @function\n     * @memberof Grid\n     * @inner\n     * @param {number} base - The base to calculate the logarithm to.\n     * @param {number} num  - The number to calculate the logarithm for.\n     * @return {number} <pre>log(base)/log(num)</pre>\n     **/\n    baseLog: (base, num) => { return Math.log(base) / Math.log(num); },\n    /**\n     * Calculate the raster scale for a given logarithmic mapping.<br>\n     * <br>\n     * Example (with adjustFactor=2):<br>\n     * <pre>\n     * If scale is 4.33, then the mapping is 1/2 (because 2^2 <= 4.33 <= 2^3)<br>\n     * If scale is 0.33, then the mapping is 2 because (2^(1/2) >= 0.33 >= 2^(1/4)\n     * </pre>\n     *\n     * @member mapRasterScale\n     * @function\n     * @memberof Grid\n     * @inner\n     * @param {number} adjustFactor The base for the logarithmic raster scaling when zoomed.\n     * @param {number} scale        The currently used scale factor.\n     * @return {number}\n     **/\n    mapRasterScale: (adjustFactor, scale) => {\n        var gf = 1.0;\n        if (scale >= 1) {\n            gf = Math.abs(Math.floor(1 / Grid.utils.baseLog(adjustFactor, scale)));\n            gf = 1 / Math.pow(adjustFactor, gf);\n        }\n        else {\n            gf = Math.abs(Math.floor(Grid.utils.baseLog(1 / adjustFactor, 1 / (scale + 1))));\n        }\n        return gf;\n    }\n};\n//# sourceMappingURL=Grid.js.map","/**\n * @author   Ikaros Kappler\n * @date     2018-11-11 (Alaaf)\n * @modified 2020-03-28 Ported this class from vanilla-JS to Typescript.\n * @modified 2020-07-28 Changed the `delete` key code from 8 to 46.\n * @modified 2020-10-04 Changed `window` to `globalThis`.\n * @modified 2020-10-04 Added extended JSDoc.\n * @modified 2022-02-02 Added the `destroy` method.\n * @version  1.1.0\n *\n * @file KeyHandler\n * @public\n **/\n/**\n * @classdesc A generic key handler.\n *\n * Example\n * =======\n * @example\n *      // Javascript\n *\tnew KeyHandler( { trackAll : true } )\n *\t    .down('enter',function() { console.log('ENTER was hit.'); } )\n *\t    .press('enter',function() { console.log('ENTER was pressed.'); } )\n *\t    .up('enter',function() { console.log('ENTER was released.'); } )\n *\n *          .down('e',function() { console.log('e was hit. shift is pressed?',keyHandler.isDown('shift')); } )\n *\n *\t    .up('windows',function() { console.log('windows was released.'); } )\n *\t;\n */\nexport class KeyHandler {\n    /**\n     * The constructor.\n     *\n     * @constructor\n     * @instance\n     * @memberof KeyHandler\n     * @param {HTMLElement} options.element (optional) The HTML element to listen on; if null then 'window' will be used.\n     * @param {boolean} options.trackAll (optional) Set to true if you want to keep track of _all_ keys (keyStatus).\n     **/\n    constructor(options) {\n        this.downListeners = [];\n        this.pressListeners = [];\n        this.upListeners = [];\n        this.keyStates = {};\n        options = options || {};\n        this.element = options.element ? options.element : globalThis;\n        this.downListeners = [];\n        this.pressListeners = [];\n        this.upListeners = [];\n        this.keyStates = [];\n        // This could be made configurable in a later version. It allows to\n        // keep track of the key status no matter if there are any listeners\n        // on the key or not.\n        this.trackAllKeys = options.trackAll || false;\n        // Install the listeners\n        this.installListeners();\n    }\n    /**\n     * A helper function to fire key events from this KeyHandler.\n     *\n     * @param {KeyboardEvent} event - The key event to fire.\n     * @param {Array<XKeyListener>} listener - The listeners to fire to.\n     */\n    fireEvent(event, listeners) {\n        let hasListener = false;\n        for (var i in listeners) {\n            var lis = listeners[i];\n            if (lis.keyCode != event.keyCode)\n                continue;\n            lis.listener(event);\n            hasListener = true;\n        }\n        return hasListener;\n    }\n    /**\n     * Internal function to fire a new keydown event to all listeners.\n     * You should not call this function on your own unless you know what you do.\n     *\n     * @name fireDownEvent\n     * @memberof KeyHandler\n     * @instance\n     * @private\n     * @param {KeyboardEvent} e\n     * @param {KeyHandler} handler\n     * @return {void}\n     */\n    fireDownEvent(e, handler) {\n        if (handler.fireEvent(e, handler.downListeners) || handler.trackAllKeys) {\n            // Down event has listeners. Update key state.\n            handler.keyStates[e.keyCode] = \"down\";\n        }\n    }\n    /**\n     * Internal function to fire a new keypress event to all listeners.\n     * You should not call this function on your own unless you know what you do.\n     *\n     * @name firePressEvent\n     * @memberof KeyHandler\n     * @instance\n     * @private\n     * @param {KeyboardEvent} e\n     * @param {KeyHandler} handler\n     * @return void\n     */\n    firePressEvent(e, handler) {\n        handler.fireEvent(e, handler.pressListeners);\n    }\n    /**\n     * Internal function to fire a new keyup event to all listeners.\n     * You should not call this function on your own unless you know what you do.\n     *\n     * @name fireUpEvent\n     * @memberof KeyHandler\n     * @instance\n     * @private\n     * @param {KeyboardEvent} e\n     * @param {KeyHandler} handler\n     * @return {void}\n     */\n    fireUpEvent(e, handler) {\n        if (handler.fireEvent(e, handler.upListeners) || handler.trackAllKeys) {\n            // Up event has listeners. Clear key state.\n            delete handler.keyStates[e.keyCode];\n        }\n    }\n    /**\n     * Resolve the key/name code.\n     */\n    static key2code(key) {\n        if (typeof key == \"number\")\n            return key;\n        if (typeof key != \"string\")\n            throw \"Unknown key name or key type (should be a string or integer): \" + key;\n        if (KeyHandler.KEY_CODES[key])\n            return KeyHandler.KEY_CODES[key];\n        throw \"Unknown key (cannot resolve key code): \" + key;\n    }\n    /**\n     * Install the required listeners into the initially passed element.\n     *\n     * By default the listeners are installed into the root element specified on\n     * construction (or 'window').\n     */\n    installListeners() {\n        var _self = this;\n        this.element.addEventListener(\"keydown\", (this._keyDownListener = (e) => {\n            _self.fireDownEvent(e, _self);\n        }));\n        this.element.addEventListener(\"keypress\", (this._keyPressListener = (e) => {\n            _self.firePressEvent(e, _self);\n        }));\n        this.element.addEventListener(\"keyup\", (this._keyUpListener = (e) => {\n            _self.fireUpEvent(e, _self);\n        }));\n    }\n    /**\n     *  Remove all installed event listeners from the underlying element.\n     */\n    releaseListeners() {\n        this.element.removeEventListener(\"keydown\", this._keyDownListener);\n        this.element.removeEventListener(\"keypress\", this._keyPressListener);\n        this.element.removeEventListener(\"keyup\", this._keyUpListener);\n    }\n    /**\n     * Listen for key down. This function allows chaining.\n     *\n     * Example: new KeyHandler().down('enter',function() {console.log('Enter hit.')});\n     *\n     * @name down\n     * @memberof KeyHandler\n     * @instance\n     * @param {string|number} key -  Any key identifier, key code or one from the KEY_CODES list.\n     * @param {(e:KeyboardEvent)=>void} e -  The callback to be triggered.\n     * @return {KeyHandler} this\n     */\n    down(key, listener) {\n        this.downListeners.push({ key: key, keyCode: KeyHandler.key2code(key), listener: listener });\n        return this;\n    }\n    /**\n     * Listen for key press.\n     *\n     * Example: new KeyHandler().press('enter',function() {console.log('Enter pressed.')});\n     *\n     * @name press\n     * @memberof KeyHandler\n     * @instance\n     * @param {string|number} key - Any key identifier, key code or one from the KEY_CODES list.\n     * @param {(e:KeyboardEvent)=>void} listener - The callback to be triggered.\n     * @return {KeyHandler} this\n     */\n    press(key, listener) {\n        this.pressListeners.push({ key: key, keyCode: KeyHandler.key2code(key), listener: listener });\n        return this;\n    }\n    /**\n     * Listen for key up.\n     *\n     * Example: new KeyHandler().up('enter',function() {console.log('Enter released.')});\n     *\n     * @name up\n     * @memberof KeyHandler\n     * @instance\n     * @param {string} key - Any key identifier, key code or one from the KEY_CODES list.\n     * @param {(e:KeyboardEvent)=>void)} e - The callback to be triggered.\n     * @return {KeyHandler} this\n     */\n    up(key, listener) {\n        this.upListeners.push({ key: key, keyCode: KeyHandler.key2code(key), listener: listener });\n        return this;\n    }\n    /**\n     * Check if a specific key is currently held pressed.\n     *\n     * @param {string|number} key - Any key identifier, key code or one from the KEY_CODES list.\n     */\n    isDown(key) {\n        if (typeof key == \"number\")\n            return this.keyStates[key] ? true : false;\n        else\n            return this.keyStates[KeyHandler.key2code(key)] ? true : false;\n    }\n    /**\n     * This function should invalidate any installed listeners and invalidate this object.\n     * After calling this function the object might not hold valid data any more and\n     * should not be used any more.\n     */\n    destroy() {\n        this.releaseListeners();\n    }\n}\n/**\n * Source:\n * https://keycode.info/\n */\n// prettier-ignore\nKeyHandler.KEY_CODES = {\n    'break': 3, // alternate: 19\n    'backspace': 8,\n    // 'delete'\t : 8, // alternate: 46\n    'tab': 9,\n    'clear': 12,\n    'enter': 13,\n    'shift': 16,\n    'ctrl': 17,\n    'alt': 18,\n    'pause': 19,\n    // 'break'\t         : 19,\n    'capslock': 20,\n    'hangul': 21,\n    'hanja': 25,\n    'escape': 27,\n    'conversion': 28,\n    'non-conversion': 29, // alternate: 235?\n    'spacebar': 32,\n    'pageup': 33,\n    'pagedown': 34,\n    'end': 35,\n    'home': 36, // alternate: 172?\n    'leftarrow': 37,\n    'uparrow': 38,\n    'rightarrow': 39,\n    'downarrow': 40,\n    'select': 41,\n    'print': 42,\n    'execute': 43,\n    'printscreen': 44,\n    'insert': 45,\n    'delete': 46, // alternate: 8\n    'help': 47,\n    '0': 48,\n    '1': 49,\n    '2': 50,\n    '3': 51,\n    '4': 52,\n    '5': 53,\n    '6': 54,\n    '7': 55,\n    '8': 56,\n    '9': 57,\n    ':': 58,\n    'semicolon (firefox)': 59,\n    'equals': 59,\n    '<': 60,\n    'equals (firefox)': 61,\n    'ß': 63,\n    '@ (firefox)': 64,\n    'a': 65,\n    'b': 66,\n    'c': 67,\n    'd': 68,\n    'e': 69,\n    'f': 70,\n    'g': 71,\n    'h': 72,\n    'i': 73,\n    'j': 74,\n    'k': 75,\n    'l': 76,\n    'm': 77,\n    'n': 78,\n    'o': 79,\n    'p': 80,\n    'q': 81,\n    'r': 82,\n    's': 83,\n    't': 84,\n    'u': 85,\n    'v': 86,\n    'w': 87,\n    'x': 88,\n    'y': 89,\n    'z': 90,\n    'windows': 91,\n    'leftcommand': 91, // left ⌘\n    'chromebooksearch': 91,\n    'rightwindowkey': 92,\n    'windowsmenu': 93,\n    'rightcommant': 93, // right ⌘\n    'sleep': 95,\n    'numpad0': 96,\n    'numpad1': 97,\n    'numpad2': 98,\n    'numpad3': 99,\n    'numpad4': 100,\n    'numpad5': 101,\n    'numpad6': 102,\n    'numpad7': 103,\n    'numpad8': 104,\n    'numpad9': 105,\n    'multiply': 106,\n    'add': 107,\n    'numpadperiod': 108, // firefox, 194 on chrome\n    'subtract': 109,\n    'decimalpoint': 110,\n    'divide': 111,\n    'f1': 112,\n    'f2': 113,\n    'f3': 114,\n    'f4': 115,\n    'f5': 116,\n    'f6': 117,\n    'f7': 118,\n    'f8': 119,\n    'f9': 120,\n    'f10': 121,\n    'f11': 122,\n    'f12': 123,\n    'f13': 124,\n    'f14': 125,\n    'f15': 126,\n    'f16': 127,\n    'f17': 128,\n    'f18': 129,\n    'f19': 130,\n    'f20': 131,\n    'f21': 132,\n    'f22': 133,\n    'f23': 134,\n    'f24': 135,\n    'numlock': 144,\n    'scrolllock': 145,\n    '^': 160,\n    '!': 161,\n    // '؛' \t : 162 // (arabic semicolon)\n    '#': 163,\n    '$': 164,\n    'ù': 165,\n    'pagebackward': 166,\n    'pageforward': 167,\n    'refresh': 168,\n    'closingparen': 169, // (AZERTY)\n    '*': 170,\n    '~+*': 171,\n    // 'home'\t         : 172,\n    'minus': 173, // firefox\n    // 'mute'           : 173,\n    // 'unmute'\t : 173,\n    'decreasevolumelevel': 174,\n    'increasevolumelevel': 175,\n    'next': 176,\n    'previous': 177,\n    'stop': 178,\n    'play/pause': 179,\n    'email': 180,\n    'mute': 181, // firefox, alternate: 173\n    'unmute': 181, // alternate: 173?\n    //'decreasevolumelevel'\t182 // firefox\n    //'increasevolumelevel'\t183 // firefox\n    'semicolon': 186,\n    'ñ': 186,\n    'equal': 187,\n    'comma': 188,\n    'dash': 189,\n    'period': 190,\n    'forwardslash': 191,\n    'ç': 191, // 231 alternate?\n    'grave accent': 192,\n    //'ñ' 192,\n    'æ': 192,\n    'ö': 192,\n    '?': 193,\n    '/': 193,\n    '°': 193,\n    // 'numpadperiod'\t : 194, // chrome\n    'openbracket': 219,\n    'backslash': 220,\n    'closebracket': 221,\n    'å': 221,\n    'singlequote': 222,\n    'ø': 222,\n    'ä': 222,\n    '`': 223,\n    // 'left or right ⌘ key (firefox)'\t224\n    'altgr': 225,\n    // '< /git >, left back slash'\t226\n    'GNOME Compose Key': 230,\n    'XF86Forward': 233,\n    'XF86Back': 234,\n    'alphanumeric': 240,\n    'hiragana': 242,\n    'katakana': 242,\n    'half-width': 243,\n    'full-width': 243,\n    'kanji': 244,\n    'unlocktrackpad': 251, // Chrome/Edge\n    'toggletouchpad': 255\n};\n//# sourceMappingURL=KeyHandler.js.map","/**\n * @author   Ikaros Kappler\n * @date     2018-03-19\n * @modified 2018-04-28 Added the param 'wasDragged'.\n * @modified 2018-08-16 Added the param 'dragAmount'.\n * @modified 2018-08-27 Added the param 'element'.\n * @modified 2018-11-11 Changed the scope from a simple global var to a member of window/_context.\n * @modified 2018-11-19 Renamed the 'mousedown' function to 'down' and the 'mouseup' function to 'up'.\n * @modified 2018-11-28 Added the 'wheel' listener.\n * @modified 2018-12-09 Cleaned up some code.\n * @modified 2019-02-10 Cleaned up some more code.\n * @modified 2020-03-25 Ported this class from vanilla-JS to Typescript.\n * @modified 2020-04-08 Fixed the click event (internally fired a 'mouseup' event) (1.0.10)\n * @modified 2020-04-08 Added the optional 'name' property. (1.0.11)\n * @modified 2020-04-08 The new version always installs internal listenrs to track drag events even\n *                      if there is no external drag listener installed (1.1.0).\n * @modified 2020-10-04 Added extended JSDoc comments.\n * @modified 2020-11-25 Added the `isTouchEvent` param.\n * @modified 2021-01-10 The mouse handler is now also working with SVGElements.\n * @modified 2022-08-16 Fixed a bug in the mouse button detection.\n * @version  1.2.1\n *\n * @file MouseHandler\n * @public\n **/\nexport class XMouseEvent extends MouseEvent {\n}\nexport class XWheelEvent extends WheelEvent {\n}\n/**\n * @classdesc A simple mouse handler for demos.\n * Use to avoid load massive libraries like jQuery.\n *\n * @requires XYCoords\n */\nexport class MouseHandler {\n    /**\n     * The constructor.\n     *\n     * Pass the DOM element you want to receive mouse events from.\n     *\n     * Usage\n     * =====\n     * @example\n     *   // Javascript\n     *   new MouseHandler( document.getElementById('mycanvas') )\n     *\t    .drag( function(e) {\n     *\t\tconsole.log( 'Mouse dragged: ' + JSON.stringify(e) );\n     *\t\tif( e.params.leftMouse ) ;\n     *\t\telse if( e.params.rightMouse ) ;\n     *\t    } )\n     *\t    .move( function(e) {\n     *\t\tconsole.log( 'Mouse moved: ' + JSON.stringify(e.params) );\n     *\t    } )\n     *          .up( function(e) {\n     *              console.log( 'Mouse up. Was dragged?', e.params.wasDragged );\n     *          } )\n     *          .down( function(e) {\n     *              console.log( 'Mouse down.' );\n     *          } )\n     *          .click( function(e) {\n     *              console.log( 'Click.' );\n     *          } )\n     *          .wheel( function(e) {\n     *              console.log( 'Wheel. delta='+e.deltaY );\n     *          } )\n     *\n     * @example\n     *   // Typescript\n     *   new MouseHandler( document.getElementById('mycanvas') )\n     *\t    .drag( (e:XMouseEvent) => {\n     *\t\tconsole.log( 'Mouse dragged: ' + JSON.stringify(e) );\n     *\t\tif( e.params.leftMouse ) ;\n     *\t\telse if( e.params.rightMouse ) ;\n     *\t    } )\n     *\t    .move( (e:XMouseEvent) => {\n     *\t\tconsole.log( 'Mouse moved: ' + JSON.stringify(e.params) );\n     *\t    } )\n     *          .up( (e:XMouseEvent) => {\n     *              console.log( 'Mouse up. Was dragged?', e.params.wasDragged );\n     *          } )\n     *          .down( (e:XMouseEvent) => {\n     *              console.log( 'Mouse down.' );\n     *          } )\n     *          .click( (e:XMouseEvent) => {\n     *              console.log( 'Click.' );\n     *          } )\n     *          .wheel( (e:XWheelEvent) => {\n     *              console.log( 'Wheel. delta='+e.deltaY );\n     *          } )\n     *\n     * @constructor\n     * @instance\n     * @memberof MouseHandler\n     * @param {HTMLElement} element\n     **/\n    constructor(element, name) {\n        this.mouseDownPos = undefined;\n        this.mouseDragPos = undefined;\n        // TODO: cc\n        // private mousePos       : { x:number, y:number }|undefined = undefined;\n        this.mouseButton = -1;\n        this.listeners = {};\n        this.installed = {};\n        this.handlers = {};\n        // +----------------------------------------------------------------------\n        // | Some private vars to store the current mouse/position/button state.\n        // +-------------------------------------------------\n        this.name = name;\n        this.element = element;\n        this.mouseDownPos = undefined;\n        this.mouseDragPos = undefined;\n        // this.mousePos     = null;\n        this.mouseButton = -1;\n        this.listeners = {};\n        this.installed = {};\n        this.handlers = {};\n        // +----------------------------------------------------------------------\n        // | Define the internal event handlers.\n        // |\n        // | They will dispatch the modified event (relative mouse position,\n        // | drag offset, ...) to the callbacks.\n        // +-------------------------------------------------\n        const _self = this;\n        this.handlers[\"mousemove\"] = (e) => {\n            if (_self.listeners.mousemove)\n                _self.listeners.mousemove(_self.mkParams(e, \"mousemove\"));\n            if (_self.mouseDragPos && _self.listeners.drag)\n                _self.listeners.drag(_self.mkParams(e, \"drag\"));\n            if (_self.mouseDownPos)\n                _self.mouseDragPos = _self.relPos(e);\n        };\n        this.handlers[\"mouseup\"] = (e) => {\n            if (_self.listeners.mouseup)\n                _self.listeners.mouseup(_self.mkParams(e, \"mouseup\"));\n            _self.mouseDragPos = undefined;\n            _self.mouseDownPos = undefined;\n            _self.mouseButton = -1;\n        };\n        this.handlers[\"mousedown\"] = (e) => {\n            _self.mouseDragPos = _self.relPos(e);\n            _self.mouseDownPos = _self.relPos(e);\n            _self.mouseButton = e.button;\n            if (_self.listeners.mousedown)\n                _self.listeners.mousedown(_self.mkParams(e, \"mousedown\"));\n        };\n        this.handlers[\"click\"] = (e) => {\n            if (_self.listeners.click)\n                _self.listeners.click(_self.mkParams(e, \"click\"));\n        };\n        this.handlers[\"wheel\"] = (e) => {\n            if (_self.listeners.wheel)\n                _self.listeners.wheel(_self.mkParams(e, \"wheel\"));\n        };\n        this.element.addEventListener(\"mousemove\", this.handlers[\"mousemove\"]);\n        this.element.addEventListener(\"mouseup\", this.handlers[\"mouseup\"]);\n        this.element.addEventListener(\"mousedown\", this.handlers[\"mousedown\"]);\n        this.element.addEventListener(\"click\", this.handlers[\"click\"]);\n        this.element.addEventListener(\"wheel\", this.handlers[\"wheel\"]);\n    }\n    /**\n     * Get relative position from the given MouseEvent.\n     *\n     * @name relPos\n     * @memberof MouseHandler\n     * @instance\n     * @private\n     * @param {MouseEvent} e - The mouse event to get the relative position for.\n     * @return {XYCoords} The relative mouse coordinates.\n     */\n    relPos(e) {\n        return { x: e.offsetX, y: e.offsetY };\n    }\n    /**\n     * Build the extended event params.\n     *\n     * @name mkParams\n     * @memberof MouseHandler\n     * @instance\n     * @private\n     * @param {MouseEvent} event - The mouse event to get the relative position for.\n     * @param {string} eventName - The name of the firing event.\n     * @return {XMouseEvent}\n     */\n    mkParams(event, eventName) {\n        var _a, _b;\n        const rel = this.relPos(event);\n        const xEvent = event;\n        xEvent.params = {\n            element: this.element,\n            name: eventName,\n            isTouchEvent: false,\n            pos: rel,\n            button: event.button, // this.mouseButton,\n            leftButton: event.button === 0, // this.mouseButton === 0,\n            middleButton: event.button === 1, // this.mouseButton === 1,\n            rightButton: event.button === 2, // this.mouseButton === 2,\n            mouseDownPos: (_a = this.mouseDownPos) !== null && _a !== void 0 ? _a : { x: NaN, y: NaN },\n            draggedFrom: (_b = this.mouseDragPos) !== null && _b !== void 0 ? _b : { x: NaN, y: NaN },\n            wasDragged: this.mouseDownPos != null && (this.mouseDownPos.x != rel.x || this.mouseDownPos.y != rel.y),\n            dragAmount: this.mouseDragPos != null ? { x: rel.x - this.mouseDragPos.x, y: rel.y - this.mouseDragPos.y } : { x: 0, y: 0 }\n        };\n        return xEvent;\n    }\n    /**\n     * Install a new listener.\n     * Please note that this mouse handler can only handle one listener per event type.\n     *\n     * @name listenFor\n     * @memberof MouseHandler\n     * @instance\n     * @private\n     * @param {string} eventName - The name of the firing event to listen for.\n     * @return {void}\n     */\n    listenFor(eventName) {\n        if (this.installed[eventName])\n            return;\n        // In the new version 1.1.0 has all internal listeners installed by default.\n        this.installed[eventName] = true;\n    }\n    /**\n     * Un-install a new listener.\n     *\n     * @name listenFor\n     * @memberof MouseHandler\n     * @instance\n     * @private\n     * @param {string} eventName - The name of the firing event to unlisten for.\n     * @return {void}\n     */\n    unlistenFor(eventName) {\n        if (!this.installed[eventName])\n            return;\n        // In the new version 1.1.0 has all internal listeners installed by default.\n        delete this.installed[eventName];\n    }\n    /**\n     * Installer function to listen for a specific event: mouse-drag.\n     * Pass your callbacks here.\n     *\n     * Note: this support chaining.\n     *\n     * @name drag\n     * @memberof MouseHandler\n     * @instance\n     * @param {XMouseCallback} callback - The drag-callback to listen for.\n     * @return {MouseHandler} this\n     */\n    drag(callback) {\n        if (this.listeners.drag)\n            this.throwAlreadyInstalled(\"drag\");\n        this.listeners.drag = callback;\n        this.listenFor(\"mousedown\");\n        this.listenFor(\"mousemove\");\n        this.listenFor(\"mouseup\");\n        return this;\n    }\n    /**\n     * Installer function to listen for a specific event: mouse-move.\n     * Pass your callbacks here.\n     *\n     * Note: this support chaining.\n     *\n     * @name move\n     * @memberof MouseHandler\n     * @instance\n     * @param {XMouseCallback} callback - The move-callback to listen for.\n     * @return {MouseHandler} this\n     */\n    move(callback) {\n        if (this.listeners.mousemove)\n            this.throwAlreadyInstalled(\"mousemove\");\n        this.listenFor(\"mousemove\");\n        this.listeners.mousemove = callback;\n        return this;\n    }\n    /**\n     * Installer function to listen for a specific event: mouse-up.\n     * Pass your callbacks here.\n     *\n     * Note: this support chaining.\n     *\n     * @name up\n     * @memberof MouseHandler\n     * @instance\n     * @param {XMouseCallback} callback - The up-callback to listen for.\n     * @return {MouseHandler} this\n     */\n    up(callback) {\n        if (this.listeners.mouseup)\n            this.throwAlreadyInstalled(\"mouseup\");\n        this.listenFor(\"mouseup\");\n        this.listeners.mouseup = callback;\n        return this;\n    }\n    /**\n     * Installer function to listen for a specific event: mouse-down.\n     * Pass your callbacks here.\n     *\n     * Note: this support chaining.\n     *\n     * @name down\n     * @memberof MouseHandler\n     * @instance\n     * @param {XMouseCallback} callback - The down-callback to listen for.\n     * @return {MouseHandler} this\n     */\n    down(callback) {\n        if (this.listeners.mousedown)\n            this.throwAlreadyInstalled(\"mousedown\");\n        this.listenFor(\"mousedown\");\n        this.listeners.mousedown = callback;\n        return this;\n    }\n    /**\n     * Installer function to listen for a specific event: mouse-click.\n     * Pass your callbacks here.\n     *\n     * Note: this support chaining.\n     *\n     * @name click\n     * @memberof MouseHandler\n     * @instance\n     * @param {XMouseCallback} callback - The click-callback to listen for.\n     * @return {MouseHandler} this\n     */\n    click(callback) {\n        if (this.listeners.click)\n            this.throwAlreadyInstalled(\"click\");\n        this.listenFor(\"click\");\n        this.listeners.click = callback;\n        return this;\n    }\n    /**\n     * Installer function to listen for a specific event: mouse-wheel.\n     * Pass your callbacks here.\n     *\n     * Note: this support chaining.\n     *\n     * @name wheel\n     * @memberof MouseHandler\n     * @instance\n     * @param {XWheelCallback} callback - The wheel-callback to listen for.\n     * @return {MouseHandler} this\n     */\n    wheel(callback) {\n        if (this.listeners.wheel)\n            this.throwAlreadyInstalled(\"wheel\");\n        this.listenFor(\"wheel\");\n        this.listeners.wheel = callback;\n        return this;\n    }\n    /**\n     * An internal function to throw events.\n     *\n     * @name throwAlreadyInstalled\n     * @memberof MouseHandler\n     * @instance\n     * @private\n     * @param {string} name - The name of the event.\n     * @return {void}\n     */\n    throwAlreadyInstalled(name) {\n        throw `This MouseHandler already has a '${name}' callback. To keep the code simple there is only room for one.`;\n    }\n    /**\n     * Call this when your work is done.\n     *\n     * The function will un-install all event listeners.\n     *\n     * @name destroy\n     * @memberof MouseHandler\n     * @instance\n     * @private\n     * @return {void}\n     */\n    destroy() {\n        this.unlistenFor(\"mousedown\");\n        this.unlistenFor(\"mousemove\");\n        this.unlistenFor(\"moseup\");\n        this.unlistenFor(\"click\");\n        this.unlistenFor(\"wheel\");\n        this.element.removeEventListener(\"mousemove\", this.handlers[\"mousemove\"]);\n        this.element.removeEventListener(\"mouseup\", this.handlers[\"mousedown\"]);\n        this.element.removeEventListener(\"mousedown\", this.handlers[\"mousedown\"]);\n        this.element.removeEventListener(\"click\", this.handlers[\"click\"]);\n        this.element.removeEventListener(\"wheel\", this.handlers[\"wheel\"]);\n    }\n}\n//# sourceMappingURL=MouseHandler.js.map","/**\n * @author   Ikaros Kappler\n * @date     2019-01-30\n * @modified 2019-03-23 Added JSDoc tags.\n * @modified 2020-03-25 Ported this class from vanilla-JS to Typescript.\n * @modified 2021-01-20 Added UID.\n * @modified 2022-02-02 Added the `destroy` method.\n * @modified 2022-02-02 Cleared the `PBImage.toSVGString` function (deprecated). Use `drawutilssvg` instead.\n * @version 1.2.0\n *\n * @file PBImage\n * @fileoverview As native Image objects have only a position and with\n *               and height thei are not suitable for UI dragging interfaces.\n * @public\n **/\nimport { UIDGenerator } from \"./UIDGenerator\";\n/**\n * @classdesc A wrapper for image objects. Has an upper left and a lower right corner point.\n *\n * @requires Vertex\n * @requires SVGSerializable\n * @requires UID\n * @requires UIDGenerator\n */\nexport class PBImage {\n    /**\n     * The constructor.\n     *\n     * @constructor\n     * @name PBImage\n     * @param {Image} image - The actual image.\n     * @param {Vertex} upperLeft - The upper left corner.\n     * @param {Vertex} lowerRight - The lower right corner.\n     **/\n    constructor(image, upperLeft, lowerRight) {\n        /**\n         * Required to generate proper CSS classes and other class related IDs.\n         **/\n        this.className = \"PBImage\";\n        this.uid = UIDGenerator.next();\n        this.image = image;\n        this.upperLeft = upperLeft;\n        this.lowerRight = lowerRight;\n    }\n    /**\n     * This function should invalidate any installed listeners and invalidate this object.\n     * After calling this function the object might not hold valid data any more and\n     * should not be used.\n     */\n    destroy() {\n        this.upperLeft.destroy();\n        this.lowerRight.destroy();\n        this.isDestroyed = true;\n    }\n}\n//# sourceMappingURL=PBImage.js.map","/**\n * @author   Ikaros Kappler\n * @date     2021-11-16\n * @modified 2022-02-02 Added the `destroy` method.\n * @modified 2023-09-25 Fixed a type error in the constructor. Nothing vital.\n * @version  1.1.1\n **/\nimport { UIDGenerator } from \"./UIDGenerator\";\nimport { Vertex } from \"./Vertex\";\n/**\n * @classdesc A simple text element: position, fontSize, fontFamily, color, textAlign, lineHeight and rotation.\n *\n * @requires FontOptions\n * @requires FontSize\n * @requires FontStyle\n * @requires FontWeight\n * @requires Vertex\n * @requires SVGSerializale\n * @requires UID\n * @requires UIDGenerator\n **/\nexport class PBText {\n    /**\n     * Create a new circle with given center point and radius.\n     *\n     * @constructor\n     * @name Circle\n     * @param {Vertex} center - The center point of the circle.\n     * @param {number} radius - The radius of the circle.\n     */\n    constructor(text, anchor, options) {\n        /**\n         * Required to generate proper CSS classes and other class related IDs.\n         **/\n        this.className = \"PBText\";\n        this.uid = UIDGenerator.next();\n        this.text = text;\n        this.anchor = anchor !== null && anchor !== void 0 ? anchor : new Vertex();\n        this.color = options === null || options === void 0 ? void 0 : options.color;\n        this.fontFamily = options === null || options === void 0 ? void 0 : options.fontFamily;\n        this.fontSize = options === null || options === void 0 ? void 0 : options.fontSize;\n        this.fontStyle = options === null || options === void 0 ? void 0 : options.fontStyle;\n        this.fontWeight = options === null || options === void 0 ? void 0 : options.fontWeight;\n        this.lineHeight = options === null || options === void 0 ? void 0 : options.lineHeight;\n        this.textAlign = options === null || options === void 0 ? void 0 : options.textAlign;\n        this.rotation = options === null || options === void 0 ? void 0 : options.rotation;\n    }\n    /**\n     * This function should invalidate any installed listeners and invalidate this object.\n     * After calling this function the object might not hold valid data any more and\n     * should not be used.\n     */\n    destroy() {\n        this.anchor.destroy();\n        this.isDestroyed = true;\n    }\n} // END class\n//# sourceMappingURL=PBText.js.map","/* Port from AlloyFinger v0.1.15\n * Original by dntzhang\n * Typescript port by Ikaros Kappler\n * Github: https://github.com/IkarosKappler/AlloyFinger-Typescript\n *\n * @date    2021-02-10 (Typescript port)\n * @version 0.1.18\n */\n;\n/**\n * Tiny math function to calculate the length of a vector in euclidean space.\n *\n * @param {XYCoords} v - The vector in {x,y} notation.\n * @return {number} The length of the vector.\n */\nconst getLen = (v) => {\n    return Math.sqrt(v.x * v.x + v.y * v.y);\n};\n/**\n * Tiny math function to calculate the dot product of two vectors.\n *\n * @param {XYCoords} v1 - The first vector in {x,y} notation.\n * @param {XYCoords} v2 - The second vector in {x,y} notation.\n * @return {number} The dot product of both vectors.\n */\nconst dot = (v1, v2) => {\n    return v1.x * v2.x + v1.y * v2.y;\n};\n/**\n * Tiny math function to calculate the angle between two vectors.\n *\n * @param {XYCoords} v1 - The first vector in {x,y} notation.\n * @param {XYCoords} v2 - The second vector in {x,y} notation.\n * @return {number} The angle (in radians) between the two vectors.\n */\nconst getAngle = (v1, v2) => {\n    const mr = getLen(v1) * getLen(v2);\n    if (mr === 0)\n        return 0;\n    var r = dot(v1, v2) / mr;\n    if (r > 1)\n        r = 1;\n    return Math.acos(r);\n};\n/**\n * Tiny math function to calculate the cross product of two vectors.\n *\n * @param {XYCoords} v1 - The first vector in {x,y} notation.\n * @param {XYCoords} v2 - The second vector in {x,y} notation.\n * @return {number} The cross product of both vectors.\n */\nconst cross = (v1, v2) => {\n    return v1.x * v2.y - v2.x * v1.y;\n};\n/**\n * Tiny math function to calculate the rotate-angle (in degrees) for two vectors.\n *\n * @param {XYCoords} v1 - The first vector in {x,y} notation.\n * @param {XYCoords} v2 - The second vector in {x,y} notation.\n * @return {number} The rotate-angle in degrees for the two vectors.\n */\nconst getRotateAngle = (v1, v2) => {\n    var angle = getAngle(v1, v2);\n    if (cross(v1, v2) > 0) {\n        angle *= -1;\n    }\n    return angle * 180 / Math.PI;\n};\n/**\n * A HandlerAdmin holds all the added event handlers for one kind of event type.\n */\nclass HandlerAdmin {\n    constructor(el) {\n        this.handlers = [];\n        this.el = el;\n    }\n    ;\n    add(handler) {\n        this.handlers.push(handler);\n    }\n    ;\n    del(handler) {\n        if (!handler)\n            this.handlers = [];\n        for (var i = this.handlers.length; i >= 0; i--) {\n            if (this.handlers[i] === handler) {\n                this.handlers.splice(i, 1);\n            }\n        }\n    }\n    ;\n    dispatch(..._args) {\n        for (var i = 0, len = this.handlers.length; i < len; i++) {\n            const handler = this.handlers[i];\n            if (typeof handler === 'function') {\n                handler.apply(this.el, arguments);\n            }\n        }\n    }\n    ;\n} // END class HandlerAdmin\n/**\n * A wrapper for handler functions; converts the passed handler function into a HadlerAdmin instance..\n */\nconst wrapFunc = (el, handler) => {\n    const handlerAdmin = new HandlerAdmin(el);\n    handlerAdmin.add(handler);\n    return handlerAdmin;\n};\n/**\n * @classdesc The AlloyFinger main class. Use this to add handler functions for\n *            touch events to any HTML- or SVG-Element.\n **/\nexport class AlloyFinger {\n    constructor(el, option) {\n        this.element = typeof el == 'string' ? document.querySelector(el) : el;\n        // Fancy stuff: change `this` from the start-, move-, end- and cancel-function.\n        //    https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_objects/Function/bind\n        this.start = this.start.bind(this);\n        this.move = this.move.bind(this);\n        this.end = this.end.bind(this);\n        this.cancel = this.cancel.bind(this);\n        this.element.addEventListener(\"touchstart\", this.start, false);\n        this.element.addEventListener(\"touchmove\", this.move, false);\n        this.element.addEventListener(\"touchend\", this.end, false);\n        this.element.addEventListener(\"touchcancel\", this.cancel, false);\n        this.preV = { x: null, y: null };\n        this.pinchStartLen = null;\n        this.zoom = 1;\n        this.isDoubleTap = false;\n        const noop = () => { };\n        this.rotate = wrapFunc(this.element, option.rotate || noop);\n        this.touchStart = wrapFunc(this.element, option.touchStart || noop);\n        this.multipointStart = wrapFunc(this.element, option.multipointStart || noop);\n        this.multipointEnd = wrapFunc(this.element, option.multipointEnd || noop);\n        this.pinch = wrapFunc(this.element, option.pinch || noop);\n        this.swipe = wrapFunc(this.element, option.swipe || noop);\n        this.tap = wrapFunc(this.element, option.tap || noop);\n        this.doubleTap = wrapFunc(this.element, option.doubleTap || noop);\n        this.longTap = wrapFunc(this.element, option.longTap || noop);\n        this.singleTap = wrapFunc(this.element, option.singleTap || noop);\n        this.pressMove = wrapFunc(this.element, option.pressMove || noop);\n        this.twoFingerPressMove = wrapFunc(this.element, option.twoFingerPressMove || noop);\n        this.touchMove = wrapFunc(this.element, option.touchMove || noop);\n        this.touchEnd = wrapFunc(this.element, option.touchEnd || noop);\n        this.touchCancel = wrapFunc(this.element, option.touchCancel || noop);\n        this._cancelAllHandler = this.cancelAll.bind(this);\n        if (globalThis && typeof globalThis.addEventListener === \"function\") {\n            globalThis.addEventListener('scroll', this._cancelAllHandler);\n        }\n        this.delta = null;\n        this.last = null;\n        this.now = null;\n        this.tapTimeout = null;\n        this.singleTapTimeout = null;\n        this.longTapTimeout = null;\n        this.swipeTimeout = null;\n        this.x1 = this.x2 = this.y1 = this.y2 = null;\n        this.preTapPosition = { x: null, y: null };\n    }\n    ;\n    start(evt) {\n        if (!evt.touches)\n            return;\n        const _self = this;\n        this.now = Date.now();\n        this.x1 = evt.touches[0].pageX;\n        this.y1 = evt.touches[0].pageY;\n        this.delta = this.now - (this.last || this.now);\n        this.touchStart.dispatch(evt, this.element);\n        if (this.preTapPosition.x !== null) {\n            this.isDoubleTap = (this.delta > 0 && this.delta <= 250 && Math.abs(this.preTapPosition.x - this.x1) < 30 && Math.abs(this.preTapPosition.y - this.y1) < 30);\n            if (this.isDoubleTap)\n                clearTimeout(this.singleTapTimeout);\n        }\n        this.preTapPosition.x = this.x1;\n        this.preTapPosition.y = this.y1;\n        this.last = this.now;\n        const preV = this.preV;\n        const len = evt.touches.length;\n        if (len > 1) {\n            this._cancelLongTap();\n            this._cancelSingleTap();\n            const v = { x: evt.touches[1].pageX - this.x1, y: evt.touches[1].pageY - this.y1 };\n            preV.x = v.x;\n            preV.y = v.y;\n            this.pinchStartLen = getLen(preV);\n            this.multipointStart.dispatch(evt, this.element);\n        }\n        this._preventTap = false;\n        this.longTapTimeout = setTimeout((() => {\n            _self.longTap.dispatch(evt, _self.element);\n            _self._preventTap = true;\n        }).bind(_self), 750);\n    }\n    ;\n    move(event) {\n        if (!event.touches)\n            return;\n        const afEvent = event;\n        const preV = this.preV;\n        const len = event.touches.length;\n        const currentX = event.touches[0].pageX;\n        const currentY = event.touches[0].pageY;\n        this.isDoubleTap = false;\n        if (len > 1) {\n            const sCurrentX = afEvent.touches[1].pageX;\n            const sCurrentY = afEvent.touches[1].pageY;\n            const v = { x: afEvent.touches[1].pageX - currentX, y: afEvent.touches[1].pageY - currentY };\n            if (preV.x !== null) {\n                if (this.pinchStartLen > 0) {\n                    afEvent.zoom = getLen(v) / this.pinchStartLen;\n                    this.pinch.dispatch(afEvent, this.element);\n                }\n                afEvent.angle = getRotateAngle(v, preV);\n                this.rotate.dispatch(afEvent, this.element);\n            }\n            preV.x = v.x;\n            preV.y = v.y;\n            if (this.x2 !== null && this.sx2 !== null) {\n                afEvent.deltaX = (currentX - this.x2 + sCurrentX - this.sx2) / 2;\n                afEvent.deltaY = (currentY - this.y2 + sCurrentY - this.sy2) / 2;\n            }\n            else {\n                afEvent.deltaX = 0;\n                afEvent.deltaY = 0;\n            }\n            this.twoFingerPressMove.dispatch(afEvent, this.element);\n            this.sx2 = sCurrentX;\n            this.sy2 = sCurrentY;\n        }\n        else {\n            if (this.x2 !== null) {\n                afEvent.deltaX = currentX - this.x2;\n                afEvent.deltaY = currentY - this.y2;\n                //move事件中添加对当前触摸点到初始触摸点的判断，\n                //如果曾经大于过某个距离(比如10),就认为是移动到某个地方又移回来，应该不再触发tap事件才对。\n                //\n                // translation:\n                //    Add the judgment of the current touch point to the initial touch point in the event,\n                //    If it has been greater than a certain distance (such as 10), it is considered to be\n                //    moved to a certain place and then moved back, and the tap event should no longer be triggered.\n                const movedX = Math.abs(this.x1 - this.x2);\n                const movedY = Math.abs(this.y1 - this.y2);\n                if (movedX > 10 || movedY > 10) {\n                    this._preventTap = true;\n                }\n            }\n            else {\n                afEvent.deltaX = 0;\n                afEvent.deltaY = 0;\n            }\n            this.pressMove.dispatch(afEvent, this.element);\n        }\n        this.touchMove.dispatch(afEvent, this.element);\n        this._cancelLongTap();\n        this.x2 = currentX;\n        this.y2 = currentY;\n        if (len > 1) {\n            event.preventDefault();\n        }\n    }\n    ; // END move\n    end(event) {\n        if (!event.changedTouches)\n            return;\n        const afEvent = event;\n        this._cancelLongTap();\n        const self = this;\n        if (afEvent.touches.length < 2) {\n            this.multipointEnd.dispatch(afEvent, this.element);\n            this.sx2 = this.sy2 = null;\n        }\n        //swipe\n        if ((this.x2 && Math.abs(this.x1 - this.x2) > 30) ||\n            (this.y2 && Math.abs(this.y1 - this.y2) > 30)) {\n            afEvent.direction = this._swipeDirection(this.x1, this.x2, this.y1, this.y2);\n            this.swipeTimeout = setTimeout(function () {\n                self.swipe.dispatch(afEvent, self.element);\n            }, 0);\n        }\n        else {\n            this.tapTimeout = setTimeout(function () {\n                if (!self._preventTap) {\n                    self.tap.dispatch(afEvent, self.element);\n                }\n                // trigger double tap immediately\n                if (self.isDoubleTap) {\n                    self.doubleTap.dispatch(afEvent, self.element);\n                    self.isDoubleTap = false;\n                }\n            }, 0);\n            if (!self.isDoubleTap) {\n                self.singleTapTimeout = setTimeout(function () {\n                    self.singleTap.dispatch(afEvent, self.element);\n                }, 250);\n            }\n        }\n        this.touchEnd.dispatch(afEvent, this.element);\n        this.preV.x = 0;\n        this.preV.y = 0;\n        this.zoom = 1;\n        this.pinchStartLen = null;\n        this.x1 = this.x2 = this.y1 = this.y2 = null;\n    }\n    ; // END end\n    cancelAll() {\n        this._preventTap = true;\n        clearTimeout(this.singleTapTimeout);\n        clearTimeout(this.tapTimeout);\n        clearTimeout(this.longTapTimeout);\n        clearTimeout(this.swipeTimeout);\n    }\n    ;\n    cancel(evt) {\n        this.cancelAll();\n        this.touchCancel.dispatch(evt, this.element);\n    }\n    ;\n    _cancelLongTap() {\n        clearTimeout(this.longTapTimeout);\n    }\n    ;\n    _cancelSingleTap() {\n        clearTimeout(this.singleTapTimeout);\n    }\n    ;\n    _swipeDirection(x1, x2, y1, y2) {\n        return Math.abs(x1 - x2) >= Math.abs(y1 - y2) ? (x1 - x2 > 0 ? 'Left' : 'Right') : (y1 - y2 > 0 ? 'Up' : 'Down');\n    }\n    ;\n    on(evt, handler) {\n        if (this[evt]) {\n            // Force the generic parameter into it's expected candidate here ;)\n            const admin = this[evt];\n            admin.add(handler);\n        }\n    }\n    ;\n    off(evt, handler) {\n        if (this[evt]) {\n            // Force the generic parameter into it's expected candidate here ;)\n            const admin = this[evt];\n            admin.del(handler);\n        }\n    }\n    ;\n    destroy() {\n        if (this.singleTapTimeout) {\n            clearTimeout(this.singleTapTimeout);\n        }\n        if (this.tapTimeout) {\n            clearTimeout(this.tapTimeout);\n        }\n        if (this.longTapTimeout) {\n            clearTimeout(this.longTapTimeout);\n        }\n        if (this.swipeTimeout) {\n            clearTimeout(this.swipeTimeout);\n        }\n        this.element.removeEventListener(\"touchstart\", this.start);\n        this.element.removeEventListener(\"touchmove\", this.move);\n        this.element.removeEventListener(\"touchend\", this.end);\n        this.element.removeEventListener(\"touchcancel\", this.cancel);\n        this.rotate.del();\n        this.touchStart.del();\n        this.multipointStart.del();\n        this.multipointEnd.del();\n        this.pinch.del();\n        this.swipe.del();\n        this.tap.del();\n        this.doubleTap.del();\n        this.longTap.del();\n        this.singleTap.del();\n        this.pressMove.del();\n        this.twoFingerPressMove.del();\n        this.touchMove.del();\n        this.touchEnd.del();\n        this.touchCancel.del();\n        this.preV = this.pinchStartLen = this.zoom = this.isDoubleTap = this.delta = this.last = this.now = this.tapTimeout = this.singleTapTimeout = this.longTapTimeout = this.swipeTimeout = this.x1 = this.x2 = this.y1 = this.y2 = this.preTapPosition = this.rotate = this.touchStart = this.multipointStart = this.multipointEnd = this.pinch = this.swipe = this.tap = this.doubleTap = this.longTap = this.singleTap = this.pressMove = this.touchMove = this.touchEnd = this.touchCancel = this.twoFingerPressMove = null;\n        if (globalThis && typeof globalThis.removeEventListener === \"function\") {\n            globalThis.removeEventListener('scroll', this._cancelAllHandler);\n        }\n    }\n    ; // END destroy\n}\n;\nexport default AlloyFinger;\n//# sourceMappingURL=alloy_finger.js.map","/**\n * @author   Ikaros Kappler\n * @date     2018-11-28\n * @modified 2018-12-04 Added the toSVGString function.\n * @modified 2020-03-25 Ported this class from vanilla-JS to Typescript.\n * @modified 2021-01-20 Added UID.\n * @modified 2021-02-14 Added functions `radiusH` and `radiusV`.\n * @modified 2021-02-26 Added helper function `decribeSVGArc(...)`.\n * @modified 2021-03-01 Added attribute `rotation` to allow rotation of ellipses.\n * @modified 2021-03-03 Added the `vertAt` and `perimeter` methods.\n * @modified 2021-03-05 Added the `getFoci`, `normalAt` and `tangentAt` methods.\n * @modified 2021-03-09 Added the `clone` and `rotate` methods.\n * @modified 2021-03-10 Added the `toCubicBezier` method.\n * @modified 2021-03-15 Added `VEllipse.quarterSegmentCount` and `VEllipse.scale` functions.\n * @modified 2021-03-19 Added the `VEllipse.rotate` function.\n * @modified 2022-02-02 Added the `destroy` method.\n * @modified 2022-02-02 Cleared the `VEllipse.toSVGString` function (deprecated). Use `drawutilssvg` instead.\n * @modified 2025-03-31 ATTENTION: modified the winding direction of the `tangentAt` method to match with the Circle method. This is a breaking change!\n * @modified 2025-03-31 Adding the `VEllipse.move(amount: XYCoords)` method.\n * @modified 2025-04-19 Adding the `VEllipse.getBounds()` method.\n * @modified 2025-04-24 Adding the `VEllipse.getExtremePoints()` method for calculating minima and maxima.\n * @version  1.4.0\n *\n * @file VEllipse\n * @fileoverview Ellipses with a center and an x- and a y-axis (stored as a vertex).\n **/\nimport { Line } from \"./Line\";\nimport { Vector } from \"./Vector\";\nimport { Vertex } from \"./Vertex\";\nimport { UIDGenerator } from \"./UIDGenerator\";\nimport { CubicBezierCurve } from \"./CubicBezierCurve\";\nimport { Circle } from \"./Circle\";\nimport { Bounds } from \"./Bounds\";\n/**\n * @classdesc An ellipse class based on two vertices [centerX,centerY] and [radiusX,radiusY].\n *\n * @requires SVGSerializable\n * @requires UID\n * @requires UIDGenerator\n * @requires Vertex\n */\nexport class VEllipse {\n    /**\n     * The constructor.\n     *\n     * @constructor\n     * @param {Vertex} center - The ellipses center.\n     * @param {Vertex} axis - The x- and y-axis (the two radii encoded in a control point).\n     * @param {Vertex} rotation - [optional, default=0] The rotation of this ellipse.\n     * @name VEllipse\n     **/\n    constructor(center, axis, rotation) {\n        /**\n         * Required to generate proper CSS classes and other class related IDs.\n         **/\n        this.className = \"VEllipse\";\n        this.uid = UIDGenerator.next();\n        this.center = center;\n        this.axis = axis;\n        this.rotation = rotation || 0.0;\n    }\n    /**\n     * Clone this ellipse (deep clone).\n     *\n     * @return {VEllipse} A copy of this ellipse.s\n     */\n    clone() {\n        return new VEllipse(this.center.clone(), this.axis.clone(), this.rotation);\n    }\n    /**\n     * Get the non-negative horizonal radius of this ellipse.\n     *\n     * @method radiusH\n     * @instance\n     * @memberof VEllipse\n     * @return {number} The unsigned horizontal radius of this ellipse.\n     */\n    radiusH() {\n        return Math.abs(this.signedRadiusH());\n    }\n    /**\n     * Get the signed horizonal radius of this ellipse.\n     *\n     * @method signedRadiusH\n     * @instance\n     * @memberof VEllipse\n     * @return {number} The signed horizontal radius of this ellipse.\n     */\n    signedRadiusH() {\n        // return Math.abs(this.axis.x - this.center.x);\n        // Rotate axis back to origin before calculating radius\n        // return Math.abs(new Vertex(this.axis).rotate(-this.rotation,this.center).x - this.center.x);\n        return new Vertex(this.axis).rotate(-this.rotation, this.center).x - this.center.x;\n    }\n    /**\n     * Get the non-negative vertical radius of this ellipse.\n     *\n     * @method radiusV\n     * @instance\n     * @memberof VEllipse\n     * @return {number} The unsigned vertical radius of this ellipse.\n     */\n    radiusV() {\n        return Math.abs(this.signedRadiusV());\n    }\n    /**\n     * Get the signed vertical radius of this ellipse.\n     *\n     * @method radiusV\n     * @instance\n     * @memberof VEllipse\n     * @return {number} The signed vertical radius of this ellipse.\n     */\n    signedRadiusV() {\n        // Rotate axis back to origin before calculating radius\n        return new Vertex(this.axis).rotate(-this.rotation, this.center).y - this.center.y;\n    }\n    /**\n     * Get the the minima and maxima (points) of this (rotated) ellipse.\n     *\n     * @method getExtremePoints\n     * @instance\n     * @memberof VEllipse\n     * @return {[Vertex, Vertex, Vertex, Vertex]} Get the the minima and maxima (points) of this (rotated) ellipse.\n     */\n    getExtremePoints() {\n        const a = this.radiusH();\n        const b = this.radiusV();\n        // Calculate t_x values\n        const t_x1 = Math.atan2(-b * Math.sin(this.rotation), a * Math.cos(this.rotation));\n        const t_x2 = t_x1 + Math.PI;\n        // Calculate x values at t_x\n        const x_x1 = this.center.x + a * Math.cos(t_x1) * Math.cos(this.rotation) - b * Math.sin(t_x1) * Math.sin(this.rotation);\n        const y_x1 = this.center.y + a * Math.cos(t_x1) * Math.sin(this.rotation) + b * Math.sin(t_x1) * Math.cos(this.rotation);\n        const x_x2 = this.center.x + a * Math.cos(t_x2) * Math.cos(this.rotation) - b * Math.sin(t_x2) * Math.sin(this.rotation);\n        const y_x2 = this.center.y + a * Math.cos(t_x2) * Math.sin(this.rotation) + b * Math.sin(t_x2) * Math.cos(this.rotation);\n        let x_max, x_min;\n        if (x_x1 > x_x2) {\n            x_max = new Vertex(x_x1, y_x1);\n            x_min = new Vertex(x_x2, y_x2);\n        }\n        else {\n            x_max = new Vertex(x_x2, y_x2);\n            x_min = new Vertex(x_x1, y_x1);\n        }\n        // Calculate t_y values\n        const t_y1 = Math.atan2(b * Math.cos(this.rotation), a * Math.sin(this.rotation));\n        const t_y2 = t_y1 + Math.PI;\n        // Calculate y values at t_y\n        const x_y1 = this.center.x + a * Math.cos(t_y1) * Math.cos(this.rotation) - b * Math.sin(t_y1) * Math.sin(this.rotation);\n        const y_y1 = this.center.y + a * Math.cos(t_y1) * Math.sin(this.rotation) + b * Math.sin(t_y1) * Math.cos(this.rotation);\n        const x_y2 = this.center.x + a * Math.cos(t_y2) * Math.cos(this.rotation) - b * Math.sin(t_y2) * Math.sin(this.rotation);\n        const y_y2 = this.center.y + a * Math.cos(t_y2) * Math.sin(this.rotation) + b * Math.sin(t_y2) * Math.cos(this.rotation);\n        let y_max, y_min;\n        if (y_y1 > y_y2) {\n            y_max = new Vertex(x_y1, y_y1);\n            y_min = new Vertex(x_y2, y_y2);\n        }\n        else {\n            y_max = new Vertex(x_y2, y_y2);\n            y_min = new Vertex(x_y1, y_y1);\n        }\n        return [x_max, x_min, y_max, y_min];\n    }\n    //--- BEGIN --- Implement interface `IBounded`\n    /**\n     * Get the bounds of this ellipse.\n     *\n     * The bounds are approximated by the underlying segment buffer; the more segment there are,\n     * the more accurate will be the returned bounds.\n     *\n     * @method getBounds\n     * @instance\n     * @memberof VEllipse\n     * @return {Bounds} The bounds of this ellipse.\n     **/\n    getBounds() {\n        // Thanks to Cuixiping\n        //    https://stackoverflow.com/questions/87734/how-do-you-calculate-the-axis-aligned-bounding-box-of-an-ellipse\n        const r1 = this.radiusH();\n        const r2 = this.radiusV();\n        const ux = r1 * Math.cos(this.rotation);\n        const uy = r1 * Math.sin(this.rotation);\n        const vx = r2 * Math.cos(this.rotation + Math.PI / 2);\n        const vy = r2 * Math.sin(this.rotation + Math.PI / 2);\n        const bbox_halfwidth = Math.sqrt(ux * ux + vx * vx);\n        const bbox_halfheight = Math.sqrt(uy * uy + vy * vy);\n        return new Bounds({ x: this.center.x - bbox_halfwidth, y: this.center.y - bbox_halfheight }, { x: this.center.x + bbox_halfwidth, y: this.center.y + bbox_halfheight });\n    }\n    //--- BEGIN --- Implement interface `IBounded`\n    /**\n     * Move the ellipse by the given amount. This is equivalent by moving the `center` and `axis` points.\n     *\n     * @method move\n     * @param {XYCoords} amount - The amount to move.\n     * @instance\n     * @memberof VEllipse\n     * @return {VEllipse} this for chaining\n     **/\n    move(amount) {\n        this.center.add(amount);\n        this.axis.add(amount);\n        return this;\n    }\n    /**\n     * Scale this ellipse by the given factor from the center point. The factor will be applied to both radii.\n     *\n     * @method scale\n     * @instance\n     * @memberof VEllipse\n     * @param {number} factor - The factor to scale by.\n     * @return {VEllipse} this for chaining.\n     */\n    scale(factor) {\n        this.axis.scale(factor, this.center);\n        return this;\n    }\n    /**\n     * Rotate this ellipse around its center.\n     *\n     * @method rotate\n     * @instance\n     * @memberof VEllipse\n     * @param {number} angle - The angle to rotate by.\n     * @returns {VEllipse} this for chaining.\n     */\n    rotate(angle) {\n        this.axis.rotate(angle, this.center);\n        this.rotation += angle;\n        return this;\n    }\n    /**\n     * Get the vertex on the ellipse's outline at the given angle.\n     *\n     * @method vertAt\n     * @instance\n     * @memberof VEllipse\n     * @param {number} angle - The angle to determine the vertex at.\n     * @return {Vertex} The vertex on the outline at the given angle.\n     */\n    vertAt(angle) {\n        // Tanks to Narasinham for the vertex-on-ellipse equations\n        // https://math.stackexchange.com/questions/22064/calculating-a-point-that-lies-on-an-ellipse-given-an-angle\n        const a = this.radiusH();\n        const b = this.radiusV();\n        return new Vertex(VEllipse.utils.polarToCartesian(this.center.x, this.center.y, a, b, angle)).rotate(this.rotation, this.center);\n    }\n    /**\n     * Get the normal vector at the given angle.\n     * The normal vector is the vector that intersects the ellipse in a 90 degree angle\n     * at the given point (speicified by the given angle).\n     *\n     * Length of desired normal vector can be specified, default is 1.0.\n     *\n     * @method normalAt\n     * @instance\n     * @memberof VEllipse\n     * @param {number} angle - The angle to get the normal vector at.\n     * @param {number=1.0} length - [optional, default=1] The length of the returned vector.\n     */\n    normalAt(angle, length) {\n        const point = this.vertAt(angle - this.rotation); // HERE IS THE CORRECT BEHAVIOR!\n        const foci = this.getFoci();\n        // Calculate the angle between [point,focusA] and [point,focusB]\n        const angleA = new Line(point, foci[0]).angle();\n        const angleB = new Line(point, foci[1]).angle();\n        const centerAngle = angleA + (angleB - angleA) / 2.0;\n        const endPointA = point.clone().addX(50).clone().rotate(centerAngle, point);\n        const endPointB = point\n            .clone()\n            .addX(50)\n            .clone()\n            .rotate(Math.PI + centerAngle, point);\n        const resultVector = this.center.distance(endPointA) < this.center.distance(endPointB)\n            ? new Vector(point, endPointB)\n            : new Vector(point, endPointA);\n        if (typeof length === \"number\") {\n            resultVector.setLength(length);\n        }\n        return resultVector;\n    }\n    /**\n     * Get the tangent vector at the given angle.\n     * The tangent vector is the vector that touches the ellipse exactly at the given given\n     * point (speicified by the given angle).\n     *\n     * Note that the tangent is just 90 degree rotated normal vector.\n     *\n     * Length of desired tangent vector can be specified, default is 1.0.\n     *\n     * @method tangentAt\n     * @instance\n     * @memberof VEllipse\n     * @param {number} angle - The angle to get the tangent vector at.\n     * @param {number=1.0} length - [optional, default=1] The length of the returned vector.\n     */\n    tangentAt(angle, length) {\n        const normal = this.normalAt(angle, length);\n        return normal.inv().perp();\n    }\n    /**\n     * Get the perimeter of this ellipse.\n     *\n     * @method perimeter\n     * @instance\n     * @memberof VEllipse\n     * @return {number}\n     */\n    perimeter() {\n        // This method does not use an iterative approximation to determine the perimeter, but it uses\n        // a wonderful closed approximation found by Srinivasa Ramanujan.\n        // Matt Parker made a neat video about it:\n        //    https://www.youtube.com/watch?v=5nW3nJhBHL0\n        const a = this.radiusH();\n        const b = this.radiusV();\n        return Math.PI * (3 * (a + b) - Math.sqrt((3 * a + b) * (a + 3 * b)));\n    }\n    /**\n     * Get the two foci of this ellipse.\n     *\n     * @method getFoci\n     * @instance\n     * @memberof VEllipse\n     * @return {Array<Vertex>} An array with two elements, the two focal points of the ellipse (foci).\n     */\n    getFoci() {\n        // https://www.mathopenref.com/ellipsefoci.html\n        const rh = this.radiusH();\n        const rv = this.radiusV();\n        const sdiff = rh * rh - rv * rv;\n        // f is the distance of each focs to the center.\n        const f = Math.sqrt(Math.abs(sdiff));\n        // Foci on x- or y-axis?\n        if (sdiff < 0) {\n            return [\n                this.center.clone().addY(f).rotate(this.rotation, this.center),\n                this.center.clone().addY(-f).rotate(this.rotation, this.center)\n            ];\n        }\n        else {\n            return [\n                this.center.clone().addX(f).rotate(this.rotation, this.center),\n                this.center.clone().addX(-f).rotate(this.rotation, this.center)\n            ];\n        }\n    }\n    /**\n     * Get equally distributed points on the outline of this ellipse.\n     *\n     * @method getEquidistantVertices\n     * @instance\n     * @param {number} pointCount - The number of points.\n     * @returns {Array<Vertex>}\n     */\n    getEquidistantVertices(pointCount) {\n        const angles = VEllipse.utils.equidistantVertAngles(this.radiusH(), this.radiusV(), pointCount);\n        const result = [];\n        for (var i = 0; i < angles.length; i++) {\n            result.push(this.vertAt(angles[i]));\n        }\n        return result;\n    }\n    //--- BEGIN --- Implement interface `Intersectable`\n    /**\n     * Get the line intersections as vectors with this ellipse.\n     *\n     * @method lineIntersections\n     * @instance\n     * @param {VertTuple<Vector> ray - The line/ray to intersect this ellipse with.\n     * @param {boolean} inVectorBoundsOnly - (default=false) Set to true if only intersections within the vector bounds are of interest.\n     * @returns\n     */\n    lineIntersections(ray, inVectorBoundsOnly = false) {\n        // Question: what happens to extreme versions when ellipse is a line (width or height is zero)?\n        //           This would result in a Division_by_Zero exception!\n        // Step A: create clones for operations (keep originals unchanged)\n        const ellipseCopy = this.clone(); // VEllipse\n        const rayCopy = ray.clone(); // Vector\n        // Step B: move both so ellipse's center is located at (0,0)\n        const moveAmount = ellipseCopy.center.clone().inv();\n        ellipseCopy.move(moveAmount);\n        rayCopy.add(moveAmount);\n        // Step C: rotate eclipse backwards it's rotation, so that rotation is zero (0.0).\n        //         Rotate together with ray!\n        const rotationAmount = -ellipseCopy.rotation;\n        ellipseCopy.rotate(rotationAmount); // Rotation around (0,0) = center of translated ellipse\n        rayCopy.a.rotate(rotationAmount, ellipseCopy.center);\n        rayCopy.b.rotate(rotationAmount, ellipseCopy.center);\n        // Step D: find x/y factors to use for scaling to transform the ellipse to a circle.\n        //         Scale together with vector ray.\n        const radiusH = ellipseCopy.radiusH();\n        const radiusV = ellipseCopy.radiusV();\n        const scalingFactors = radiusH > radiusV ? { x: radiusV / radiusH, y: 1.0 } : { x: 1.0, y: radiusH / radiusV };\n        // Step E: scale ellipse AND ray by calculated factors.\n        ellipseCopy.axis.scaleXY(scalingFactors);\n        rayCopy.a.scaleXY(scalingFactors);\n        rayCopy.b.scaleXY(scalingFactors);\n        // Intermediate result: now the ellipse is transformed to a circle and we can calculate intersections :)\n        // Step F: calculate circle+line intersecions\n        const tmpCircle = new Circle(new Vertex(), ellipseCopy.radiusH()); // radiusH() === radiusV()\n        const intersections = tmpCircle.lineIntersections(rayCopy, inVectorBoundsOnly);\n        // Step G: transform intersecions back to original configuration\n        intersections.forEach(function (intersectionPoint) {\n            // Reverse transformation from above.\n            intersectionPoint.scaleXY({ x: 1 / scalingFactors.x, y: 1 / scalingFactors.y }, ellipseCopy.center);\n            intersectionPoint.rotate(-rotationAmount, ellipseCopy.center);\n            intersectionPoint.sub(moveAmount);\n        });\n        return intersections;\n    }\n    /**\n     * Get all line intersections of this polygon and their tangents along the shape.\n     *\n     * This method returns all intersection tangents (as vectors) with this shape. The returned array of vectors is in no specific order.\n     *\n     * @param line\n     * @param lineIntersectionTangents\n     * @returns\n     */\n    lineIntersectionTangents(line, inVectorBoundsOnly = false) {\n        // Find the intersections of all lines plus their tangents inside the circle bounds\n        const interSectionPoints = this.lineIntersections(line, inVectorBoundsOnly);\n        return interSectionPoints.map((vert) => {\n            // Calculate angle\n            const lineFromCenter = new Line(this.center, vert);\n            const angle = lineFromCenter.angle();\n            // Calculate tangent at angle\n            return this.tangentAt(angle);\n        });\n    }\n    //--- END --- Implement interface `Intersectable`\n    /**\n     * Convert this ellipse into cubic Bézier curves.\n     *\n     * @param {number=3} quarterSegmentCount - The number of segments per base elliptic quarter (default is 3, min is 1).\n     * @param {number=0.666666} threshold - The Bézier threshold (default value 0.666666 approximates the ellipse with best results\n     * but you might wish to use other values)\n     * @return {Array<CubicBezierCurve>} An array of cubic Bézier curves representing this ellipse.\n     */\n    toCubicBezier(quarterSegmentCount, threshold) {\n        // Math by Luc Maisonobe\n        //    http://www.spaceroots.org/documents/ellipse/node22.html\n        // Note that ellipses with radiusH=0 or radiusV=0 cannot be represented as Bézier curves.\n        // Return a single line here (as a Bézier curve)?\n        // if (Math.abs(this.radiusV()) < 0.00001) {\n        //   const radiusH = this.radiusH();\n        //   return [\n        //     new CubicBezierCurve(\n        //       this.center.clone().addX(radiusH),\n        //       this.center.clone().addX(-radiusH),\n        //       this.center.clone(),\n        //       this.center.clone()\n        //     )\n        //   ]; // TODO: test horizontal line ellipse\n        // }\n        // if (Math.abs(this.radiusH()) < 0.00001) {\n        //   const radiusV = this.radiusV();\n        //   return [\n        //     new CubicBezierCurve(\n        //       this.center.clone().addY(radiusV),\n        //       this.center.clone().addY(-radiusV),\n        //       this.center.clone(),\n        //       this.center.clone()\n        //     )\n        //   ]; // TODO: test vertical line ellipse\n        // }\n        // At least 4, but 16 seems to be a good value.\n        const segmentCount = Math.max(1, quarterSegmentCount || 3) * 4;\n        threshold = typeof threshold === \"undefined\" ? 0.666666 : threshold;\n        const radiusH = this.radiusH();\n        const radiusV = this.radiusV();\n        const curves = [];\n        const angles = VEllipse.utils.equidistantVertAngles(radiusH, radiusV, segmentCount);\n        let curAngle = angles[0] + this.rotation;\n        let startPoint = this.vertAt(curAngle);\n        for (var i = 0; i < angles.length; i++) {\n            let nextAngle = angles[(i + 1) % angles.length] + this.rotation;\n            let endPoint = this.vertAt(nextAngle);\n            if (Math.abs(radiusV) < 0.0001 || Math.abs(radiusH) < 0.0001) {\n                // Distorted ellipses can only be approximated by linear Bézier segments\n                let diff = startPoint.difference(endPoint);\n                let curve = new CubicBezierCurve(startPoint.clone(), endPoint.clone(), startPoint.clone().addXY(diff.x * 0.333, diff.y * 0.333), endPoint.clone().addXY(-diff.x * 0.333, -diff.y * 0.333));\n                curves.push(curve);\n            }\n            else {\n                let startTangent = this.tangentAt(curAngle + this.rotation);\n                let endTangent = this.tangentAt(nextAngle + this.rotation);\n                // Find intersection (ignore that the result might be null in some extreme cases)\n                let intersection = startTangent.intersection(endTangent);\n                // What if intersection is undefined?\n                // --> This *can* not happen if segmentCount > 2 and height and width of the ellipse are not zero.\n                let startDiff = startPoint.difference(intersection);\n                let endDiff = endPoint.difference(intersection);\n                let curve = new CubicBezierCurve(startPoint.clone(), endPoint.clone(), startPoint.clone().add(startDiff.scale(threshold)), endPoint.clone().add(endDiff.scale(threshold)));\n                curves.push(curve);\n            }\n            startPoint = endPoint;\n            curAngle = nextAngle;\n        }\n        return curves;\n    }\n    /**\n     * This function should invalidate any installed listeners and invalidate this object.\n     * After calling this function the object might not hold valid data any more and\n     * should not be used.\n     */\n    destroy() {\n        this.center.destroy();\n        this.axis.destroy();\n        this.isDestroyed = true;\n    }\n}\n/**\n * A static collection of ellipse-related helper functions.\n * @static\n */\nVEllipse.utils = {\n    /**\n     * Calculate a particular point on the outline of the given ellipse (center plus two radii plus angle).\n     *\n     * @name polarToCartesian\n     * @param {number} centerX - The x coordinate of the elliptic center.\n     * @param {number} centerY - The y coordinate of the elliptic center.\n     * @param {number} radiusH - The horizontal radius of the ellipse.\n     * @param {number} radiusV - The vertical radius of the ellipse.\n     * @param {number} angle - The angle (in radians) to get the desired outline point for.\n     * @reutn {XYCoords} The outlont point in absolute x-y-coordinates.\n     */\n    polarToCartesian: (centerX, centerY, radiusH, radiusV, angle) => {\n        // Tanks to Narasinham for the vertex-on-ellipse equations\n        // https://math.stackexchange.com/questions/22064/calculating-a-point-that-lies-on-an-ellipse-given-an-angle\n        var s = Math.sin(Math.PI / 2 - angle);\n        var c = Math.cos(Math.PI / 2 - angle);\n        return {\n            x: centerX + (radiusH * radiusV * s) / Math.sqrt(Math.pow(radiusH * c, 2) + Math.pow(radiusV * s, 2)),\n            y: centerY + (radiusH * radiusV * c) / Math.sqrt(Math.pow(radiusH * c, 2) + Math.pow(radiusV * s, 2))\n        };\n    },\n    /**\n     * Get the `theta` for a given `phi` (used to determine equidistant points on ellipse).\n     *\n     * @param radiusH\n     * @param radiusV\n     * @param phi\n     * @returns {number} theta\n     */\n    phiToTheta: (radiusH, radiusV, phi) => {\n        //  See https://math.stackexchange.com/questions/172766/calculating-equidistant-points-around-an-ellipse-arc\n        var tanPhi = Math.tan(phi);\n        var tanPhi2 = tanPhi * tanPhi;\n        var theta = -Math.PI / 2 + phi + Math.atan(((radiusH - radiusV) * tanPhi) / (radiusV + radiusH * tanPhi2));\n        return theta;\n    },\n    /**\n     * Get n equidistant points on the elliptic arc.\n     *\n     * @param pointCount\n     * @returns\n     */\n    equidistantVertAngles: (radiusH, radiusV, pointCount) => {\n        const angles = [];\n        for (var i = 0; i < pointCount; i++) {\n            var phi = Math.PI / 2.0 + ((Math.PI * 2) / pointCount) * i;\n            let theta = VEllipse.utils.phiToTheta(radiusH, radiusV, phi);\n            angles[i] = theta;\n        }\n        return angles;\n    }\n}; // END utils\n//# sourceMappingURL=VEllipse.js.map","/**\n * Implementation of elliptic sectors.\n * Note that sectors are constructed in clockwise direction.\n *\n * @author   Ikaros Kappler\n * @date     2021-02-26\n * @modified 2022-02-02 Added the `destroy` method.\n * @modified 2022-11-01 Tweaked the `endpointToCenterParameters` function to handle negative values, too, without errors.\n * @modified 2025-04-01 Adapting a the `toCubicBezier` calculation to match an underlying change in the vertAt and tangentAt calculation of ellipses (was required to hamonize both methods with circles).\n * @modified 2025-04-02 Adding `VEllipseSector.containsAngle` method.\n * @modified 2025-04-02 Adding `VEllipseSector.lineIntersections` and `VEllipseSector.lineIntersectionTangents` and implementing `Intersectable`.\n * @modified 2025-04-07 Adding value wrapping (0 to TWO_PI) to the `VEllipseSector.containsAngle` method.\n * @modified 2025-04-09 Adding the `VEllipseSector.move` method.\n * @modified 2025-04-19 Added the `VEllipseSector.getStartPoint` and `getEndPoint` methods.\n * @modified 2025-04-23 Added the `VEllipseSector.getBounds` method.\n * @version  1.2.0\n */\nimport { Bounds } from \"./Bounds\";\nimport { CubicBezierCurve } from \"./CubicBezierCurve\";\nimport { geomutils } from \"./geomutils\";\nimport { Line } from \"./Line\";\nimport { UIDGenerator } from \"./UIDGenerator\";\nimport { VEllipse } from \"./VEllipse\";\nimport { Vertex } from \"./Vertex\";\n/**\n * @classdesc A class for elliptic sectors.\n *\n * @requires Line\n * @requires Vector\n * @requires VertTuple\n * @requires Vertex\n * @requires SVGSerializale\n * @requires UID\n * @requires UIDGenerator\n **/\nexport class VEllipseSector {\n    /**\n     * Create a new elliptic sector from the given ellipse and two angles.\n     *\n     * Note that the direction from start to end goes clockwise, and that start and end angle\n     * will be wrapped to [0,PI*2).\n     *\n     * @constructor\n     * @name VEllipseSector\n     * @param {VEllipse} - The underlying ellipse to use.\n     * @param {number} startAngle - The start angle of the sector.\n     * @param {numner} endAngle - The end angle of the sector.\n     */\n    constructor(ellipse, startAngle, endAngle) {\n        /**\n         * Required to generate proper CSS classes and other class related IDs.\n         **/\n        this.className = \"VEllipseSector\";\n        this.uid = UIDGenerator.next();\n        this.ellipse = ellipse;\n        this.startAngle = geomutils.wrapMinMax(startAngle, 0, Math.PI * 2);\n        this.endAngle = geomutils.wrapMinMax(endAngle, 0, Math.PI * 2);\n    }\n    /**\n     * Move the ellipse sector by the given amount.\n     *\n     * @method move\n     * @param {XYCoords} amount - The amount to move.\n     * @instance\n     * @memberof VEllipseSector\n     * @return {VEllipseSector} this for chaining\n     **/\n    move(amount) {\n        this.ellipse.move(amount);\n        return this;\n    }\n    /**\n     * Checks wether the given angle (must be inside 0 and PI*2) is contained inside this sector.\n     *\n     * @param {number} angle - The numeric angle to check.\n     * @method containsAngle\n     * @instance\n     * @memberof VEllipseSectpr\n     * @return {boolean} True if (and only if) this sector contains the given angle.\n     */\n    containsAngle(angle) {\n        angle = geomutils.mapAngleTo2PI(angle); // wrapMinMax(angle, 0, Math.PI * 2);\n        const sAngle = geomutils.mapAngleTo2PI(this.startAngle);\n        const eAngle = geomutils.mapAngleTo2PI(this.endAngle);\n        // TODO: cleanup\n        // if (this.startAngle <= this.endAngle) {\n        //   return angle >= this.startAngle && angle < this.endAngle;\n        // } else {\n        //   // startAngle > endAngle\n        //   return angle >= this.startAngle || angle < this.endAngle;\n        // }\n        if (sAngle <= eAngle) {\n            return angle >= sAngle && angle < eAngle;\n        }\n        else {\n            // startAngle > endAngle\n            return angle >= sAngle || angle < eAngle;\n        }\n    }\n    /**\n     * Get the sectors starting point (on the underlying ellipse, located at the start angle).\n     *\n     * @method getStartPoint\n     * @instance\n     * @memberof VEllipseSector\n     * @return {Vertex} The sector's stating point.\n     */\n    getStartPoint() {\n        return this.ellipse.vertAt(this.startAngle);\n    }\n    /**\n     * Get the sectors ending point (on the underlying ellipse, located at the end angle).\n     *\n     * @method getEndPoint\n     * @instance\n     * @memberof VEllipseSector\n     * @return {Vertex} The sector's ending point.\n     */\n    getEndPoint() {\n        return this.ellipse.vertAt(this.endAngle);\n    }\n    //--- BEGIN --- Implement interface `IBounded`\n    /**\n     * Get the bounds of this elliptic sector.\n     *\n     * The bounds are approximated by the underlying segment buffer; the more segment there are,\n     * the more accurate will be the returned bounds.\n     *\n     * @method getBounds\n     * @instance\n     * @memberof VEllipse\n     * @return {Bounds} The bounds of this elliptic sector.\n     **/\n    getBounds() {\n        // Calculage angles from east, west, north and south box points and check if they are inside\n        const extremes = this.ellipse.getExtremePoints();\n        const candidates = extremes.filter(point => {\n            const angle = new Line(this.ellipse.center, point).angle() - this.ellipse.rotation;\n            return this.containsAngle(angle);\n        });\n        return Bounds.computeFromVertices([this.getStartPoint(), this.getEndPoint()].concat(candidates));\n    }\n    //--- BEGIN --- Implement interface `Intersectable`\n    /**\n     * Get the line intersections as vectors with this ellipse.\n     *\n     * @method lineIntersections\n     * @instance\n     * @memberof VEllipseSectpr\n     * @param {VertTuple<Vector>} ray - The line/ray to intersect this ellipse with.\n     * @param {boolean} inVectorBoundsOnly - (default=false) Set to true if only intersections within the vector bounds are of interest.\n     * @returns\n     */\n    lineIntersections(ray, inVectorBoundsOnly = false) {\n        // First get all line intersections from underlying ellipse.\n        const ellipseIntersections = this.ellipse.lineIntersections(ray, inVectorBoundsOnly);\n        // Drop all intersection points that are not contained in the circle sectors bounds.\n        const tmpLine = new Line(this.ellipse.center, new Vertex());\n        return ellipseIntersections.filter((intersectionPoint) => {\n            tmpLine.b.set(intersectionPoint);\n            const lineAngle = tmpLine.angle();\n            return this.containsAngle(lineAngle - this.ellipse.rotation);\n        });\n    }\n    /**\n     * Get all line intersections of this polygon and their tangents along the shape.\n     *\n     * This method returns all intersection tangents (as vectors) with this shape. The returned array of vectors is in no specific order.\n     *\n     * @method lineIntersections\n     * @memberof VEllipseSectpr\n     * @param line\n     * @param lineIntersectionTangents\n     * @returns\n     */\n    lineIntersectionTangents(line, inVectorBoundsOnly = false) {\n        // Find the intersections of all lines plus their tangents inside the circle bounds\n        const interSectionPoints = this.lineIntersections(line, inVectorBoundsOnly);\n        return interSectionPoints.map((vert) => {\n            // Calculate angle\n            const lineFromCenter = new Line(this.ellipse.center, vert);\n            const angle = lineFromCenter.angle();\n            // console.log(\"angle\", (angle / Math.PI) * 180.0);\n            // const angle = Math.random() * Math.PI * 2; // TODO\n            // Calculate tangent at angle\n            return this.ellipse.tangentAt(angle);\n        });\n    }\n    //--- END --- Implement interface `Intersectable`\n    /**\n     * Convert this elliptic sector into cubic Bézier curves.\n     *\n     * @param {number=3} quarterSegmentCount - The number of segments per base elliptic quarter (default is 3, min is 1).\n     * @param {number=0.666666} threshold - The Bézier threshold (default value 0.666666 approximates the ellipse with best results\n     * but you might wish to use other values)\n     * @return {Array<CubicBezierCurve>} An array of cubic Bézier curves representing the elliptic sector.\n     */\n    toCubicBezier(quarterSegmentCount, threshold) {\n        // There are at least 4 segments required (dour quarters) to approximate a whole\n        // ellipse with Bézier curves.\n        // A visually 'good' approximation should have 12; this seems to be a good value (anything multiple of 4).\n        const segmentCount = Math.max(1, quarterSegmentCount || 3) * 4;\n        threshold = typeof threshold === \"undefined\" ? 0.666666 : threshold;\n        const radiusH = this.ellipse.radiusH();\n        const radiusV = this.ellipse.radiusV();\n        var startAngle = VEllipseSector.ellipseSectorUtils.normalizeAngle(this.startAngle);\n        var endAngle = VEllipseSector.ellipseSectorUtils.normalizeAngle(this.endAngle);\n        // Find all angles inside start and end\n        var angles = VEllipseSector.ellipseSectorUtils.equidistantVertAngles(radiusH, radiusV, startAngle, endAngle, segmentCount);\n        angles = [startAngle].concat(angles).concat([endAngle]);\n        const curves = [];\n        let curAngle = angles[0];\n        let startPoint = this.ellipse.vertAt(curAngle);\n        for (var i = 0; i + 1 < angles.length; i++) {\n            let nextAngle = angles[(i + 1) % angles.length];\n            let endPoint = this.ellipse.vertAt(nextAngle);\n            let startTangent = this.ellipse.tangentAt(curAngle + this.ellipse.rotation);\n            let endTangent = this.ellipse.tangentAt(nextAngle + this.ellipse.rotation);\n            // Distorted ellipses can only be approximated by linear Bézier segments\n            if (Math.abs(radiusV) < 0.0001 || Math.abs(radiusH) < 0.0001) {\n                let diff = startPoint.difference(endPoint);\n                let curve = new CubicBezierCurve(startPoint.clone(), endPoint.clone(), startPoint.clone().addXY(diff.x * 0.333, diff.y * 0.333), endPoint.clone().addXY(-diff.x * 0.333, -diff.y * 0.333));\n                curves.push(curve);\n            }\n            else {\n                // Find intersection\n                let intersection = startTangent.intersection(endTangent);\n                // What if intersection is undefined?\n                // --> This *can* not happen if segmentCount > 2 and height and width of the ellipse are not zero.\n                if (intersection) {\n                    // It's VERY LIKELY hat this ALWAYS happens; it's just a typesave variant.\n                    // Intersection cannot be null.\n                    let startDiff = startPoint.difference(intersection);\n                    let endDiff = endPoint.difference(intersection);\n                    let curve = new CubicBezierCurve(startPoint.clone(), endPoint.clone(), startPoint.clone().add(startDiff.scale(threshold)), endPoint.clone().add(endDiff.scale(threshold)));\n                    curves.push(curve);\n                }\n            }\n            startPoint = endPoint;\n            curAngle = nextAngle;\n        }\n        return curves;\n    }\n    /**\n     * This function should invalidate any installed listeners and invalidate this object.\n     * After calling this function the object might not hold valid data any more and\n     * should not be used.\n     */\n    destroy() {\n        this.ellipse.destroy();\n        this.isDestroyed = true;\n    }\n}\nVEllipseSector.ellipseSectorUtils = {\n    /**\n     * Helper function to convert an elliptic section to SVG arc params (for the `d` attribute).\n     * Inspiration found at:\n     *    https://stackoverflow.com/questions/5736398/how-to-calculate-the-svg-path-for-an-arc-of-a-circle\n     *\n     * @param {boolean} options.moveToStart - If false (default=true) the initial 'Move' command will not be used.\n     * @return [ 'A', radiusH, radiusV, rotation, largeArcFlag=1|0, sweepFlag=0, endx, endy ]\n     */\n    describeSVGArc: (x, y, radiusH, radiusV, startAngle, endAngle, rotation, options) => {\n        if (typeof options === \"undefined\")\n            options = { moveToStart: true };\n        if (typeof rotation === \"undefined\")\n            rotation = 0.0;\n        // Important note: this function only works if start- and end-angle are within\n        // one whole circle [x,x+2*PI].\n        // Revelations of more than 2*PI might result in unexpected arcs.\n        // -> Use the geomutils.wrapMax( angle, 2*PI )\n        startAngle = geomutils.wrapMax(startAngle, Math.PI * 2);\n        endAngle = geomutils.wrapMax(endAngle, Math.PI * 2);\n        // Find the start- and end-point on the rotated ellipse\n        // XYCoords to Vertex (for rotation)\n        var end = new Vertex(VEllipse.utils.polarToCartesian(x, y, radiusH, radiusV, endAngle));\n        var start = new Vertex(VEllipse.utils.polarToCartesian(x, y, radiusH, radiusV, startAngle));\n        end.rotate(rotation, { x: x, y: y });\n        start.rotate(rotation, { x: x, y: y });\n        // Boolean stored as integers (0|1).\n        var diff = endAngle - startAngle;\n        var largeArcFlag;\n        if (diff < 0) {\n            largeArcFlag = Math.abs(diff) < Math.PI ? 1 : 0;\n        }\n        else {\n            largeArcFlag = Math.abs(diff) > Math.PI ? 1 : 0;\n        }\n        const sweepFlag = 1;\n        const pathData = [];\n        if (options.moveToStart) {\n            pathData.push(\"M\", start.x, start.y);\n        }\n        // Arc rotation in degrees, not radians.\n        const r2d = 180 / Math.PI;\n        pathData.push(\"A\", radiusH, radiusV, rotation * r2d, largeArcFlag, sweepFlag, end.x, end.y);\n        return pathData;\n    }, // END function describeSVGArc\n    /**\n     * Helper function to find second-kind elliptic angles, so that the euclidean distance along the the\n     * elliptic sector is the same for all.\n     *\n     * Note that this is based on the full ellipse calculuation and start and end will be cropped; so the\n     * distance from the start angle to the first angle and/or the distance from the last angle to\n     * the end angle may be different to the others.\n     *\n     * Furthermore the computation is only possible on un-rotated ellipses; if your source ellipse has\n     * a rotation on the plane please 'rotate' the result angles afterwards to find matching angles.\n     *\n     * Returned angles are normalized to the interval `[ 0, PI*2 ]`.\n     *\n     * @param {number} radiusH - The first (horizonal) radius of the ellipse.\n     * @param {number} radiusV - The second (vertical) radius of the ellipse.\n     * @param {number} startAngle - The opening angle of your elliptic sector (please use normalized angles).\n     * @param {number} endAngle - The closing angle of your elliptic sector (please use normalized angles).\n     * @param {number} fullEllipsePointCount - The number of base segments to use from the source ellipse (12 or 16 are good numbers).\n     * @return {Array<number>} An array of n angles inside startAngle and endAngle (where n <= fullEllipsePointCount).\n     */\n    equidistantVertAngles: (radiusH, radiusV, startAngle, endAngle, fullEllipsePointCount) => {\n        var ellipseAngles = VEllipse.utils.equidistantVertAngles(radiusH, radiusV, fullEllipsePointCount);\n        ellipseAngles = ellipseAngles.map((angle) => VEllipseSector.ellipseSectorUtils.normalizeAngle(angle));\n        const angleIsInRange = (angle) => {\n            if (startAngle < endAngle)\n                return angle >= startAngle && angle <= endAngle;\n            else\n                return angle >= startAngle || (angle <= endAngle && angle >= 0);\n        };\n        // Drop all angles outside the sector\n        ellipseAngles = ellipseAngles.filter(angleIsInRange);\n        // Now we need to sort the angles to the first one in the array is the closest to startAngle.\n        // --> find the angle that is closest to the start angle\n        const startIndex = VEllipseSector.ellipseSectorUtils.findClosestToStartAngle(startAngle, endAngle, ellipseAngles);\n        // Bring all angles into the correct order\n        //    Idea: use splice or slice here?\n        const angles = [];\n        for (var i = 0; i < ellipseAngles.length; i++) {\n            angles.push(ellipseAngles[(startIndex + i) % ellipseAngles.length]);\n        }\n        return angles;\n    },\n    findClosestToStartAngle: (startAngle, endAngle, ellipseAngles) => {\n        // Note: endAngle > 0 && startAngle > 0\n        if (startAngle > endAngle) {\n            const n = ellipseAngles.length;\n            for (var i = 0; i < n; i++) {\n                const ea = geomutils.wrapMinMax(ellipseAngles[i], 0, Math.PI * 2);\n                if (ea >= startAngle && ea >= endAngle) {\n                    return i;\n                }\n            }\n        }\n        return 0;\n    },\n    normalizeAngle: (angle) => (angle < 0 ? Math.PI * 2 + angle : angle),\n    /**\n     * Convert the elliptic arc from endpoint parameters to center parameters as described\n     * in the w3c svg arc implementation note.\n     *\n     * https://www.w3.org/TR/SVG/implnote.html#ArcConversionEndpointToCenter\n     *\n     * @param {number} x1 - The x component of the start point (end of last SVG command).\n     * @param {number} y1 - The y component of the start point (end of last SVG command).\n     * @param {number} rx - The first (horizontal) radius of the ellipse.\n     * @param {number} ry - The second (vertical) radius of the ellipse.\n     * @param {number} phi - The ellipse's rotational angle (angle of axis rotation) in radians (not in degrees as the SVG command uses!)\n     * @param {boolean} fa - The large-arc-flag (boolean, not 0 or 1).\n     * @param {boolean} fs - The sweep-flag (boolean, not 0 or 1).\n     * @param {number} x2 - The x component of the end point (end of last SVG command).\n     * @param {number} y2 - The y component of the end point (end of last SVG command).\n     * @returns\n     */\n    endpointToCenterParameters(x1, y1, rx, ry, phi, fa, fs, x2, y2) {\n        // console.log(\"endpointToCenterParameters\", x1, y1, phi, rx, ry, fa, fs, x2, y2);\n        // Thanks to\n        //    https://observablehq.com/@toja/ellipse-and-elliptical-arc-conversion\n        const abs = Math.abs;\n        const sin = Math.sin;\n        const cos = Math.cos;\n        const sqrt = Math.sqrt;\n        const pow = (n) => {\n            return n * n;\n        };\n        const sinphi = sin(phi);\n        const cosphi = cos(phi);\n        // Step 1: simplify through translation/rotation\n        const x = (cosphi * (x1 - x2)) / 2 + (sinphi * (y1 - y2)) / 2;\n        const y = (-sinphi * (x1 - x2)) / 2 + (cosphi * (y1 - y2)) / 2;\n        const px = pow(x), py = pow(y), prx = pow(rx), pry = pow(ry);\n        // correct of out-of-range radii\n        const L = px / prx + py / pry;\n        if (L > 1) {\n            rx = sqrt(L) * abs(rx);\n            ry = sqrt(L) * abs(ry);\n        }\n        else {\n            rx = abs(rx);\n            ry = abs(ry);\n        }\n        // Step 2 + 3: compute center\n        const sign = fa === fs ? -1 : 1;\n        // const M: number = sqrt((prx * pry - prx * py - pry * px) / (prx * py + pry * px)) * sign;\n        const M = sqrt(Math.abs((prx * pry - prx * py - pry * px) / (prx * py + pry * px))) * sign;\n        const _cx = (M * (rx * y)) / ry;\n        const _cy = (M * (-ry * x)) / rx;\n        const cx = cosphi * _cx - sinphi * _cy + (x1 + x2) / 2;\n        const cy = sinphi * _cx + cosphi * _cy + (y1 + y2) / 2;\n        // Step 4: Compute start and end angle\n        const center = new Vertex(cx, cy);\n        const axis = center.clone().addXY(rx, ry);\n        const ellipse = new VEllipse(center, axis, 0);\n        // console.log(\"VELLIPSE::::::\", ellipse);\n        ellipse.rotate(phi);\n        const startAngle = new Line(ellipse.center, new Vertex(x1, y1)).angle();\n        const endAngle = new Line(ellipse.center, new Vertex(x2, y2)).angle();\n        return new VEllipseSector(ellipse, startAngle - phi, endAngle - phi);\n    }\n}; // END ellipseSectorUtils\n//# sourceMappingURL=VEllipseSector.js.map","/**\n * @author   Ikaros Kappler\n * @date     2018-10-23\n * @modified 2018-11-19 Added multi-select and multi-drag.\n * @modified 2018-12-04 Added basic SVG export.\n * @modified 2018-12-09 Extended the constructor (canvas).\n * @modified 2018-12-18 Added the config.redrawOnResize param.\n * @modified 2018-12-18 Added the config.defaultCanvas{Width,Height} params.\n * @modified 2018-12-19 Added CSS scaling.\n * @modified 2018-12-28 Removed the unused 'drawLabel' param. Added the 'enableMouse' and 'enableKeys' params.\n * @modified 2018-12-29 Added the 'drawOrigin' param.\n * @modified 2018-12-29 Renamed the 'autoCenterOffset' param to 'autoAdjustOffset'. Added the params 'offsetAdjustXPercent' and 'offsetAdjustYPercent'.\n * @modified 2019-01-14 Added params 'drawBezierHandleLines' and 'drawBezierHandlePoints'. Added the 'redraw' praam to the add() function.\n * @modified 2019-01-16 Added params 'drawHandleLines' and 'drawHandlePoints'. Added the new params to the dat.gui interface.\n * @modified 2019-01-30 Added the 'Vector' type (extending the Line class).\n * @modified 2019-01-30 Added the 'PBImage' type (a wrapper for images).\n * @modified 2019-02-02 Added the 'canvasWidthFactor' and 'canvasHeightFactor' params.\n * @modified 2019-02-03 Removed the drawBackgroundImage() function, with had no purpose at all. Just add an image to the drawables-list.\n * @modified 2019-02-06 Vertices (instace of Vertex) can now be added. Added the 'draggable' attribute to the vertex attributes.\n * @modified 2019-02-10 Fixed a draggable-bug in PBImage handling (scaling was not possible).\n * @modified 2019-02-10 Added the 'enableTouch' option (default is true).\n * @modified 2019-02-14 Added the console for debugging (setConsole(object)).\n * @modified 2019-02-19 Added two new constants: DEFAULT_CLICK_TOLERANCE and DEFAULT_TOUCH_TOLERANCE.\n * @modified 2019-02-19 Added the second param to the locatePointNear(Vertex,Number) function.\n * @modified 2019-02-20 Removed the 'loadFile' entry from the GUI as it was experimental and never in use.\n * @modified 2019-02-23 Removed the 'rebuild' function as it had no purpose.\n * @modified 2019-02-23 Added scaling of the click-/touch-tolerance with the CSS scale.\n * @modified 2019-03-23 Added JSDoc tags. Changed the default value of config.drawOrigin to false.\n * @modified 2019-04-03 Fixed the touch-drag position detection for canvas elements that are not located at document position (0,0).\n * @modified 2019-04-03 Tweaked the fit-to-parent function to work with paddings and borders.\n * @modified 2019-04-28 Added the preClear callback param (called before the canvas was cleared on redraw and before any elements are drawn).\n * @modified 2019-09-18 Added basics for WebGL support (strictly experimental).\n * @modified 2019-10-03 Added the .beginDrawCycle call in the redraw function.\n * @modified 2019-11-06 Added fetch.num, fetch.val, fetch.bool, fetch.func functions.\n * @modified 2019-11-13 Fixed an issue with the mouse-sensitive area around vertices (were affected by zoom).\n * @modified 2019-11-13 Added the 'enableMouseWheel' param.\n * @modified 2019-11-18 Added the Triangle class as a regular drawable element.\n * @modified 2019-11-18 The add function now works with arrays, too.\n * @modified 2019-11-18 Added the _handleColor helper function to determine the render color of non-draggable vertices.\n * @modified 2019-11-19 Fixed a bug in the resizeCanvas function; retina resolution was not possible.\n * @modified 2019-12-04 Added relative positioned zooming.\n * @modified 2019-12-04 Added offsetX and offsetY params.\n * @modified 2019-12-04 Added an 'Set to fullsize retina' button to the GUI config.\n * @modified 2019-12-07 Added the drawConfig for lines, polygons, ellipse, triangles, bezier curves and image control lines.\n * @modified 2019-12-08 Fixed a css scale bug in the viewport() function.\n * @modified 2019-12-08 Added the drawconfig UI panel (line colors and line widths).\n * @modified 2020-02-06 Added handling for the end- and end-control-points of non-cirular Bézier paths (was still missing).\n * @modified 2020-02-06 Fixed a drag-amount bug in the move handling of end points of Bezier paths (control points was not properly moved when non circular).\n * @modified 2020-03-28 Ported this class from vanilla-JS to Typescript.\n * @modified 2020-03-29 Fixed the enableSVGExport flag (read enableEport before).\n * @modified 2020-05-09 Included the Cirlcle class.\n * @modified 2020-06-22 Added the rasterScaleX and rasterScaleY config params.\n * @modified 2020-06-03 Fixed the selectedVerticesOnPolyon(Polygon) function: non-selectable vertices were selected too, before.\n * @modified 2020-07-06 Replacing Touchy.js by AlloyFinger.js\n * @modified 2020-07-27 Added the getVertexNear(XYCoords,number) function\n * @modified 2020-07-27 Extended the remove(Drawable) function: vertices are now removed, too.\n * @modified 2020-07-28 Added PlotBoilerplate.revertMousePosition(number,number) –  the inverse function of transformMousePosition(...).\n * @modified 2020-07-31 Added PlotBoilerplate.getDraggedElementCount() to check wether any elements are currently being dragged.\n * @modified 2020-08-19 Added the VertexAttributes.visible attribute to make vertices invisible.\n * @modified 2020-11-17 Added pure click handling (no dragEnd and !wasMoved jiggliny any more) to the PlotBoilerplate.\n * @modified 2020-12-11 Added the `removeAll(boolean)` function.\n * @modified 2020-12-17 Added the `CircleSector` drawable.\n * @modified 2021-01-04 Avoiding multiple redraw call on adding multiple Drawables (array).\n * @modified 2021-01-08 Added param `draw:DraLib<void>` to the methods `drawVertices`, `drawGrid` and `drawSelectPolygon`.\n * @modified 2021-01-08 Added the customizable `drawAll(...)` function.\n * @modified 2021-01-09 Added the `drawDrawable(...)` function.\n * @modified 2021-01-10 Added the `eventCatcher` element (used to track mouse events on SVGs).\n * @modified 2021-01-26 Fixed SVG resizing.\n * @modified 2021-01-26 Replaced the old SVGBuilder by the new `drawutilssvg` library.\n * @modified 2021-02-08 Fixed a lot of es2015 compatibility issues.\n * @modified 2021-02-18 Adding `adjustOffset(boolean)` function.\n * @modified 2021-03-01 Updated the `PlotBoilerplate.draw(...)` function: ellipses are now rotate-able.\n * @modified 2021-03-03 Added the `VEllipseSector` drawable.\n * @modified 2021-03-29 Clearing `currentClassName` and `currentId` after drawing each drawable.\n * @modified 2021-04-25 Extending `remove` to accept arrays of drawables.\n * @modified 2021-11-16 Adding the `PBText` drawable.\n * @modified 2022-08-01 Added `title` to the params.\n * @modified 2022-10-25 Added the `origin` to the default draw config.\n * @modified 2022-11-06 Adding an XML declaration to the SVG export routine.\n * @modified 2022-11-23 Added the `drawRaster` (default=true) option to the config/drawconfig.\n * @modified 2023-02-04 Fixed a bug in the `drawDrawable` function; fill's current classname was not set.\n * @modified 2023-02-10 Fixing an issue of the `style.position` setting when `fitToParent=true` from `absolute` to `static` (default).\n * @modified 2023-02-10 Cleaning up most type errors in the main class (mostly null checks).\n * @modified 2023-02-10 Adding `enableZoom` and `enablePan` (both default true) to have the option to disable these functions.\n * @modified 2023-09-29 Adding proper dicionary key and value types to the params of `PlotBoilerplate.utils.safeMergeByKeys` (was `object` before).\n * @modified 2024-07-08 Adding `PlotBoilerplate.getGUI()` to retrieve the GUI instance.\n * @modified 2024-08-25 Extending main class `PlotBoilerplate` optional param `isBackdropFiltersEnabled`.\n * @modified 2024-12-02 Adding the `triggerRedraw` to the `removeAll` method.\n * @modified 2025-05-07 Changing the return type of `removeVertex` from `void` to `boolean`.\n * @modified 2025-05-07 Handling content changes now with `contentChangeListeners`.\n * @modified 2025-05-07 Added `PlogBoilerplate.addContentChangeListener` and `.removeContentChangeListener`.\n * @modified 2025-05-07 Moving full vectors now by default when vector point a is moved.\n * @modified 2025-05-20 Applying `lineWith` parameter in the draw routine for vectors (had been missing).\n * @modified 2026-03-13 Changed visibility of `setZoom` and `setOffset` to public. There was no good reason to have the private.\n * @modified 2026-04-04 Added `isInPanningMode` attribute and `isPanning` method.\n *\n * @version  1.22.0\n *\n * @file PlotBoilerplate\n * @fileoverview The main class.\n * @public\n **/\nvar __setFunctionName = (this && this.__setFunctionName) || function (f, name, prefix) {\n    if (typeof name === \"symbol\") name = name.description ? \"[\".concat(name.description, \"]\") : \"\";\n    return Object.defineProperty(f, \"name\", { configurable: true, value: prefix ? \"\".concat(prefix, \" \", name) : name });\n};\nvar _a;\nimport AlloyFinger from \"alloyfinger-typescript\";\nimport { drawutils } from \"./draw\";\nimport { drawutilsgl } from \"./drawgl\";\nimport { drawutilssvg } from \"./drawutilssvg\";\nimport { BezierPath } from \"./BezierPath\";\nimport { Bounds } from \"./Bounds\";\nimport { Circle } from \"./Circle\";\nimport { CircleSector } from \"./CircleSector\";\nimport { Grid } from \"./Grid\";\nimport { KeyHandler } from \"./KeyHandler\";\nimport { Line } from \"./Line\";\nimport { MouseHandler } from \"./MouseHandler\";\nimport { PBImage } from \"./PBImage\";\nimport { Polygon } from \"./Polygon\";\nimport { Triangle } from \"./Triangle\";\nimport { VEllipse } from \"./VEllipse\";\nimport { VEllipseSector } from \"./VEllipseSector\";\nimport { Vector } from \"./Vector\";\nimport { Vertex } from \"./Vertex\";\nimport { VertexAttr } from \"./VertexAttr\";\nimport { PBText } from \"./PBText\";\n/**\n * @classdesc The main class of the PlotBoilerplate.\n *\n * @requires Vertex\n * @requires Line\n * @requires Vector\n * @requires Polygon\n * @requires PBImage\n * @requires VEllipse\n * @requires Circle\n * @requires MouseHandler\n * @requires KeyHandler\n * @requires VertexAttr\n * @requires CubicBezierCurve\n * @requires BezierPath\n * @requires Drawable\n * @requires DrawConfig\n * @requires IHooks\n * @requires PBParams\n * @requires Triangle\n * @requires drawutils\n * @requires drawutilsgl\n * @requires SVGSerializable\n * @requires XYCoords\n * @requires XYDimension\n */\nexport class PlotBoilerplate {\n    /**\n     * The constructor.\n     *\n     * @constructor\n     * @name PlotBoilerplate\n     * @public\n     * @param {object} config={} - The configuration.\n     * @param {HTMLCanvasElement} config.canvas - Your canvas element in the DOM (required).\n     * @param {boolean=} [config.fullSize=true] - If set to true the canvas will gain full window size.\n     * @param {boolean=} [config.fitToParent=true] - If set to true the canvas will gain the size of its parent container (overrides fullSize).\n     * @param {number=}  [config.scaleX=1.0] - The initial x-zoom. Default is 1.0.\n     * @param {number=}  [config.scaleY=1.0] - The initial y-zoom. Default is 1.0.\n     * @param {number=}  [config.offsetX=1.0] - The initial x-offset. Default is 0.0. Note that autoAdjustOffset=true overrides these values.\n     * @param {number=}  [config.offsetY=1.0] - The initial y-offset. Default is 0.0. Note that autoAdjustOffset=true overrides these values.\n     * @param {boolean=} [config.rasterGrid=true] - If set to true the background grid will be drawn rastered.\n     * @param {boolean=} [config.rasterScaleX=1.0] - Define the default horizontal raster scale (default=1.0).\n     * @param {boolean=} [config.rasterScaleY=1.0] - Define the default vertical raster scale (default=1.0).\n     * @param {number=}  [config.rasterAdjustFactor=1.0] - The exponential limit for wrapping down the grid. (2.0 means: halve the grid each 2.0*n zoom step).\n     * @param {boolean=} [config.drawOrigin=false] - Draw a crosshair at (0,0).\n     * @param {boolean=} [config.autoAdjustOffset=true] -  When set to true then the origin of the XY plane will\n     *                         be re-adjusted automatically (see the params\n     *                         offsetAdjust{X,Y}Percent for more).\n     * @param {number=}  [config.offsetAdjustXPercent=50] - The x-fallback position for the origin after\n     *                         resizing the canvas.\n     * @param {number=}  [config.offsetAdjustYPercent=50] - The y-fallback position for the origin after\n     *                         resizing the canvas.\n     * @param {number=}  [config.defaultCanvasWidth=1024] - The canvas size fallback (width) if no automatic resizing\n     *                         is switched on.\n     * @param {number=}  [config.defaultCanvasHeight=768] - The canvas size fallback (height) if no automatic resizing\n     *                         is switched on.\n     * @param {number=}  [config.canvasWidthFactor=1.0] - Scaling factor (width) upon the canvas size.\n     *                         In combination with cssScale{X,Y} this can be used to obtain\n     *                         sub pixel resolutions for retina displays.\n     * @param {number=}  [config.canvasHeightFactor=1.0] - Scaling factor (height) upon the canvas size.\n     *                         In combination with cssScale{X,Y} this can be used to obtain\n     *                         sub pixel resolutions for retina displays.\n     * @param {number=}  [config.cssScaleX=1.0] - Visually resize the canvas (horizontally) using CSS transforms (scale).\n     * @param {number=}  [config.cssScaleY=1.0] - Visually resize the canvas (vertically) using CSS transforms (scale).\n     * @param {boolan=}  [config.cssUniformScale=true] - CSS scale x and y obtaining aspect ratio.\n     * @param {boolean=} [config.autoDetectRetina=true] - When set to true (default) the canvas will try to use the display's pixel ratio.\n     * @param {string=}  [config.backgroundColor=#ffffff] - The backround color.\n     * @param {boolean=} [config.redrawOnResize=true] - Switch auto-redrawing on resize on/off (some applications\n     *                         might want to prevent automatic redrawing to avoid data loss from the draw buffer).\n     * @param {boolean=} [config.drawBezierHandleLines=true] - Indicates if Bézier curve handles should be drawn (used for\n     *                         editors, no required in pure visualizations).\n     * @param {boolean=} [config.drawBezierHandlePoints=true] - Indicates if Bézier curve handle points should be drawn.\n     * @param {function=} [config.preClear=null] - A callback function that will be triggered just before the\n     *                         draw function clears the canvas (before anything else was drawn).\n     * @param {function=} [config.preDraw=null] - A callback function that will be triggered just before the draw\n     *                         function starts.\n     * @param {function=} [config.postDraw=null] - A callback function that will be triggered right after the drawing\n     *                         process finished.\n     * @param {boolean=} [config.enableMouse=true] - Indicates if the application should handle mouse events for you.\n     * @param {boolean=} [config.enableTouch=true] - Indicates if the application should handle touch events for you.\n     * @param {boolean=} [config.enableKeys=true] - Indicates if the application should handle key events for you.\n     * @param {boolean=} [config.enableMouseWheel=true] - Indicates if the application should handle mouse wheel events for you.\n     * @param {boolean=} [config.enablePan=true] - (default true) Set to false if you want to disable panning completely.\n     * @param {boolean=} [config.enableZoom=true] - (default true) Set to false if you want to disable zooming completely.\n     * @param {boolean=} [config.enableGL=false] - Indicates if the application should use the experimental WebGL features (not recommended).\n     * @param {boolean=} [config.enableSVGExport=true] - Indicates if the SVG export should be enabled (default is true).\n     *                                                   Note that changes from the postDraw hook might not be visible in the export.\n     * @param {string=} [config.title=null] - Specify any hover tile here. It will be attached as a `title` attribute to the most elevated element.\n     */\n    constructor(config, drawConfig) {\n        var _b, _c;\n        /**\n         * A list of content change listeners.\n         */\n        this.contentChangeListeners = [];\n        /**\n         * A discrete timestamp to identify single render cycles.\n         * Note that using system time milliseconds is not a safe way to identify render frames, as on modern powerful machines\n         * multiple frames might be rendered within each millisecond.\n         * @member {number}\n         * @memberof plotboilerplate\n         * @instance\n         * @private\n         */\n        this.renderTime = 0;\n        /**\n         * A storage variable for retrieving the GUI instance once it was created.\n         */\n        this._gui = null;\n        // This should be in some static block ...\n        VertexAttr.model = {\n            bezierAutoAdjust: false,\n            renderTime: 0,\n            selectable: true,\n            isSelected: false,\n            draggable: true,\n            visible: true\n        };\n        if (typeof config.canvas === \"undefined\") {\n            throw \"No canvas specified.\";\n        }\n        /**\n         * A global config that's attached to the dat.gui control interface.\n         *\n         * @member {Object}\n         * @memberof PlotBoilerplate\n         * @instance\n         */\n        const f = PlotBoilerplate.utils.fetch;\n        this.config = {\n            canvas: config.canvas,\n            fullSize: f.val(config, \"fullSize\", true),\n            fitToParent: f.bool(config, \"fitToParent\", true),\n            scaleX: f.num(config, \"scaleX\", 1.0),\n            scaleY: f.num(config, \"scaleY\", 1.0),\n            offsetX: f.num(config, \"offsetX\", 0.0),\n            offsetY: f.num(config, \"offsetY\", 0.0),\n            rasterGrid: f.bool(config, \"rasterGrid\", true),\n            drawRaster: f.bool(config, \"drawRaster\", true),\n            rasterScaleX: f.num(config, \"rasterScaleX\", 1.0),\n            rasterScaleY: f.num(config, \"rasterScaleY\", 1.0),\n            rasterAdjustFactor: f.num(config, \"rasterAdjustdFactror\", 2.0),\n            drawOrigin: f.bool(config, \"drawOrigin\", false),\n            autoAdjustOffset: f.val(config, \"autoAdjustOffset\", true),\n            offsetAdjustXPercent: f.num(config, \"offsetAdjustXPercent\", 50),\n            offsetAdjustYPercent: f.num(config, \"offsetAdjustYPercent\", 50),\n            backgroundColor: config.backgroundColor || \"#ffffff\",\n            redrawOnResize: f.bool(config, \"redrawOnResize\", true),\n            defaultCanvasWidth: f.num(config, \"defaultCanvasWidth\", PlotBoilerplate.DEFAULT_CANVAS_WIDTH),\n            defaultCanvasHeight: f.num(config, \"defaultCanvasHeight\", PlotBoilerplate.DEFAULT_CANVAS_HEIGHT),\n            canvasWidthFactor: f.num(config, \"canvasWidthFactor\", 1.0),\n            canvasHeightFactor: f.num(config, \"canvasHeightFactor\", 1.0),\n            cssScaleX: f.num(config, \"cssScaleX\", 1.0),\n            cssScaleY: f.num(config, \"cssScaleY\", 1.0),\n            cssUniformScale: f.bool(config, \"cssUniformScale\", true),\n            saveFile: () => {\n                _self.hooks.saveFile(_self);\n            },\n            setToRetina: () => {\n                _self._setToRetina();\n            },\n            autoDetectRetina: f.bool(config, \"autoDetectRetina\", true),\n            enableSVGExport: f.bool(config, \"enableSVGExport\", true),\n            // Listeners/observers\n            preClear: f.func(config, \"preClear\", null),\n            preDraw: f.func(config, \"preDraw\", null),\n            postDraw: f.func(config, \"postDraw\", null),\n            // Interaction\n            enableMouse: f.bool(config, \"enableMouse\", true),\n            enableTouch: f.bool(config, \"enableTouch\", true),\n            enableKeys: f.bool(config, \"enableKeys\", true),\n            enableMouseWheel: f.bool(config, \"enableMouseWheel\", true),\n            enableZoom: f.bool(config, \"enableZoom\", true), // default=true\n            enablePan: f.bool(config, \"enablePan\", true), // default=true\n            // Experimental (and unfinished)\n            enableGL: f.bool(config, \"enableGL\", false),\n            isBackdropFiltersEnabled: f.bool(config, \"isBackdropFiltersEnabled\", true)\n        }; // END confog\n        /**\n         * Configuration for drawing things.\n         *\n         * @member {Object}\n         * @memberof PlotBoilerplate\n         * @instance\n         */\n        this.drawConfig = {\n            drawVertices: true,\n            drawBezierHandleLines: f.bool(config, \"drawBezierHandleLines\", true),\n            drawBezierHandlePoints: f.bool(config, \"drawBezierHandlePoints\", true),\n            drawHandleLines: f.bool(config, \"drawHandleLines\", true),\n            drawHandlePoints: f.bool(config, \"drawHandlePoints\", true),\n            drawGrid: f.bool(config, \"drawGrid\", true),\n            drawRaster: f.bool(config, \"drawRaster\", true),\n            bezier: {\n                color: \"#00a822\",\n                lineWidth: 2,\n                handleLine: {\n                    color: \"rgba(180,180,180,0.5)\",\n                    lineWidth: 1\n                },\n                pathVertex: {\n                    color: \"#B400FF\",\n                    lineWidth: 1,\n                    fill: true\n                },\n                controlVertex: {\n                    color: \"#B8D438\",\n                    lineWidth: 1,\n                    fill: true\n                }\n            },\n            // bezierPath: {\n            //   color: \"#0022a8\",\n            //   lineWidth: 1\n            // },\n            polygon: {\n                color: \"#0022a8\",\n                lineWidth: 1\n            },\n            triangle: {\n                color: \"#6600ff\",\n                lineWidth: 1\n            },\n            ellipse: {\n                color: \"#2222a8\",\n                lineWidth: 1\n            },\n            ellipseSector: {\n                color: \"#a822a8\",\n                lineWidth: 2\n            },\n            circle: {\n                color: \"#22a8a8\",\n                lineWidth: 2\n            },\n            circleSector: {\n                color: \"#2280a8\",\n                lineWidth: 1\n            },\n            vertex: {\n                color: \"#a8a8a8\",\n                lineWidth: 1\n            },\n            selectedVertex: {\n                color: \"#c08000\",\n                lineWidth: 2\n            },\n            line: {\n                color: \"#a844a8\",\n                lineWidth: 1\n            },\n            vector: {\n                color: \"#ff44a8\",\n                lineWidth: 1\n            },\n            image: {\n                color: \"#a8a8a8\",\n                lineWidth: 1\n            },\n            text: {\n                color: \"rgba(192,0,128,0.5)\",\n                lineWidth: 1,\n                fill: true,\n                anchor: true\n            },\n            origin: {\n                color: \"#000000\"\n            }\n        }; // END drawConfig\n        // +---------------------------------------------------------------------------------\n        // | Object members.\n        // +-------------------------------\n        this.grid = new Grid(new Vertex(0, 0), new Vertex(50, 50));\n        this.canvasSize = { width: PlotBoilerplate.DEFAULT_CANVAS_WIDTH, height: PlotBoilerplate.DEFAULT_CANVAS_HEIGHT };\n        const canvasElement = typeof config.canvas === \"string\" ? document.querySelector(config.canvas) : config.canvas;\n        if (typeof canvasElement === \"undefined\") {\n            throw `Cannot initialize PlotBoilerplate with a null canvas (element \"${config.canvas} not found).`;\n        }\n        // Which renderer to use: Canvas2D, WebGL (experimental) or SVG?\n        if (canvasElement.tagName.toLowerCase() === \"canvas\") {\n            this.canvas = canvasElement;\n            this.eventCatcher = this.canvas;\n            if (this.config.enableGL && typeof drawutilsgl === \"undefined\") {\n                console.warn(`Cannot use webgl. Package was compiled without experimental gl support. Please use plotboilerplate-glsupport.min.js instead.`);\n                console.warn(`Disabling GL and falling back to Canvas2D.`);\n                this.config.enableGL = false;\n            }\n            if (this.config.enableGL) {\n                // Override the case 'null' here. If GL is not supported, well then nothing works.\n                const ctx = this.canvas.getContext(\"webgl\"); // webgl-experimental?\n                this.draw = new drawutilsgl(ctx, false);\n                // PROBLEM: same instance of fill and draw when using WebGL.\n                //          Shader program cannot be duplicated on the same context.\n                this.fill = this.draw.copyInstance(true);\n                console.warn(\"Initialized with experimental mode enableGL=true. Note that this is not yet fully implemented.\");\n            }\n            else {\n                // Override the case 'null' here. If context creation is not supported, well then nothing works.\n                const ctx = this.canvas.getContext(\"2d\");\n                this.draw = new drawutils(ctx, false);\n                this.fill = new drawutils(ctx, true);\n            }\n        }\n        else if (canvasElement.tagName.toLowerCase() === \"svg\") {\n            if (typeof drawutilssvg === \"undefined\")\n                throw `The svg draw library is not yet integrated part of PlotBoilerplate. Please include ./src/js/utils/helpers/drawutils.svg into your document.`;\n            this.canvas = canvasElement;\n            this.draw = new drawutilssvg(this.canvas, new Vertex(), // offset\n            new Vertex(), // scale\n            this.canvasSize, false, // fillShapes=false\n            this.drawConfig, false // isSecondary=false\n            );\n            this.fill = this.draw.copyInstance(true); // fillShapes=true\n            if (this.canvas.parentElement) {\n                this.eventCatcher = document.createElement(\"div\");\n                this.eventCatcher.style.position = \"absolute\";\n                this.eventCatcher.style.left = \"0\";\n                this.eventCatcher.style.top = \"0\";\n                this.eventCatcher.style.cursor = \"pointer\";\n                this.canvas.parentElement.style.position = \"relative\";\n                this.canvas.parentElement.appendChild(this.eventCatcher);\n            }\n            else {\n                this.eventCatcher = document.body;\n            }\n        }\n        else {\n            throw \"Element is neither a canvas nor an svg element.\";\n        }\n        // At this point the event cacher element is deinfed and located at highest elevation.\n        // Set `title` attribut?\n        if (config.title) {\n            this.eventCatcher.setAttribute(\"title\", config.title);\n        }\n        this.draw.scale.set((_b = this.config.scaleX) !== null && _b !== void 0 ? _b : 1.0, this.config.scaleY);\n        this.fill.scale.set((_c = this.config.scaleX) !== null && _c !== void 0 ? _c : 1.0, this.config.scaleY);\n        this.vertices = [];\n        this.selectPolygon = null;\n        this.draggedElements = [];\n        this.drawables = [];\n        this.console = console;\n        this.hooks = {\n            // This is changable from the outside\n            saveFile: PlotBoilerplate._saveFile\n        };\n        var _self = this;\n        globalThis.addEventListener(\"resize\", () => _self.resizeCanvas());\n        this.resizeCanvas();\n        if (config.autoDetectRetina) {\n            this._setToRetina();\n        }\n        this.installInputListeners();\n        // Apply the configured CSS scale.\n        this.updateCSSscale();\n        // Init\n        this.redraw();\n        // Gain focus\n        this.canvas.focus();\n    } // END constructor\n    /**\n     * This function opens a save-as file dialog and – once an output file is\n     * selected – stores the current canvas contents as an SVG image.\n     *\n     * It is the default hook for saving files and can be overwritten.\n     *\n     * @method _saveFile\n     * @instance\n     * @memberof PlotBoilerplate\n     * @return {void}\n     * @private\n     **/\n    static _saveFile(pb) {\n        // Create fake SVG node\n        const svgNode = document.createElementNS(\"http://www.w3.org/2000/svg\", \"svg\");\n        // Draw everything to fake node.\n        var tosvgDraw = new drawutilssvg(svgNode, pb.draw.offset, pb.draw.scale, pb.canvasSize, false, // fillShapes=false\n        pb.drawConfig);\n        var tosvgFill = tosvgDraw.copyInstance(true); // fillShapes=true\n        tosvgDraw.beginDrawCycle(0);\n        tosvgFill.beginDrawCycle(0);\n        if (pb.config.preClear) {\n            pb.config.preClear();\n        }\n        tosvgDraw.clear(pb.config.backgroundColor || \"white\");\n        if (pb.config.preDraw) {\n            pb.config.preDraw(tosvgDraw, tosvgFill);\n        }\n        pb.drawAll(0, tosvgDraw, tosvgFill);\n        pb.drawVertices(0, tosvgDraw);\n        if (pb.config.postDraw)\n            pb.config.postDraw(tosvgDraw, tosvgFill);\n        tosvgDraw.endDrawCycle(0);\n        tosvgFill.endDrawCycle(0);\n        // Full support in all browsers \\o/\n        //    https://caniuse.com/xml-serializer\n        var serializer = new XMLSerializer();\n        var svgCode = serializer.serializeToString(svgNode);\n        // Add: '<?xml version=\"1.0\" encoding=\"utf-8\"?>\\n' ?\n        var blob = new Blob(['<?xml version=\"1.0\" encoding=\"utf-8\"?>\\n' + svgCode], { type: \"image/svg;charset=utf-8\" });\n        // See documentation for FileSaver.js for usage.\n        //    https://github.com/eligrey/FileSaver.js\n        if (typeof globalThis[\"saveAs\"] !== \"function\") {\n            throw \"Cannot save file; did you load the ./utils/savefile helper function and the eligrey/SaveFile library?\";\n        }\n        var _saveAs = globalThis[\"saveAs\"];\n        _saveAs(blob, \"plotboilerplate.svg\");\n    }\n    /**\n     * This function sets the canvas resolution to factor 2.0 (or the preferred pixel ratio of your device) for retina displays.\n     * Please not that in non-GL mode this might result in very slow rendering as the canvas buffer size may increase.\n     *\n     * @method _setToRetina\n     * @instance\n     * @memberof PlotBoilerplate\n     * @return {void}\n     * @private\n     **/\n    _setToRetina() {\n        this.config.autoDetectRetina = true;\n        const pixelRatio = globalThis.devicePixelRatio || 1;\n        this.config.cssScaleX = this.config.cssScaleY = 1.0 / pixelRatio;\n        this.config.canvasWidthFactor = this.config.canvasHeightFactor = pixelRatio;\n        this.resizeCanvas();\n        this.updateCSSscale();\n    }\n    isPanning() {\n        return this.isInPanningMode;\n    }\n    /**\n     * Set the current zoom and draw offset to fit the given bounds.\n     *\n     * This method currently restores the aspect zoom ratio.\n     *\n     **/\n    fitToView(bounds) {\n        const canvasCenter = new Vertex(this.canvasSize.width / 2.0, this.canvasSize.height / 2.0);\n        const canvasRatio = this.canvasSize.width / this.canvasSize.height;\n        const ratio = bounds.width / bounds.height;\n        // Find the new draw offset\n        const center = new Vertex(bounds.max.x - bounds.width / 2.0, bounds.max.y - bounds.height / 2.0)\n            .inv()\n            .addXY(this.canvasSize.width / 2.0, this.canvasSize.height / 2.0);\n        this.setOffset(center);\n        if (canvasRatio < ratio) {\n            const newUniformZoom = this.canvasSize.width / bounds.width;\n            this.setZoom(newUniformZoom, newUniformZoom, canvasCenter);\n        }\n        else {\n            const newUniformZoom = this.canvasSize.height / bounds.height;\n            this.setZoom(newUniformZoom, newUniformZoom, canvasCenter);\n        }\n        this.redraw();\n    }\n    /**\n     * Set the console for this instance.\n     *\n     * @method setConsole\n     * @param {Console} con - The new console object (default is globalThis.console).\n     * @instance\n     * @memberof PlotBoilerplate\n     * @return {void}\n     **/\n    setConsole(con) {\n        this.console = con;\n    }\n    /**\n     * Update the CSS scale for the canvas depending onf the cssScale{X,Y} settings.<br>\n     * <br>\n     * This function is usually only used inernally.\n     *\n     * @method updateCSSscale\n     * @instance\n     * @memberof PlotBoilerplate\n     * @return {void}\n     * @private\n     **/\n    updateCSSscale() {\n        var _b, _c, _d, _e;\n        if (this.config.cssUniformScale) {\n            PlotBoilerplate.utils.setCSSscale(this.canvas, (_b = this.config.cssScaleX) !== null && _b !== void 0 ? _b : 1.0, (_c = this.config.cssScaleX) !== null && _c !== void 0 ? _c : 1.0);\n        }\n        else {\n            PlotBoilerplate.utils.setCSSscale(this.canvas, (_d = this.config.cssScaleX) !== null && _d !== void 0 ? _d : 1.0, (_e = this.config.cssScaleY) !== null && _e !== void 0 ? _e : 1.0);\n        }\n    }\n    /**\n     * Adds a new content change listener to this instance. Adding duplicates is not possible.\n     *\n     * @param {PBContentChangeListener} listener - The listenre to add.\n     * @method addContentChangeListener\n     * @instance\n     * @memberof PlotBoilerplate\n     * @returns {void}\n     */\n    addContentChangeListener(listener) {\n        for (var i in this.contentChangeListeners) {\n            if (this.contentChangeListeners[i] === listener) {\n                return;\n            }\n        }\n        this.contentChangeListeners.push(listener);\n    }\n    /**\n     * Removes an existing content change listener from this instance.\n     *\n     * @param {PBContentChangeListener} listener - The listenre to add.\n     * @method removeContentChangeListener\n     * @instance\n     * @memberof PlotBoilerplate\n     * @returns {void}\n     */\n    removeContentChangeListener(listener) {\n        for (var i = 0; i < this.contentChangeListeners.length; i++) {\n            if (this.contentChangeListeners[i] === listener) {\n                this.contentChangeListeners.splice(i, 1);\n                return;\n            }\n        }\n    }\n    _fireContentChanged(addedDrawables, removedDrawables) {\n        for (var i in this.contentChangeListeners) {\n            const listener = this.contentChangeListeners[i];\n            if (listener && typeof listener === \"function\") {\n                listener({\n                    type: addedDrawables.length > 0 ? \"DRAWABLES_ADDED\" : \"DRAWABLES_REMOVED\",\n                    addedDrawables: addedDrawables,\n                    removedDrawables: removedDrawables\n                });\n            }\n        }\n    }\n    /**\n     * Add a drawable object.<br>\n     * <br>\n     * This must be either:<br>\n     * <pre>\n     *  * a Vertex\n     *  * a Line\n     *  * a Vector\n     *  * a VEllipse\n     *  * a VEllipseSector\n     *  * a Circle\n     *  * a Polygon\n     *  * a Triangle\n     *  * a BezierPath\n     *  * a BPImage\n     * </pre>\n     *\n     * @param {Drawable|Drawable[]} drawable - The drawable (of one of the allowed class instance) to add.\n     * @param {boolean} [redraw=true] - If true the function will trigger redraw after the drawable(s) was/were added.\n     * @method add\n     * @instance\n     * @memberof PlotBoilerplate\n     * @return {void}\n     **/\n    add(drawable, redraw, doNotFireEvent) {\n        if (Array.isArray(drawable)) {\n            const arr = drawable;\n            for (var i = 0; i < arr.length; i++) {\n                this.add(arr[i], false, doNotFireEvent);\n            }\n            // !doNotFireEvent && this._fireContentChanged(arr, []);\n        }\n        else {\n            const addedDrawables = [drawable];\n            if (drawable instanceof Vertex) {\n                this.drawables.push(drawable);\n                this.vertices.push(drawable);\n            }\n            else if (drawable instanceof Line) {\n                // Add some lines\n                this.drawables.push(drawable);\n                this.vertices.push(drawable.a);\n                this.vertices.push(drawable.b);\n                addedDrawables.push(drawable.a, drawable.b);\n            }\n            else if (drawable instanceof Vector) {\n                this.drawables.push(drawable);\n                this.vertices.push(drawable.a);\n                this.vertices.push(drawable.b);\n                addedDrawables.push(drawable.a, drawable.b);\n                drawable.a.listeners.addDragListener((event) => {\n                    drawable.b.add(event.params.dragAmount);\n                });\n            }\n            else if (drawable instanceof VEllipse) {\n                this.vertices.push(drawable.center);\n                this.vertices.push(drawable.axis);\n                addedDrawables.push(drawable.center, drawable.axis);\n                this.drawables.push(drawable);\n                drawable.center.listeners.addDragListener((event) => {\n                    drawable.axis.add(event.params.dragAmount);\n                });\n            }\n            else if (drawable instanceof VEllipseSector) {\n                this.vertices.push(drawable.ellipse.center);\n                this.vertices.push(drawable.ellipse.axis);\n                addedDrawables.push(drawable.ellipse.center, drawable.ellipse.axis);\n                this.drawables.push(drawable);\n                drawable.ellipse.center.listeners.addDragListener((event) => {\n                    drawable.ellipse.axis.add(event.params.dragAmount);\n                });\n            }\n            else if (drawable instanceof Circle) {\n                this.vertices.push(drawable.center);\n                addedDrawables.push(drawable.center);\n                this.drawables.push(drawable);\n            }\n            else if (drawable instanceof CircleSector) {\n                this.vertices.push(drawable.circle.center);\n                addedDrawables.push(drawable.circle.center);\n                this.drawables.push(drawable);\n            }\n            else if (drawable instanceof Polygon) {\n                this.drawables.push(drawable);\n                for (var i = 0; i < drawable.vertices.length; i++) {\n                    this.vertices.push(drawable.vertices[i]);\n                    addedDrawables.push(drawable.vertices[i]);\n                }\n            }\n            else if (drawable instanceof Triangle) {\n                this.drawables.push(drawable);\n                this.vertices.push(drawable.a);\n                this.vertices.push(drawable.b);\n                this.vertices.push(drawable.c);\n                addedDrawables.push(drawable.a, drawable.b, drawable.c);\n            }\n            else if (drawable instanceof BezierPath) {\n                this.drawables.push(drawable);\n                const bezierPath = drawable;\n                for (var i = 0; i < bezierPath.bezierCurves.length; i++) {\n                    if (!drawable.adjustCircular && i == 0) {\n                        this.vertices.push(bezierPath.bezierCurves[i].startPoint);\n                        addedDrawables.push(bezierPath.bezierCurves[i].startPoint);\n                    }\n                    this.vertices.push(bezierPath.bezierCurves[i].endPoint);\n                    this.vertices.push(bezierPath.bezierCurves[i].startControlPoint);\n                    this.vertices.push(bezierPath.bezierCurves[i].endControlPoint);\n                    addedDrawables.push(bezierPath.bezierCurves[i].endPoint, bezierPath.bezierCurves[i].startControlPoint, bezierPath.bezierCurves[i].endControlPoint);\n                    bezierPath.bezierCurves[i].startControlPoint.attr.selectable = false;\n                    bezierPath.bezierCurves[i].endControlPoint.attr.selectable = false;\n                }\n                PlotBoilerplate.utils.enableBezierPathAutoAdjust(drawable);\n            }\n            else if (drawable instanceof PBImage) {\n                this.vertices.push(drawable.upperLeft);\n                this.vertices.push(drawable.lowerRight);\n                addedDrawables.push(drawable.upperLeft, drawable.lowerRight);\n                this.drawables.push(drawable);\n                // Todo: think about a IDragEvent interface\n                drawable.upperLeft.listeners.addDragListener((e) => {\n                    drawable.lowerRight.add(e.params.dragAmount);\n                });\n                drawable.lowerRight.attr.selectable = false;\n            }\n            else if (drawable instanceof PBText) {\n                this.vertices.push(drawable.anchor);\n                addedDrawables.push(drawable.anchor);\n                this.drawables.push(drawable);\n                drawable.anchor.attr.selectable = false;\n            }\n            else {\n                throw \"Cannot add drawable of unrecognized type: \" + typeof drawable + \".\";\n            }\n            !doNotFireEvent && this._fireContentChanged(addedDrawables, []);\n        }\n        // This is a workaround for backwards compatibility when the 'redraw' param was not yet present.\n        if (redraw || typeof redraw == \"undefined\") {\n            this.redraw();\n        }\n    }\n    /**\n     * Remove a drawable object.<br>\n     * <br>\n     * This must be either:<br>\n     * <pre>\n     *  * a Vertex\n     *  * a Line\n     *  * a Vector\n     *  * a VEllipse\n     *  * a Circle\n     *  * a Polygon\n     *  * a BezierPath\n     *  * a BPImage\n     *  * a Triangle\n     * </pre>\n     *\n     * @param {Drawable|Array<Drawable>} drawable - The drawable (of one of the allowed class instance) to remove.\n     * @param {boolean} [redraw=false]\n     * @param {removeWidth}\n     * @method remove\n     * @instance\n     * @memberof PlotBoilerplate\n     * @return {void}\n     **/\n    remove(drawable, redraw, removeWithVertices, doNotFireEvent) {\n        if (Array.isArray(drawable)) {\n            const removedDrawables = [];\n            for (var i = 0; i < drawable.length; i++) {\n                if (this.remove(drawable[i], false, removeWithVertices, true)) {\n                    removedDrawables.push(drawable[i]);\n                }\n            }\n            if (redraw) {\n                this.redraw();\n            }\n            !doNotFireEvent && this._fireContentChanged([], removedDrawables);\n            return removedDrawables.length > 0;\n        }\n        if (drawable instanceof Vertex) {\n            const wasRemoved = this.removeVertex(drawable, false, false);\n            if (redraw) {\n                this.redraw();\n            }\n            !doNotFireEvent && this._fireContentChanged([], [drawable]);\n            return wasRemoved;\n        }\n        let wasRemoved = false;\n        const removedDrawables = [];\n        for (var i = 0; i < this.drawables.length; i++) {\n            if (this.drawables[i] === drawable || this.drawables[i].uid === drawable.uid) {\n                this.drawables.splice(i, 1);\n                removedDrawables.push(drawable);\n                if (removeWithVertices) {\n                    // Check if some listeners need to be removed\n                    if (drawable instanceof Line) {\n                        // Add some lines\n                        this.removeVertex(drawable.a, false, true);\n                        this.removeVertex(drawable.b, false, true);\n                        removedDrawables.push(drawable.a, drawable.b);\n                    }\n                    else if (drawable instanceof Vector) {\n                        this.removeVertex(drawable.a, false, true);\n                        this.removeVertex(drawable.b, false, true);\n                        removedDrawables.push(drawable.a, drawable.b);\n                    }\n                    else if (drawable instanceof VEllipse) {\n                        this.removeVertex(drawable.center, false, true);\n                        this.removeVertex(drawable.axis, false, true);\n                        removedDrawables.push(drawable.center, drawable.axis);\n                    }\n                    else if (drawable instanceof VEllipseSector) {\n                        this.removeVertex(drawable.ellipse.center, false, true);\n                        this.removeVertex(drawable.ellipse.axis, false, true);\n                        removedDrawables.push(drawable.ellipse.center, drawable.ellipse.axis);\n                    }\n                    else if (drawable instanceof Circle) {\n                        this.removeVertex(drawable.center, false, true);\n                    }\n                    else if (drawable instanceof CircleSector) {\n                        this.removeVertex(drawable.circle.center, false, true);\n                        removedDrawables.push(drawable.circle.center);\n                    }\n                    else if (drawable instanceof Polygon) {\n                        // for( var i in drawable.vertices )\n                        for (var i = 0; i < drawable.vertices.length; i++) {\n                            this.removeVertex(drawable.vertices[i], false, true);\n                            removedDrawables.push(drawable.vertices[i]);\n                        }\n                    }\n                    else if (drawable instanceof Triangle) {\n                        this.removeVertex(drawable.a, false, true);\n                        this.removeVertex(drawable.b, false, true);\n                        this.removeVertex(drawable.c, false, true);\n                        removedDrawables.push(drawable.a, drawable.b, drawable.c);\n                    }\n                    else if (drawable instanceof BezierPath) {\n                        for (var i = 0; i < drawable.bezierCurves.length; i++) {\n                            this.removeVertex(drawable.bezierCurves[i].startPoint, false, true);\n                            this.removeVertex(drawable.bezierCurves[i].startControlPoint, false, true);\n                            this.removeVertex(drawable.bezierCurves[i].endControlPoint, false, true);\n                            removedDrawables.push(drawable.bezierCurves[i].startPoint, drawable.bezierCurves[i].startControlPoint, drawable.bezierCurves[i].endControlPoint);\n                            if (i + 1 == drawable.bezierCurves.length) {\n                                this.removeVertex(drawable.bezierCurves[i].endPoint, false, true);\n                                removedDrawables.push(drawable.bezierCurves[i].endPoint);\n                            }\n                        }\n                    }\n                    else if (drawable instanceof PBImage) {\n                        this.removeVertex(drawable.upperLeft, false, true);\n                        this.removeVertex(drawable.lowerRight, false, true);\n                        removedDrawables.push(drawable.upperLeft, drawable.lowerRight);\n                    }\n                    else if (drawable instanceof PBText) {\n                        this.removeVertex(drawable.anchor, false, true);\n                        removedDrawables.push(drawable.anchor);\n                    }\n                } // END removeWithVertices\n                if (redraw) {\n                    this.redraw();\n                }\n                !doNotFireEvent && this._fireContentChanged([], removedDrawables);\n                wasRemoved = true;\n            } // END if\n        } // END for\n        return wasRemoved;\n    }\n    /**\n     * Remove a vertex from the vertex list.<br>\n     *\n     * @param {Vertex} vert - The vertex to remove.\n     * @param {boolean} [redraw=false]\n     * @method removeVertex\n     * @instance\n     * @memberof PlotBoilerplate\n     * @return {boolean}\n     **/\n    removeVertex(vert, redraw, doNotFireEvent) {\n        for (var i = 0; i < this.vertices.length; i++) {\n            if (this.vertices[i] === vert) {\n                this.vertices.splice(i, 1);\n                if (redraw) {\n                    this.redraw();\n                }\n                !doNotFireEvent && this._fireContentChanged([], [vert]);\n                return true;\n            }\n        }\n        return false;\n    }\n    /**\n     * Remove all elements.\n     *\n     * If you want to keep the vertices, pass `true`.\n     *\n     * @method removeAll\n     * @param {boolean=false} keepVertices\n     * @param {boolean=true} triggerRedraw - By default this method triggers the redraw routine; passing `false` will suppress redrawing.\n     * @instance\n     * @memberof PlotBoilerplate\n     * @return {void}\n     */\n    removeAll(keepVertices, triggerRedraw) {\n        let removedDrawables = this.drawables;\n        this.drawables = [];\n        if (!Boolean(keepVertices)) {\n            removedDrawables = removedDrawables.concat(this.vertices);\n            this.vertices = [];\n        }\n        if (triggerRedraw || typeof triggerRedraw === \"undefined\") {\n            this.redraw();\n        }\n        removedDrawables.length > 0 && this._fireContentChanged([], removedDrawables);\n    }\n    /**\n     * Find the vertex near the given position.\n     *\n     * The position is the absolute vertex position, not the x-y-coordinates on the canvas.\n     *\n     * @param {XYCoords} position - The position of the vertex to search for.\n     * @param {number} pixelTolerance - A radius around the position to include into the search.\n     *                                  Note that the tolerance will be scaled up/down when zoomed.\n     * @return The vertex near the given position or undefined if none was found there.\n     **/\n    getVertexNear(pixelPosition, pixelTolerance) {\n        var _b, _c;\n        const p = this.locatePointNear(this.transformMousePosition(pixelPosition.x, pixelPosition.y), pixelTolerance / Math.min((_b = this.config.cssScaleX) !== null && _b !== void 0 ? _b : 1.0, (_c = this.config.cssScaleY) !== null && _c !== void 0 ? _c : 1.0));\n        if (p && p.typeName == \"vertex\") {\n            return this.vertices[p.vindex];\n        }\n        return undefined;\n    }\n    /**\n     * Draw the grid with the current config settings.<br>\n     *\n     * This function is usually only used internally.\n     *\n     * @method drawGrid\n     * @param {DrawLib} draw - The drawing library to use to draw lines.\n     * @private\n     * @instance\n     * @memberof PlotBoilerplate\n     * @return {void}\n     **/\n    drawGrid(draw) {\n        if (typeof draw === \"undefined\") {\n            draw = this.draw;\n        }\n        const gScale = {\n            x: (Grid.utils.mapRasterScale(this.config.rasterAdjustFactor, this.draw.scale.x) * this.config.rasterScaleX) /\n                this.config.cssScaleX,\n            y: (Grid.utils.mapRasterScale(this.config.rasterAdjustFactor, this.draw.scale.y) * this.config.rasterScaleY) /\n                this.config.cssScaleY\n        };\n        var gSize = { width: this.grid.size.x * gScale.x, height: this.grid.size.y * gScale.y };\n        var cs = { width: this.canvasSize.width / 2, height: this.canvasSize.height / 2 };\n        var offset = this.draw.offset.clone().inv();\n        // console.log( \"drawGrid\", gScale, gSize, cs, offset );\n        offset.x =\n            ((Math.round(offset.x + cs.width) / Math.round(gSize.width)) * gSize.width) / this.draw.scale.x +\n                (((this.draw.offset.x - cs.width) / this.draw.scale.x) % gSize.width);\n        offset.y =\n            ((Math.round(offset.y + cs.height) / Math.round(gSize.height)) * gSize.height) / this.draw.scale.y +\n                (((this.draw.offset.y - cs.height) / this.draw.scale.x) % gSize.height);\n        if (this.drawConfig.drawGrid) {\n            draw.setCurrentClassName(null);\n            if (this.config.rasterGrid) {\n                // TODO: move config member to drawConfig\n                draw.setCurrentId(\"raster\");\n                draw.raster(offset, this.canvasSize.width / this.draw.scale.x, this.canvasSize.height / this.draw.scale.y, gSize.width, gSize.height, \"rgba(0,128,255,0.125)\");\n            }\n            else {\n                draw.setCurrentId(\"grid\");\n                draw.grid(offset, this.canvasSize.width / this.draw.scale.x, this.canvasSize.height / this.draw.scale.y, gSize.width, gSize.height, \"rgba(0,128,255,0.095)\");\n            }\n        }\n    }\n    /**\n     * Draw the origin with the current config settings.<br>\n     *\n     * This function is usually only used internally.\n     *\n     * @method drawOrigin\n     * @param {DrawLib} draw - The drawing library to use to draw lines.\n     * @private\n     * @instance\n     * @memberof PlotBoilerplate\n     * @return {void}\n     **/\n    drawOrigin(draw) {\n        // Add a crosshair to mark the origin\n        draw.setCurrentId(\"origin\");\n        draw.crosshair({ x: 0, y: 0 }, 10, this.drawConfig.origin.color);\n    }\n    /**\n     * This is just a tiny helper function to determine the render color of vertices.\n     **/\n    _handleColor(h, color) {\n        return h.attr.isSelected ? this.drawConfig.selectedVertex.color : h.attr.draggable ? color : \"rgba(128,128,128,0.5)\";\n    }\n    /**\n     * Draw all drawables.\n     *\n     * This function is usually only used internally.\n     *\n     * @method drawDrawables\n     * @param {number} renderTime - The current render time. It will be used to distinct\n     *                              already draw vertices from non-draw-yet vertices.\n     * @param {DrawLib} draw - The drawing library to use to draw lines.\n     * @param {DrawLib} fill - The drawing library to use to fill areas.\n     * @instance\n     * @memberof PlotBoilerplate\n     * @return {void}\n     **/\n    drawDrawables(renderTime, draw, fill) {\n        for (var i in this.drawables) {\n            var d = this.drawables[i];\n            this.draw.setCurrentId(d.uid);\n            this.fill.setCurrentId(d.uid);\n            this.draw.setCurrentClassName(d.className);\n            this.fill.setCurrentClassName(d.className);\n            this.drawDrawable(d, renderTime, draw, fill);\n        }\n    }\n    /**\n     * Draw the given drawable.\n     *\n     * This function is usually only used internally.\n     *\n     * @method drawDrawable\n     * @param {Drawable} d - The drawable to draw.\n     * @param {number} renderTime - The current render time. It will be used to distinct\n     *                              already draw vertices from non-draw-yet vertices.\n     * @param {DrawLib} draw - The drawing library to use to draw lines.\n     * @param {DrawLib} fill - The drawing library to use to fill areas.\n     * @instance\n     * @memberof PlotBoilerplate\n     * @return {void}\n     **/\n    drawDrawable(d, renderTime, draw, fill) {\n        if (d instanceof BezierPath) {\n            var curveIndex = 0;\n            for (var c in d.bezierCurves) {\n                // Restore these settings again in each loop (will be overwritten)\n                this.draw.setCurrentId(`${d.uid}-${curveIndex}`);\n                this.fill.setCurrentId(`${d.uid}-${curveIndex}`);\n                this.draw.setCurrentClassName(d.className);\n                this.fill.setCurrentClassName(d.className);\n                draw.cubicBezier(d.bezierCurves[c].startPoint, d.bezierCurves[c].endPoint, d.bezierCurves[c].startControlPoint, d.bezierCurves[c].endControlPoint, this.drawConfig.bezier.color, this.drawConfig.bezier.lineWidth);\n                if (this.drawConfig.drawBezierHandlePoints && this.drawConfig.drawHandlePoints) {\n                    if (d.bezierCurves[c].startPoint.attr.visible) {\n                        const df = this.drawConfig.bezier.pathVertex.fill ? fill : draw;\n                        df.setCurrentId(`${d.uid}_h0`);\n                        df.setCurrentClassName(`${d.className}-start-handle`);\n                        if (d.bezierCurves[c].startPoint.attr.bezierAutoAdjust) {\n                            df.squareHandle(d.bezierCurves[c].startPoint, 5, this._handleColor(d.bezierCurves[c].startPoint, this.drawConfig.bezier.pathVertex.color));\n                        }\n                        else {\n                            df.diamondHandle(d.bezierCurves[c].startPoint, 7, this._handleColor(d.bezierCurves[c].startPoint, this.drawConfig.bezier.pathVertex.color));\n                        }\n                    }\n                    d.bezierCurves[c].startPoint.attr.renderTime = renderTime;\n                    if (d.bezierCurves[c].endPoint.attr.visible) {\n                        const df = this.drawConfig.bezier.pathVertex.fill ? fill : draw;\n                        df.setCurrentId(`${d.uid}_h0`);\n                        df.setCurrentClassName(`${d.className}-start-handle`);\n                        if (d.bezierCurves[c].endPoint.attr.bezierAutoAdjust) {\n                            df.squareHandle(d.bezierCurves[c].endPoint, 5, this._handleColor(d.bezierCurves[c].endPoint, this.drawConfig.bezier.pathVertex.color));\n                        }\n                        else {\n                            df.diamondHandle(d.bezierCurves[c].endPoint, 7, this._handleColor(d.bezierCurves[c].endPoint, this.drawConfig.bezier.pathVertex.color));\n                        }\n                    }\n                    if (d.bezierCurves[c].startControlPoint.attr.visible) {\n                        const df = this.drawConfig.bezier.controlVertex.fill ? fill : draw;\n                        df.setCurrentId(`${d.uid}_h2`);\n                        df.setCurrentClassName(`${d.className}-start-control-handle`);\n                        df.circleHandle(d.bezierCurves[c].startControlPoint, 3, this._handleColor(d.bezierCurves[c].startControlPoint, this.drawConfig.bezier.controlVertex.color));\n                    }\n                    if (d.bezierCurves[c].endControlPoint.attr.visible) {\n                        const df = this.drawConfig.bezier.controlVertex.fill ? fill : draw;\n                        df.setCurrentId(`${d.uid}_h3`);\n                        df.setCurrentClassName(`${d.className}-end-control-handle`);\n                        df.circleHandle(d.bezierCurves[c].endControlPoint, 3, this._handleColor(d.bezierCurves[c].endControlPoint, this.drawConfig.bezier.controlVertex.color));\n                    }\n                    d.bezierCurves[c].startPoint.attr.renderTime = renderTime;\n                    d.bezierCurves[c].endPoint.attr.renderTime = renderTime;\n                    d.bezierCurves[c].startControlPoint.attr.renderTime = renderTime;\n                    d.bezierCurves[c].endControlPoint.attr.renderTime = renderTime;\n                }\n                else {\n                    d.bezierCurves[c].startPoint.attr.renderTime = renderTime;\n                    d.bezierCurves[c].endPoint.attr.renderTime = renderTime;\n                    d.bezierCurves[c].startControlPoint.attr.renderTime = renderTime;\n                    d.bezierCurves[c].endControlPoint.attr.renderTime = renderTime;\n                }\n                if (this.drawConfig.drawBezierHandleLines && this.drawConfig.drawHandleLines) {\n                    draw.setCurrentId(`${d.uid}_l0`);\n                    draw.setCurrentClassName(`${d.className}-start-line`);\n                    draw.handleLine(d.bezierCurves[c].startPoint, d.bezierCurves[c].startControlPoint);\n                    draw.setCurrentId(`${d.uid}_l1`);\n                    draw.setCurrentClassName(`${d.className}-end-line`);\n                    draw.handleLine(d.bezierCurves[c].endPoint, d.bezierCurves[c].endControlPoint);\n                }\n                curveIndex++;\n            } // END for\n        }\n        else if (d instanceof Polygon) {\n            draw.polygon(d, this.drawConfig.polygon.color, this.drawConfig.polygon.lineWidth);\n            if (!this.drawConfig.drawHandlePoints) {\n                for (var i in d.vertices) {\n                    d.vertices[i].attr.renderTime = renderTime;\n                }\n            }\n        }\n        else if (d instanceof Triangle) {\n            draw.polyline([d.a, d.b, d.c], false, this.drawConfig.triangle.color, this.drawConfig.triangle.lineWidth);\n            if (!this.drawConfig.drawHandlePoints) {\n                d.a.attr.renderTime = d.b.attr.renderTime = d.c.attr.renderTime = renderTime;\n            }\n        }\n        else if (d instanceof VEllipse) {\n            if (this.drawConfig.drawHandleLines) {\n                draw.setCurrentId(`${d.uid}_e0`);\n                draw.setCurrentClassName(`${d.className}-v-line`);\n                draw.handleLine(d.center.clone().add(0, d.signedRadiusV()).rotate(d.rotation, d.center), d.axis); // , \"#c8c8c8\");\n                draw.setCurrentId(`${d.uid}_e1`);\n                draw.setCurrentClassName(`${d.className}-h-line`);\n                draw.handleLine(d.center.clone().add(d.signedRadiusH(), 0).rotate(d.rotation, d.center), d.axis); // , \"#c8c8c8\");\n            }\n            draw.setCurrentId(d.uid);\n            draw.setCurrentClassName(`${d.className}`);\n            draw.ellipse(d.center, \n            // Math.abs(d.axis.x-d.center.x), Math.abs(d.axis.y-d.center.y),\n            d.radiusH(), d.radiusV(), this.drawConfig.ellipse.color, this.drawConfig.ellipse.lineWidth, d.rotation);\n            if (!this.drawConfig.drawHandlePoints) {\n                d.center.attr.renderTime = renderTime;\n                d.axis.attr.renderTime = renderTime;\n            }\n        }\n        else if (d instanceof VEllipseSector) {\n            draw.setCurrentId(d.uid);\n            draw.setCurrentClassName(`${d.className}`);\n            const data = VEllipseSector.ellipseSectorUtils.describeSVGArc(d.ellipse.center.x, d.ellipse.center.y, d.ellipse.radiusH(), d.ellipse.radiusV(), d.startAngle, d.endAngle, d.ellipse.rotation, { moveToStart: true });\n            draw.path(data, this.drawConfig.ellipseSector.color, this.drawConfig.ellipseSector.lineWidth);\n        }\n        else if (d instanceof Circle) {\n            draw.circle(d.center, d.radius, this.drawConfig.circle.color, this.drawConfig.circle.lineWidth);\n        }\n        else if (d instanceof CircleSector) {\n            draw.circleArc(d.circle.center, d.circle.radius, d.startAngle, d.endAngle, this.drawConfig.circleSector.color, this.drawConfig.circleSector.lineWidth);\n        }\n        else if (d instanceof Vertex) {\n            if (this.drawConfig.drawVertices && (!d.attr.selectable || !d.attr.draggable) && d.attr.visible) {\n                // Draw as special point (grey)\n                draw.circleHandle(d, 7, this.drawConfig.vertex.color);\n                d.attr.renderTime = renderTime;\n            }\n        }\n        else if (d instanceof Line) {\n            draw.line(d.a, d.b, this.drawConfig.line.color, this.drawConfig.line.lineWidth);\n            if (!this.drawConfig.drawHandlePoints || !d.a.attr.selectable)\n                d.a.attr.renderTime = renderTime;\n            if (!this.drawConfig.drawHandlePoints || !d.b.attr.selectable)\n                d.b.attr.renderTime = renderTime;\n        }\n        else if (d instanceof Vector) {\n            draw.arrow(d.a, d.b, this.drawConfig.vector.color, this.drawConfig.vector.lineWidth);\n            if (this.drawConfig.drawHandlePoints && d.b.attr.selectable && d.b.attr.visible) {\n                draw.setCurrentId(`${d.uid}_h0`);\n                draw.setCurrentClassName(`${d.className}-handle`);\n                draw.circleHandle(d.b, 3, \"#a8a8a8\");\n            }\n            else {\n                d.b.attr.renderTime = renderTime;\n            }\n            if (!this.drawConfig.drawHandlePoints || !d.a.attr.selectable)\n                d.a.attr.renderTime = renderTime;\n            if (!this.drawConfig.drawHandlePoints || !d.b.attr.selectable)\n                d.b.attr.renderTime = renderTime;\n        }\n        else if (d instanceof PBImage) {\n            if (this.drawConfig.drawHandleLines) {\n                draw.setCurrentId(`${d.uid}_l0`);\n                draw.setCurrentClassName(`${d.className}-line`);\n                draw.line(d.upperLeft, d.lowerRight, this.drawConfig.image.color, this.drawConfig.image.lineWidth);\n            }\n            fill.setCurrentId(d.uid);\n            fill.image(d.image, d.upperLeft, d.lowerRight.clone().sub(d.upperLeft));\n            if (this.drawConfig.drawHandlePoints) {\n                draw.setCurrentId(`${d.uid}_h0`);\n                draw.setCurrentClassName(`${d.className}-lower-right`);\n                draw.circleHandle(d.lowerRight, 3, this.drawConfig.image.color);\n                d.lowerRight.attr.renderTime = renderTime;\n            }\n        }\n        else if (d instanceof PBText) {\n            fill.setCurrentId(d.uid);\n            fill.text(d.text, d.anchor.x, d.anchor.y, d);\n            if (this.drawConfig.text.anchor) {\n                draw.setCurrentId(`${d.uid}_a0`);\n                draw.setCurrentClassName(`${d.className}-anchor`);\n                (this.drawConfig.text.fill ? fill : draw).point(d.anchor, this.drawConfig.text.color);\n            }\n            d.anchor.attr.renderTime = renderTime;\n        }\n        else {\n            console.error(\"Cannot draw object. Unknown class.\");\n        }\n        draw.setCurrentClassName(null);\n        draw.setCurrentId(null);\n        fill.setCurrentClassName(null);\n        fill.setCurrentId(null);\n    }\n    /**\n     * Draw the select-polygon (if there is one).\n     *\n     * This function is usually only used internally.\n     *\n     * @method drawSelectPolygon\n     * @private\n     * @instance\n     * @memberof PlotBoilerplate\n     * @return {void}\n     **/\n    drawSelectPolygon(draw) {\n        // Draw select polygon?\n        if (this.selectPolygon != null && this.selectPolygon.vertices.length > 0) {\n            draw.setCurrentId(this.selectPolygon.uid);\n            draw.polygon(this.selectPolygon, \"#888888\");\n            draw.crosshair(this.selectPolygon.vertices[0], 3, \"#008888\");\n        }\n    }\n    /**\n     * Draw all vertices that were not yet drawn with the given render time.<br>\n     * <br>\n     * This function is usually only used internally.\n     *\n     * @method drawVertices\n     * @private\n     * @param {number} renderTime - The current render time. It is used to distinct\n     *                              already draw vertices from non-draw-yet vertices.\n     * @instance\n     * @memberof PlotBoilerplate\n     * @return {void}\n     **/\n    drawVertices(renderTime, draw) {\n        // Draw all vertices as small squares if they were not already drawn by other objects\n        for (var i in this.vertices) {\n            if (this.drawConfig.drawVertices && this.vertices[i].attr.renderTime != renderTime && this.vertices[i].attr.visible) {\n                draw.setCurrentId(this.vertices[i].uid);\n                draw.squareHandle(this.vertices[i], 5, this._handleColor(this.vertices[i], \"rgb(0,128,192)\"));\n                this.vertices[i].attr.renderTime = renderTime;\n            }\n        }\n    }\n    /**\n     * Trigger redrawing of all objects.<br>\n     * <br>\n     * Usually this function is automatically called when objects change.\n     *\n     * @method redraw\n     * @instance\n     * @memberof PlotBoilerplate\n     * @return {void}\n     **/\n    redraw() {\n        const renderTime = this.renderTime++;\n        // Tell the drawing library that a new drawing cycle begins (required for the GL lib).\n        this.draw.beginDrawCycle(renderTime);\n        this.fill.beginDrawCycle(renderTime);\n        if (this.config.preClear)\n            this.config.preClear();\n        this.clear();\n        if (this.config.preDraw)\n            this.config.preDraw(this.draw, this.fill);\n        this.drawAll(renderTime, this.draw, this.fill);\n        if (this.config.postDraw)\n            this.config.postDraw(this.draw, this.fill);\n        this.draw.endDrawCycle(renderTime);\n        this.fill.endDrawCycle(renderTime);\n    }\n    /**\n     * Draw all: drawables, grid, select-polygon and vertices.\n     *\n     * @method drawAll\n     * @instance\n     * @memberof PlotBoilerplate\n     * @return {void}\n     **/\n    drawAll(renderTime, draw, fill) {\n        if (this.config.drawRaster) {\n            this.drawGrid(draw);\n        }\n        if (this.config.drawOrigin) {\n            this.drawOrigin(draw);\n        }\n        this.drawDrawables(renderTime, draw, fill);\n        this.drawVertices(renderTime, draw);\n        this.drawSelectPolygon(draw);\n        // Clear IDs and classnames (postDraw hook might draw somthing and the do not want\n        // to interfered with that).\n        draw.setCurrentId(null);\n        draw.setCurrentClassName(null);\n    } // END redraw\n    /**\n     * This function clears the canvas with the configured background color.<br>\n     * <br>\n     * This function is usually only used internally.\n     *\n     * @method clear\n     * @private\n     * @instance\n     * @memberof PlotBoilerplate\n     * @return {void}\n     **/\n    clear() {\n        // Note that elements might have an alpha channel. Clear the scene first.\n        this.draw.clear(this.config.backgroundColor || \"white\");\n    }\n    /**\n     * Clear the selection.<br>\n     * <br>\n     * This function is usually only used internally.\n     *\n     * @method clearSelection\n     * @private\n     * @param {boolean=} [redraw=false] - Indicates if the redraw function should be triggered.\n     * @instance\n     * @memberof PlotBoilerplate\n     * @return {PlotBoilerplate} this\n     **/\n    clearSelection(redraw) {\n        for (var i in this.vertices)\n            this.vertices[i].attr.isSelected = false;\n        if (redraw)\n            this.redraw();\n        return this;\n    }\n    /**\n     * Get the current view port.\n     *\n     * @method viewport\n     * @instance\n     * @memberof PlotBoilerplate\n     * @return {Bounds} The current viewport.\n     **/\n    viewport() {\n        var _b, _c;\n        return new Bounds(this.transformMousePosition(0, 0), this.transformMousePosition(this.canvasSize.width * ((_b = this.config.cssScaleX) !== null && _b !== void 0 ? _b : 1.0), this.canvasSize.height * ((_c = this.config.cssScaleY) !== null && _c !== void 0 ? _c : 1.0)));\n    }\n    /**\n     * Trigger the saveFile.hook.\n     *\n     * @method saveFile\n     * @instance\n     * @memberof PlotBoilerplate\n     * @return {void}\n     **/\n    saveFile() {\n        this.hooks.saveFile(this);\n    }\n    /**\n     * Internal helper function used to get 'float' properties from elements.\n     * Used to determine border withs and paddings that were defined using CSS.\n     */\n    // TODO: this was moved to the DOM utils\n    getFProp(elem, propName) {\n        return parseFloat(globalThis.getComputedStyle(elem, null).getPropertyValue(propName));\n    }\n    /**\n     * Get the available inner space of the given container.\n     *\n     * Size minus padding minus border.\n     **/\n    // TODO: this was moved to the DOM utils\n    getAvailableContainerSpace() {\n        const container = this.canvas.parentNode; // Element | Document | DocumentFragment;\n        this.canvas.style.display = \"none\";\n        var padding = this.getFProp(container, \"padding\") || 0, border = this.getFProp(this.canvas, \"border-width\") || 0, pl = this.getFProp(container, \"padding-left\") || padding, pr = this.getFProp(container, \"padding-right\") || padding, pt = this.getFProp(container, \"padding-top\") || padding, pb = this.getFProp(container, \"padding-bottom\") || padding, bl = this.getFProp(this.canvas, \"border-left-width\") || border, br = this.getFProp(this.canvas, \"border-right-width\") || border, bt = this.getFProp(this.canvas, \"border-top-width\") || border, bb = this.getFProp(this.canvas, \"border-bottom-width\") || border;\n        var w = container.clientWidth;\n        var h = container.clientHeight;\n        this.canvas.style.display = \"block\";\n        return { width: w - pl - pr - bl - br, height: h - pt - pb - bt - bb };\n    }\n    /**\n     * This function resizes the canvas to the required settings (toggles fullscreen).<br>\n     * <br>\n     * This function is usually only used internally but feel free to call it if resizing required.\n     *\n     * @method resizeCanvas\n     * @instance\n     * @memberof PlotBoilerplate\n     * @return {void}\n     **/\n    resizeCanvas() {\n        var _b, _c, _d, _e, _f, _g;\n        const _self = this;\n        const _setSize = (w, h) => {\n            var _b, _c;\n            w *= (_b = _self.config.canvasWidthFactor) !== null && _b !== void 0 ? _b : 1.0;\n            h *= (_c = _self.config.canvasHeightFactor) !== null && _c !== void 0 ? _c : 1.0;\n            _self.canvasSize.width = w;\n            _self.canvasSize.height = h;\n            if (_self.canvas instanceof HTMLCanvasElement) {\n                _self.canvas.width = w;\n                _self.canvas.height = h;\n            }\n            else if (_self.canvas instanceof SVGElement) {\n                this.canvas.setAttribute(\"viewBox\", `0 0 ${w} ${h}`);\n                this.canvas.setAttribute(\"width\", `${w}`);\n                this.canvas.setAttribute(\"height\", `${h}`);\n                this.draw.setSize(_self.canvasSize); // No need to set size to this.fill (instance copy)\n                this.eventCatcher.style.width = `${w}px`;\n                this.eventCatcher.style.height = `${h}px`;\n            }\n            else {\n                console.error(\"Error: cannot resize canvas element because it seems neither be a HTMLCanvasElement nor an SVGElement.\");\n            }\n            if (_self.config.autoAdjustOffset) {\n                // _self.draw.offset.x = _self.fill.offset.x = _self.config.offsetX = w*(_self.config.offsetAdjustXPercent/100);\n                // _self.draw.offset.y = _self.fill.offset.y = _self.config.offsetY = h*(_self.config.offsetAdjustYPercent/100);\n                _self.adjustOffset(false);\n            }\n        };\n        if (_self.config.fullSize && !_self.config.fitToParent) {\n            // Set editor size\n            var width = globalThis.innerWidth || document.documentElement.clientWidth || document.body.clientWidth;\n            var height = globalThis.innerHeight || document.documentElement.clientHeight || document.body.clientHeight;\n            _self.canvas.style.position = \"absolute\";\n            _self.canvas.style.width = ((_b = _self.config.canvasWidthFactor) !== null && _b !== void 0 ? _b : 1.0) * width + \"px\";\n            _self.canvas.style.height = ((_c = _self.config.canvasWidthFactor) !== null && _c !== void 0 ? _c : 1.0) * height + \"px\";\n            _self.canvas.style.top = \"0px\";\n            _self.canvas.style.left = \"0px\";\n            _setSize(width, height);\n        }\n        else if (_self.config.fitToParent) {\n            // Set editor size\n            _self.canvas.style.position = \"static\";\n            const space = this.getAvailableContainerSpace();\n            _self.canvas.style.width = ((_d = _self.config.canvasWidthFactor) !== null && _d !== void 0 ? _d : 1.0) * space.width + \"px\";\n            _self.canvas.style.height = ((_e = _self.config.canvasHeightFactor) !== null && _e !== void 0 ? _e : 1.0) * space.height + \"px\";\n            _self.canvas.style.top = \"\";\n            _self.canvas.style.left = \"\";\n            _setSize(space.width, space.height);\n        }\n        else {\n            _self.canvas.style.width = \"\";\n            _self.canvas.style.height = \"\";\n            _setSize((_f = _self.config.defaultCanvasWidth) !== null && _f !== void 0 ? _f : 1024, (_g = _self.config.defaultCanvasHeight) !== null && _g !== void 0 ? _g : 768);\n        }\n        if (_self.config.redrawOnResize)\n            _self.redraw();\n    }\n    /**\n     *  Add all vertices inside the polygon to the current selection.<br>\n     *\n     * @method selectVerticesInPolygon\n     * @param {Polygon} polygon - The polygonal selection area.\n     * @instance\n     * @memberof PlotBoilerplate\n     * @return {void}\n     **/\n    selectVerticesInPolygon(polygon) {\n        for (var i in this.vertices) {\n            if (this.vertices[i].attr.selectable && polygon.containsVert(this.vertices[i]))\n                this.vertices[i].attr.isSelected = true;\n        }\n    }\n    /**\n     * (Helper) Locates the point (index) at the passed position. Using an internal tolerance of 7 pixels.\n     *\n     * The result is an object { type : 'bpath', pindex, cindex, pid }\n     *\n     * Returns false if no point is near the passed position.\n     *\n     * @method locatePointNear\n     * @param {Vertex} point - The polygonal selection area.\n     * @param {number=} [tolerance=7] - The tolerance to use identtifying vertices.\n     * @private\n     * @return {IDraggable} Or false if none found.\n     **/\n    locatePointNear(point, tolerance) {\n        const _self = this;\n        if (typeof tolerance == \"undefined\")\n            tolerance = 7;\n        // Apply the zoom (the tolerant area should not shrink or grow when zooming)\n        tolerance /= _self.draw.scale.x;\n        // Search in vertices\n        for (var vindex = 0; vindex < _self.vertices.length; vindex++) {\n            var vert = _self.vertices[vindex];\n            if ((vert.attr.draggable || vert.attr.selectable) && vert.distance(point) < tolerance) {\n                // { type : 'vertex', vindex : vindex };\n                return new PlotBoilerplate.Draggable(vert, PlotBoilerplate.Draggable.VERTEX).setVIndex(vindex);\n            }\n        }\n        return null;\n    }\n    /**\n     * Handle left-click event.<br>\n     *\n     * @method handleClick\n     * @param {number} x - The click X position on the canvas.\n     * @param {number} y - The click Y position on the canvas.\n     * @private\n     * @return {void}\n     **/\n    handleClick(e) {\n        const _self = this;\n        var point = this.locatePointNear(_self.transformMousePosition(e.params.pos.x, e.params.pos.y), PlotBoilerplate.DEFAULT_CLICK_TOLERANCE / Math.min(_self.config.cssScaleX || 1.0, _self.config.cssScaleY || 1.0));\n        if (point) {\n            _self.vertices[point.vindex].listeners.fireClickEvent(e);\n            if (this.keyHandler && this.keyHandler.isDown(\"shift\")) {\n                if (point.typeName == \"bpath\") {\n                    let vert = _self.paths[point.pindex].bezierCurves[point.cindex].getPointByID(point.pid);\n                    if (vert.attr.selectable)\n                        vert.attr.isSelected = !vert.attr.isSelected;\n                }\n                else if (point.typeName == \"vertex\") {\n                    let vert = _self.vertices[point.vindex];\n                    if (vert.attr.selectable)\n                        vert.attr.isSelected = !vert.attr.isSelected;\n                }\n                _self.redraw();\n            }\n            else if (this.keyHandler && this.keyHandler.isDown(\"y\")) {\n                _self.vertices[point.vindex].attr.bezierAutoAdjust = !_self.vertices[point.vindex].attr.bezierAutoAdjust;\n                _self.redraw();\n            }\n        }\n        else if (_self.selectPolygon != null) {\n            const vert = _self.transformMousePosition(e.params.pos.x, e.params.pos.y);\n            _self.selectPolygon.vertices.push(new Vertex(vert.x, vert.y));\n            _self.redraw();\n        }\n    }\n    /**\n     * Transforms the given x-y-(mouse-)point to coordinates respecting the view offset\n     * and the zoom settings.\n     *\n     * @method transformMousePosition\n     * @param {number} x - The x position relative to the canvas.\n     * @param {number} y - The y position relative to the canvas.\n     * @instance\n     * @memberof PlotBoilerplate\n     * @return {XYCoords} A simple object <pre>{ x : Number, y : Number }</pre> with the transformed coordinates.\n     **/\n    transformMousePosition(x, y) {\n        return {\n            x: (x / this.config.cssScaleX - this.config.offsetX) / this.config.scaleX,\n            y: (y / this.config.cssScaleY - this.config.offsetY) / this.config.scaleY\n        };\n    }\n    /**\n     * Revert a transformed mouse position back to canvas coordinates.\n     *\n     * This is the inverse function of `transformMousePosition`.\n     *\n     * @method revertMousePosition\n     * @param {number} x - The x component of the position to revert.\n     * @param {number} y - The y component of the position to revert.\n     * @instance\n     * @memberof PlotBoilerplate\n     * @return {XYCoords} The canvas coordinates for the given position.\n     **/\n    revertMousePosition(x, y) {\n        return { x: x / this.config.cssScaleX + this.config.offsetX, y: y / this.config.cssScaleY + this.config.offsetY };\n    }\n    /**\n     * Determine if any elements are currently being dragged (on mouse move or touch move).\n     *\n     * @method getDraggedElementCount\n     * @instance\n     * @memberof PlotBoilerplate\n     * @return {number} The number of elements that are currently being dragged.\n     **/\n    getDraggedElementCount() {\n        return this.draggedElements.length;\n    }\n    /**\n     * (Helper) The mouse-down handler.\n     *\n     * It selects vertices for dragging.\n     *\n     * @method mouseDownHandler.\n     * @param {XMouseEvent} e - The event to handle\n     * @private\n     * @return {void}\n     **/\n    mouseDownHandler(e) {\n        const _self = this;\n        if (e.button != 0)\n            return; // Only react on left mouse or touch events\n        var draggablePoint = _self.locatePointNear(_self.transformMousePosition(e.params.pos.x, e.params.pos.y), PlotBoilerplate.DEFAULT_CLICK_TOLERANCE / Math.min(_self.config.cssScaleX, _self.config.cssScaleY));\n        if (!draggablePoint)\n            return;\n        // Drag all selected elements?\n        if (draggablePoint.typeName == \"vertex\" && _self.vertices[draggablePoint.vindex].attr.isSelected) {\n            // Multi drag\n            // for( var i in _self.vertices ) {\n            for (var i = 0; i < _self.vertices.length; i++) {\n                if (_self.vertices[i].attr.isSelected) {\n                    _self.draggedElements.push(new PlotBoilerplate.Draggable(_self.vertices[i], PlotBoilerplate.Draggable.VERTEX).setVIndex(i));\n                    _self.vertices[i].listeners.fireDragStartEvent(e);\n                }\n            }\n        }\n        else {\n            // Single drag\n            if (!_self.vertices[draggablePoint.vindex].attr.draggable)\n                return;\n            _self.draggedElements.push(draggablePoint);\n            if (draggablePoint.typeName == \"bpath\")\n                _self.paths[draggablePoint.pindex].bezierCurves[draggablePoint.cindex]\n                    .getPointByID(draggablePoint.pid)\n                    .listeners.fireDragStartEvent(e);\n            else if (draggablePoint.typeName == \"vertex\")\n                _self.vertices[draggablePoint.vindex].listeners.fireDragStartEvent(e);\n        }\n        _self.redraw();\n    }\n    /**\n     * The mouse-drag handler.\n     *\n     * It moves selected elements around or performs the panning if the ctrl-key if\n     * hold down.\n     *\n     * @method mouseDragHandler.\n     * @param {XMouseEvent} e - The event to handle\n     * @private\n     * @return {void}\n     **/\n    mouseDragHandler(e) {\n        const _self = this;\n        const oldDragAmount = { x: e.params.dragAmount.x, y: e.params.dragAmount.y };\n        e.params.dragAmount.x /= _self.config.cssScaleX;\n        e.params.dragAmount.y /= _self.config.cssScaleY;\n        // Important note to: this.keyHandler.isDown('ctrl')\n        //    We should not use this for any input.\n        //    Reason: most browsers use [Ctrl]+[t] to create new browser tabs.\n        //            If so, the key-up event for [Ctrl] will be fired in the _new tab_,\n        //            not this one. So this tab will never receive any [Ctrl-down] events\n        //            until next keypress; the implication is, that [Ctrl] would still\n        //            considered to be pressed which is not true.\n        // if (this.keyHandler && (this.keyHandler.isDown(\"alt\") || this.keyHandler.isDown(\"spacebar\"))) {\n        if (this.isInPanningMode) {\n            if (!this.config.enablePan) {\n                return;\n            }\n            _self.setOffset(_self.draw.offset.clone().add(e.params.dragAmount));\n            _self.redraw();\n        }\n        else {\n            // Convert drag amount by scaling\n            // Warning: this possibly invalidates the dragEvent for other listeners!\n            //          Rethink the solution when other features are added.\n            e.params.dragAmount.x /= _self.draw.scale.x;\n            e.params.dragAmount.y /= _self.draw.scale.y;\n            for (var i in _self.draggedElements) {\n                var p = _self.draggedElements[i];\n                if (p.typeName == \"bpath\") {\n                    _self.paths[p.pindex].moveCurvePoint(p.cindex, p.pid, new Vertex(e.params.dragAmount.x, e.params.dragAmount.y));\n                    _self.paths[p.pindex].bezierCurves[p.cindex].getPointByID(p.pid).listeners.fireDragEvent(e);\n                }\n                else if (p.typeName == \"vertex\") {\n                    if (!_self.vertices[p.vindex].attr.draggable)\n                        continue;\n                    _self.vertices[p.vindex].add(e.params.dragAmount);\n                    _self.vertices[p.vindex].listeners.fireDragEvent(e);\n                }\n            }\n        }\n        // Restore old event values!\n        e.params.dragAmount.x = oldDragAmount.x;\n        e.params.dragAmount.y = oldDragAmount.y;\n        _self.redraw();\n    }\n    /**\n     * The mouse-up handler.\n     *\n     * It clears the dragging-selection.\n     *\n     * @method mouseUpHandler.\n     * @param {XMouseEvent} e - The event to handle\n     * @private\n     * @return {void}\n     **/\n    mouseUpHandler(e) {\n        const _self = this;\n        if (e.button != 0)\n            return; // Only react on left mouse;\n        if (!e.params.wasDragged) {\n            _self.handleClick(e); // e.params.pos.x, e.params.pos.y );\n        }\n        for (var i in _self.draggedElements) {\n            var p = _self.draggedElements[i];\n            if (p.typeName == \"bpath\") {\n                _self.paths[p.pindex].bezierCurves[p.cindex].getPointByID(p.pid).listeners.fireDragEndEvent(e);\n            }\n            else if (p.typeName == \"vertex\") {\n                _self.vertices[p.vindex].listeners.fireDragEndEvent(e);\n            }\n        }\n        _self.draggedElements = [];\n        _self.redraw();\n    }\n    /**\n     * The mouse-wheel handler.\n     *\n     * It performs the zooming.\n     *\n     * @method mouseWheelHandler.\n     * @param {XMouseEvent} e - The event to handle\n     * @private\n     * @return {void}\n     **/\n    mouseWheelHandler(e) {\n        if (!this.config.enableZoom) {\n            return;\n        }\n        var zoomStep = 1.25; // Make configurable?\n        // CHANGED replaced _self by this\n        const _self = this;\n        const we = e;\n        if (we.deltaY < 0) {\n            _self.setZoom(_self.config.scaleX * zoomStep, _self.config.scaleY * zoomStep, new Vertex(e.params.pos.x, e.params.pos.y));\n        }\n        else if (we.deltaY > 0) {\n            _self.setZoom(_self.config.scaleX / zoomStep, _self.config.scaleY / zoomStep, new Vertex(e.params.pos.x, e.params.pos.y));\n        }\n        e.preventDefault();\n        _self.redraw();\n    }\n    /**\n     * Re-adjust the configured offset depending on the current canvas size and zoom (scaleX and scaleY).\n     *\n     * @method adjustOffset\n     * @param {boolean=false} redraw - [optional] If set the canvas will redraw with the new offset (default=false).\n     * @return {void}\n     **/\n    adjustOffset(redraw) {\n        this.draw.offset.x =\n            this.fill.offset.x =\n                this.config.offsetX =\n                    this.canvasSize.width * (this.config.offsetAdjustXPercent / 100);\n        this.draw.offset.y =\n            this.fill.offset.y =\n                this.config.offsetY =\n                    this.canvasSize.height * (this.config.offsetAdjustYPercent / 100);\n        if (redraw) {\n            this.redraw();\n        }\n    }\n    /**\n     * Set the new draw offset.\n     *\n     * Note: the function will not trigger any redraws.\n     *\n     * @param {Vertex} newOffset - The new draw offset to use.\n     **/\n    setOffset(newOffset) {\n        this.draw.offset.set(newOffset);\n        this.fill.offset.set(newOffset);\n        this.config.offsetX = newOffset.x;\n        this.config.offsetY = newOffset.y;\n    }\n    /**\n     * Set a new zoom value (and re-adjust the draw offset).\n     *\n     * Note: the function will not trigger any redraws.\n     *\n     * @param {number} zoomFactorX - The new horizontal zoom value.\n     * @param {number} zoomFactorY - The new vertical zoom value.\n     * @param {Vertex} interactionPos - The position of mouse/touch interaction.\n     **/\n    setZoom(zoomFactorX, zoomFactorY, interactionPos) {\n        let oldPos = this.transformMousePosition(interactionPos.x, interactionPos.y);\n        this.draw.scale.x = this.fill.scale.x = this.config.scaleX = Math.max(zoomFactorX, 0.01);\n        this.draw.scale.y = this.fill.scale.y = this.config.scaleY = Math.max(zoomFactorY, 0.01);\n        let newPos = this.transformMousePosition(interactionPos.x, interactionPos.y);\n        let newOffsetX = this.draw.offset.x + (newPos.x - oldPos.x) * this.draw.scale.x;\n        let newOffsetY = this.draw.offset.y + (newPos.y - oldPos.y) * this.draw.scale.y;\n        this.setOffset({ x: newOffsetX, y: newOffsetY });\n    }\n    installInputListeners() {\n        var _self = this;\n        if (this.config.enableMouse) {\n            // Install a mouse handler on the canvas.\n            new MouseHandler(this.eventCatcher ? this.eventCatcher : this.canvas)\n                .down((e) => {\n                _self.mouseDownHandler(e);\n            })\n                .drag((e) => {\n                _self.mouseDragHandler(e);\n            })\n                .up((e) => {\n                _self.mouseUpHandler(e);\n            });\n        }\n        else {\n            _self.console.log(\"Mouse interaction disabled.\");\n        }\n        if (this.config.enableMouseWheel) {\n            // Install a mouse handler on the canvas.\n            new MouseHandler(this.eventCatcher ? this.eventCatcher : this.canvas).wheel((e) => {\n                _self.mouseWheelHandler(e);\n            });\n        }\n        else {\n            _self.console.log(\"Mouse wheel interaction disabled.\");\n        }\n        if (this.config.enableTouch) {\n            // Install a touch handler on the canvas.\n            const relPos = (pos) => {\n                const bounds = _self.canvas.getBoundingClientRect();\n                return { x: pos.x - bounds.left, y: pos.y - bounds.top };\n            };\n            // Make PB work together with both, AlloyFinger as a esm module or a commonjs function.\n            if (typeof globalThis[\"AlloyFinger\"] === \"function\" ||\n                typeof globalThis[\"createAlloyFinger\"] === \"function\") {\n                try {\n                    var touchMovePos = null;\n                    var touchDownPos = null;\n                    var draggedElement = null;\n                    var multiTouchStartScale = null;\n                    const clearTouch = () => {\n                        touchMovePos = null;\n                        touchDownPos = null;\n                        draggedElement = null;\n                        multiTouchStartScale = null;\n                        _self.draggedElements = [];\n                    };\n                    const afProps = {\n                        // touchStart: (evt: TouchEvent) => {\n                        touchStart: (evt) => {\n                            if (evt.touches.length == 1) {\n                                touchMovePos = new Vertex(relPos({ x: evt.touches[0].clientX, y: evt.touches[0].clientY }));\n                                touchDownPos = new Vertex(relPos({ x: evt.touches[0].clientX, y: evt.touches[0].clientY }));\n                                draggedElement = _self.locatePointNear(_self.transformMousePosition(touchMovePos.x, touchMovePos.y), PlotBoilerplate.DEFAULT_TOUCH_TOLERANCE / Math.min(_self.config.cssScaleX, _self.config.cssScaleY));\n                                if (draggedElement && draggedElement.typeName == \"vertex\") {\n                                    var draggingVertex = _self.vertices[draggedElement.vindex];\n                                    var fakeEvent = {\n                                        params: {\n                                            isTouchEvent: true,\n                                            dragAmount: { x: 0, y: 0 },\n                                            wasDragged: false,\n                                            mouseDownPos: touchDownPos.clone(),\n                                            mouseDragPos: touchDownPos.clone(),\n                                            vertex: draggingVertex\n                                        }\n                                    };\n                                    _self.draggedElements = [draggedElement];\n                                    draggingVertex.listeners.fireDragStartEvent(fakeEvent);\n                                }\n                            }\n                        },\n                        touchMove: (evt) => {\n                            if (evt.touches.length == 1 && draggedElement) {\n                                evt.preventDefault();\n                                evt.stopPropagation();\n                                if (!touchDownPos || !touchMovePos) {\n                                    return;\n                                }\n                                var rel = relPos({ x: evt.touches[0].clientX, y: evt.touches[0].clientY });\n                                var trans = _self.transformMousePosition(rel.x, rel.y);\n                                var diff = new Vertex(_self.transformMousePosition(touchMovePos.x, touchMovePos.y)).difference(trans);\n                                if (draggedElement.typeName == \"vertex\") {\n                                    if (!_self.vertices[draggedElement.vindex].attr.draggable)\n                                        return;\n                                    _self.vertices[draggedElement.vindex].add(diff);\n                                    var draggingVertex = _self.vertices[draggedElement.vindex];\n                                    var fakeEvent = {\n                                        isTouchEvent: true,\n                                        params: {\n                                            dragAmount: diff.clone(),\n                                            wasDragged: true,\n                                            mouseDownPos: touchDownPos.clone(),\n                                            mouseDragPos: touchDownPos.clone().add(diff),\n                                            vertex: draggingVertex\n                                        }\n                                    };\n                                    draggingVertex.listeners.fireDragEvent(fakeEvent);\n                                    _self.redraw();\n                                }\n                                touchMovePos = new Vertex(rel);\n                            }\n                            else if (evt.touches.length == 2) {\n                                if (!this.config.enablePan) {\n                                    return;\n                                }\n                                // If at least two fingers touch and move, then change the draw offset (panning).\n                                evt.preventDefault();\n                                evt.stopPropagation();\n                                _self.setOffset(_self.draw.offset\n                                    .clone()\n                                    .addXY(evt.deltaX, evt.deltaY)); // Apply zoom?\n                                _self.redraw();\n                            }\n                        },\n                        touchEnd: (evt) => {\n                            // Note: e.touches.length is 0 here\n                            if (draggedElement && draggedElement.typeName == \"vertex\") {\n                                if (!touchDownPos) {\n                                    return;\n                                }\n                                var draggingVertex = _self.vertices[draggedElement.vindex];\n                                var fakeEvent = {\n                                    isTouchEvent: true,\n                                    params: {\n                                        dragAmount: { x: 0, y: 0 },\n                                        wasDragged: false,\n                                        mouseDownPos: touchDownPos.clone(),\n                                        mouseDragPos: touchDownPos.clone(),\n                                        vertex: draggingVertex\n                                    }\n                                };\n                                // Check if vertex was moved\n                                if (touchMovePos && touchDownPos && touchDownPos.distance(touchMovePos) < 0.001) {\n                                    // if( e.touches.length == 1 && diff.x == 0 && diff.y == 0 ) {\n                                    draggingVertex.listeners.fireClickEvent(fakeEvent);\n                                }\n                                else {\n                                    draggingVertex.listeners.fireDragEndEvent(fakeEvent);\n                                }\n                            }\n                            clearTouch();\n                        },\n                        touchCancel: (evt) => {\n                            clearTouch();\n                        },\n                        multipointStart: (evt) => {\n                            multiTouchStartScale = _self.draw.scale.clone();\n                        },\n                        multipointEnd: (evt) => {\n                            multiTouchStartScale = null;\n                        },\n                        pinch: (evt) => {\n                            if (!this.config.enableZoom) {\n                                return;\n                            }\n                            const touchItem0 = evt.touches.item(0);\n                            const touchItem1 = evt.touches.item(1);\n                            if (!evt.touches || !multiTouchStartScale || !touchItem0 || !touchItem1) {\n                                return;\n                            }\n                            // For pinching there must be at least two touch items\n                            const fingerA = new Vertex(touchItem0.clientX, touchItem0.clientY);\n                            const fingerB = new Vertex(touchItem1.clientX, touchItem1.clientY);\n                            const center = new Line(fingerA, fingerB).vertAt(0.5);\n                            _self.setZoom(multiTouchStartScale.x * evt.zoom, multiTouchStartScale.y * evt.zoom, center);\n                            _self.redraw();\n                        }\n                    }; // END afProps\n                    if (window[\"createAlloyFinger\"]) {\n                        // window[\"createAlloyFinger\"](this.eventCatcher ? this.eventCatcher : this.canvas, afProps);\n                        const createAlloyFinger = window[\"createAlloyFinger\"];\n                        createAlloyFinger(this.eventCatcher ? this.eventCatcher : this.canvas, afProps);\n                    }\n                    else {\n                        /* tslint:disable-next-line */\n                        new AlloyFinger(this.eventCatcher ? this.eventCatcher : this.canvas, afProps);\n                    }\n                }\n                catch (e) {\n                    console.error(\"Failed to initialize AlloyFinger!\");\n                    console.error(e);\n                }\n            }\n            else if (globalThis[\"Touchy\"] && typeof globalThis[\"Touchy\"] == \"function\") {\n                console.error(\"[Deprecation] Found Touchy which is not supported any more. Please use AlloyFinger instead.\");\n                // Convert absolute touch positions to relative DOM element position (relative to canvas)\n            }\n            else {\n                console.warn(\"Cannot initialize the touch handler. AlloyFinger is missig. Did you include it?\");\n            }\n        }\n        else {\n            _self.console.log(\"Touch interaction disabled.\");\n        }\n        if (this.config.enableKeys) {\n            // Install key handler\n            this.keyHandler = new KeyHandler({ trackAll: true })\n                .down(\"escape\", function () {\n                _self.clearSelection(true);\n            })\n                .down(\"shift\", function () {\n                _self.selectPolygon = new Polygon();\n                _self.redraw();\n            })\n                .up(\"shift\", function () {\n                // Find and select vertices in the drawn area\n                if (_self.selectPolygon == null)\n                    return;\n                _self.selectVerticesInPolygon(_self.selectPolygon);\n                _self.selectPolygon = null;\n                _self.redraw();\n            })\n                .down(\"alt\", function () {\n                _self.isInPanningMode = true;\n            })\n                .up(\"alt\", function () {\n                _self.isInPanningMode = false;\n            })\n                .down(\"spacebar\", function () {\n                _self.isInPanningMode = true;\n            })\n                .up(\"spacebar\", function () {\n                _self.isInPanningMode = false;\n            });\n        } // END IF enableKeys?\n        else {\n            _self.console.log(\"Keyboard interaction disabled.\");\n        }\n    }\n    /**\n     * Creates a control GUI (a dat.gui instance) for this\n     * plot boilerplate instance.\n     *\n     * @method createGUI\n     * @instance\n     * @memberof PlotBoilerplate\n     * @return {dat.gui.GUI}\n     **/\n    createGUI(props) {\n        // This function moved to the helper utils.\n        // We do not want to include the whole dat.GUI package.\n        const utils = globalThis[\"utils\"];\n        // if (globalThis[\"utils\"] && typeof globalThis[\"utils\"].createGUI == \"function\") {\n        //   return (globalThis[\"utils\" as keyof Object] as any as ({createGUI : (pb:PlotBoilerplate,props:DatGuiProps|undefined)=>GUI })).createGUI(this, props);\n        if (utils && typeof utils.createGUI === \"function\") {\n            return (this._gui = utils.createGUI(this, props));\n        }\n        else {\n            throw \"Cannot create dat.GUI or lil-gui instance; did you load the ./utils/creategui helper function an the dat.GUI/lil-gui library?\";\n        }\n    }\n    /**\n     * Retriebe the GUI once it was created. If the `createGUI` method was not called or failed to create any\n     * GUI then null is returned.\n     * @returns {GUI | null}\n     */\n    getGUI() {\n        return this._gui;\n    }\n} // END class PlotBoilerplate\n/** @constant {number} */\nPlotBoilerplate.DEFAULT_CANVAS_WIDTH = 1024;\n/** @constant {number} */\nPlotBoilerplate.DEFAULT_CANVAS_HEIGHT = 768;\n/** @constant {number} */\nPlotBoilerplate.DEFAULT_CLICK_TOLERANCE = 8;\n/** @constant {number} */\nPlotBoilerplate.DEFAULT_TOUCH_TOLERANCE = 32;\n/**\n * A wrapper class for draggable items (mostly vertices).\n * @private\n **/\nPlotBoilerplate.Draggable = (_a = class {\n        constructor(item, typeName) {\n            this.item = item;\n            this.typeName = typeName;\n        }\n        isVertex() {\n            return this.typeName == PlotBoilerplate.Draggable.VERTEX;\n        }\n        setVIndex(vindex) {\n            this.vindex = vindex;\n            return this;\n        }\n    },\n    __setFunctionName(_a, \"Draggable\"),\n    _a.VERTEX = \"vertex\",\n    _a);\n/**\n * A set of helper functions.\n **/\nPlotBoilerplate.utils = {\n    /**\n     * Merge the elements in the 'extension' object into the 'base' object based on\n     * the keys of 'base'.\n     *\n     * @param {Object} base\n     * @param {Object} extension\n     * @return {Object} base extended by the new attributes.\n     **/\n    safeMergeByKeys: (base, extension) => {\n        for (var k in extension) {\n            if (!extension.hasOwnProperty(k)) {\n                continue;\n            }\n            if (base.hasOwnProperty(k)) {\n                const typ = typeof base[k];\n                const extVal = extension[k];\n                try {\n                    if (typ == \"boolean\") {\n                        if (typeof extVal === \"string\")\n                            base[k] = Boolean(!!JSON.parse(extVal));\n                        else\n                            base[k] = extVal;\n                    }\n                    else if (typ == \"number\") {\n                        if (typeof extVal === \"string\")\n                            base[k] = Number(JSON.parse(extVal) * 1);\n                        else\n                            base[k] = extension[k];\n                    }\n                    else if (typ == \"function\" && typeof extVal == \"function\") {\n                        base[k] = extension[k];\n                    }\n                    else {\n                        // Probably a sting\n                        base[k] = extension[k];\n                    }\n                }\n                catch (e) {\n                    console.error(\"error in key \", k, extVal, e);\n                }\n            }\n            else {\n                base[k] = extension[k];\n            }\n        }\n        return base;\n    },\n    /*\n    __safeMergeByKeys: <KeyType extends string | number | symbol, ValueType extends boolean | number | string | Function>(\n      base: Record<KeyType, ValueType>,\n      extension: Record<KeyType, string>\n    ): Record<KeyType, ValueType> => {\n      for (var k in extension) {\n        if (!extension.hasOwnProperty(k)) continue;\n        if (base.hasOwnProperty(k)) {\n          var typ = typeof base[k];\n          try {\n            if (typ == \"boolean\") base[k] = !!JSON.parse(extension[k]);\n            else if (typ == \"number\") base[k] = JSON.parse(extension[k]) * 1;\n            else if (typ == \"function\" && typeof extension[k] == \"function\") base[k] = extension[k];\n            else base[k] = extension[k];\n          } catch (e) {\n            console.error(\"error in key \", k, extension[k], e);\n          }\n        } else {\n          base[k] = extension[k];\n        }\n      }\n      return base;\n    },\n    *()\n\n    /**\n     * A helper function to scale elements (usually the canvas) using CSS.\n     *\n     * transform-origin is at (0,0).\n     *\n     * @param {HTMLElement} element - The DOM element to scale.\n     * @param {number} scaleX The - X scale factor.\n     * @param {number} scaleY The - Y scale factor.\n     * @return {void}\n     **/\n    setCSSscale: (element, scaleX, scaleY) => {\n        // element.style[\"transform-origin\"] = \"0 0\";\n        element.style.transformOrigin = \"0 0\";\n        if (scaleX == 1.0 && scaleY == 1.0) {\n            // element.style.transform = null;\n            element.style.removeProperty(\"transform\");\n        }\n        else\n            element.style.transform = \"scale(\" + scaleX + \",\" + scaleY + \")\";\n    },\n    // A helper for fetching data from objects.\n    fetch: {\n        /**\n         * A helper function to the the object property value specified by the given key.\n         *\n         * @param {any} object   - The object to get the property's value from. Must not be null.\n         * @param {string} key      - The key of the object property (the name).\n         * @param {any}    fallback - A default value if the key does not exist.\n         **/\n        val: (obj, key, fallback) => {\n            if (!obj.hasOwnProperty(key))\n                return fallback;\n            if (typeof obj[key] == \"undefined\")\n                return fallback;\n            return obj[key];\n        },\n        /**\n         * A helper function to the the object property numeric value specified by the given key.\n         *\n         * @param {any}    object   - The object to get the property's value from. Must not be null.\n         * @param {string} key      - The key of the object property (the name).\n         * @param {number} fallback - A default value if the key does not exist.\n         * @return {number}\n         **/\n        num: (obj, key, fallback) => {\n            if (!obj.hasOwnProperty(key))\n                return fallback;\n            if (typeof obj[key] === \"number\")\n                return obj[key];\n            else {\n                try {\n                    return JSON.parse(obj[key]) * 1;\n                }\n                catch (e) {\n                    return fallback;\n                }\n            }\n        },\n        /**\n         * A helper function to the the object property boolean value specified by the given key.\n         *\n         * @param {any}     object   - The object to get the property's value from. Must not be null.\n         * @param {string}  key      - The key of the object property (the name).\n         * @param {boolean} fallback - A default value if the key does not exist.\n         * @return {boolean}\n         **/\n        bool: (obj, key, fallback) => {\n            if (!obj.hasOwnProperty(key))\n                return fallback;\n            if (typeof obj[key] == \"boolean\")\n                return obj[key];\n            else {\n                try {\n                    return !!JSON.parse(obj[key]);\n                }\n                catch (e) {\n                    return fallback;\n                }\n            }\n        },\n        /**\n         * A helper function to the the object property function-value specified by the given key.\n         *\n         * @param {any}      object   - The object to get the property's value from. Must not be null.\n         * @param {string}   key      - The key of the object property (the name).\n         * @param {function} fallback - A default value if the key does not exist.\n         * @return {function}\n         **/\n        func: (obj, key, fallback) => {\n            if (!obj.hasOwnProperty(key))\n                return fallback;\n            if (typeof obj[key] !== \"function\")\n                return fallback;\n            return obj[key];\n        }\n    }, // END fetch\n    /**\n     * Installs vertex listeners to the path's vertices so that controlpoints\n     * move with their path points when dragged.\n     *\n     * Bézier path points with attr.bezierAutoAdjust==true will have their\n     * two control points audo-updated if moved, too (keep path connections smooth).\n     *\n     * @param {BezierPath} bezierPath - The path to use auto-adjustment for.\n     **/\n    enableBezierPathAutoAdjust: (bezierPath) => {\n        for (var i = 0; i < bezierPath.bezierCurves.length; i++) {\n            // This should be wrapped into the BezierPath implementation.\n            bezierPath.bezierCurves[i].startPoint.listeners.addDragListener(function (e) {\n                var cindex = bezierPath.locateCurveByStartPoint(e.params.vertex);\n                bezierPath.bezierCurves[cindex].startPoint.addXY(-e.params.dragAmount.x, -e.params.dragAmount.y);\n                bezierPath.moveCurvePoint(cindex * 1, bezierPath.START_POINT, e.params.dragAmount);\n                bezierPath.updateArcLengths();\n            });\n            bezierPath.bezierCurves[i].startControlPoint.listeners.addDragListener(function (e) {\n                var cindex = bezierPath.locateCurveByStartControlPoint(e.params.vertex);\n                if (!bezierPath.bezierCurves[cindex].startPoint.attr.bezierAutoAdjust)\n                    return;\n                bezierPath.adjustPredecessorControlPoint(cindex * 1, true, // obtain handle length?\n                false // update arc lengths\n                );\n                bezierPath.updateArcLengths();\n            });\n            bezierPath.bezierCurves[i].endControlPoint.listeners.addDragListener(function (e) {\n                var cindex = bezierPath.locateCurveByEndControlPoint(e.params.vertex);\n                if (!bezierPath.bezierCurves[cindex % bezierPath.bezierCurves.length].endPoint.attr.bezierAutoAdjust)\n                    return;\n                bezierPath.adjustSuccessorControlPoint(cindex * 1, true, // obtain handle length?\n                false // update arc lengths\n                );\n                bezierPath.updateArcLengths();\n            });\n            if (i + 1 == bezierPath.bezierCurves.length) {\n                // && !bezierPath.adjustCircular ) {\n                // Move last control point with the end point (if not circular)\n                bezierPath.bezierCurves[bezierPath.bezierCurves.length - 1].endPoint.listeners.addDragListener(function (e) {\n                    if (!bezierPath.adjustCircular) {\n                        var cindex = bezierPath.locateCurveByEndPoint(e.params.vertex);\n                        bezierPath.moveCurvePoint(cindex * 1, bezierPath.END_CONTROL_POINT, new Vertex({ x: e.params.dragAmount.x, y: e.params.dragAmount.y }));\n                    }\n                    bezierPath.updateArcLengths();\n                });\n            }\n        } // END for\n    }\n}; // END utils\nexport default PlotBoilerplate;\n//# sourceMappingURL=PlotBoilerplate.js.map","/**\n * Generate regular polygons (N-Gons) and stars (N-Stars).\n *\n * @author   Ikaros Kappler\n * @date     2023-11-24 (plain Javascript)\n * @modified 2024-01-29 Ported to Typescript.\n * @version 1.0.0\n */\nimport { Polygon } from \"../Polygon\";\nimport { Vertex } from \"../Vertex\";\nexport const NGons = {\n    ngon: (n, radius) => {\n        const center = new Vertex(0, 0);\n        const verts = [];\n        for (var i = 0; i < n; i++) {\n            var vert = new Vertex(radius, 0);\n            vert.rotate(((Math.PI * 2) / n) * i, center);\n            verts.push(vert);\n        }\n        return new Polygon(verts);\n    },\n    nstar: (n, radiusA, radiusB) => {\n        const center = new Vertex(0, 0);\n        const verts = [];\n        for (var i = 0; i < n; i++) {\n            var vert = new Vertex(i % 2 === 0 ? radiusA : radiusB, 0);\n            vert.rotate(((Math.PI * 2) / n) * i, center);\n            verts.push(vert);\n        }\n        return new Polygon(verts);\n    }\n};\n//# sourceMappingURL=NGons.js.map","/*\n * A speed-improved perlin and simplex noise algorithms for 2D.\n *\n * Based on example code by Stefan Gustavson (stegu@itn.liu.se).\n * Optimisations by Peter Eastman (peastman@drizzle.stanford.edu).\n * Better rank ordering method by Stefan Gustavson in 2012.\n * Converted to Javascript by Joseph Gentle.\n *\n * Version 2012-03-09\n *\n * This code was placed in the public domain by its original author,\n * Stefan Gustavson. You may use it as you see fit, but\n * attribution is appreciated.\n *\n * @modified 2023-03-07 Ikaros Kappler; ported to Typescript & refactored to class.\n * @modified 2025-11-12 Ikaros Kappler; moved from a different project `floatsim` and refactored the class.\n */\nclass Grad {\n    constructor(x, y, z) {\n        this.x = x;\n        this.y = y;\n        this.z = z;\n    }\n    dot2(x, y) {\n        return this.x * x + this.y * y;\n    }\n    dot3(x, y, z) {\n        return this.x * x + this.y * y + this.z * z;\n    }\n}\nconst grad3 = [\n    new Grad(1, 1, 0),\n    new Grad(-1, 1, 0),\n    new Grad(1, -1, 0),\n    new Grad(-1, -1, 0),\n    new Grad(1, 0, 1),\n    new Grad(-1, 0, 1),\n    new Grad(1, 0, -1),\n    new Grad(-1, 0, -1),\n    new Grad(0, 1, 1),\n    new Grad(0, -1, 1),\n    new Grad(0, 1, -1),\n    new Grad(0, -1, -1)\n];\nconst p = [\n    151, 160, 137, 91, 90, 15, 131, 13, 201, 95, 96, 53, 194, 233, 7, 225, 140, 36, 103, 30, 69, 142, 8, 99, 37, 240, 21, 10, 23,\n    190, 6, 148, 247, 120, 234, 75, 0, 26, 197, 62, 94, 252, 219, 203, 117, 35, 11, 32, 57, 177, 33, 88, 237, 149, 56, 87, 174, 20,\n    125, 136, 171, 168, 68, 175, 74, 165, 71, 134, 139, 48, 27, 166, 77, 146, 158, 231, 83, 111, 229, 122, 60, 211, 133, 230, 220,\n    105, 92, 41, 55, 46, 245, 40, 244, 102, 143, 54, 65, 25, 63, 161, 1, 216, 80, 73, 209, 76, 132, 187, 208, 89, 18, 169, 200, 196,\n    135, 130, 116, 188, 159, 86, 164, 100, 109, 198, 173, 186, 3, 64, 52, 217, 226, 250, 124, 123, 5, 202, 38, 147, 118, 126, 255,\n    82, 85, 212, 207, 206, 59, 227, 47, 16, 58, 17, 182, 189, 28, 42, 223, 183, 170, 213, 119, 248, 152, 2, 44, 154, 163, 70, 221,\n    153, 101, 155, 167, 43, 172, 9, 129, 22, 39, 253, 19, 98, 108, 110, 79, 113, 224, 232, 178, 185, 112, 104, 218, 246, 97, 228,\n    251, 34, 242, 193, 238, 210, 144, 12, 191, 179, 162, 241, 81, 51, 145, 235, 249, 14, 239, 107, 49, 192, 214, 31, 181, 199, 106,\n    157, 184, 84, 204, 176, 115, 121, 50, 45, 127, 4, 150, 254, 138, 236, 205, 93, 222, 114, 67, 29, 24, 72, 243, 141, 128, 195, 78,\n    66, 215, 61, 156, 180\n];\n// To remove the need for index wrapping, double the permutation table length\n// const perm = new Array<number>(512);\n// const gradP = new Array<Grad>(512);\n// Skewing and unskewing factors for 2, 3, and 4 dimensions\nconst F2 = 0.5 * (Math.sqrt(3) - 1);\nconst G2 = (3 - Math.sqrt(3)) / 6;\nconst F3 = 1 / 3;\nconst G3 = 1 / 6;\nconst fade = (t) => {\n    return t * t * t * (t * (t * 6 - 15) + 10);\n};\nconst lerp = (a, b, t) => {\n    return (1 - t) * a + t * b;\n};\n// export const noise = {\nexport class PerlinNoise {\n    constructor() {\n        // To remove the need for index wrapping, double the permutation table length\n        this.perm = new Array(512);\n        this.gradP = new Array(512);\n        // Use initial seed.\n        this.seed(0);\n    }\n    // This isn't a very good seeding function, but it works ok. It supports 2^16\n    // different seed values. Write something better if you need more seeds.\n    //   module.seed = function (seed) {\n    seed(seed) {\n        if (seed > 0 && seed < 1) {\n            // Scale the seed out\n            seed *= 65536;\n        }\n        seed = Math.floor(seed);\n        if (seed < 256) {\n            seed |= seed << 8;\n        }\n        for (var i = 0; i < 256; i++) {\n            var v;\n            if (i & 1) {\n                v = p[i] ^ (seed & 255);\n            }\n            else {\n                v = p[i] ^ ((seed >> 8) & 255);\n            }\n            this.perm[i] = this.perm[i + 256] = v;\n            this.gradP[i] = this.gradP[i + 256] = grad3[v % 12];\n        }\n        return this;\n    }\n    // 2D simplex noise\n    simplex2(xin, yin) {\n        var n0, n1, n2; // Noise contributions from the three corners\n        // Skew the input space to determine which simplex cell we're in\n        const s = (xin + yin) * F2; // Hairy factor for 2D\n        var i = Math.floor(xin + s);\n        var j = Math.floor(yin + s);\n        const t = (i + j) * G2;\n        const x0 = xin - i + t; // The x,y distances from the cell origin, unskewed.\n        const y0 = yin - j + t;\n        // For the 2D case, the simplex shape is an equilateral triangle.\n        // Determine which simplex we are in.\n        var i1, j1; // Offsets for second (middle) corner of simplex in (i,j) coords\n        if (x0 > y0) {\n            // lower triangle, XY order: (0,0)->(1,0)->(1,1)\n            i1 = 1;\n            j1 = 0;\n        }\n        else {\n            // upper triangle, YX order: (0,0)->(0,1)->(1,1)\n            i1 = 0;\n            j1 = 1;\n        }\n        // A step of (1,0) in (i,j) means a step of (1-c,-c) in (x,y), and\n        // a step of (0,1) in (i,j) means a step of (-c,1-c) in (x,y), where\n        // c = (3-sqrt(3))/6\n        const x1 = x0 - i1 + G2; // Offsets for middle corner in (x,y) unskewed coords\n        const y1 = y0 - j1 + G2;\n        const x2 = x0 - 1 + 2 * G2; // Offsets for last corner in (x,y) unskewed coords\n        const y2 = y0 - 1 + 2 * G2;\n        // Work out the hashed gradient indices of the three simplex corners\n        i &= 255;\n        j &= 255;\n        const gi0 = this.gradP[i + this.perm[j]];\n        const gi1 = this.gradP[i + i1 + this.perm[j + j1]];\n        const gi2 = this.gradP[i + 1 + this.perm[j + 1]];\n        // Calculate the contribution from the three corners\n        var t0 = 0.5 - x0 * x0 - y0 * y0;\n        if (t0 < 0) {\n            n0 = 0;\n        }\n        else {\n            t0 *= t0;\n            n0 = t0 * t0 * gi0.dot2(x0, y0); // (x,y) of grad3 used for 2D gradient\n        }\n        var t1 = 0.5 - x1 * x1 - y1 * y1;\n        if (t1 < 0) {\n            n1 = 0;\n        }\n        else {\n            t1 *= t1;\n            n1 = t1 * t1 * gi1.dot2(x1, y1);\n        }\n        var t2 = 0.5 - x2 * x2 - y2 * y2;\n        if (t2 < 0) {\n            n2 = 0;\n        }\n        else {\n            t2 *= t2;\n            n2 = t2 * t2 * gi2.dot2(x2, y2);\n        }\n        // Add contributions from each corner to get the final noise value.\n        // The result is scaled to return values in the interval [-1,1].\n        return 70 * (n0 + n1 + n2);\n    }\n    // 3D simplex noise\n    simplex3(xin, yin, zin) {\n        var n0, n1, n2, n3; // Noise contributions from the four corners\n        // Skew the input space to determine which simplex cell we're in\n        const s = (xin + yin + zin) * F3; // Hairy factor for 2D\n        var i = Math.floor(xin + s);\n        var j = Math.floor(yin + s);\n        var k = Math.floor(zin + s);\n        const t = (i + j + k) * G3;\n        const x0 = xin - i + t; // The x,y distances from the cell origin, unskewed.\n        const y0 = yin - j + t;\n        const z0 = zin - k + t;\n        // For the 3D case, the simplex shape is a slightly irregular tetrahedron.\n        // Determine which simplex we are in.\n        var i1, j1, k1; // Offsets for second corner of simplex in (i,j,k) coords\n        var i2, j2, k2; // Offsets for third corner of simplex in (i,j,k) coords\n        if (x0 >= y0) {\n            if (y0 >= z0) {\n                i1 = 1;\n                j1 = 0;\n                k1 = 0;\n                i2 = 1;\n                j2 = 1;\n                k2 = 0;\n            }\n            else if (x0 >= z0) {\n                i1 = 1;\n                j1 = 0;\n                k1 = 0;\n                i2 = 1;\n                j2 = 0;\n                k2 = 1;\n            }\n            else {\n                i1 = 0;\n                j1 = 0;\n                k1 = 1;\n                i2 = 1;\n                j2 = 0;\n                k2 = 1;\n            }\n        }\n        else {\n            if (y0 < z0) {\n                i1 = 0;\n                j1 = 0;\n                k1 = 1;\n                i2 = 0;\n                j2 = 1;\n                k2 = 1;\n            }\n            else if (x0 < z0) {\n                i1 = 0;\n                j1 = 1;\n                k1 = 0;\n                i2 = 0;\n                j2 = 1;\n                k2 = 1;\n            }\n            else {\n                i1 = 0;\n                j1 = 1;\n                k1 = 0;\n                i2 = 1;\n                j2 = 1;\n                k2 = 0;\n            }\n        }\n        // A step of (1,0,0) in (i,j,k) means a step of (1-c,-c,-c) in (x,y,z),\n        // a step of (0,1,0) in (i,j,k) means a step of (-c,1-c,-c) in (x,y,z), and\n        // a step of (0,0,1) in (i,j,k) means a step of (-c,-c,1-c) in (x,y,z), where\n        // c = 1/6.\n        const x1 = x0 - i1 + G3; // Offsets for second corner\n        const y1 = y0 - j1 + G3;\n        const z1 = z0 - k1 + G3;\n        const x2 = x0 - i2 + 2 * G3; // Offsets for third corner\n        const y2 = y0 - j2 + 2 * G3;\n        const z2 = z0 - k2 + 2 * G3;\n        const x3 = x0 - 1 + 3 * G3; // Offsets for fourth corner\n        const y3 = y0 - 1 + 3 * G3;\n        const z3 = z0 - 1 + 3 * G3;\n        // Work out the hashed gradient indices of the four simplex corners\n        i &= 255;\n        j &= 255;\n        k &= 255;\n        const gi0 = this.gradP[i + this.perm[j + this.perm[k]]];\n        const gi1 = this.gradP[i + i1 + this.perm[j + j1 + this.perm[k + k1]]];\n        const gi2 = this.gradP[i + i2 + this.perm[j + j2 + this.perm[k + k2]]];\n        const gi3 = this.gradP[i + 1 + this.perm[j + 1 + this.perm[k + 1]]];\n        // Calculate the contribution from the four corners\n        var t0 = 0.5 - x0 * x0 - y0 * y0 - z0 * z0;\n        if (t0 < 0) {\n            n0 = 0;\n        }\n        else {\n            t0 *= t0;\n            n0 = t0 * t0 * gi0.dot3(x0, y0, z0); // (x,y) of grad3 used for 2D gradient\n        }\n        var t1 = 0.5 - x1 * x1 - y1 * y1 - z1 * z1;\n        if (t1 < 0) {\n            n1 = 0;\n        }\n        else {\n            t1 *= t1;\n            n1 = t1 * t1 * gi1.dot3(x1, y1, z1);\n        }\n        var t2 = 0.5 - x2 * x2 - y2 * y2 - z2 * z2;\n        if (t2 < 0) {\n            n2 = 0;\n        }\n        else {\n            t2 *= t2;\n            n2 = t2 * t2 * gi2.dot3(x2, y2, z2);\n        }\n        var t3 = 0.5 - x3 * x3 - y3 * y3 - z3 * z3;\n        if (t3 < 0) {\n            n3 = 0;\n        }\n        else {\n            t3 *= t3;\n            n3 = t3 * t3 * gi3.dot3(x3, y3, z3);\n        }\n        // Add contributions from each corner to get the final noise value.\n        // The result is scaled to return values in the interval [-1,1].\n        return 32 * (n0 + n1 + n2 + n3);\n    }\n    // 2D Perlin Noise\n    perlin2(x_init, y_init) {\n        // Find unit grid cell containing point\n        var X = Math.floor(x_init), Y = Math.floor(y_init);\n        // Get relative xy coordinates of point within that cell\n        const x = x_init - X;\n        const y = y_init - Y;\n        // Wrap the integer cells at 255 (smaller integer period can be introduced here)\n        X = X & 255;\n        Y = Y & 255;\n        // Calculate noise contributions from each of the four corners\n        const n00 = this.gradP[X + this.perm[Y]].dot2(x, y);\n        const n01 = this.gradP[X + this.perm[Y + 1]].dot2(x, y - 1);\n        const n10 = this.gradP[X + 1 + this.perm[Y]].dot2(x - 1, y);\n        const n11 = this.gradP[X + 1 + this.perm[Y + 1]].dot2(x - 1, y - 1);\n        // Compute the fade curve value for x\n        const u = fade(x);\n        // Interpolate the four results\n        return lerp(lerp(n00, n10, u), lerp(n01, n11, u), fade(y));\n    }\n    // 3D Perlin Noise\n    perlin3(x_init, y_init, z_init) {\n        // Find unit grid cell containing point\n        var X = Math.floor(x_init), Y = Math.floor(y_init), Z = Math.floor(z_init);\n        // Get relative xyz coordinates of point within that cell\n        const x = x_init - X;\n        const y = y_init - Y;\n        const z = z_init - Z;\n        // Wrap the integer cells at 255 (smaller integer period can be introduced here)\n        X = X & 255;\n        Y = Y & 255;\n        Z = Z & 255;\n        // Calculate noise contributions from each of the eight corners\n        const n000 = this.gradP[X + this.perm[Y + this.perm[Z]]].dot3(x, y, z);\n        const n001 = this.gradP[X + this.perm[Y + this.perm[Z + 1]]].dot3(x, y, z - 1);\n        const n010 = this.gradP[X + this.perm[Y + 1 + this.perm[Z]]].dot3(x, y - 1, z);\n        const n011 = this.gradP[X + this.perm[Y + 1 + this.perm[Z + 1]]].dot3(x, y - 1, z - 1);\n        const n100 = this.gradP[X + 1 + this.perm[Y + this.perm[Z]]].dot3(x - 1, y, z);\n        const n101 = this.gradP[X + 1 + this.perm[Y + this.perm[Z + 1]]].dot3(x - 1, y, z - 1);\n        const n110 = this.gradP[X + 1 + this.perm[Y + 1 + this.perm[Z]]].dot3(x - 1, y - 1, z);\n        const n111 = this.gradP[X + 1 + this.perm[Y + 1 + this.perm[Z + 1]]].dot3(x - 1, y - 1, z - 1);\n        // Compute the fade curve value for x, y, z\n        const u = fade(x);\n        const v = fade(y);\n        const w = fade(z);\n        // Interpolate\n        return lerp(lerp(lerp(n000, n100, u), lerp(n001, n101, u), w), lerp(lerp(n010, n110, u), lerp(n011, n111, u), w), v);\n    }\n}\n// noise.seed(0);\n//# sourceMappingURL=PerlinNoise.js.map","/**\n * A collection of SVG path generation tools.\n *\n * @author  Ikaros Kappler\n * @date    2025-04-04\n * @version 1.0.0\n */\nimport { Circle } from \"../Circle\";\nimport { geomutils } from \"../geomutils\";\nexport const SVGPathUtils = {\n    /**\n     * Creates an SVG shape resembling a circlular ring sector.\n     *\n     * @param {Vertex} center - The center position of the ring.\n     * @param {number} innerRadius - The inner radius of the ring.\n     * @param {number} outerRadius - The outer radius of the ring.\n     * @param {number} startAngle - The start angle of the ring.\n     * @param {number} endAngle - The end angle of the ring.\n     * @returns {SVGPathParams} SVG path parmams for a closed shape representing the circular ring sector.\n     */\n    mkCircularRingSector: (center, innerRadius, outerRadius, startAngle, endAngle) => {\n        const innerStart = Circle.circleUtils.vertAt(startAngle, innerRadius).add(center);\n        const innerEnd = Circle.circleUtils.vertAt(endAngle, innerRadius).add(center);\n        const outerStart = Circle.circleUtils.vertAt(startAngle, outerRadius).add(center);\n        const outerEnd = Circle.circleUtils.vertAt(endAngle, outerRadius).add(center);\n        const buffer = [\"M\", innerStart.x, innerStart.y];\n        // var isLargeArcRequired = geomutils.mapAngleTo2PI(Math.abs(startAngle - endAngle)) >= Math.PI;\n        // var isLargeArcRequired = Math.abs(geomutils.mapAngleTo2PI(startAngle) - geomutils.mapAngleTo2PI(endAngle)) >= Math.PI;\n        const isLargeArcRequired = geomutils.mapAngleTo2PI(geomutils.mapAngleTo2PI(startAngle) - geomutils.mapAngleTo2PI(endAngle)) >= Math.PI;\n        const rotation = 0.0;\n        const innerLargeArcFlag = isLargeArcRequired ? 0 : 1;\n        const innerSweepFlag = 1; // isLargeArcRequired ? 1 : 0; // 1;\n        const outerLargeArcFlag = isLargeArcRequired ? 0 : 1;\n        const outerSweepFlag = 0; // isLargeArcRequired ? 0 : 1; // 0;\n        buffer.push(\"A\", innerRadius, innerRadius, rotation, innerLargeArcFlag, innerSweepFlag, innerEnd.x, innerEnd.y);\n        buffer.push(\"L\", outerEnd.x, outerEnd.y);\n        buffer.push(\"A\", outerRadius, outerRadius, rotation, outerLargeArcFlag, outerSweepFlag, outerStart.x, outerStart.y);\n        buffer.push(\"Z\");\n        return buffer;\n    }\n};\n//# sourceMappingURL=SVGPathUtils.js.map","/**\n * @author Extended, bugfixed and ported to TypeScript by Ikaros Kappler.\n * @modified 2018-xx-xx Added a clone() function.\n * @modified 2018-xx-xx Allowing leading '#' in the makeHEX() function.\n * @modified 2018-11-28 Fixed the checkHEX() function to accept 000000.\n * @modified 2019-11-18 Added a generic parse(string) function that detects the format.\n * @modified 2020-01-09 Fixed a bug in the parse(string) function. Hex colors with only three elements were considered faulty.\n * @modified 2020-10-23 Ported to Typescript.\n * @modified 2021-02-08 Fixed a lot of es2015 compatibility issues.\n * @modified 2021-02-08 Added basic tsdoc/jsdoc comments.\n * @modified 2021-11-05 Fixing the regex to parse rgba-strings.\n * @modified 2021-11-05 Added return value `this` to all modifier functions (for chaining).\n * @modified 2021-11-07 Changed the behavior of `darken` and `lighten`: the passed value is handled relative now which makes values much easier predictable and makes the change feel more 'natural'.\n * @modified 2021-11-07 Did the same with `saturate` and `desaturate`.\n * @modified 2021-11-07 Did the same with the `fadein` and `fadeout` functions.\n * @modified 2021-11-07 Added setRed, setGreen, setBlue, setHue, setSaturation, setLiminance functions.\n * @modified 2022-05-11 Modified the `clone` function by just copying the numeric calues, not re-calculating the whole color.\n * @modified 2022-05-11 Fixed the `interpolate` function.\n * @modified 2023-01-23 Added `Color.set(Color)` function to set all values (r,g,b,h,s,l,a) simultanoeusly.\n * @modified 2024-03-10 Fixed some NaN type check for Typescript 5 compatibility.\n * @modified 2025-08-08 Fixed an issue in the static `makeRGB` method: values in [0..1] are now correctly reconized (1.0 was excluded).\n * @modified 2025-08-08 Added static color instances (singletons): Color.Red, Color.Gold, Color.Yellow, Color.Green, Color.LimeGreen, Color.Blue, Color.MediumBlue, Color.Purple.\n * @modified 2025-09-01 Adding all standard web colors. Source: https://en.wikipedia.org/wiki/Web_colors\n * @modified 2025-09-01 Modifying the `Sanitizer.RGB` helper method: recognoizing 0 to 255 as valid values (not only 1 to 255).\n * @modified 2025-09-01 Modifying the `Color.parse` method: recognizing CSS color strings now.\n * @version 0.0.14\n **/\n/**\n * @classdesc A color class, inspired by neolitec's Javascript class.\n *    Original found at\n *      https://gist.github.com/neolitec/1344610\n *    Thanks to neolitec\n */\nexport class Color {\n    /**\n     * Construct a new color with `r=0 g=0 b=0`.\n     *\n     * Consider using the `makeHex`, `makeRGB` or `makeHSL` functions.\n     *\n     * @constructor\n     * @instance\n     * @memberof Color\n     */\n    constructor() {\n        this.r = this.g = this.b = 0;\n        this.h = this.s = this.l = 0;\n        this.a = 1;\n    }\n    // --- RGB ----------------------------------\n    /**\n     * Get this color as a CSS `rgb` string.\n     *\n     * Consult this for details: https://developer.mozilla.org/en-US/docs/Web/CSS/color_value\n     *\n     * @method cssRGB\n     * @instance\n     * @memberof Color\n     * @return {string} This color as a CSS rgb string.\n     */\n    cssRGB() {\n        return \"rgb(\" + Math.round(255 * this.r) + \",\" + Math.round(255 * this.g) + \",\" + Math.round(255 * this.b) + \")\";\n    }\n    /**\n     * Get this color as a CSS `rgba` string.\n     *\n     * Consult this for details: https://developer.mozilla.org/en-US/docs/Web/CSS/color_value\n     *\n     * @method cssRGBA\n     * @instance\n     * @memberof Color\n     * @return {string} This color as a CSS rgba string.\n     */\n    cssRGBA() {\n        return `rgba(${Math.round(255 * this.r)},${Math.round(255 * this.g)},${Math.round(255 * this.b)},${this.a})`;\n    }\n    /**\n     * Get the red component of this RGB(A)color. This method just returns the `r` color attribute.\n     *\n     * @method red\n     * @instance\n     * @memberof Color\n     * @return {number} A value between 0.0 and 1.0.\n     */\n    red() {\n        return this.r;\n    }\n    /**\n     * Get the green component of this RGB(A) color. This method just returns the `g` color attribute.\n     *\n     * @method green\n     * @instance\n     * @memberof Color\n     * @return {number} A value between 0.0 and 1.0.\n     */\n    green() {\n        return this.g;\n    }\n    /**\n     * Get the blue component of this RGB(A) color. This method just returns the `b` color attribute.\n     *\n     * @method blue\n     * @instance\n     * @memberof Color\n     * @return {number} A value between 0.0 and 1.0.\n     */\n    blue() {\n        return this.b;\n    }\n    set(color) {\n        this.r = color.r;\n        this.g = color.g;\n        this.b = color.b;\n        this.a = color.a;\n        this.h = color.h;\n        this.s = color.s;\n        this.l = color.l;\n        return this;\n    }\n    setRed(r) {\n        this.r = r;\n        return this;\n    }\n    setBlue(b) {\n        this.b = b;\n        Color.Converter.RGBToHSL(this);\n        return this;\n    }\n    setAlpha(a) {\n        this.a = a;\n        Color.Converter.RGBToHSL(this);\n        return this;\n    }\n    setGreen(g) {\n        this.g = g;\n        Color.Converter.RGBToHSL(this);\n        return this;\n    }\n    setHue(h) {\n        this.h = h;\n        Color.Converter.HSLToRGB(this);\n        return this;\n    }\n    setSaturation(s) {\n        this.s = s;\n        Color.Converter.HSLToRGB(this);\n        return this;\n    }\n    setLuminance(l) {\n        this.l = l;\n        Color.Converter.HSLToRGB(this);\n        return this;\n    }\n    // --- HSL ----------------------------------\n    /**\n     * Get this color as a CSS `hsl` string.\n     *\n     * @method cssHSL\n     * @instance\n     * @memberof Color\n     * @return {string} This color as a CSS hsl string.\n     */\n    cssHSL() {\n        return \"hsl(\" + Math.round(360 * this.h) + \",\" + Math.round(100 * this.s) + \"%,\" + Math.round(100 * this.l) + \"%)\";\n    }\n    /**\n     * Get this color as a CSS `hsla` string.\n     *\n     * @method cssHSLA\n     * @instance\n     * @memberof Color\n     * @return {string} This color as a CSS hsla string.\n     */\n    cssHSLA() {\n        return (\"hsla(\" +\n            Math.round(360 * this.h) +\n            \",\" +\n            Math.round(100 * this.s) +\n            \"%,\" +\n            Math.round(100 * this.l) +\n            \"%,\" +\n            Math.round(this.a) +\n            \")\");\n    }\n    /**\n     * Get the hue component of this HSL(A) color. This method just returns the `h` color attribute.\n     *\n     * @method hue\n     * @instance\n     * @memberof Color\n     * @return {number} A value between 0.0 and 1.0.\n     */\n    hue() {\n        return this.h;\n    }\n    /**\n     * Get the saturation component of this HSL(A) color. This method just returns the `s` color attribute.\n     *\n     * @method saturation\n     * @instance\n     * @memberof Color\n     * @return {number} A value between 0.0 and 1.0.\n     */\n    saturation() {\n        return this.s;\n    }\n    /**\n     * Get the lightness component of this HSL(A) color. This method just returns the `l` color attribute.\n     *\n     * @method lightness\n     * @instance\n     * @memberof Color\n     * @return {number} A value between 0.0 and 1.0.\n     */\n    lightness() {\n        return this.l;\n    }\n    // --- HEX ----------------------------------\n    /**\n     * Get this color as a CSS-HEX string (non-alpha): #rrggbb\n     *\n     * @method cssHEX\n     * @instance\n     * @memberof Color\n     * @return {string} This color as a CSS-HEX string.\n     */\n    cssHEX() {\n        return (\"#\" +\n            (255 * this.r < 16 ? \"0\" : \"\") +\n            Math.round(255 * this.r).toString(16) +\n            (255 * this.g < 16 ? \"0\" : \"\") +\n            Math.round(255 * this.g).toString(16) +\n            (255 * this.b < 16 ? \"0\" : \"\") +\n            Math.round(255 * this.b).toString(16));\n    }\n    // --- Transparency ----------------------------------\n    /**\n     * Get the alpha channel (transparency) of this color.\n     *\n     * @method alpha\n     * @instance\n     * @memberof Color\n     * @return {number} A value between 0.0 and 1.0.\n     */\n    alpha() {\n        return this.a;\n    }\n    // --- Modifiers ----------------------------------\n    //   saturate(v: string | number): Color {\n    //     if (\"string\" == typeof v && v.indexOf(\"%\") > -1 && (v = parseInt(v)) != NaN) {\n    //       this.s += v / 100;\n    //     } else if (\"number\" == typeof v) {\n    //       // range 255\n    //       this.s += v / 255;\n    //     } else {\n    //       throw new Error(\"error: bad modifier format (percent or number)\");\n    //     }\n    //     if (this.s > 1) this.s = 1;\n    //     else if (this.s < 0) this.s = 0;\n    //     Color.Converter.HSLToRGB(this);\n    //     return this;\n    //   }\n    saturate(v) {\n        // if (\"string\" == typeof v && v.indexOf(\"%\") > -1 && (v = parseInt(v)) != NaN) {\n        if (\"string\" == typeof v && v.indexOf(\"%\") > -1 && !Number.isNaN((v = parseInt(v)))) {\n            this.s += (1 - this.s) * (v / 100);\n        }\n        else if (\"number\" == typeof v) {\n            if (v >= -0.0 && v <= 1.0) {\n                // range 255\n                this.s += (1 - this.s) * v;\n            }\n            else {\n                // range 0-1\n                this.s += (1 - this.s) * (v / 255);\n            }\n        }\n        else {\n            throw new Error(\"error: bad modifier format (percent or number)\");\n        }\n        if (this.s > 1)\n            this.s = 1;\n        else if (this.s < 0)\n            this.s = 0;\n        Color.Converter.HSLToRGB(this);\n        return this;\n    }\n    desaturate(v) {\n        // if (\"string\" == typeof v && v.indexOf(\"%\") > -1 && (v = parseInt(v)) != NaN) {\n        if (\"string\" == typeof v && v.indexOf(\"%\") > -1 && !Number.isNaN((v = parseInt(v)))) {\n            this.s -= v / 100;\n        }\n        else if (\"number\" == typeof v) {\n            if (v >= 0.0 && v <= 1.0) {\n                // range 255\n                this.s -= this.s * v;\n            }\n            else {\n                // range 0-1\n                this.s -= this.s * (v / 255);\n            }\n        }\n        else {\n            throw new Error(\"error: bad modifier format (percent or number)\");\n        }\n        if (this.s > 1)\n            this.s = 1;\n        else if (this.s < 0)\n            this.s = 0;\n        Color.Converter.HSLToRGB(this);\n        return this;\n    }\n    lighten(v) {\n        // if (\"string\" == typeof v && v.indexOf(\"%\") > -1 && (v = parseInt(v)) != NaN) {\n        if (\"string\" == typeof v && v.indexOf(\"%\") > -1 && !Number.isNaN((v = parseInt(v)))) {\n            this.l += (1 - this.l) * (v / 100);\n        }\n        else if (\"number\" == typeof v) {\n            if (v >= 0.0 && v <= 1.0) {\n                // range 0.0...1.0\n                this.l += (1 - this.l) * v;\n            }\n            else {\n                // range 255\n                this.l += (1 - this.l) * (v / 255);\n            }\n        }\n        else {\n            throw new Error(\"error: bad modifier format (percent or number)\");\n        }\n        if (this.l > 1)\n            this.l = 1;\n        else if (this.l < 0)\n            this.l = 0;\n        Color.Converter.HSLToRGB(this);\n        return this;\n    }\n    darken(v) {\n        // if (\"string\" == typeof v && v.indexOf(\"%\") > -1 && (v = parseInt(v)) != NaN) {\n        if (\"string\" == typeof v && v.indexOf(\"%\") > -1 && !Number.isNaN((v = parseInt(v)))) {\n            this.l -= this.l * (v / 100);\n        }\n        else if (\"number\" == typeof v) {\n            if (v >= 0.0 && v <= 1.0) {\n                // range 0.0...1.0\n                this.l -= this.l * v;\n            }\n            else {\n                // range 255\n                this.l -= this.l * (v / 255);\n            }\n        }\n        else {\n            throw new Error(\"error: bad modifier format (percent or number)\");\n        }\n        if (this.l > 1)\n            this.l = 1;\n        else if (this.l < 0)\n            this.l = 0;\n        Color.Converter.HSLToRGB(this);\n        return this;\n    }\n    fadein(v) {\n        // if (\"string\" == typeof v && v.indexOf(\"%\") > -1 && (v = parseInt(v)) != NaN) {\n        if (\"string\" == typeof v && v.indexOf(\"%\") > -1 && !Number.isNaN((v = parseInt(v)))) {\n            this.a += (1 - this.a) * (v / 100);\n        }\n        else if (\"number\" == typeof v) {\n            if (v >= 0.0 && v <= 1.0) {\n                // range 0-1\n                this.a += (1 - this.a) * v;\n            }\n            else {\n                // range 255\n                this.a += (1 - this.a) * (v / 255);\n            }\n        }\n        else {\n            throw new Error(\"error: bad modifier format (percent or number)\");\n        }\n        console.log(\"New alpha\", this.a);\n        if (this.a > 1)\n            this.a = 1;\n        else if (this.a < 0)\n            this.a = 0;\n        Color.Converter.HSLToRGB(this);\n        return this;\n    }\n    fadeout(v) {\n        // if (\"string\" == typeof v && v.indexOf(\"%\") > -1 && (v = parseInt(v)) != NaN) {\n        if (\"string\" == typeof v && v.indexOf(\"%\") > -1 && !Number.isNaN((v = parseInt(v)))) {\n            this.a -= v / 100;\n        }\n        else if (\"number\" == typeof v) {\n            if (v >= 0.0 && v <= 1.0) {\n                // range 0-1\n                this.a -= v;\n            }\n            else {\n                // range 255\n                this.a -= v / 255;\n            }\n        }\n        else {\n            throw new Error(\"error: bad modifier format (percent or number)\");\n        }\n        if (this.a > 1)\n            this.a = 1;\n        else if (this.a < 0)\n            this.a = 0;\n        Color.Converter.HSLToRGB(this);\n        return this;\n    }\n    spin(v) {\n        // if (\"string\" == typeof v && v.indexOf(\"%\") > -1 && (v = parseInt(v)) != NaN) this.h += v / 100;\n        if (\"string\" == typeof v && v.indexOf(\"%\") > -1 && !Number.isNaN((v = parseInt(v)))) {\n            this.h += v / 100;\n        }\n        else if (\"number\" == typeof v) {\n            // range 360\n            this.h += v / 360;\n        }\n        else {\n            throw new Error(\"error: bad modifier format (percent or number)\");\n        }\n        if (this.h > 1)\n            this.h = 1;\n        else if (this.h < 0)\n            this.h = 0;\n        Color.Converter.HSLToRGB(this);\n        return this;\n    }\n    static makeRGB(...args) {\n        const c = new Color();\n        let sanitized;\n        if (args.length < 3 || args.length > 4) {\n            throw new Error(\"error: 3 or 4 arguments\");\n        }\n        sanitized = Color.Sanitizer.RGB(args[0], args[1], args[2]);\n        c.r = sanitized[0];\n        c.g = sanitized[1];\n        c.b = sanitized[2];\n        if (args.length == 4) {\n            c.a = args[3];\n        }\n        else {\n            c.a = 1.0;\n        }\n        Color.Converter.RGBToHSL(c);\n        return c;\n    }\n    static makeHSL(...args) {\n        const c = new Color();\n        let sanitized;\n        if (args.length < 3 || args.length > 4) {\n            throw new Error(\"error: 3 or 4 arguments\");\n        }\n        sanitized = Color.Sanitizer.HSL(args[0], args[1], args[2]);\n        c.h = sanitized[0];\n        c.s = sanitized[1];\n        c.l = sanitized[2];\n        if (args.length == 4) {\n            c.a = typeof args[3] === \"string\" ? Number.parseFloat(args[3]) : args[3];\n        }\n        else {\n            c.a = 1.0;\n        }\n        Color.Converter.HSLToRGB(c);\n        return c;\n    }\n    static makeHEX(value) {\n        var c = new Color(), sanitized;\n        // Edit Ika 2018-0308\n        // Allow leading '#'\n        if (value && value.startsWith(\"#\")) {\n            value = value.substr(1);\n        }\n        Color.Validator.checkHEX(value);\n        if (value.length == 3) {\n            sanitized = Color.Sanitizer.RGB(parseInt(value.substr(0, 1) + value.substr(0, 1), 16), parseInt(value.substr(1, 1) + value.substr(1, 1), 16), parseInt(value.substr(2, 1) + value.substr(2, 1), 16));\n        }\n        else if (value.length == 6) {\n            sanitized = Color.Sanitizer.RGB(parseInt(value.substr(0, 2), 16), parseInt(value.substr(2, 2), 16), parseInt(value.substr(4, 2), 16));\n        }\n        else {\n            throw new Error(\"error: 3 or 6 arguments\");\n        }\n        c.r = sanitized[0];\n        c.g = sanitized[1];\n        c.b = sanitized[2];\n        c.a = 1.0; // TODO: Accept #xxxxxxxx (8 chars, too, for alpha)\n        Color.Converter.RGBToHSL(c);\n        return c;\n    }\n    /**\n     * Parse the given color string. Currently only these formate are recognized: hex, rgb, rgba.\n     *\n     * @method parse\n     * @static\n     * @memberof Color\n     * @param {string} str - The string representation to parse.\n     * @return {Color} The color instance that's represented by the given string.\n     */\n    static parse(str) {\n        if (typeof str == \"undefined\") {\n            return null;\n        }\n        if ((str = str.trim().toLowerCase()).length == 0) {\n            return null;\n        }\n        if (str.startsWith(\"#\")) {\n            return Color.makeHEX(str.substring(1, str.length));\n        }\n        if (str.startsWith(\"rgb\")) {\n            var parts = str.match(/^rgba?\\(\\s*(\\d{1,3})\\s*,\\s*(\\d{1,3})\\s*,\\s*(\\d{1,3})\\s*,?\\s*(\\d*(?:\\.\\d+\\s*)?)\\)$/);\n            if (!parts) {\n                throw \"Unrecognized color format (2): \" + str;\n            }\n            // [ str, r, g, b, a|undefined ]\n            //   console.log(\"parts\", parts);\n            if (parts.length <= 4 || typeof parts[4] == \"undefined\" || parts[4] == \"\") {\n                return Color.makeRGB(parts[1], parts[2], parts[3]);\n            }\n            else {\n                return Color.makeRGB(parts[1], parts[2], parts[3], Number(parts[4]));\n            }\n        }\n        // Try to locate by CSS color name\n        const keys = Object.keys(Color.CSS_COLORS);\n        const cssColorKey = keys.reduce((prevKey, curKey) => {\n            if (curKey && curKey.toLowerCase() === str.toLowerCase()) {\n                return curKey;\n            }\n            return prevKey;\n        }, null);\n        if (cssColorKey) {\n            const cssColor = Color.CSS_COLORS[cssColorKey];\n            // console.log(\"cssColor?\", cssColor, str, cssColorKey);\n            if (cssColor) {\n                // console.log(\"CONSTRUCTOR?\", cssColor.constructor);\n                return cssColor.clone();\n            }\n        }\n        throw \"Unrecognized color format (1): \" + str;\n    }\n    /**\n     * Create a clone of this color (RGB).\n     *\n     * @method clone\n     * @instance\n     * @memberof Color\n     * @return {Color} A clone of this color (in RGB mode).\n     */\n    clone() {\n        // return Color.makeRGB(this.r, this.g, this.b, this.a);\n        const col = new Color();\n        col.r = this.r;\n        col.g = this.g;\n        col.b = this.b;\n        col.a = this.a;\n        col.h = this.h;\n        col.s = this.s;\n        col.l = this.l;\n        return col;\n    }\n    /**\n     * Interpolate this color on the RGB scale.\n     *\n     * @method interpolate\n     * @instance\n     * @memberof Color\n     * @param {Color} c - The color to interpolate to.\n     * @param {number} t - An interpolation value between 0.0 and 1.0.\n     * @return {Color} A clone of this color (in RGB mode).\n     */\n    interpolate(c, t) {\n        this.r += (c.r - this.r) * t;\n        this.g += (c.g - this.g) * t;\n        this.b += (c.b - this.b) * t;\n        this.a += (c.a - this.a) * t;\n        return this;\n    }\n} // END class\nColor.Sanitizer = {\n    RGB: (...args) => {\n        var o = [];\n        if (args.length == 0) {\n            return [];\n        }\n        // const allAreFrac = Color.testFrac( arguments );\n        for (var i = 0; i < args.length; i++) {\n            var c = args[i];\n            if (\"string\" == typeof c && c.indexOf(\"%\") > -1) {\n                // if ((c = parseInt(c)) == NaN) throw new Error(\"Bad format\");\n                if (Number.isNaN((c = parseInt(c)))) {\n                    throw new Error(\"Bad format\");\n                }\n                if (c < 0 || c > 100)\n                    throw new Error(\"Bad format\");\n                o[i] = c / 100;\n            }\n            else {\n                // if (\"string\" == typeof c && (c = parseInt(c)) == NaN) {\n                if (\"string\" == typeof c && Number.isNaN((c = parseInt(c)))) {\n                    throw new Error(\"Bad format\");\n                }\n                if (c < 0) {\n                    throw new Error(\"Bad format\");\n                }\n                //else if( allAreFrac ) o[i] = c; // c >= 0 && c <= 1 (all)\n                else if (c >= 0 && c <= 1) {\n                    o[i] = c;\n                }\n                // else if(c >= 0.0 && c <= 1.0) o[i] = c;\n                else if (c >= 0 && c < 256) {\n                    o[i] = c / 255;\n                }\n                // ???\n                // else if(c >= 0 && c < 256) o[i] = c/255;\n                else\n                    throw new Error(\"Bad format (\" + c + \")\");\n            }\n        }\n        return o;\n    },\n    HSL: function (...args) {\n        if (args.length < 3 || args.length > 4) {\n            throw new Error(\"3 or 4 arguments required\");\n        }\n        var h = args[0], s = args[1], l = args[2];\n        // if (\"string\" == typeof h && (h = parseFloat(h)) == NaN) throw new Error(\"Bad format for hue\");\n        if (\"string\" == typeof h && Number.isNaN((h = parseFloat(h)))) {\n            throw new Error(\"Bad format for hue\");\n        }\n        if (h < 0 || h > 360)\n            throw new Error(\"Hue out of range (0..360)\");\n        else if (((\"\" + h).indexOf(\".\") > -1 && h > 1) || (\"\" + h).indexOf(\".\") == -1)\n            h /= 360;\n        if (\"string\" == typeof s && s.indexOf(\"%\") > -1) {\n            // if ((s = parseInt(s)) == NaN) throw new Error(\"Bad format for saturation\");\n            if (Number.isNaN((s = parseInt(s)))) {\n                throw new Error(\"Bad format for saturation\");\n            }\n            if (s < 0 || s > 100) {\n                throw new Error(\"Bad format for saturation\");\n            }\n            s /= 100;\n        }\n        else {\n            s = typeof s === \"string\" ? Number.parseFloat(s) : s;\n            if (s < 0 || s > 1) {\n                throw new Error(\"Bad format for saturation\");\n            }\n        }\n        if (\"string\" == typeof l && l.indexOf(\"%\") > -1) {\n            // if ((l = parseInt(l)) == NaN) throw new Error(\"Bad format for lightness\");\n            if (Number.isNaN((l = parseInt(l)))) {\n                throw new Error(\"Bad format for lightness\");\n            }\n            if (l < 0 || l > 100) {\n                throw new Error(\"Bad format for lightness\");\n            }\n            l /= 100;\n        }\n        else {\n            l = typeof l === \"string\" ? Number.parseFloat(l) : l;\n            if (l < 0 || l > 1) {\n                throw new Error(\"Bad format for lightness\");\n            }\n        }\n        return [h, s, l];\n    }\n}; // ENd sanitizer\nColor.Validator = {\n    /**\n     * Check a hexa color (without #)\n     */\n    checkHEX: (value) => {\n        if (value.length != 6 && value.length != 3)\n            throw new Error(\"Hexa color: bad length (\" + value.length + \"),\" + value);\n        value = value.toLowerCase();\n        //for( var i in value ) {\n        for (var i = 0; i < value.length; i++) {\n            var c = value.charCodeAt(i);\n            if (!((c >= 48 && c <= 57) || (c >= 97 && c <= 102)))\n                throw new Error(`Hexa color: out of range for \"${value}\" at position ${i}.`);\n        }\n    }\n};\nColor.Converter = {\n    /**\n     * Calculates HSL Color.\n     * RGB must be normalized.\n     * http://mjijackson.com/2008/02/rgb-to-hsl-and-rgb-to-hsv-color-model-conversion-algorithms-in-javascript\n     */\n    RGBToHSL: (color) => {\n        var r = color.r;\n        var g = color.g;\n        var b = color.b;\n        var max = Math.max(r, g, b);\n        var min = Math.min(r, g, b);\n        color.l = (max + min) / 2;\n        if (max == min) {\n            color.h = color.s = 0; // achromatic\n        }\n        else {\n            var d = max - min;\n            color.s = color.l > 0.5 ? d / (2 - max - min) : d / (max + min);\n            switch (max) {\n                case r:\n                    color.h = (g - b) / d + (g < b ? 6 : 0);\n                    break;\n                case g:\n                    color.h = (b - r) / d + 2;\n                    break;\n                case b:\n                    color.h = (r - g) / d + 4;\n                    break;\n            }\n            color.h /= 6;\n        }\n    },\n    /**\n     * Calculates RGB color (nomalized).\n     * HSL must be normalized.\n     *\n     * http://mjijackson.com/2008/02/rgb-to-hsl-and-rgb-to-hsv-color-model-conversion-algorithms-in-javascript\n     */\n    HSLToRGB: (color) => {\n        var h = color.h;\n        var s = color.s;\n        var l = color.l;\n        if (s == 0) {\n            color.r = color.g = color.b = l; // achromatic\n        }\n        else {\n            var q = l < 0.5 ? l * (1 + s) : l + s - l * s;\n            var p = 2 * l - q;\n            color.r = Color.Converter.hue2rgb(p, q, h + 1 / 3);\n            color.g = Color.Converter.hue2rgb(p, q, h);\n            color.b = Color.Converter.hue2rgb(p, q, h - 1 / 3);\n        }\n    },\n    hue2rgb: (p, q, t) => {\n        if (t < 0)\n            t += 1;\n        if (t > 1)\n            t -= 1;\n        if (t < 1 / 6)\n            return p + (q - p) * 6 * t;\n        if (t < 1 / 2)\n            return q;\n        if (t < 2 / 3)\n            return p + (q - p) * (2 / 3 - t) * 6;\n        return p;\n    }\n};\n// Source\n//    https://en.wikipedia.org/wiki/Web_colors\n// Pink colors\nColor.MediumVioletRed = Color.makeRGB(199, 21, 133);\nColor.DeepPink = Color.makeRGB(255, 20, 147);\nColor.PaleVioletRed = Color.makeRGB(219, 112, 147);\nColor.HotPink = Color.makeRGB(255, 105, 180);\nColor.LightPink = Color.makeRGB(255, 182, 193);\nColor.Pink = Color.makeRGB(255, 192, 203);\n// Red colors\nColor.DarkRed = Color.makeRGB(139, 0, 0);\nColor.Red = Color.makeRGB(255, 0, 0);\nColor.Firebrick = Color.makeRGB(178, 34, 34);\nColor.Crimson = Color.makeRGB(220, 20, 60);\nColor.IndianRed = Color.makeRGB(205, 92, 92);\nColor.LightCoral = Color.makeRGB(240, 128, 128);\nColor.Salmon = Color.makeRGB(250, 128, 114);\nColor.DarkSalmon = Color.makeRGB(233, 150, 122);\nColor.LightSalmon = Color.makeRGB(255, 160, 122);\n// Orange colors\nColor.OrangeRed = Color.makeRGB(255, 69, 0);\nColor.Tomato = Color.makeRGB(255, 99, 71);\nColor.DarkOrange = Color.makeRGB(255, 140, 0);\nColor.Coral = Color.makeRGB(255, 127, 80);\nColor.Orange = Color.makeRGB(255, 165, 0);\n// Yellow colors\nColor.DarkKhaki = Color.makeRGB(189, 183, 107);\nColor.Gold = Color.makeRGB(255, 215, 0);\nColor.Khaki = Color.makeRGB(240, 230, 140);\nColor.PeachPuff = Color.makeRGB(255, 218, 185);\nColor.Yellow = Color.makeRGB(255, 255, 0);\nColor.PaleGoldenrod = Color.makeRGB(238, 232, 170);\nColor.Moccasin = Color.makeRGB(255, 228, 181);\nColor.PapayaWhip = Color.makeRGB(255, 239, 213);\nColor.LightGoldenrodYellow = Color.makeRGB(250, 250, 210);\nColor.LemonChiffon = Color.makeRGB(255, 250, 205);\nColor.LightYellow = Color.makeRGB(255, 255, 224);\n// Brown colors\nColor.Maroon = Color.makeRGB(128, 0, 0);\nColor.Brown = Color.makeRGB(165, 42, 42);\nColor.SaddleBrown = Color.makeRGB(139, 69, 19);\nColor.Sienna = Color.makeRGB(160, 82, 45);\nColor.Chocolate = Color.makeRGB(210, 105, 30);\nColor.DarkGoldenrod = Color.makeRGB(184, 134, 11);\nColor.Peru = Color.makeRGB(205, 133, 63);\nColor.RosyBrown = Color.makeRGB(188, 143, 143);\nColor.Goldenrod = Color.makeRGB(218, 165, 32);\nColor.SandyBrown = Color.makeRGB(244, 164, 96);\nColor.Tan = Color.makeRGB(210, 180, 140);\nColor.Burlywood = Color.makeRGB(222, 184, 135);\nColor.Wheat = Color.makeRGB(245, 222, 179);\nColor.NavajoWhite = Color.makeRGB(255, 222, 173);\nColor.Bisque = Color.makeRGB(255, 228, 196);\nColor.BlanchedAlmond = Color.makeRGB(255, 235, 205);\nColor.Cornsilk = Color.makeRGB(255, 248, 220);\n// Purple, violet, and magenta colors\nColor.Indigo = Color.makeRGB(75, 0, 130);\nColor.Purple = Color.makeRGB(128, 0, 128);\nColor.DarkMagenta = Color.makeRGB(139, 0, 139);\nColor.DarkViolet = Color.makeRGB(148, 0, 211);\nColor.DarkSlateBlue = Color.makeRGB(72, 61, 139);\nColor.BlueViolet = Color.makeRGB(138, 43, 226);\nColor.DarkOrchid = Color.makeRGB(153, 50, 204);\nColor.Fuchsia = Color.makeRGB(255, 0, 255);\nColor.Magenta = Color.makeRGB(255, 0, 255);\nColor.SlateBlue = Color.makeRGB(106, 90, 205);\nColor.MediumSlateBlue = Color.makeRGB(123, 104, 238);\nColor.MediumOrchid = Color.makeRGB(186, 85, 211);\nColor.MediumPurple = Color.makeRGB(147, 112, 219);\nColor.Orchid = Color.makeRGB(218, 112, 214);\nColor.Violet = Color.makeRGB(238, 130, 238);\nColor.Plum = Color.makeRGB(221, 160, 221);\nColor.Thistle = Color.makeRGB(216, 191, 216);\nColor.Lavender = Color.makeRGB(230, 230, 250);\n// Blue colors\nColor.MidnightBlue = Color.makeRGB(25, 25, 112);\nColor.Navy = Color.makeRGB(0, 0, 128);\nColor.DarkBlue = Color.makeRGB(0, 0, 139);\nColor.MediumBlue = Color.makeRGB(0, 0, 205);\nColor.Blue = Color.makeRGB(0, 0, 255);\nColor.RoyalBlue = Color.makeRGB(65, 105, 225);\nColor.SteelBlue = Color.makeRGB(70, 130, 180);\nColor.DodgerBlue = Color.makeRGB(30, 144, 255);\nColor.DeepSkyBlue = Color.makeRGB(0, 191, 255);\nColor.CornflowerBlue = Color.makeRGB(100, 149, 237);\nColor.SkyBlue = Color.makeRGB(135, 206, 235);\nColor.LightSkyBlue = Color.makeRGB(135, 206, 250);\nColor.LightSteelBlue = Color.makeRGB(176, 196, 222);\nColor.LightBlue = Color.makeRGB(173, 216, 230);\nColor.PowderBlue = Color.makeRGB(176, 224, 230);\n// Cyan colors\nColor.Teal = Color.makeRGB(0, 128, 128);\nColor.DarkCyan = Color.makeRGB(0, 139, 139);\nColor.LightSeaGreen = Color.makeRGB(32, 178, 170);\nColor.CadetBlue = Color.makeRGB(95, 158, 160);\nColor.DarkTurquoise = Color.makeRGB(0, 206, 209);\nColor.MediumTurquoise = Color.makeRGB(72, 209, 204);\nColor.Turquoise = Color.makeRGB(64, 224, 208);\nColor.Aqua = Color.makeRGB(0, 255, 255);\nColor.Cyan = Color.makeRGB(0, 255, 255);\nColor.Aquamarine = Color.makeRGB(127, 255, 212);\nColor.PaleTurquoise = Color.makeRGB(175, 238, 238);\nColor.LightCyan = Color.makeRGB(224, 255, 255);\n// Green colors\nColor.DarkGreen = Color.makeRGB(0, 100, 0);\nColor.Green = Color.makeRGB(0, 128, 0);\nColor.DarkOliveGreen = Color.makeRGB(85, 107, 47);\nColor.ForestGreen = Color.makeRGB(34, 139, 34);\nColor.SeaGreen = Color.makeRGB(46, 139, 87);\nColor.Olive = Color.makeRGB(128, 128, 0);\nColor.OliveDrab = Color.makeRGB(107, 142, 35);\nColor.MediumSeaGreen = Color.makeRGB(60, 179, 113);\nColor.LimeGreen = Color.makeRGB(50, 205, 50);\nColor.Lime = Color.makeRGB(0, 255, 0);\nColor.SpringGreen = Color.makeRGB(0, 255, 127);\nColor.MediumSpringGreen = Color.makeRGB(0, 250, 154);\nColor.DarkSeaGreen = Color.makeRGB(143, 188, 143);\nColor.MediumAquamarine = Color.makeRGB(102, 205, 170);\nColor.YellowGreen = Color.makeRGB(154, 205, 50);\nColor.LawnGreen = Color.makeRGB(124, 252, 0);\nColor.Chartreuse = Color.makeRGB(127, 255, 0);\nColor.LightGreen = Color.makeRGB(144, 238, 144);\nColor.GreenYellow = Color.makeRGB(173, 255, 47);\nColor.PaleGreen = Color.makeRGB(152, 251, 152);\n// White colors\nColor.MistyRose = Color.makeRGB(255, 228, 225);\nColor.AntiqueWhite = Color.makeRGB(250, 235, 215);\nColor.Linen = Color.makeRGB(250, 240, 230);\nColor.Beige = Color.makeRGB(245, 245, 220);\nColor.WhiteSmoke = Color.makeRGB(245, 245, 245);\nColor.LavenderBlush = Color.makeRGB(255, 240, 245);\nColor.OldLace = Color.makeRGB(253, 245, 230);\nColor.AliceBlue = Color.makeRGB(240, 248, 255);\nColor.Seashell = Color.makeRGB(255, 245, 238);\nColor.GhostWhite = Color.makeRGB(248, 248, 255);\nColor.Honeydew = Color.makeRGB(240, 255, 240);\nColor.FloralWhite = Color.makeRGB(255, 250, 240);\nColor.Azure = Color.makeRGB(240, 255, 255);\nColor.MintCream = Color.makeRGB(245, 255, 250);\nColor.Snow = Color.makeRGB(255, 250, 250);\nColor.Ivory = Color.makeRGB(255, 255, 240);\nColor.White = Color.makeRGB(255, 255, 255);\n// Gray and black colors\nColor.Black = Color.makeRGB(0, 0, 0);\nColor.DarkSlateGray = Color.makeRGB(47, 79, 79);\nColor.DimGray = Color.makeRGB(105, 105, 105);\nColor.SlateGray = Color.makeRGB(112, 128, 144);\nColor.Gray = Color.makeRGB(128, 128, 128);\nColor.LightSlateGray = Color.makeRGB(119, 136, 153);\nColor.DarkGray = Color.makeRGB(169, 169, 169);\nColor.Silver = Color.makeRGB(192, 192, 192);\nColor.LightGray = Color.makeRGB(211, 211, 211);\nColor.Gainsboro = Color.makeRGB(220, 220, 220);\nColor.CSS_COLORS = {\n    // Pink Color.XYZ,lors\n    MediumVioletRed: Color.MediumVioletRed,\n    DeepPink: Color.DeepPink,\n    PaleVioletRed: Color.PaleVioletRed,\n    HotPink: Color.HotPink,\n    LightPink: Color.LightPink,\n    Pink: Color.Pink,\n    // Red Color.XYZ,lors\n    DarkRed: Color.DarkRed,\n    Red: Color.Red,\n    Firebrick: Color.Firebrick,\n    Crimson: Color.Crimson,\n    IndianRed: Color.IndianRed,\n    LightCoral: Color.LightCoral,\n    Salmon: Color.Salmon,\n    DarkSalmon: Color.DarkSalmon,\n    LightSalmon: Color.LightSalmon,\n    // Orange Color.XYZ,lors\n    OrangeRed: Color.OrangeRed,\n    Tomato: Color.Tomato,\n    DarkOrange: Color.DarkOrange,\n    Coral: Color.Coral,\n    Orange: Color.Orange,\n    // Yellow Color.XYZ,lors\n    DarkKhaki: Color.DarkKhaki,\n    Gold: Color.Gold,\n    Khaki: Color.Khaki,\n    PeachPuff: Color.PeachPuff,\n    Yellow: Color.Yellow,\n    PaleGoldenrod: Color.PaleGoldenrod,\n    Moccasin: Color.Moccasin,\n    PapayaWhip: Color.PapayaWhip,\n    LightGoldenrodYellow: Color.LightGoldenrodYellow,\n    LemonChiffon: Color.LemonChiffon,\n    LightYellow: Color.LightYellow,\n    // Brown Color.XYZ,lors\n    Maroon: Color.Maroon,\n    Brown: Color.Brown,\n    SaddleBrown: Color.SaddleBrown,\n    Sienna: Color.Sienna,\n    Chocolate: Color.Chocolate,\n    DarkGoldenrod: Color.DarkGoldenrod,\n    Peru: Color.Peru,\n    RosyBrown: Color.RosyBrown,\n    Goldenrod: Color.Goldenrod,\n    SandyBrown: Color.SandyBrown,\n    Tan: Color.Tan,\n    Burlywood: Color.Burlywood,\n    Wheat: Color.Wheat,\n    NavajoWhite: Color.NavajoWhite,\n    Bisque: Color.Bisque,\n    BlanchedAlmond: Color.BlanchedAlmond,\n    Cornsilk: Color.Cornsilk,\n    // Purple, violet, and magenta Color.XYZ,lors\n    Indigo: Color.Indigo,\n    Purple: Color.Purple,\n    DarkMagenta: Color.DarkMagenta,\n    DarkViolet: Color.DarkViolet,\n    DarkSlateBlue: Color.DarkSlateBlue,\n    BlueViolet: Color.BlueViolet,\n    DarkOrchid: Color.DarkOrchid,\n    Fuchsia: Color.Fuchsia,\n    Magenta: Color.Magenta,\n    SlateBlue: Color.SlateBlue,\n    MediumSlateBlue: Color.MediumSlateBlue,\n    MediumOrchid: Color.MediumOrchid,\n    MediumPurple: Color.MediumPurple,\n    Orchid: Color.Orchid,\n    Violet: Color.Violet,\n    Plum: Color.Plum,\n    Thistle: Color.Thistle,\n    Lavender: Color.Lavender,\n    // Blue Colors\n    MidnightBlue: Color.MidnightBlue,\n    Navy: Color.Navy,\n    DarkBlue: Color.DarkBlue,\n    MediumBlue: Color.MediumBlue,\n    Blue: Color.Blue,\n    RoyalBlue: Color.RoyalBlue,\n    SteelBlue: Color.SteelBlue,\n    DodgerBlue: Color.DodgerBlue,\n    DeepSkyBlue: Color.DeepSkyBlue,\n    CornflowerBlue: Color.CornflowerBlue,\n    SkyBlue: Color.SkyBlue,\n    LightSkyBlue: Color.LightSkyBlue,\n    LightSteelBlue: Color.LightSteelBlue,\n    LightBlue: Color.LightBlue,\n    PowderBlue: Color.PowderBlue,\n    // Coyan Colors\n    Teal: Color.Teal,\n    DarkCyan: Color.DarkCyan,\n    LightSeaGreen: Color.LightSeaGreen,\n    CadetBlue: Color.CadetBlue,\n    DarkTurquoise: Color.DarkTurquoise,\n    MediumTurquoise: Color.MediumTurquoise,\n    Turquoise: Color.Turquoise,\n    Aqua: Color.Aqua,\n    Cyan: Color.Cyan,\n    Aquamarine: Color.Aquamarine,\n    PaleTurquoise: Color.PaleTurquoise,\n    LightCyan: Color.LightCyan,\n    // Green Colors\n    DarkGreen: Color.DarkGreen,\n    Green: Color.Green,\n    DarkOliveGreen: Color.DarkOliveGreen,\n    ForestGreen: Color.ForestGreen,\n    SeaGreen: Color.SeaGreen,\n    Olive: Color.Olive,\n    OliveDrab: Color.OliveDrab,\n    MediumSeaGreen: Color.MediumSeaGreen,\n    LimeGreen: Color.LimeGreen,\n    Lime: Color.Lime,\n    SpringGreen: Color.SpringGreen,\n    MediumSpringGreen: Color.MediumSpringGreen,\n    DarkSeaGreen: Color.DarkSeaGreen,\n    MediumAquamarine: Color.MediumAquamarine,\n    YellowGreen: Color.YellowGreen,\n    LawnGreen: Color.LawnGreen,\n    Chartreuse: Color.Chartreuse,\n    LightGreen: Color.LightGreen,\n    GreenYellow: Color.GreenYellow,\n    PaleGreen: Color.PaleGreen,\n    // White Color.XYZ,lors\n    MistyRose: Color.MistyRose,\n    AntiqueWhite: Color.AntiqueWhite,\n    Linen: Color.Linen,\n    Beige: Color.Beige,\n    WhiteSmoke: Color.WhiteSmoke,\n    LavenderBlush: Color.LavenderBlush,\n    OldLace: Color.OldLace,\n    AliceBlue: Color.AliceBlue,\n    Seashell: Color.Seashell,\n    GhostWhite: Color.GhostWhite,\n    Honeydew: Color.Honeydew,\n    FloralWhite: Color.FloralWhite,\n    Azure: Color.Azure,\n    MintCream: Color.MintCream,\n    Snow: Color.Snow,\n    Ivory: Color.Ivory,\n    White: Color.White,\n    // Gray and black Color.XYZ,lors\n    Black: Color.Black,\n    DarkSlateGray: Color.DarkSlateGray,\n    DimGray: Color.DimGray,\n    SlateGray: Color.SlateGray,\n    Gray: Color.Gray,\n    LightSlateGray: Color.LightSlateGray,\n    DarkGray: Color.DarkGray,\n    Silver: Color.Silver,\n    LightGray: Color.LightGray,\n    Gainsboro: Color.Gainsboro\n};\n//# sourceMappingURL=Color.js.map","/**\n * @author   Ikaros Kappler\n * @date     2018-11-10\n * @modified 2020-10-23 Ported to Typescript.\n * @modified 2020-10-30 Exporting each color under its name globally.\n * @modified 2025-12-08 Replaying self defined colors by official web colors.\n * @modified 2026-03-18 Fixing global `WebColors` array.\n * @version  1.0.3\n **/\nimport { Color } from \"./datastructures/Color\";\nexport const Red = Color.Red; // Color.makeRGB(255,67,55);\nexport const Pink = Color.Pink; // Color.makeRGB(232,31,100);\nexport const Purple = Color.Purple; // Color.makeRGB(156,39,175);\nexport const DeepPurple = Color.DeepPink; // Color.makeRGB(103,59,184);\nexport const Indigo = Color.Indigo; // Color.makeRGB(64,81,181);\nexport const Blue = Color.Blue; // Color.makeRGB(35,151,245);\nexport const LightBlue = Color.LightBlue; // Color.makeRGB(6,170,245);\nexport const Cyan = Color.Cyan; // Color.makeRGB(3,189,214);\nexport const Teal = Color.Teal; // Color.makeRGB(1,150,137);\nexport const Green = Color.Green; // Color.makeRGB(77,175,82);\nexport const LightGreen = Color.LightGreen; // Color.makeRGB(141,195,67);\n/**\n * A set of beautiful web colors (I know, beauty is in the eye of the beholder).\n *\n * I found this color chart with 11 colors and think it is somewhat nice\n *    https://www.pinterest.com/pin/229965124706497134/\n *\n * @requires Color\n *\n */\nexport const WebColors = [\n    Color.Red,\n    Color.Pink,\n    Color.Purple,\n    Color.DeepPink,\n    Color.Indigo,\n    Color.Blue,\n    Color.LightBlue,\n    Color.Cyan,\n    Color.Teal,\n    Color.Green,\n    Color.LightGreen\n];\n/**\n * A helper function to shuffle the colors into a new order.\n */\nexport const shuffleWebColors = (order) => {\n    const result = Array(order.length);\n    for (var i = 0; i < order.length; i++) {\n        result[i] = WebColors[order[i] % WebColors.length];\n    }\n    return result;\n};\n//# sourceMappingURL=WebColors.js.map","/**\n * @requires Color\n *\n * @date 2020-10-27\n **/\nimport { shuffleWebColors } from \"./WebColors\";\nconst ORDER_CONTRAST = [8, 0, 6, 4, 1, 9, 2, 10, 3, 7, 5];\nexport const WebColorsContrast = shuffleWebColors(ORDER_CONTRAST);\n//# sourceMappingURL=WebColorsContrast.js.map","/**\n * @author   Ikaros Kappler\n * @version  1.0.0\n * @date     2018-11-11\n **/\nimport { Color } from \"./datastructures/Color\";\n/**\n * A mix of green shades.\n *\n * @requires Color\n */\nexport const WebColorsMalachite = [\n    Color.makeRGB(0, 21, 6),\n    Color.makeRGB(0, 30, 12),\n    Color.makeRGB(0, 52, 28),\n    Color.makeRGB(0, 81, 47),\n    Color.makeRGB(21, 134, 88),\n    Color.makeRGB(0, 46, 19),\n    Color.makeRGB(0, 68, 40),\n    Color.makeRGB(11, 81, 55),\n    Color.makeRGB(0, 91, 46),\n    Color.makeRGB(0, 111, 46),\n    Color.makeRGB(33, 140, 106)\n];\n//# sourceMappingURL=WebColorsMalachite.js.map","/**\n * An equivalent of lodash.array_fill(...).\n *\n * @author Ikaros Kappler\n * @date 2020-10-23\n * @version 1.0.0\n **/\nexport const arrayFill = (count, initialValue) => {\n    const arr = Array(count);\n    for (var i = 0; i < count; i++)\n        arr[i] = initialValue;\n    return arr;\n};\n//# sourceMappingURL=arrayFill.js.map","/**\n * @author Ikaros Kappler\n * @date 2020-10-23\n * @version 1.0.0\n **/\nimport { arrayFill } from \"./arrayFill\";\n/**\n * A matrix-fill helper function. Equivalent of lodash.array_fill(...).\n */\nexport const matrixFill = (countA, countB, initialValue) => {\n    const arr = Array(countA);\n    for (var i = 0; i < countA; i++) {\n        arr[i] = arrayFill(countB, initialValue);\n    }\n    return arr;\n};\n//# sourceMappingURL=matrixFill.js.map","/**\n * @classdesc A circular interval set.\n *\n * @author   Ikaros Kappler\n * @date     2020-10-02\n * @modified 2020-10-18 Ported to Typescript from vanilla JS.\n * @modified 2020-10-22 Added the removeAt funcion.\n * @version  1.0.1\n * @name CircularIntervalSet\n **/\nexport class CircularIntervalSet {\n    /**\n     * Create a new CircularIntervalSet with the given lower and upperBound (start and end).\n     *\n     * The intervals inside lower and upper bound will initially be added to this set (full range).\n     *\n     * @param {number} start\n     * @param {number} end\n     * @method clear\n     * @memberof CircularIntervalSet\n     **/\n    constructor(start, end) {\n        this.start = start;\n        this.end = end;\n        this.intervals = [[start, end]];\n    }\n    ;\n    /**\n     * Clear this set (will be empty after this operation).\n     *\n     * @method clear\n     * @instance\n     * @memberof CircularIntervalSet\n     * @return {void}\n     **/\n    clear() {\n        this.intervals = [];\n    }\n    ;\n    /**\n     * Remove the interval at given index.\n     *\n     * @param {number} index\n     * @method removeAt\n     * @instance\n     * @memberof CircularIntervalSet\n     * @return {void}\n     **/\n    // Todo: remove? (not in use any more?)\n    removeAt(index) {\n        if (index < 0 || index >= this.intervals.length)\n            return;\n        this.intervals.splice(index, 1);\n    }\n    ;\n    /**\n     * Intersect all sub intervalls with the given range (must be inside bounds).\n     *\n     * @param {number} start\n     * @param {number} end\n     * @method intersect\n     * @instance\n     * @memberof CircularIntervalSet\n     * @return {void}\n     **/\n    intersect(start, end) {\n        for (var i = 0; i < this.intervals.length;) {\n            if (start <= end) {\n                if ((this.intervals[i][0] >= end || this.intervals[i][1] <= start)) {\n                    // Current interval is fully outside range.\n                    // REMOVE\n                    this.intervals.splice(i, 1);\n                }\n                else if (this.intervals[i][0] >= start && this.intervals[i][1] <= end) {\n                    // Current interval is fully inside.\n                    // KEEP\n                    i++;\n                }\n                else if (this.intervals[i][0] <= start && this.intervals[i][1] >= end) {\n                    // Desired range lies inside current interval.\n                    // CUT OFF LEFT AND RIGHT.\n                    this.intervals.splice(i, 1, [start, end]);\n                    i++;\n                }\n                else if (this.intervals[i][0] <= start && this.intervals[i][1] < end) {\n                    // Right end is inside range.\n                    // CUT OFF LEFT.\n                    this.intervals[i][0] = start;\n                    i++;\n                }\n                else if (this.intervals[i][0] > start && this.intervals[i][1] >= end) {\n                    // LEFT end is inside range.\n                    // CUT OFF RIGHT.\n                    this.intervals[i][1] = end;\n                    i++;\n                }\n                else {\n                    // NOOP\n                    i++;\n                }\n            }\n            else {\n                // start > end\n                if (this.intervals[i][0] >= end && this.intervals[i][1] <= start) {\n                    // Current interval is fully outside range.\n                    // REMOVE\n                    this.intervals.splice(i, 1);\n                }\n                else if (this.intervals[i][0] >= start) {\n                    // Full inside (right range).\n                    // Keep.\n                    i++;\n                }\n                else if (this.intervals[i][1] <= end) {\n                    // Full inside (left range).\n                    // Keep.\n                    i++;\n                }\n                else if (this.intervals[i][0] >= end && this.intervals[i][1] > start) {\n                    // Right part inside.\n                    // Cut off left part.\n                    this.intervals.splice(i, 1, [start, this.intervals[i][1]]);\n                    i++;\n                }\n                else if (this.intervals[i][0] <= end && this.intervals[i][1] < start) {\n                    // Left part inside.\n                    // Cut off right part.\n                    this.intervals.splice(i, 1, [this.intervals[i][0], end]);\n                    i++;\n                }\n                else if (this.intervals[i][0] <= end && this.intervals[i][1] >= start) {\n                    // Start and end inside, inner part is not.\n                    // Cut into two.\n                    this.intervals.splice(i, 1, [this.intervals[i][0], end], [start, this.intervals[i][1]]);\n                    i += 2;\n                }\n                else {\n                    // NOOP\n                    i++;\n                }\n            }\n        }\n    }\n    ;\n    /**\n     * Convert this set to a human readable string.\n     *\n     * @method toString\n     * @instance\n     * @memberof CircularIntervalSet\n     * @return {string}\n     **/\n    toString() {\n        return JSON.stringify(this.intervals);\n    }\n    ;\n}\n//# sourceMappingURL=CircularIntervalSet.js.map","/**\n * @author   Ikaros Kappler\n * @date     2020-10-05\n * @modified 2021-02-08 Fixed a lot of es2015 compatibility issues.\n * @modified 2024-02-23 Fixed some null-type conflicts.\n * @version  1.0.2\n * @file CircleIntersections\n * @public\n **/\nimport { arrayFill } from \"./arrayFill\";\nimport { matrixFill } from \"./matrixFill\";\nimport { CircleSector } from \"../../CircleSector\";\nimport { Line } from \"../../Line\";\nimport { CircularIntervalSet } from \"../datastructures/CircularIntervalSet\";\n/**\n * @classdesc A script for finding the intersection points of two or\n * multiple circles (the 'radical lines').\n *\n * Based on the C++ implementation by Robert King\n *    https://stackoverflow.com/questions/3349125/circle-circle-intersection-points\n * and the 'Circles and spheres' article by Paul Bourke.\n *    http://paulbourke.net/geometry/circlesphere/\n *\n * @requires arrayFill\n * @requires matrixFill\n * @requires Circle\n * @requires IndexPair\n * @requires Matrix\n * @requires Interval\n * @requires Line\n * @requires CirularIntervalSet\n */\nexport class CircleIntersections {\n    /**\n     * Find all connected outer path partitions.\n     *\n     * @method findOuterPartitions\n     * @static\n     * @memberof CircleIntersections\n     * @param {Array<Circle>} circles - The circles to find intersections for.\n     * @param {Array<CircularIntervalSet>} intervalSets - The determined interval sets (see `findOuterCircleIntervals`).\n     * @return {Array<Array<IndexPair>>} An array of paths, each defined by a sequence of IndexPairs adressing circle i and interval j.\n     **/\n    static findOuterPartitions(circles, intervalSets) {\n        // For tracking which interval we already used for detecting the partition\n        // we need a matrix; find the maximal interval length.\n        let maxSetLength = 0;\n        for (var i = 0; i < intervalSets.length; i++) {\n            maxSetLength = Math.max(maxSetLength, intervalSets[i].intervals.length);\n        }\n        const usedIntervals = matrixFill(intervalSets.length, maxSetLength, false);\n        var path = null;\n        var pathList = [];\n        while ((path = CircleIntersections.findOuterPartition(circles, intervalSets, usedIntervals)) != null) {\n            pathList.push(path);\n        }\n        return pathList;\n    }\n    /**\n     * Find all connected outer path partitions (as CircleSectors).\n     *\n     * @method findOuterPartitionsAsSectors\n     * @static\n     * @memberof CircleIntersections\n     * @param {Array<Circle>} circles - The circles to find intersections for.\n     * @param {Array<CircularIntervalSet>} intervalSets - The determined interval sets (see `findOuterCircleIntervals`).\n     * @return {Array<Array<CircleSector>>} An array of paths, each defined by a sequence of SircleSectors.\n     **/\n    static findOuterPartitionsAsSectors(circles, intervalSets) {\n        const partitions = CircleIntersections.findOuterPartitions(circles, intervalSets);\n        const partitionsAsArcs = [];\n        for (var p = 0; p < partitions.length; p++) {\n            const path = partitions[p];\n            const pathAsArcs = [];\n            for (var i = 0; i < path.length; i++) {\n                const circleIndex = path[i].i;\n                const circle = circles[circleIndex];\n                var interval = intervalSets[path[i].i].intervals[path[i].j];\n                // Params: circle, startAngle, endAngle\n                pathAsArcs.push(new CircleSector(circle, interval[0], interval[1]));\n            } // END for\n            partitionsAsArcs.push(pathAsArcs);\n        } // END for\n        return partitionsAsArcs;\n    }\n    /**\n     * Build the n*n intersection matrix: contains the radical line at (i,j) if circle i and circle j do intersect;\n     * conatins null at (i,j) otherwise.\n     *\n     * Note that this matrix is symmetrical: if circles (i,j) intersect with line (A,B), then also circles (j,i) intersect\n     * with line (B,A).\n     *\n     * The returned two-dimensional matrix (array) has exactly as many entries as the passed circle array.\n     *\n     * @method buildRadicalLineMatrix\n     * @static\n     * @memberof CircleIntersections\n     * @param {Array<Circle>} circles - The circles to find intersections for.\n     * @return {Array<Array<Line>>} A 2d-matrix containing the radical lines where circles intersect.\n     **/\n    static buildRadicalLineMatrix(circles) {\n        var radicalLines = [];\n        for (var i = 0; i < circles.length; i++) {\n            if (!radicalLines[i]) {\n                radicalLines[i] = arrayFill(circles.length, null);\n            }\n            for (var j = 0; j < circles.length; j++) {\n                if (i == j)\n                    continue;\n                if (radicalLines[i][j])\n                    continue;\n                radicalLines[i][j] = circles[i].circleIntersection(circles[j]);\n                // Build symmetrical matrix\n                var tmpRadLine = radicalLines[i][j];\n                if (tmpRadLine) {\n                    if (!radicalLines[j]) {\n                        radicalLines[j] = arrayFill(circles.length, null);\n                    }\n                    // Use reverse line\n                    radicalLines[j][i] = new Line(tmpRadLine.b, tmpRadLine.a);\n                }\n            }\n        }\n        return radicalLines;\n    }\n    /**\n     * Find all circles (indices) which are completely located inside another circle.\n     *\n     * The returned array conatins the array indices.\n     *\n     * @method findInnerCircles\n     * @static\n     * @memberof CircleIntersections\n     * @param {Array<Circle>} circles - The circles to find intersections for.\n     * @return {Array<number>}\n     **/\n    static findInnerCircles(circles) {\n        const innerCircleIndices = [];\n        for (var i = 0; i < circles.length; i++) {\n            for (var j = 0; j < circles.length; j++) {\n                if (i == j)\n                    continue;\n                if (circles[j].containsCircle(circles[i])) {\n                    innerCircleIndices.push(i);\n                }\n            }\n        }\n        return innerCircleIndices;\n    }\n    /**\n     * Calculate all outer circle intervals (sections that belong to the outermost line), dermined by the given\n     * circles and their radical lines.\n     *\n     * The returned array contains IntervalSets - one for each circle - indicating the remaining circle sections.\n     *\n     * @method findOuterCircleIntervals\n     * @static\n     * @memberof CircleIntersections\n     * @param {Array<Circle>} circles - The circles to find intersections for.\n     * @param {Array<Line>} intersectionMatrix\n     * @return {Array<number>}\n     **/\n    static findOuterCircleIntervals(circles, intersectionMatrix) {\n        const intervalSets = [];\n        for (var i = 0; i < circles.length; i++) {\n            intervalSets[i] = new CircularIntervalSet(0, 2 * Math.PI);\n            for (var j = 0; j < circles.length; j++) {\n                if (i == j)\n                    continue;\n                if (intersectionMatrix[i][j] !== null) {\n                    // const interval : Interval = CircleIntersections.radicalLineToInterval( circle, radicalLine );\n                    CircleIntersections.handleCircleInterval(circles[i], intersectionMatrix[i][j], intervalSets[i]);\n                }\n                else if (circles[j].containsCircle(circles[i])) {\n                    intervalSets[i].clear();\n                }\n            }\n        }\n        return intervalSets;\n    }\n    /**\n     * Calculate the next connected partition from the given set of circles and outer path intervals. The function\n     * will pick a random unused circle interval and detect all adjacent intervals until a closed partition\n     * was found.\n     *\n     * If an interval (circle section) was already visited will be stored in the `usedIntervalSetRecords` matrix (thus\n     * is must be large enough to map all sections).\n     *\n     * The returned array contains IndexPairs (i,j) - one for each circle i - indicating the used circle section j.\n     *\n     * @method findOuterPartition\n     * @static\n     * @memberof CircleIntersections\n     * @param {Array<Circle>} circles - The circles to find intersections for.\n     * @param {Array<CircularIntervalSet>} intervalSets - The circle intervals that form the intersection outline.\n     * @param {Matrix<boolean>} usedIntervals - A matrix for remembering which circle intervals were always used.\n     * @return {Array<Indexpair>|null} The next partition or `null` if no more can be found.\n     **/\n    static findOuterPartition(circles, intervalSets, usedIntervals) {\n        let intLocation = CircleIntersections.randomUnusedInterval(intervalSets, usedIntervals);\n        const path = [];\n        while (intLocation != null) {\n            path.push(intLocation);\n            usedIntervals[intLocation.i][intLocation.j] = true;\n            intLocation = CircleIntersections.findAdjacentInterval(circles, intLocation, intervalSets, usedIntervals, 0.001);\n        }\n        return path.length == 0 ? null : path;\n    }\n    /**\n     * Convert a radical line (belonging to a circle) into an interval: start angle and end angle.\n     *\n     * @method radicalLineToInterval\n     * @static\n     * @private\n     * @memberof CircleIntersections\n     * @param {Circle} circle - The circle itself.\n     * @param {Line} radicaLine - The radical line to convert (must have two intersection points on the circle).\n     * @return {Interval} The interval `[startAngle,endAngle]` determined by the radical line.\n     **/\n    static radicalLineToInterval(circle, radicalLine) {\n        // Get angle sections in the circles\n        const lineA = new Line(circle.center, radicalLine.a);\n        const lineB = new Line(circle.center, radicalLine.b);\n        let angleA = lineA.angle();\n        let angleB = lineB.angle();\n        // Map angles to [0 ... 2*PI]\n        // (the angle() function might return negative angles in [-PI .. 0 .. PI])\n        if (angleA < 0)\n            angleA = Math.PI * 2 + angleA;\n        if (angleB < 0)\n            angleB = Math.PI * 2 + angleB;\n        return [angleA, angleB];\n    }\n    /**\n     * This is a helper fuction used by `findOuterCircleIntervals`.\n     *\n     * It applies the passed radical line by intersecting the remaining circle sections with the new section.\n     *\n     * @method handleCircleInterval\n     * @static\n     * @private\n     * @memberof CircleIntersections\n     * @param {Circle} circle - The circles to find intersections for.\n     * @param {Line} radicalLine - The radical line to apply.\n     * @param {CircularIntervalSet} intervalSet - The CircularIntervalSet to use (must have left and right border: 0 and 2*PI).\n     * @return {void}\n     **/\n    static handleCircleInterval(circle, radicalLine, intervalSet) {\n        const interval = CircleIntersections.radicalLineToInterval(circle, radicalLine);\n        intervalSet.intersect(interval[1], interval[0]);\n    }\n    /**\n     * Pick a random unused circle interval. This function is used by the `findOuterPartition` function, which\n     * starts the detection with any random section.\n     *\n     * @method randomUnusedInterval\n     * @static\n     * @private\n     * @memberof CircleIntersections\n     * @param {Array<CircularIntervalSet>} intervalSets - An array of all available interval sets/intervals.\n     * @param {Matrix<boolean>} usedIntervals - A matrix indicating which intervals have already been used/visited by the algorithm\n     * @return {IndexPair|null}\n     **/\n    static randomUnusedInterval(intervalSets, usedIntervals) {\n        for (var i = 0; i < intervalSets.length; i++) {\n            for (var j = 0; j < intervalSets[i].intervals.length; j++) {\n                if (!usedIntervals[i][j]) {\n                    return { i: i, j: j };\n                }\n            }\n        }\n        return null;\n    }\n    /**\n     * Find the next adjacent circle interval for the given interval.\n     * starts the detection with any random section.\n     *\n     * @method randomUnusedInterval\n     * @static\n     * @private\n     * @memberof CircleIntersections\n     * @param {Array<CircularIntervalSet>} intervalSets - An array of all available interval sets/intervals.\n     * @param {Matrix<boolean>} usedIntervals - A matrix indicating which intervals have already been used/visited by the algorithm\n     * @return {IndexPair|null}\n     **/\n    static findAdjacentInterval(circles, intLocation, intervalSets, usedIntervalSetRecords, epsilon) {\n        var curInterval = intervalSets[intLocation.i].intervals[intLocation.j];\n        var curEndPoint = circles[intLocation.i].vertAt(curInterval[1]);\n        for (var i = 0; i < intervalSets.length; i++) {\n            for (var j = 0; j < intervalSets[i].intervals.length; j++) {\n                if (usedIntervalSetRecords[i][j]) {\n                    continue;\n                }\n                var interval = intervalSets[i].intervals[j];\n                var startPoint = circles[i].vertAt(interval[0]);\n                if (curEndPoint.distance(startPoint) < epsilon)\n                    return { i: i, j: j };\n            }\n        }\n        return null;\n    }\n}\n//# sourceMappingURL=CircleIntersections.js.map","/**\n * Remove duplicate vertices (2d) from an array.\n *\n * This method war taken and refactored from an older demo.\n *\n * @author   Ikaros Kappler\n * @date     2021-07-13\n * @modified 2023-10-28 Refactored and ported to Typescript.\n * @modified 2024-12-17 Simplified this method to work with generic sub types of XYCoords as well.\n * @version  1.0.1\n */\nimport { geomutils } from \"../../geomutils\";\nconst EPS = 0.000001;\n/**\n * Filter the array and clear all duplicates.\n *\n * The original array is left unchanged. The vertices in the array are not cloned.\n *\n * @param {XYCoords[]} vertices\n * @param {number=EPS} epsilon\n * @return {Vertex[]}\n */\nexport const clearDuplicateVertices = (vertices, epsilon) => {\n    if (typeof epsilon === \"undefined\") {\n        epsilon = EPS;\n    }\n    const result = [];\n    for (var i = 0; i < vertices.length; i++) {\n        if (!containsElementFrom(vertices, vertices[i], i + 1, epsilon)) {\n            result.push(vertices[i]);\n        }\n    }\n    return result;\n};\nconst isCloseTo = (vertA, vertB, eps) => {\n    // return vertA.distance(vertB) < eps;\n    return geomutils.dist4(vertA.x, vertA.y, vertB.x, vertB.y) < eps;\n};\nconst containsElementFrom = (vertices, vertex, fromIndex, epsilon) => {\n    for (var i = fromIndex; i < vertices.length; i++) {\n        if (isCloseTo(vertices[i], vertex, epsilon)) {\n            return true;\n        }\n    }\n    return false;\n};\n//# sourceMappingURL=clearDuplicateVertices.js.map","/**\n * @author   Ikaros Kappler\n * @version  1.1.0\n * @date     2022-10-17\n * @modified 2023-11-27 Added the `GenericPath.getAllStartEndPoints()` function.\n */\nexport class GenericPath {\n    constructor(startSegment) {\n        this.segments = [startSegment];\n    }\n    /**\n     * Get the number of segments in this path.\n     *\n     * @method getSegmentCount\n     * @memberof Path\n     * @return {number} The number (integer) of path segments.\n     */\n    getSegmentCount() {\n        return this.segments.length;\n    }\n    /**\n     * Get the path segment at the given index.\n     *\n     * @method getSegmentAt\n     * @memberof Path\n     * @return {PathSegment} The paths segment at the given index.\n     */\n    getSegmentAt(index) {\n        return this.segments[index];\n    }\n    /**\n     * Create a deep clone of this path.\n     *\n     * @method clone\n     * @memberof Path\n     * @return {Path} A deep clone/copy of this path.\n     */\n    clone() {\n        const newPath = new GenericPath(this.segments[this.segments.length - 1].clone().reverse());\n        for (var i = this.segments.length - 2; i >= 0; i--) {\n            newPath.segments.push(this.segments[i].clone().reverse());\n        }\n        return newPath;\n    }\n    /**\n     * Reverse this path (swap start and end and thus – the direction) in-place.\n     *\n     * @method reverse\n     * @memberof Path\n     * @return {PathSegment} This path instance.\n     */\n    reverse() {\n        const newSegments = [];\n        for (var i = this.segments.length - 1; i >= 0; i--) {\n            newSegments.push(this.segments[i].reverse());\n        }\n        this.segments = newSegments;\n        return this;\n    }\n    /**\n     * Get the start point of this path segment.\n     *\n     * @method getStartPoint\n     * @memberof PathSegment\n     * @return {Vertex} The start point of this path segment.\n     */\n    getStartPoint() {\n        return this.segments[0].getStartPoint();\n    }\n    /**\n     * Get the end point of this path segment.\n     *\n     * @method getEndPoint\n     * @memberof PathSegment\n     * @return {Vertex} The end point of this path segment.\n     */\n    getEndPoint() {\n        return this.segments[this.segments.length - 1].getEndPoint();\n    }\n    /**\n     * Get the tangent's end point at the start point of this segment.\n     *\n     * @method getStartTangent\n     * @memberof PathSegment\n     * @return {Vertex} The end point of the starting point's tangent.\n     */\n    getStartTangent() {\n        return this.segments[0].getStartTangent();\n    }\n    /**\n     * Get the tangent's end point at the end point of this segment.\n     *\n     * @method getEndTangent\n     * @memberof PathSegment\n     * @return {Vertex} The end point of the ending point's tangent.\n     */\n    getEndTangent() {\n        return this.segments[this.segments.length - 1].getEndTangent();\n    }\n    /**\n     * Get the sequence of all start/end points of this path.\n     * Assumption is: each path segment's end point is located on the next segment's start point\n     * to shape a full connected path.\n     *\n     * No arcs are considered here, just plain linear segments.\n     *\n     * @returns {Array<Vertex>}\n     */\n    getAllStartEndPoints() {\n        const verts = [this.segments[0].getStartPoint()];\n        this.segments.forEach((segment) => {\n            verts.push(segment.getEndPoint());\n        });\n        return verts;\n    }\n}\n//# sourceMappingURL=GenericPath.js.map","/**\n * A function to detect connected paths on the plane given by a random set of segments.\n *\n * Note that is algorithm operates IN PLACE and will ALTER your INPUT array.\n *\n * @author  Ikaros Kappler\n * @version 1.0.0\n * @date    2022-10-17\n */\nimport { GenericPath } from \"../datastructures/GenericPath\";\n/**\n * A private helper function that initializes the visitation tracking and reverses\n * dangling path ends to connect them with preceding paths.\n *\n * Note that this function alters those dangling path segments IN PLACE!\n *\n * @param segments\n * @param epsilon\n * @returns\n */\nconst initVisitationArray = (segments, epsilon) => {\n    const result = []; // { visited: false, hasPredecessor: false }\n    for (var i = 0; i < segments.length; i++) {\n        result.push({ visited: false, hasPredecessor: false, hasSuccessor: false });\n        for (var j = 0; j < segments.length; j++) {\n            if (i === j) {\n                continue;\n            }\n            if (segments[i].getStartPoint().distance(segments[j].getEndPoint()) < epsilon ||\n                segments[i].getStartPoint().distance(segments[j].getStartPoint()) < epsilon) {\n                result[i].hasPredecessor = true;\n            }\n            if (segments[i].getEndPoint().distance(segments[j].getEndPoint()) < epsilon ||\n                segments[i].getEndPoint().distance(segments[j].getStartPoint()) < epsilon) {\n                result[i].hasSuccessor = true;\n            }\n        }\n    }\n    // After first initialization make sure that no loose path ends are dangling around\n    // if the affected path segment has a predecessor (but nu successor).\n    //\n    // Revert those segments. This makes the actual detection algorithm much easier.\n    for (var i = 0; i < segments.length; i++) {\n        if (!result[i].hasSuccessor && result[i].hasPredecessor) {\n            segments[i] = segments[i].reverse();\n            result[i].hasPredecessor = false;\n            result[i].hasSuccessor = true;\n        }\n    }\n    return result;\n};\n/**\n * Find the next unvisited path segment (private helper function).\n *\n * There is a special order: starting path segments (those without any predecessor)\n * will be preferred. If no more open paths are available (no starting path segments),\n * then no more unvisited paths are available or all remaining paths are loops (without\n * determined start/end).\n *\n * Doing this keeps us from the need to run a final loop to connect detected sub paths.\n *\n * @param {Array<PathSegment>} segments - The path segments to search in.\n * @param { Array<Visitation>} isSegmentVisited\n * @returns {number} The index of the next unvisited path segment or -1 if no more are available.\n */\nconst locateUnvisitedSegment = (segments, isSegmentVisited) => {\n    // First run: detect beginnings\n    for (var i = 0; i < segments.length; i++) {\n        if (!isSegmentVisited[i].hasPredecessor && !isSegmentVisited[i].visited) {\n            return i;\n        }\n    }\n    // Second run: if no beginnings exist -> use inner path segment\n    for (var i = 0; i < segments.length; i++) {\n        if (!isSegmentVisited[i].visited) {\n            return i;\n        }\n    }\n    return -1;\n};\n/**\n * Get the next adjacent path segment to the given (current) segment. This is a private\n * helper function.\n *\n * Note that the function will revert the adjacent path segment if required, so the next\n * starting point 'equals' the current ending point.\n *\n * The visitation tracker will be updated if the adjacent segment was found.\n *\n * @param {Array<PathSegment>} segments - The total set of available path segments (visited and invisited).\n * @param {Array<Visitation>} isSegmentVisited - A tracker of visited path segments so far.\n * @param {PathSegment} currentSegment - The current path segment to find the adjacent segment for.\n * @param {number} epsilon - The epsilon to use to detect 'equal' start/end points. Must be >= 0.\n * @returns {PathSegment | null} The next adjacent path segment of null if no such exists.\n */\nconst getAdjacentSegment = (segments, isSegmentVisited, currentSegment, epsilon) => {\n    for (var j = 0; j < segments.length; j++) {\n        if (isSegmentVisited[j].visited) {\n            continue;\n        }\n        var nextSegment = segments[j];\n        // [start]---[end] [start]---[end]\n        if (currentSegment.getEndPoint().distance(nextSegment.getStartPoint()) < epsilon) {\n            isSegmentVisited[j].visited = true;\n            return nextSegment;\n        }\n        // [start]---[end] [end]---[start]\n        else if (currentSegment.getEndPoint().distance(nextSegment.getEndPoint()) < epsilon) {\n            isSegmentVisited[j].visited = true;\n            return nextSegment.reverse();\n        }\n    }\n    return null;\n};\n/**\n * A private helper function to find the adjacent full path for the given path segment,\n * considering the current path segment is a starting segment (or one inside a loop).\n *\n * @param {Array<PathSegment>} segments - The total set of available path segments.\n * @param { Array<Visitation>} isSegmentVisited - A tracker to determine which segments have already been visited.\n * @param {number} currentSegmentIndex - The index of the current segments to find the containing path for.\n * @param {number} epsilon - The epsilon to use to determine 'equal' path points. Must be >= 0.\n * @returns {GenericPath} The dected path which consists at least of the current path segment.\n */\nconst detectAdjacentPath = (segments, isSegmentVisited, currentSegmentIndex, epsilon) => {\n    var currentSegment = segments[currentSegmentIndex];\n    isSegmentVisited[currentSegmentIndex].visited = true;\n    const path = new GenericPath(currentSegment); // { segments: [currentSegment], reverse };\n    var i = 0;\n    // A safety break if something goes wrong\n    while (i < segments.length && currentSegment) {\n        currentSegment = getAdjacentSegment(segments, isSegmentVisited, currentSegment, epsilon);\n        if (currentSegment) {\n            path.segments.push(currentSegment);\n        }\n        i++;\n    }\n    return path;\n};\n/**\n * Run a path detection on the given set of path segments.\n *\n * Note that the array and some path segments may be altered (like reversal) IN PLACE.\n *\n * @param {Array<PathSegment>} segments - The total set (array) of available path segments.\n * @param {number=1.0} epsilon - (optional) An epsilon to use to tell if two plane points should be considered 'equal'.\n * @returns {Array<GenericPath>} An array containing all detected path (consisting of adjacent path segments of the original set).\n */\nexport const detectPaths = (segments, epsilon) => {\n    const eps = typeof epsilon === \"undefined\" || epsilon < 0 ? 1.0 : epsilon;\n    const isSegmentVisited = initVisitationArray(segments, eps);\n    const resultPaths = [];\n    var nextSegmentIndex = -1;\n    var i = 0;\n    while ((nextSegmentIndex = locateUnvisitedSegment(segments, isSegmentVisited)) !== -1 && i < segments.length) {\n        isSegmentVisited[nextSegmentIndex].visited = true;\n        // A safety break (to avoid infinited loops during development).\n        i++;\n        const path = detectAdjacentPath(segments, isSegmentVisited, nextSegmentIndex, eps);\n        i += path.getSegmentCount() - 1;\n        resultPaths.push(path);\n    }\n    return resultPaths;\n};\n//# sourceMappingURL=detectPaths.js.map","/**\n * A function to detect contour lines from 3D terrain data.\n *\n * For usage see demo `./demos/48-contour-plot`.\n *\n * @requires detectPaths\n * @requires GenericPath\n * @author   Ikaros Kappler\n * @date     2023-11-05\n * @modified 2023-11-20 Addig path detection on a triangle based grid.\n * @version  1.0.0\n */\nimport { Line } from \"../../Line\";\nimport { Vertex } from \"../../Vertex\";\nimport { detectPaths } from \"./detectPaths\";\nimport { clearDuplicateVertices } from \"./clearDuplicateVertices\";\nexport class ContourLineDetection {\n    /**\n     * Creates a new instance for calculating contour lines from the given data grid.\n     * @param {IDataGrid2d<number>} dataGrid - The data grid to use. Must not contain any NaN or null values.\n     * @param {boolean=?} debugMode - (optional) Pass `true` to log warnings on (rare) critical edge cases where the algorithm might fail.\n     */\n    constructor(dataGrid, debugMode) {\n        this.rawLinearPathSegments = [];\n        // Activates/deactivates warning messages on rare edge cases where local path detection fails.\n        this.debugMode = false;\n        this.dataGrid = dataGrid;\n        this.debugMode = Boolean(debugMode);\n    }\n    /**\n     * Detect contour paths from the underlying data source.\n     *\n     * @param {number} criticalHeightValue - The height value. If above data's maximum or below data's minimum then the result will be empty (no intersections).\n     * @param {number} options.closeGapType - `CLOSE_GAP_TYPE_NONE` or `CLOSE_GAP_TYPE_ABOVE` or `CLOSE_GAP_TYPE_BELOW`.\n     * @param {boolean=false} options.useTriangles - If set to true the detection will split each face3 quad into two triangle faces.\n     * @param {pathDetectEpsilon=0.000001} options.pathDetectEpsilon - (optional) The epsilon to tell if two points are located 'in the same place'. Used for connected path detection. If not specified the value `0.0000001` is used.\n     * @param {pointEliminationEpsilon=0.0000001} options.pointEliminationEpsilon - (optional) The epsilon for duplicate point elimination (default is 0.000001).\n     * @param {function?} onRawSegmentsDetected - (optional) Get the interim result of all detected single lines before path detection starts; DO NOT MODIFY the array.\n     * @returns {Array<GenericPath>} - A list of connected paths that resemble the contour lines of the data/terrain at the given height value.\n     */\n    detectContourPaths(criticalHeightValue, options) {\n        var _a, _b;\n        options = options || { closeGapType: ContourLineDetection.CLOSE_GAP_TYPE_NONE };\n        // First: clear the buffer\n        this.rawLinearPathSegments = [];\n        // Imagine a face4 element like this\n        //    (x,y)       (x+1,y)\n        //         A-----B\n        //         |   / |\n        //         | /   |\n        //         D-----C\n        //  (x,y+1)        (x+1,y+1)\n        //\t   then result in the buffer will be\n        //   [ [A,B],\n        //     [D,C] ]\n        // Note that the diagonal line (used for triangles) is optional; depends on `options.useTriangles`.\n        const heightFace = [\n            [0, 0],\n            [0, 0]\n        ];\n        for (var y = 0; y + 1 < this.dataGrid.ySegmentCount; y++) {\n            for (var x = 0; x + 1 < this.dataGrid.xSegmentCount; x++) {\n                this.dataGrid.getDataFace4At(x, y, heightFace);\n                this.findHeightFaceIntersectionLines(x, y, heightFace, criticalHeightValue, (_a = options.pointEliminationEpsilon) !== null && _a !== void 0 ? _a : 0.0000001, options.useTriangles);\n            }\n        }\n        // Collect value above/below on the y axis\n        if (options.closeGapType == ContourLineDetection.CLOSE_GAP_TYPE_ABOVE ||\n            options.closeGapType == ContourLineDetection.CLOSE_GAP_TYPE_BELOW) {\n            const xExtremes = [0, this.dataGrid.xSegmentCount - 1];\n            for (var i = 0; i < xExtremes.length; i++) {\n                const x = xExtremes[i];\n                for (var y = 0; y + 1 < this.dataGrid.ySegmentCount; y++) {\n                    const nextX = x;\n                    const nextY = y + 1;\n                    this.detectAboveBelowLerpSegment(x, y, nextX, nextY, criticalHeightValue, options.closeGapType);\n                }\n            }\n            const yExtremes = [0, this.dataGrid.ySegmentCount - 1];\n            for (var j = 0; j < yExtremes.length; j++) {\n                var y = yExtremes[j];\n                for (var x = 0; x + 1 < this.dataGrid.xSegmentCount; x++) {\n                    const nextX = x + 1;\n                    const nextY = y;\n                    this.detectAboveBelowLerpSegment(x, y, nextX, nextY, criticalHeightValue, options.closeGapType);\n                }\n            }\n        }\n        if (options.onRawSegmentsDetected) {\n            options.onRawSegmentsDetected(this.rawLinearPathSegments);\n        }\n        // Detect connected paths\n        let pathSegments = detectPaths(this.rawLinearPathSegments, (_b = options.pathDetectEpsilon) !== null && _b !== void 0 ? _b : 0.0000001); // Epsilon\n        // Filter out segments with only a single line of length~=0\n        pathSegments = pathSegments.filter(function (pathSegment) {\n            return (pathSegment.segments.length != 1 ||\n                (pathSegment.segments.length === 1 && pathSegment.segments[0].length() > 0.1));\n        });\n        return pathSegments;\n    }\n    /**\n     * This function will calculate a single intersecion line of the given face4 data\n     * segment. If the given face does not intersect with the plane at the given `heightValue`\n     * then no segments will be stored.\n     *\n     * @param {number} xIndex - The x position (index) of the data face.\n     * @param {number} yIndex - The y position (index) of the data face.\n     * @param {[[number,number],[number,number]]} heightFace - The data sample that composes the face4 as a two-dimensional number array.\n     * @param {number} heightValue - The height value of the intersection plane to check for.\n     * @returns {Line|null}\n     */\n    findHeight4FaceIntersectionLine(xIndex, yIndex, heightFace, heightValue, pointEliminationEpsilon) {\n        const heightValueA = heightFace[0][0]; // value at (x,y)\n        const heightValueB = heightFace[1][0];\n        const heightValueC = heightFace[1][1];\n        const heightValueD = heightFace[0][1];\n        if (heightValueA === null || heightValueB === null || heightValueC === null || heightValueD === null) {\n            throw `[findHeightFace4IntersectionLine] Cannot extract data face at (${xIndex},${yIndex}). Some values are null.`;\n        }\n        let points = [];\n        // Case A: use full quad face\n        if (this.isBetween(heightValueA, heightValueB, heightValue)) {\n            const lerpValueByHeight = this.getLerpRatio(heightValueA, heightValueB, heightValue);\n            points.push(new Vertex(this.lerp(xIndex, xIndex + 1, lerpValueByHeight), yIndex));\n        }\n        if (this.isBetween(heightValueB, heightValueC, heightValue)) {\n            const lerpValueByHeight = this.getLerpRatio(heightValueB, heightValueC, heightValue);\n            points.push(new Vertex(xIndex + 1, this.lerp(yIndex, yIndex + 1, lerpValueByHeight)));\n        }\n        if (this.isBetween(heightValueC, heightValueD, heightValue)) {\n            const lerpValueByHeight = this.getLerpRatio(heightValueC, heightValueD, heightValue);\n            points.push(new Vertex(this.lerp(xIndex + 1, xIndex, lerpValueByHeight), yIndex + 1));\n        }\n        if (this.isBetween(heightValueD, heightValueA, heightValue)) {\n            const lerpValueByHeight = this.getLerpRatio(heightValueD, heightValueA, heightValue);\n            points.push(new Vertex(xIndex, this.lerp(yIndex + 1, yIndex, lerpValueByHeight)));\n        }\n        // Warning: if a plane intersection point is located EXACTLY on the corner\n        // edge of a face, then the two adjacent edges will result in 2x the same\n        // intersecion point. This must be handled as one, so filter the point list\n        // by an epsilon.\n        points = clearDuplicateVertices(points, pointEliminationEpsilon); // 0.000001);\n        if (points.length >= 2) {\n            const startPoint = points[0];\n            const endPoint = points[1];\n            if (this.debugMode && points.length > 2) {\n                console.warn(\"[findHeightFace4IntersectionLine] Detected more than 2 points on one face whre only 0 or 2 should appear. At \", xIndex, yIndex, points);\n            }\n            return new Line(startPoint, endPoint);\n        }\n        else {\n            if (this.debugMode && points.length === 1) {\n                console.warn(\"[findHeightFace4IntersectionLine] Point list has only one point (should not happen).\");\n            }\n            return null;\n        }\n    }\n    /**\n     * This function will calculate a single intersecion line of the given face4 data\n     * segment. If the given face does not intersect with the plane at the given `heightValue`\n     * then no segments will be stored.\n     *\n     * @param {number} xIndex - The x position (index) of the data face.\n     * @param {number} yIndex - The y position (index) of the data face.\n     * @param {[[number,number],[number,number]]} heightFace - The data sample that composes the face4 as a two-dimensional number array.\n     * @param {number} heightValue - The height value of the intersection plane to check for.\n     * @returns {Line|null}\n     */\n    findHeightFaceIntersectionLines(xIndex, yIndex, heightFace, criticalHeightValue, pointEliminationEpsilon, useTriangles) {\n        // Imagine a face4 element like this\n        //    (x,y)       (x+1,y)\n        //         A-----B\n        //         |   / |\n        //         | /   |\n        //         D-----C\n        //  (x,y+1)        (x+1,y+1)\n        //\t   then result in the buffer will be\n        //   [ [A,B],\n        //     [D,C] ]\n        if (useTriangles) {\n            const lineA = this.findHeighteFace3IntersectionLine(xIndex, yIndex, xIndex, yIndex + 1, xIndex + 1, yIndex, [heightFace[0][0], heightFace[0][1], heightFace[1][0]], criticalHeightValue, pointEliminationEpsilon);\n            if (lineA) {\n                this.rawLinearPathSegments.push(lineA);\n            }\n            const lineB = this.findHeighteFace3IntersectionLine(xIndex, yIndex + 1, xIndex + 1, yIndex + 1, xIndex + 1, yIndex, [heightFace[0][1], heightFace[1][1], heightFace[1][0]], criticalHeightValue, pointEliminationEpsilon);\n            if (lineB) {\n                this.rawLinearPathSegments.push(lineB);\n            }\n        }\n        else {\n            const line = this.findHeight4FaceIntersectionLine(xIndex, yIndex, heightFace, criticalHeightValue, pointEliminationEpsilon);\n            if (line) {\n                this.rawLinearPathSegments.push(line);\n            }\n        }\n    }\n    /**\n     * This function will calculate a single intersecion line of the given face3 data\n     * segment. If the given face does not intersect with the plane at the given `heightValue`\n     * then no segments will be stored.\n     *\n     * @param {number} xIndexA - The x position (index) of the first triangle data point.\n     * @param {number} yIndexA - The y position (index) of the first triangle data point.\n     * @param {[[number,number],[number,number]]} heightFace - The data sample that composes the face4 as a two-dimensional number array.\n     * @param {number} heightValue - The height value of the intersection plane to check for.\n     * @returns {Line|null}\n     */\n    findHeighteFace3IntersectionLine(xIndexA, yIndexA, xIndexB, yIndexB, xIndexC, yIndexC, heightFace, heightValue, pointEliminationEpsilon) {\n        const heightValueA = heightFace[0]; // value at (x,y)\n        const heightValueB = heightFace[1];\n        const heightValueC = heightFace[2];\n        if (heightValueA === null || heightValueB === null || heightValueC === null) {\n            throw `[findHeightFace3IntersectionLine] Cannot extract data face at (${xIndexA},${yIndexA}). Some values are null.`;\n        }\n        let points = [];\n        // Case A: use full quad face\n        if (this.isBetween(heightValueA, heightValueB, heightValue)) {\n            const lerpValueByHeight = this.getLerpRatio(heightValueA, heightValueB, heightValue);\n            points.push(new Vertex(this.lerp(xIndexA, xIndexB, lerpValueByHeight), this.lerp(yIndexA, yIndexB, lerpValueByHeight)));\n        }\n        if (this.isBetween(heightValueB, heightValueC, heightValue)) {\n            const lerpValueByHeight = this.getLerpRatio(heightValueB, heightValueC, heightValue);\n            // points.push(new Vertex(xIndex + 1, this.lerp(yIndex, yIndex + 1, lerpValueByHeight)));\n            points.push(new Vertex(this.lerp(xIndexB, xIndexC, lerpValueByHeight), this.lerp(yIndexB, yIndexC, lerpValueByHeight)));\n        }\n        if (this.isBetween(heightValueC, heightValueA, heightValue)) {\n            const lerpValueByHeight = this.getLerpRatio(heightValueC, heightValueA, heightValue);\n            // points.push(new Vertex(this.lerp(xIndex + 1, xIndex, lerpValueByHeight), yIndex + 1));\n            points.push(new Vertex(this.lerp(xIndexC, xIndexA, lerpValueByHeight), this.lerp(yIndexC, yIndexA, lerpValueByHeight)));\n        }\n        // Warning: if a plane intersection point is located EXACTLY on the corner\n        // edge of a face, then the two adjacent edges will result in 2x the same\n        // intersecion point. This must be handled as one, so filter the point list\n        // by an epsilon.\n        points = clearDuplicateVertices(points, pointEliminationEpsilon); // 0.0000001);\n        if (points.length >= 2) {\n            const startPoint = points[0];\n            const endPoint = points[1];\n            if (this.debugMode && points.length > 2) {\n                console.warn(\"[findHeightFace3IntersectionLine] Detected more than 2 points on one face whre only 0 or 2 should appear. At \", xIndexA, yIndexA, points);\n            }\n            return new Line(startPoint, endPoint);\n        }\n        else {\n            if (this.debugMode && points.length === 1) {\n                console.warn(\"[findHeightFace3IntersectionLine] Point list has only one point (should not happen).\");\n            }\n            return null;\n        }\n    }\n    /**\n     * This procedure will look at the face4 at the ((x,y),(nextX,nextY)) position – which are four values –\n     * and determines the local contour lines for these cases.\n     *\n     * This is used to detect and calculate edge cases on the borders of the underliying height data:\n     *  * left and right border (x=0, x=data.xSegmentCount)\n     *  * top and bottom border (x=y, x=data.ySegmentCount)\n     *\n     * Resulting path segments will be stored in the global `rawLinearPathSegments` array for further processing.\n     *\n     * @param {number} x\n     * @param {number} y\n     * @param {number} nextX\n     * @param {number} nextY\n     * @param {number} criticalHeightValue\n     * @param {number} closeGapType - CLOSE_GAP_TYPE_ABOVE or CLOSE_GAP_TYPE_BELOW.\n     * @return {void}\n     */\n    detectAboveBelowLerpSegment(x, y, nextX, nextY, criticalHeightValue, closeGapType) {\n        const heightValueA = this.dataGrid.getDataValueAt(x, y);\n        const heightValueB = this.dataGrid.getDataValueAt(nextX, nextY);\n        //   if (heightValueA >= criticalHeightValue && heightValueB >= criticalHeightValue) {\n        if (this.areBothValuesOnRequiredPlaneSide(heightValueA, heightValueB, criticalHeightValue, closeGapType)) {\n            //  Both above\n            const line = new Line(new Vertex(x, y), new Vertex(nextX, nextY));\n            this.rawLinearPathSegments.push(line);\n        }\n        else if ((closeGapType == ContourLineDetection.CLOSE_GAP_TYPE_ABOVE &&\n            heightValueA >= criticalHeightValue &&\n            heightValueB <= criticalHeightValue) ||\n            (closeGapType == ContourLineDetection.CLOSE_GAP_TYPE_BELOW &&\n                heightValueA <= criticalHeightValue &&\n                heightValueB >= criticalHeightValue)) {\n            // Only one of both (first) is above -> interpolate to find exact intersection point\n            const lerpValueByHeight = this.getLerpRatio(heightValueA, heightValueB, criticalHeightValue);\n            const interpLine = new Line(new Vertex(x, y), new Vertex(this.lerp(x, nextX, lerpValueByHeight), this.lerp(y, nextY, lerpValueByHeight)));\n            this.rawLinearPathSegments.push(interpLine);\n        }\n        else if ((closeGapType == ContourLineDetection.CLOSE_GAP_TYPE_ABOVE &&\n            heightValueA <= criticalHeightValue &&\n            heightValueB >= criticalHeightValue) ||\n            (closeGapType == ContourLineDetection.CLOSE_GAP_TYPE_BELOW &&\n                heightValueA >= criticalHeightValue &&\n                heightValueB <= criticalHeightValue)) {\n            // Only one of both (second) is above -> interpolate to find exact intersection point\n            const lerpValueByHeight = this.getLerpRatio(heightValueA, heightValueB, criticalHeightValue);\n            const interpLine = new Line(new Vertex(this.lerp(x, nextX, lerpValueByHeight), this.lerp(y, nextY, lerpValueByHeight)), new Vertex(nextX, nextY));\n            this.rawLinearPathSegments.push(interpLine);\n        }\n    }\n    /**\n     * Checks if both value are on the same side of the critical value (above or below). The `closeGapType`\n     * indictes if `CLOSE_GAP_TYPE_BELOW` or `CLOSE_GAP_TYPE_ABOVE` should be used as a rule.\n     *\n     * @param {number} valueA\n     * @param {number} valueB\n     * @param {number} criticalValue\n     * @param {number} closeGapType\n     * @returns {boolean}\n     */\n    areBothValuesOnRequiredPlaneSide(valueA, valueB, criticalValue, closeGapType) {\n        return ((closeGapType == ContourLineDetection.CLOSE_GAP_TYPE_BELOW && valueA <= criticalValue && valueB <= criticalValue) ||\n            (closeGapType == ContourLineDetection.CLOSE_GAP_TYPE_ABOVE && valueA >= criticalValue && valueB >= criticalValue));\n    }\n    /**\n     * Test if a given numeric value (`curValue`) is between the given values `valA` and `valB`.\n     * Value A and B don't need to be in ascending order, so `valA <= curValue <= valB` and `valB <= curvalue <= valA`\n     * will do the job.\n     *\n     * @param {number} valA - The first of the two bounds.\n     * @param {number} valB - The second of the two bounds.\n     * @param {number} curValue - The value to check if it is between (or equal) to the given bounds.\n     * @returns {boolean}\n     */\n    isBetween(valA, valB, curValue) {\n        return (valA <= curValue && curValue <= valB) || (valB <= curValue && curValue <= valA);\n    }\n    /**\n     * Get a 'lerp' value - which is some sort of percentage/ratio for the `curValue` inside the\n     * range of the given interval `[valA ... valB]`.\n     *\n     * Examples:\n     *  * getLerpRatio(0,100,50) === 0.5\n     *  * getLerpRatio(50,100,75) === 0.5\n     *  * getLerpRatio(0,100,0) === 0.0\n     *  * getLerpRatio(0,100,100) === 1.0\n     *  * getLerpRatio(0,100,-50) === -0.5\n     *\n     * @param {number} valA\n     * @param {number} valB\n     * @param {number} curValue\n     * @returns\n     */\n    getLerpRatio(valA, valB, curValue) {\n        return (curValue - valA) / (valB - valA);\n    }\n    /**\n     * Helper function to lerp a numeric value.\n     *\n     * @param {number} min - The min (start) value. Doesn't necesarily need to be the smaller one.\n     * @param {number} max - The max (end) value. Doesn't necesarily need to be the larger one.\n     * @param {number} ratio - The lerp ratio; usually a value between 0.0 and 1.0, but other values a valid for linear interpolation, too.\n     * @returns {number}\n     */\n    lerp(min, max, ratio) {\n        return min + (max - min) * ratio;\n    }\n}\nContourLineDetection.CLOSE_GAP_TYPE_NONE = 0;\nContourLineDetection.CLOSE_GAP_TYPE_ABOVE = 1;\nContourLineDetection.CLOSE_GAP_TYPE_BELOW = 2;\n//# sourceMappingURL=ContourLineDetection.js.map","/**\n * @author   Rosettcode, rewritten and ported to TypeScript by Ikaros Kappler\n * @date     2020-05-04\n * @modified 2020-08-17 Ported this function from vanilla JS to TypeScript.\n * @version  1.0.1\n *\n * @file convexHull\n * @public\n **/\n/**\n * @description The Convex Hull algorithm, found at RosettaCode:\n *\n * https://rosettacode.org/wiki/Convex_hull#JavaScript\n *\n * @requires XYCoords\n *\n * @global\n * @name convexHull\n * @param {Array<XYCoords>} points - The points on the 2D plane to find the convex hull for.\n * @return {Array<XYCoords>} A ordered array of points defining the convex hull.\n **/\nexport const getConvexHull = (points) => {\n    points.sort(comparison);\n    const L = [];\n    for (var i = 0; i < points.length; i++) {\n        while (L.length >= 2 && cross(L[L.length - 2], L[L.length - 1], points[i]) <= 0) {\n            L.pop();\n        }\n        L.push(points[i]);\n    }\n    const U = [];\n    for (var i = points.length - 1; i >= 0; i--) {\n        while (U.length >= 2 && cross(U[U.length - 2], U[U.length - 1], points[i]) <= 0) {\n            U.pop();\n        }\n        U.push(points[i]);\n    }\n    L.pop();\n    U.pop();\n    return L.concat(U);\n};\n/**\n * Compare two vertices to create an order on the 2D plane.\n *\n * @name comparison\n * @private\n * @param {XYCoords} a - The first of the two points to compare.\n * @param {XYCoords} b - The second of the two points to compare.\n * @return {number} A number indicating the order (negative if `a` is 'smaller', 0 if both are equal, positive if `a` is 'larger').\n **/\nconst comparison = (a, b) => {\n    return a.x == b.x ? a.y - b.y : a.x - b.x;\n};\n/**\n * Calculate the cross product of the three coordinates, interpreted as vectors.\n *\n * @name cross\n * @private\n * @param {XYCoords} a\n * @param {XYCoords} b\n * @param {XYCoords} o\n * @return {number} The cross product of the three 'vectors'.\n **/\nconst cross = (a, b, o) => {\n    return (a.x - o.x) * (b.y - o.y) - (a.y - o.y) * (b.x - o.x);\n};\n//# sourceMappingURL=convexHull.js.map","/**\n * @author   mbostock, extended and ported to TypeScript by Ikaros Kappler\n * @date     2020-05-19\n * @modified 2021-02-08 Fixed a lot of es2015 compatibility issues.\n * @modified 2024-03-24 Fixing some unstrict types to match with the new Typescript settings.\n * @version  1.0.3\n * @file     contextPolygonIncircle\n * @public\n */\nimport { Circle } from \"../../Circle\";\nimport { geomutils } from \"../../geomutils\";\nimport { Line } from \"../../Line\";\nimport { Triangle } from \"../../Triangle\";\n/**\n * For circle-polygon-intersection-count detection we need an epsilon to\n * eliminate smaller precision errors.\n */\nconst EPS = 0.000001;\n/**\n * Compute the max sized inlying circle in the given convex (!) polygon - also called the\n * convex-polygon incircle.\n *\n * The function will return an object with either: the circle, and the triangle that defines\n * the three tangent points where the circle touches the polygon.\n *\n * Inspired by\n *  https://observablehq.com/@mbostock/convex-polygon-incircle\n *  https://observablehq.com/@mbostock/circle-tangent-to-three-lines\n *\n *\n * @requires Circle\n * @requires Line\n * @requires Vertex\n * @requires Triangle\n * @requires nsectAngle\n * @requires geomutils\n *\n * @global\n * @name convexPolygonIncircle\n * @param {Polygon} convexHull - The actual convex polygon.\n * @return {PolygonIncircle} A pair of a circle (the incircle) and a triangle (the three points where the circle is touching the polygon).\n */\nexport const convexPolygonIncircle = (convexHull) => {\n    var n = convexHull.vertices.length;\n    var bestCircle = null;\n    var bestTriangle = null;\n    for (var a = 0; a < n; a++) {\n        for (var b = a + 1; b < n; b++) {\n            for (var c = b + 1; c < n; c++) {\n                // As these lines are part of the convex hull, we know that\n                //  * line a preceeds line b and\n                //  * line b preceeds line c :)\n                let lineA = new Line(convexHull.vertices[a], convexHull.vertices[(a + 1) % n]);\n                let lineB = new Line(convexHull.vertices[b], convexHull.vertices[(b + 1) % n]);\n                let lineC = new Line(convexHull.vertices[c], convexHull.vertices[(c + 1) % n]);\n                // Find intersections by expanding the lines\n                let vertB = lineA.intersection(lineB);\n                let vertC = lineB.intersection(lineC);\n                if (!vertB || !vertC) {\n                    continue;\n                }\n                // An object: { center: Vertex, radius: number }\n                let triangle = getTangentTriangle4(lineA.a, vertB, vertC, lineC.b);\n                if (!triangle) {\n                    continue;\n                }\n                // Workaround. There will be a future version where the 'getCircumCircle()' functions\n                // returns a real Circle instance.\n                let _circle = triangle.getCircumcircle();\n                let circle = new Circle(_circle.center, _circle.radius);\n                // Count the number of intersections with the convex hull:\n                // If there are exactly three, we have found an in-lying circle.\n                //  * Check if this one is better (bigger) than the old one.\n                //  * Also check if the circle is located inside the polygon;\n                //    The construction can, in some cases, produce an out-lying circle.\n                if (!convexHull.containsVert(circle.center)) {\n                    continue;\n                }\n                var circleIntersections = findCircleIntersections(convexHull, circle);\n                if (circleIntersections.length == 3 && (bestCircle == undefined || bestCircle.radius < circle.radius)) {\n                    bestCircle = circle;\n                    bestTriangle = triangle;\n                }\n            }\n        }\n    }\n    return { circle: bestCircle, triangle: bestTriangle };\n};\n/**\n * This function computes the three points for the inner maximum circle\n * lying tangential to the three subsequential lines (given by four points).\n *\n * Compute the circle from that triangle by using Triangle.getCircumcircle().\n *\n * Not all three lines should be parallel, otherwise the circle might have infinite radius.\n *\n * LineA := [vertA, vertB]\n * LineB := [vertB, vertC]\n * LineC := [vertC, vertD]\n *\n * @param {Vertex} vertA - The first point of the three connected lines.\n * @param {Vertex} vertB - The second point of the three connected lines.\n * @param {Vertex} vertC - The third point of the three connected lines.\n * @param {Vertex} vertD - The fourth point of the three connected lines.\n * @return {Triangle} The triangle of the circular tangential points with the given lines (3 or 4 of them).\n */\nconst getTangentTriangle4 = (vertA, vertB, vertC, vertD) => {\n    const lineA = new Line(vertA, vertB);\n    const lineB = new Line(vertB, vertC);\n    const lineC = new Line(vertC, vertD);\n    const bisector1 = geomutils.nsectAngle(vertB, vertA, vertC, 2)[0]; // bisector of first triangle\n    const bisector2 = geomutils.nsectAngle(vertC, vertB, vertD, 2)[0]; // bisector of second triangle\n    const intersection = bisector1.intersection(bisector2);\n    if (!intersection) {\n        return null;\n    }\n    // Find the closest points on one of the polygon lines (all have same distance by construction)\n    const circleIntersA = lineA.getClosestPoint(intersection);\n    const circleIntersB = lineB.getClosestPoint(intersection);\n    const circleIntersC = lineC.getClosestPoint(intersection);\n    return new Triangle(circleIntersA, circleIntersB, circleIntersC);\n};\n/**\n * Find all intersecting lines (indices) on the polyon that intersect the circle.\n *\n * @param {Polygon} convexHull - The polygon to detect the intersections on (here this is the convex hull given).\n * @param {Circle} circle - The circle to detect the intersections with.\n * @return {Array<number>} The indices of those lines that intersect (or touch) the circle.\n **/\nconst findCircleIntersections = (convexHull, circle) => {\n    const result = [];\n    for (var i = 0; i < convexHull.vertices.length; i++) {\n        var line = new Line(convexHull.vertices[i], convexHull.vertices[(i + 1) % convexHull.vertices.length]);\n        // Use an epsilon here because circle coordinates can be kind of unprecise in the detail.\n        if (circle.lineDistance(line) < EPS) {\n            result.push(i);\n        }\n    }\n    return result;\n};\n//# sourceMappingURL=convexPolygonIncircle.js.map","/**\n * @classdesc A HobbyCurve/HobbyPath calculation class: compute a set of optimal\n *            cubic Bézier curves from a sequence of vertices.\n *\n * This Hobby curve (path) implementation was strongly inspired by\n * the one by Prof. Dr. Edmund Weitz:\n * Here's the website:\n *  http://weitz.de/hobby/\n *\n * @date     2020-04-07\n * @author   Transformed to a JS-class by Ikaros Kappler\n * @modified 2020-08-19 Ported from vanilla JS to TypeScript.\n * @version 1.0.1\n *\n * @file HobbyPath\n * @public\n **/\nimport { CubicBezierCurve } from \"../../CubicBezierCurve\";\nimport { Vertex } from \"../../Vertex\";\n/**\n * @classdesc A HobbyCurve/HobbyPath calculation class: compute a set of optimal\n *            cubic Bézier curves from a sequence of vertices.\n *\n * @requires CubicBezierCurve\n * @requires Vertex\n */\nexport class HobbyPath {\n    /**\n     * @constructor\n     * @name HobbyPath\n     * @param {Array<Vertex>=} vertices? - An optional array of vertices to initialize the path with.\n     **/\n    constructor(vertices) {\n        this.vertices = vertices ? vertices : [];\n    }\n    /**\n     * Add a new point to the end of the vertex sequence.\n     *\n     * @name addPoint\n     * @memberof HobbyPath\n     * @instance\n     * @param {Vertex} p - The vertex (point) to add.\n     **/\n    addPoint(p) {\n        this.vertices.push(p);\n    }\n    /**\n     * Generate a sequence of cubic Bézier curves from the point set.\n     *\n     * @name generateCurve\n     * @memberof HobbyPath\n     * @instance\n     * @param {boolean=} circular - Specify if the path should be closed.\n     * @param {number=0} omega - (default=0) An optional tension parameter.\n     * @return Array<CubicBezierCurve>\n     **/\n    generateCurve(circular, omega) {\n        let n = this.vertices.length;\n        if (n > 1) {\n            if (n == 2) {\n                // for two points, just draw a straight line\n                return [new CubicBezierCurve(this.vertices[0], this.vertices[1], this.vertices[0], this.vertices[1])];\n            }\n            else {\n                const curves = [];\n                let controlPoints = this.hobbyControls(circular, omega);\n                for (let i = 0; i < n - (circular ? 0 : 1); i++) {\n                    // if i is n-1, the \"next\" point is the first one\n                    let j = (i + 1) % n; // Use a succ function here?\n                    curves.push(new CubicBezierCurve(this.vertices[i], this.vertices[j], controlPoints.startControlPoints[i], controlPoints.endControlPoints[i]));\n                }\n                return curves;\n            }\n        }\n        else {\n            return [];\n        }\n    }\n    /**\n     * Computes the control point coordinates for a Hobby curve through\n     * the points given.\n     *\n     * @name hobbyControls\n     * @memberof HobbyPath\n     * @instance\n     * @param {boolean}  circular - If true, then the path will be closed.\n     * @param {number=0} omega    - The 'curl' or the path.\n     * @return {IControlPoints} An object with two members: startControlPoints and endControlPoints (Array<Vertex>).\n     **/\n    hobbyControls(circular, omega) {\n        // This is a version that works for both, closed and non-closed paths.\n        if (typeof omega === \"undefined\")\n            omega = 0;\n        let n = this.vertices.length - (circular ? 0 : 1);\n        let D = new Array(n);\n        let ds = new Array(n);\n        var succ = (i) => {\n            return circular ? (i + 1) % n : i + 1;\n        };\n        var pred = (i) => {\n            return circular ? (i + n - 1) % n : i - 1;\n        };\n        for (let i = 0; i < n; i++) {\n            // the \"next\" point in a modular way\n            let j = succ(i);\n            ds[i] = this.vertices[i].difference(this.vertices[j]);\n            D[i] = Math.sqrt(ds[i].x * ds[i].x + ds[i].y * ds[i].y);\n        }\n        let gamma = new Array(n + (circular ? 0 : 1));\n        for (let i = circular ? 0 : 1; i < n; i++) {\n            // the \"previous\" point in a modular way\n            let k = pred(i);\n            let sin = ds[k].y / D[k];\n            let cos = ds[k].x / D[k];\n            let vec = HobbyPath.utils.rotate(ds[i], -sin, cos);\n            gamma[i] = Math.atan2(vec.y, vec.x);\n        }\n        if (!circular)\n            gamma[n] = 0;\n        let a = new Array(n + (circular ? 0 : 1));\n        let b = new Array(n + (circular ? 0 : 1));\n        let c = new Array(n + (circular ? 0 : 1));\n        let d = new Array(n + (circular ? 0 : 1));\n        for (let i = circular ? 0 : 1; i < n; i++) {\n            // j is the \"next\" point, k the \"previous\" one\n            let j = succ(i);\n            let k = pred(i);\n            // see video for the equations\n            a[i] = 1 / D[k];\n            b[i] = (2 * D[k] + 2 * D[i]) / (D[k] * D[i]);\n            c[i] = 1 / D[i];\n            d[i] = -(2 * gamma[i] * D[i] + gamma[j] * D[k]) / (D[k] * D[i]);\n        }\n        // make matrix tridiagonal in preparation for the \"sherman\" function\n        var alpha;\n        var beta;\n        if (circular) {\n            let s = a[0] * omega; // Use omega here?\n            a[0] = 0;\n            let t = c[n - 1] * omega; // Use omega here?\n            c[n - 1] = 0;\n            alpha = HobbyPath.utils.sherman(a, b, c, d, s, t);\n            beta = new Array(n);\n            for (let i = 0; i < n - (circular ? 0 : 1); i++) {\n                // \"next\" point\n                let j = succ(i);\n                beta[i] = -gamma[j] - alpha[j];\n            }\n        }\n        else {\n            // see the Jackowski article for the following values; the result\n            // will be that the curvature at the first point is identical to the\n            // curvature at the second point (and likewise for the last and\n            // second-to-last)\n            b[0] = 2 + omega;\n            c[0] = 2 * omega + 1;\n            d[0] = -c[0] * gamma[1];\n            a[n] = 2 * omega + 1;\n            b[n] = 2 + omega;\n            d[n] = 0;\n            // solve system for the angles called \"alpha\" in the video\n            alpha = HobbyPath.utils.thomas(a, b, c, d);\n            // compute \"beta\" angles from \"alpha\" angles\n            beta = new Array(n);\n            for (let i = 0; i < n - 1; i++)\n                beta[i] = -gamma[i + 1] - alpha[i + 1];\n            // again, see Jackowski article\n            beta[n - 1] = -alpha[n];\n        }\n        let startControlPoints = new Array(n);\n        let endControlPoints = new Array(n);\n        for (let i = 0; i < n; i++) {\n            let j = succ(i);\n            let a = (HobbyPath.utils.rho(alpha[i], beta[i]) * D[i]) / 3;\n            let b = (HobbyPath.utils.rho(beta[i], alpha[i]) * D[i]) / 3;\n            let v = HobbyPath.utils.normalize(HobbyPath.utils.rotateAngle(ds[i], alpha[i]));\n            startControlPoints[i] = new Vertex(this.vertices[i].x + a * v.x, this.vertices[i].y + a * v.y);\n            v = HobbyPath.utils.normalize(HobbyPath.utils.rotateAngle(ds[i], -beta[i]));\n            endControlPoints[i] = new Vertex(this.vertices[j].x - b * v.x, this.vertices[j].y - b * v.y);\n        }\n        return { startControlPoints: startControlPoints, endControlPoints: endControlPoints };\n    }\n} // END class\nHobbyPath.utils = {\n    // rotates a vector [x, y] about an angle; the angle is implicitly\n    // determined by its sine and cosine\n    rotate: (vert, sin, cos) => {\n        return new Vertex(vert.x * cos - vert.y * sin, vert.x * sin + vert.y * cos);\n    },\n    // rotates a vector [x, y] about the angle alpha\n    rotateAngle: (vert, alpha) => {\n        return HobbyPath.utils.rotate(vert, Math.sin(alpha), Math.cos(alpha));\n    },\n    // returns a normalized version of the vector\n    normalize: (vec) => {\n        let n = Math.hypot(vec.x, vec.y);\n        if (n == 0)\n            return new Vertex(0, 0);\n        else\n            return new Vertex(vec.x / n, vec.y / n); // TODO: do in-place\n    },\n    // the \"velocity function\" (also called rho in the video); a and b are\n    // the angles alpha and beta, the return value is the distance between\n    // a control point and its neighboring point; to compute sigma(a,b)\n    // we'll simply use rho(b,a)\n    rho: (a, b) => {\n        // see video for formula\n        let sa = Math.sin(a);\n        let sb = Math.sin(b);\n        let ca = Math.cos(a);\n        let cb = Math.cos(b);\n        let s5 = Math.sqrt(5);\n        let num = 4 + Math.sqrt(8) * (sa - sb / 16) * (sb - sa / 16) * (ca - cb);\n        let den = 2 + (s5 - 1) * ca + (3 - s5) * cb;\n        return num / den;\n    },\n    // Implements the Thomas algorithm for a tridiagonal system with i-th\n    // row a[i]x[i-1] + b[i]x[i] + c[i]x[i+1] = d[i] starting with row\n    // i=0, ending with row i=n-1 and with a[0] = c[n-1] = 0.  Returns the\n    // values x[i] as an array.\n    thomas: (a, b, c, d) => {\n        let n = a.length;\n        let cc = new Array(n);\n        let dd = new Array(n);\n        // forward sweep\n        cc[0] = c[0] / b[0];\n        dd[0] = d[0] / b[0];\n        for (let i = 1; i < n; i++) {\n            let den = b[i] - cc[i - 1] * a[i];\n            cc[i] = c[i] / den;\n            dd[i] = (d[i] - dd[i - 1] * a[i]) / den;\n        }\n        let x = new Array(n);\n        // back substitution\n        x[n - 1] = dd[n - 1];\n        for (let i = n - 2; i >= 0; i--)\n            x[i] = dd[i] - cc[i] * x[i + 1];\n        return x;\n    },\n    // Solves an \"almost\" tridiagonal linear system with i-th row\n    // a[i]x[i-1] + b[i]x[i] + c[i]x[i+1] = d[i] starting with row i=0,\n    // ending with row i=n-1 and with a[0] = c[n-1] = 0.  Returns the\n    // values x[i] as an array.  The system is not really tridiagonal\n    // because the 0-th row is b[0]x[0] + c[0]x[1] + sx[n-1] = d[0] and\n    // row n-1 is tx[0] + a[n-1]x[n-2] + b[n-1]x[n-1] = d[n-1].  The\n    // Sherman-Morrison-Woodbury formula is used so that the function\n    // \"thomas\" can be called to solve the system.\n    sherman: (a, b, c, d, s, t) => {\n        const n = a.length;\n        const u = new Array(n);\n        u.fill(0, 1, n - 1);\n        u[0] = 1;\n        u[n - 1] = 1;\n        let v = new Array(n);\n        v.fill(0, 1, n - 1);\n        v[0] = t;\n        v[n - 1] = s;\n        b[0] -= t;\n        b[n - 1] -= s;\n        // this would be more efficient if computed in parallel, but hey...\n        const Td = HobbyPath.utils.thomas(a, b, c, d);\n        const Tu = HobbyPath.utils.thomas(a, b, c, u);\n        const factor = (t * Td[0] + s * Td[n - 1]) / (1 + t * Tu[0] + s * Tu[n - 1]);\n        const x = new Array(n);\n        for (let i = 0; i < n; i++)\n            x[i] = Td[i] - factor * Tu[i];\n        return x;\n    }\n};\n//# sourceMappingURL=HobbyPath.js.map","/**\n * @author   Ikaros Kappler (ported from basic script to class).\n * @date     2020-04-15\n * @modified 2020-08-19 Ported this class from vanilla JS to TypeScript.\n * @version  1.0.0\n *\n * @file CubicSplinePath\n * @public\n **/\nimport { CubicBezierCurve } from \"../../CubicBezierCurve\";\nimport { HobbyPath } from \"./HobbyPath\";\nimport { Vertex } from \"../../Vertex\";\n;\n/**\n * @classdesc Compute a natural cubic Bézier spline path from a given sequence of points/vertices.\n *\n * Inspired by http://weitz.de/hobby/\n *\n * @requires CubicBezierCurve\n * @requires HobbyPath\n * @requires Vertex\n */\nexport class CubicSplinePath {\n    /**\n     * @constructor\n     * @name CubicSplinePath\n     * @param {Array<Vertex>=} vertices? - An optional array of vertices to initialize the path with.\n     **/\n    constructor(vertices) {\n        this.vertices = vertices ? vertices : [];\n    }\n    ;\n    /**\n    * Add a new point to the end of the vertex sequence.\n    *\n    * @name addPoint\n    * @memberof CubicSplinePath\n    * @instance\n    * @param {Vertex} p - The vertex (point) to add.\n    **/\n    addPoint(p) {\n        this.vertices.push(p);\n    }\n    ;\n    /**\n     * Generate a sequence of cubic Bézier curves from the point set.\n     *\n     * @name generateCurve\n     * @memberof CubicSplinePath\n     * @instance\n     * @param {boolean=} circular - Specify if the path should be closed.\n     * @return Array<CubicBezierCurve>\n     **/\n    generateCurve(circular) {\n        const xs = [];\n        const ys = [];\n        for (var i = 0; i < this.vertices.length; i++) {\n            xs.push(this.vertices[i].x);\n            ys.push(this.vertices[i].y);\n        }\n        const curves = [];\n        let n = this.vertices.length;\n        if (n > 1) {\n            if (n == 2) {\n                // for two points, just draw a straight line\n                curves.push(new CubicBezierCurve(this.vertices[0], this.vertices[1], this.vertices[0], this.vertices[1]));\n            }\n            else {\n                if (!circular) {\n                    // open curve\n                    // x1 and y1 contain the coordinates of the first control\n                    // points, x2 and y2 those of the second\n                    const controlsX = CubicSplinePath.utils.naturalControlsOpen(xs);\n                    const controlsY = CubicSplinePath.utils.naturalControlsOpen(ys);\n                    for (let i = 1; i < n; i++) {\n                        // add Bézier segment - two control points and next node\n                        curves.push(new CubicBezierCurve(this.vertices[i - 1], this.vertices[i], new Vertex(controlsX.start[i - 1], controlsY.start[i - 1]), // x1[i-1], y1[i-1]), // new Vertex(x1[i-1], y1[i-1]),\n                        new Vertex(controlsX.end[i - 1], controlsY.end[i - 1]) // new Vertex(x2[i-1], y2[i-1])\n                        ));\n                    }\n                }\n                else {\n                    // closed curve, i.e. endpoints are connected\n                    // see comments for open curve\n                    let controlsX = CubicSplinePath.utils.naturalControlsClosed(xs);\n                    let controlsY = CubicSplinePath.utils.naturalControlsClosed(ys);\n                    for (let i = 0; i < n; i++) {\n                        // if i is n-1, the \"next\" point is the first one\n                        let j = (i + 1) % n;\n                        curves.push(new CubicBezierCurve(this.vertices[i], this.vertices[j], new Vertex(controlsX.start[i], controlsY.start[i]), // new Vertex(x1[i], y1[i]),\n                        new Vertex(controlsX.end[i], controlsY.end[i]) // new Vertex(x2[i], y2[i])\n                        ));\n                    }\n                }\n            }\n        }\n        return curves;\n    }\n    ;\n}\nCubicSplinePath.utils = {\n    naturalControlsClosed: (coords) => {\n        const n = coords.length;\n        // a, b, and c are the diagonals of the tridiagonal matrix, d is the\n        // right side\n        const a = new Array(n);\n        const b = new Array(n);\n        const c = new Array(n);\n        const d = new Array(n);\n        // the video explains why the matrix is filled this way\n        b[0] = 4;\n        c[0] = 1;\n        d[0] = 4 * coords[0] + 2 * coords[1];\n        a[n - 1] = 1;\n        b[n - 1] = 4;\n        d[n - 1] = 4 * coords[n - 1] + 2 * coords[0];\n        for (let i = 1; i < n - 1; i++) {\n            a[i] = 1;\n            b[i] = 4;\n            c[i] = 1;\n            d[i] = 4 * coords[i] + 2 * coords[i + 1];\n        }\n        // add a one to the two empty corners and solve the system for the\n        // first control points\n        const x1 = HobbyPath.utils.sherman(a, b, c, d, 1, 1);\n        // compute second controls points from first\n        const x2 = new Array(n);\n        for (let i = 0; i < n - 1; i++)\n            x2[i] = 2 * coords[i + 1] - x1[i + 1];\n        x2[n - 1] = 2 * coords[0] - x1[0];\n        return { start: x1, end: x2 };\n    },\n    // computes two arrays for the first and second controls points for a\n    // natural cubic spline through the points in K, an \"open\" curve where\n    // the curve doesn't return to the starting point; the function works\n    // with one coordinate at a time, i.e. it has to be called twice\n    naturalControlsOpen: (coords) => {\n        const n = coords.length - 1;\n        // a, b, and c are the diagonals of the tridiagonal matrix, d is the\n        // right side\n        const a = new Array(n);\n        const b = new Array(n);\n        const c = new Array(n);\n        const d = new Array(n);\n        // the video explains why the matrix is filled this way\n        b[0] = 2;\n        c[0] = 1;\n        d[0] = coords[0] + 2 * coords[1];\n        a[n - 1] = 2;\n        b[n - 1] = 7;\n        d[n - 1] = 8 * coords[n - 1] + coords[n];\n        for (let i = 1; i < n - 1; i++) {\n            a[i] = 1;\n            b[i] = 4;\n            c[i] = 1;\n            d[i] = 4 * coords[i] + 2 * coords[i + 1];\n        }\n        // solve the system to get the first control points\n        const x1 = HobbyPath.utils.thomas(a, b, c, d);\n        // compute second controls points from first\n        const x2 = new Array(n);\n        for (let i = 0; i < n - 1; i++) {\n            x2[i] = 2 * coords[i + 1] - x1[i + 1];\n        }\n        x2[n - 1] = (coords[n] + x1[n - 1]) / 2;\n        return { start: x1, end: x2 };\n    }\n}; // END utils\n; // END class\n//# sourceMappingURL=CubicSplinePath.js.map","/**\n * @classdesc A simple voronoi cell (part of a voronoi diagram), stored as an array of\n * adjacent triangles.\n *\n * @requires Line\n * @requires Triangle\n * @requires Polygon\n * @requires Vertex\n *\n * @author   Ikaros Kappler\n * @date     2018-04-11\n * @modified 2018-05-04 Added the 'sharedVertex' param to the constructor. Extended open cells into 'infinity'.\n * @modified 2019-10-25 Fixed a serious bug in the toPathArray function; cell with only one vertex (extreme cases) returned invalid arrays which broke the rendering.\n * @modified 2019-12-09 Removed an unnecesary if-condition from the _calculateOpenEdgePoint(...) helper function.\n * @modified 2020-05-18 Added function VoronoiCell.toPolygon().\n * @modified 2020-08-12 Ported this class from vanilla JS to TypeScript.\n * @modified 2020-08-17 Added some missing type declarations.\n * @modified 2021-01-20 Members `triangles` and `sharedVertex` are now public.\n * @version  1.1.3\n *\n * @file VoronoiCell\n * @public\n **/\nimport { Line } from \"../../Line\";\nimport { Polygon } from \"../../Polygon\";\nimport { Vertex } from \"../../Vertex\";\nexport class VoronoiCell {\n    /**\n     * The constructor.\n     *\n     * @constructor\n     * @name VoronoiCell\n     * @param {Triangle[]} triangles    The passed triangle array must contain an ordered sequence of\n     *                                  adjacent triangles.\n     * @param {Vertex}     sharedVertex This is the 'center' of the voronoi cell; all triangles must share\n     *                                  that vertex.\n     **/\n    constructor(triangles, sharedVertex) {\n        if (typeof triangles === 'undefined')\n            triangles = [];\n        if (typeof sharedVertex === 'undefined')\n            sharedVertex = new Vertex(0, 0);\n        this.triangles = triangles;\n        this.sharedVertex = sharedVertex;\n    }\n    ;\n    /**\n     * Check if the first and the last triangle in the path are NOT connected.\n     *\n     * @method isOpen\n     * @instance\n     * @memberof VoronoiCell\n     * @return {boolean}\n     **/\n    isOpen() {\n        // There must be at least three triangles\n        return this.triangles.length < 3 || !this.triangles[0].isAdjacent(this.triangles[this.triangles.length - 1]);\n    }\n    ;\n    /**\n     * Convert this Voronoi cell to a path polygon, consisting of all Voronoi cell corner points.\n     *\n     * Note that open Voronoi cell cannot properly converted to Polygons as they are considered\n     * infinite. 'Open' Voronoi edges will be cut off at their innermose vertices.\n     *\n     * @method toPolygon\n     * @instance\n     * @memberof VoronoiCell\n     * @return {Polygon}\n     **/\n    toPolygon() {\n        return new Polygon(this.toPathArray(), this.isOpen());\n    }\n    ;\n    /**\n     * Convert the voronoi cell path data to an SVG polygon data string.\n     *\n     * \"x0,y0 x1,y1 x2,y2 ...\"\n     *\n     * @method toPathSVGString\n     * @instance\n     * @memberof VoronoiCell\n     * @return {string}\n     **/\n    toPathSVGString() {\n        if (this.triangles.length == 0)\n            return \"\";\n        const arr = this.toPathArray();\n        return arr.map((vert) => { return '' + vert.x + ',' + vert.y; }).join(' ');\n    }\n    ;\n    /**\n     * Convert the voronoi cell path data to an array.\n     *\n     * [vertex0, vertex1, vertex2, ... ]\n     *\n     * @method toPathArray\n     * @instance\n     * @memberof VoronoiCell\n     * @return {Vertex[]}\n     **/\n    toPathArray() {\n        if (this.triangles.length == 0)\n            return [];\n        if (this.triangles.length == 1)\n            return [this.triangles[0].getCircumcircle().center];\n        const arr = [];\n        // Working for path begin\n        if (false && this.isOpen())\n            arr.push(VoronoiCell._calcOpenEdgePoint(this.triangles[0], this.triangles[1], this.sharedVertex));\n        for (var t = 0; t < this.triangles.length; t++) {\n            var cc = this.triangles[t].getCircumcircle();\n            arr.push(cc.center);\n        }\n        // Urgh, this is not working right now.\n        /* if( false && this.isOpen() )\n            arr.push( VoronoiCell._calcOpenEdgePoint( this.triangles[ this.triangles.length-1 ], this.triangles[ this.triangles.length-2 ], this.sharedVertex ) );\n        */\n        return arr;\n    }\n    /**\n     * A helper function.\n     *\n     * Calculate the 'infinite' open edge point based on the open path triangle\n     * 'tri' and its neighbour 'neigh'.\n     *\n     * This function is used to determine outer hull points.\n     *\n     * @method _calcOpenEdhePoint\n     * @private\n     * @static\n     * @instance\n     * @memberof VoronoiCell\n     * @return {Vertex}\n     **/\n    static _calcOpenEdgePoint(tri, neigh, sharedVertex) {\n        const center = tri.getCircumcircle().center;\n        // Find non-adjacent edge (=outer edge)\n        const edgePoint = VoronoiCell._findOuterEdgePoint(tri, neigh, sharedVertex);\n        // const perpendicular : Vertex = VoronoiCell._perpendicularLinePoint( sharedVertex, edgePoint, center );\n        const perpendicular = new Line(sharedVertex, edgePoint).getClosestPoint(center);\n        // It is not necesary to make a difference on the determinant here\n        const openEdgePoint = new Vertex(perpendicular.x + (center.x - perpendicular.x) * 1000, perpendicular.y + (center.y - perpendicular.y) * 1000);\n        return openEdgePoint;\n    }\n    ;\n    /**\n     * A helper function.\n     *\n     * Find the outer (not adjacent) vertex in triangle 'tri' which has triangle 'neighbour'.\n     *\n     * This function is used to determine outer hull points.\n     *\n     * @return {Vertex}\n     **/\n    static _findOuterEdgePoint(tri, neighbour, sharedVertex) {\n        if (tri.a.equals(sharedVertex)) {\n            if (neighbour.a.equals(tri.b) || neighbour.b.equals(tri.b) || neighbour.c.equals(tri.b))\n                return tri.c;\n            else\n                return tri.b;\n        }\n        if (tri.b.equals(sharedVertex)) {\n            if (neighbour.a.equals(tri.a) || neighbour.b.equals(tri.a) || neighbour.c.equals(tri.a))\n                return tri.c;\n            else\n                return tri.a;\n        }\n        // Here:\n        //    tri.c.equals(sharedVertex) \n        if (neighbour.a.equals(tri.a) || neighbour.b.equals(tri.a) || neighbour.c.equals(tri.a))\n            return tri.b;\n        else\n            return tri.a;\n    }\n    ;\n}\n//# sourceMappingURL=VoronoiCell.js.map","/**\n * @requires Line\n * @requires Vertex\n *\n * @author   Ikaros Kappler\n * @date     2020-12-04\n * @modified 2020-12-09 Ported from vanilla JS to Typescript.\n * @modified 2024-11-22 Fixed a type error in line 41.\n */\nimport { Line } from \"../../Line\";\nimport { Vertex } from \"../../Vertex\";\n/**\n * Collect all self-intersection points of the given polygon.\n *\n * If the given polygon (vertices) is not self intersecting then the returned array is empty.\n *\n * @name findPolygonSelfIntersections\n * @param {Array<Vertex>} vertices - The vertices that form the polygon.\n * @return {Array<Vertex>}\n */\nexport const findPolygonSelfIntersections = (vertices) => {\n    const pointList = [];\n    const lineA = new Line(new Vertex(), new Vertex());\n    const lineB = new Line(new Vertex(), new Vertex());\n    const n = vertices.length;\n    for (var a = 0; a < n; a++) {\n        lineA.a.set(vertices[a]);\n        lineA.b.set(vertices[(a + 1) % n]);\n        for (var b = 0; b < n; b++) {\n            // Same edge or neighbour edges intersect by definition.\n            // Skip them.\n            if (a == b || a + 1 == b || a == b + 1 || (a == 0 && b + 1 == n) || (b == 0 && a + 1 == n))\n                continue;\n            lineB.a.set(vertices[b]);\n            lineB.b.set(vertices[(b + 1) % n]);\n            // Commpute the intersection point of the (infinite) lines.\n            // The point is undefined if and only if both line are parallel (co-linear).\n            const intersectionPoint = lineA.intersection(lineB);\n            // Check if the intersection point is on both (finite) edges of the polygon.\n            if (intersectionPoint && lineA.hasPoint(intersectionPoint) && lineB.hasPoint(intersectionPoint)) {\n                pointList.push(intersectionPoint);\n            }\n        }\n    }\n    return pointList;\n};\n//# sourceMappingURL=findPolygonSelfIntersections.js.map","/**\n * @author Original from Martin Sojka. Ported to TypesScript by Ikaros Kappler\n * @date   2020-11-10\n */\nimport { Color } from \"../datastructures/Color\";\nconst BLACK = Color.makeRGB(0, 0, 0);\nconst WHITE = Color.makeRGB(255, 255, 255);\n/**\n * Contrast color algorithm by Martin Sojka's.\n * Found at\n *    https://gamedev.stackexchange.com/questions/38536/given-a-rgb-color-x-how-to-find-the-most-contrasting-color-y/38542#38542\n *\n * @requires Color\n */\nexport const getContrastColor = (color) => {\n    // r,g,b in [0..1]\n    const gamma = 2.2;\n    const L = 0.2126 * Math.pow(color.r, gamma) + 0.7152 * Math.pow(color.g, gamma) + 0.0722 * Math.pow(color.b, gamma);\n    const use_black = L > Math.pow(0.5, gamma);\n    return use_black ? BLACK : WHITE;\n};\n//# sourceMappingURL=getContrastColor.js.map","/**\n * A DataGrid2d implementation on 2 dimensional arrays.\n *\n * @author   Ikaros Kappler\n * @date     2025-10-16\n * @modified 2025-10-28 Added `DataGrid2dArrayMatrix.setAll(function)`.\n * @modified 2025-10-28 Fixed a bug in the `DataGrid2dArrayMatrix.toString()` method.\n * @version  1.0.0\n **/\nimport { arrayFill } from \"../algorithms/arrayFill\";\nexport class DataGrid2dArrayMatrix {\n    /**\n     * Create a new DataGrid2d from the given\n     * @throws Error if xSegmentCount*ySegmentCount is larger than the capacity of the array/list.\n     * @param list\n     * @param xSegmentCount\n     * @param ySegmentCount\n     */\n    constructor(xSegmentCount, ySegmentCount, initialValue) {\n        if (xSegmentCount <= 0) {\n            throw `Cannot create DataGrid2dArray, xSegmentCount (${xSegmentCount}) must be > 0.`;\n        }\n        if (ySegmentCount <= 0) {\n            throw `Cannot create DataGrid2dArray, ySegmentCount (${ySegmentCount}) must be > 0.`;\n        }\n        // this.canvas = document.getElementById(canvasId);\n        this.xSegmentCount = xSegmentCount;\n        this.ySegmentCount = ySegmentCount;\n        this._matrix = [];\n        for (var i = 0; i < ySegmentCount; i++) {\n            this._matrix.push(arrayFill(xSegmentCount, initialValue));\n        }\n    }\n    /**\n     * Set the matrix value at the given (x,y) position to a new value.\n     *\n     * @param {number} xIndex - The horizontal matrix position to set.\n     * @param {number} yIndex - The vertical matrix position to set.\n     * @param {T} value - The new value.\n     */\n    set(xIndex, yIndex, value) {\n        this._matrix[yIndex][xIndex] = value;\n    }\n    /**\n     * Getthe matrix value at the given (x,y) position.\n     *\n     * @param {number} xIndex - The horizontal matrix position to set.\n     * @param {number} yIndex - The vertical matrix position to set.\n     * @return {T} value - The new value.\n     */\n    get(xIndex, yIndex) {\n        return this.getDataValueAt(xIndex, yIndex);\n    }\n    /**\n     * Set all matrix values. The passed factory function must accept respective (x,y) positions.\n     *\n     * @param {Function} factory - The factory function to determine the new values to set.\n     * @return {DataGrid2dArrayMatrix<T>} this - for chaning.\n     */\n    setAll(factory) {\n        for (var x = 0; x < this.xSegmentCount; x++) {\n            for (var y = 0; y < this.ySegmentCount; y++) {\n                this.set(x, y, factory(x, y));\n            }\n        }\n        return this;\n    }\n    find(condition) {\n        for (var x = 0; x < this.xSegmentCount; x++) {\n            for (var y = 0; y < this.ySegmentCount; y++) {\n                if (condition(this.get(x, y), x, y, this)) {\n                    return {\n                        xIndex: x,\n                        yIndex: y,\n                        xRel: x / this.xSegmentCount,\n                        yRel: y / this.ySegmentCount\n                    };\n                }\n            }\n        }\n        return null;\n    }\n    /**\n     * @override\n     */\n    getMinDataValue() {\n        return this.minDataValue;\n    }\n    /**\n     * @override\n     */\n    getMaxDataValue() {\n        return this.maxDataValue;\n    }\n    /**\n     * @override\n     */\n    getDataValueAt(xIndex, yIndex, isDebug) {\n        return this._matrix[yIndex][xIndex];\n    }\n    /**\n     * @override\n     */\n    getDataFace4At(xIndex, yIndex, buffer) {\n        // buffer: array[2][2]\n        buffer[0][0] = this.getDataValueAt(xIndex, yIndex);\n        buffer[1][0] = this.getDataValueAt(xIndex + 1, yIndex);\n        buffer[1][1] = this.getDataValueAt(xIndex + 1, yIndex + 1);\n        buffer[0][1] = this.getDataValueAt(xIndex, yIndex + 1);\n    }\n    /**\n     * A helper method to convert a boolean matrix to a parsable string.\n     *\n     * @param {DataGrid2dArrayMatrix<boolean>} matrix\n     * @returns {string}\n     */\n    static toString(matrix) {\n        const buffer = [];\n        for (var y = 0; y < matrix.ySegmentCount; y++) {\n            for (var x = 0; x < matrix.xSegmentCount; x++) {\n                buffer.push(matrix.get(x, y) ? \"X\" : \".\");\n            }\n            buffer.push(\"\\n\");\n        }\n        return buffer.join(\"\");\n    }\n    /**\n     * Simple way to parse a data matrix from a string. `false` should be coded as '.' character,\n     * `true` must be coded as 'X' character.\n     *\n     * @param {string} str - The input string.\n     * @param {number} width - The desired width of the matrix (xSegmentCount).\n     * @param {number} height - The desired height of the matrix (ySegmentCount).\n     * @returns {DataGrid2dArrayMatrix<boolean>}\n     */\n    static parseBooleanMatrix(str, width, height) {\n        const matrix = new DataGrid2dArrayMatrix(width, height, false);\n        const lines = str.trim().split(\"\\n\");\n        for (var y = 0; y < lines.length && y < height; y++) {\n            lines[y] = lines[y].trim();\n            for (var x = 0; x < lines[y].length && x < width; x++) {\n                if (y < height && x < width && lines[y].charAt(x) === \"X\") {\n                    matrix.set(x, y, true);\n                }\n            }\n        }\n        return matrix;\n    }\n}\n//# sourceMappingURL=DataGrid2dArrayMatrix.js.map","/**\n * A script to convert any boolean matrix to rounded paths.\n *\n * @author  Ikaros Kappler\n * @date    2025-10-17 (ported to Typescript from a demo-script)\n * @version 1.0.0\n */\nimport { Bounds } from \"../../Bounds\";\nimport { DataGrid2dArrayMatrix } from \"../datastructures/DataGrid2dArrayMatrix\";\nconst LEFT_BORDER = 0;\nconst TOP_BORDER = 1;\nconst RIGHT_BORDER = 2;\nconst BOTTOM_BORDER = 3;\n/**\n * Computes an array of paths from the given boolean matrix.\n *\n * @param {DataGrid2dArrayMatrix<boolean>} matrix\n * @param {PixelCornerPathOptions} options\n * @returns\n */\nexport const pixelCornersToRoundPaths = (matrix, options) => {\n    const paths = [];\n    const visitedLeftBorderMatrix = new DataGrid2dArrayMatrix(matrix.xSegmentCount, matrix.ySegmentCount, false);\n    const origin = options && options.origin ? options.origin : { x: 0, y: 0 };\n    const squareSize = options && typeof options.squareSize === \"number\" ? options.squareSize : 10;\n    const gapSize = options && typeof options.gapSize === \"number\" ? options.gapSize : 2;\n    const curveFactor = options && typeof options.curveFactor === \"number\" ? options.curveFactor : 0.666;\n    // Find an unvisited pixel with a free left neighbour\n    const condition = (value, x, y, _matrix) => {\n        return (value === true &&\n            visitedLeftBorderMatrix.get(x, y) === false &&\n            // is left neighbour free?\n            (x - 1 < 0 || _matrix.get(x - 1, y) === false));\n    };\n    // Just to be sure the while loop terminates after a maximum number of iterations.\n    const safetyLimit = matrix.xSegmentCount * matrix.ySegmentCount + 1;\n    // The next unvisited pixel position.\n    var nonVisitedPosition;\n    var i = 0;\n    while ((nonVisitedPosition = matrix.find(condition)) && i++ < safetyLimit) {\n        // console.log(\"nonVisitedPosition\", nonVisitedPosition);\n        // Condition: if a point was found then its left neighbour is empty.\n        //            So by this the current pixel's left bound is definitely a path start.\n        const squareBox = getSquareBox(origin, squareSize, gapSize, nonVisitedPosition.xIndex, nonVisitedPosition.yIndex);\n        const west = squareBox.getWestPoint();\n        // A starting point was found: Initialize the next path.\n        var pathData = [\n            // Start point\n            \"M\",\n            west.x,\n            west.y\n        ];\n        // Now from this point starting (left pixel corner) construct the next sequence of path commands.\n        __constructPath(pathData, matrix, visitedLeftBorderMatrix, nonVisitedPosition, LEFT_BORDER, origin, squareSize, gapSize, curveFactor);\n        paths.push(pathData);\n        // console.log(\"pathData\", pathData);\n    }\n    return paths;\n};\n/**\n * Construct a bounding box representing the visual square bounds for the given pixel.\n *\n * @param {XYCoords} origin - The origin to build the paths from (upper left corner of the graphics).\n * @param {number} squareSize - The number of pixels to use to represent a pixel square.\n * @param {number} gapSize - The number of pixels to use for gaps between squares.\n * @param {number} x - The x position inside the data grid (matrix offset).\n * @param {number} y - They  position inside the data grid (matrix offset).\n * @returns\n */\nconst getSquareBox = (origin, squareSize, gapSize, x, y) => {\n    return new Bounds({\n        x: origin.x + x * (squareSize + gapSize),\n        y: origin.y + y * (squareSize + gapSize)\n    }, {\n        x: origin.x + x * (squareSize + gapSize) + squareSize,\n        y: origin.y + y * (squareSize + gapSize) + squareSize\n    });\n};\n/**\n * Lerp between these two numbers using the passed lerp amount (usually a value in 0.0-1.0).\n *\n * @param {number} a\n * @param {number} b\n * @param {number} lerpFactor\n * @returns {number}\n */\nconst lerp = (a, b, lerpFactor) => {\n    return a + (b - a) * lerpFactor;\n};\n/**\n * Construct a path command for a cubic Bézier curve.\n *\n * @param {SVGPathParams} pathData\n * @param {XYCoords} start\n * @param {XYCoords} controlA\n * @param {XYCoords} controlB\n * @param {XYCoords} end\n * @param {number} curveFactor\n */\nconst addRoundCorner = (pathData, start, controlA, controlB, end, curveFactor) => {\n    pathData.push(\"C\", lerp(start.x, controlA.x, curveFactor), lerp(start.y, controlA.y, curveFactor), lerp(end.x, controlB.x, curveFactor), lerp(end.y, controlB.y, curveFactor), end.x, end.y);\n};\n/**\n * Construct a new path command for a straight line.\n *\n * @param {SVGPathParams} pathData\n * @param {XYCoords} target\n */\nconst addStraightLine = (pathData, target) => {\n    pathData.push(\"L\", target.x, target.y);\n};\n/**\n * A helper function for constructing the next path, beginning at the passed matrix position.\n *\n * Note the path will be created at the left border of the given 'pixel', constructe\n * in clockwise order.\n *\n * @param {SVGPathParams} pathData\n * @param {DataGrid2dArrayMatrix<boolean>} matrix - The data matrix to use.\n * @param {DataGrid2dArrayMatrix<boolean>} visitedLeftBordersMatrix - A helper matrix to keep track of visited pixels.\n * @param {RasterPosition} startingPosition\n * @param {number} startingBorderDirection\n * @param {XYCoords} origin\n * @param {number} squareSize\n * @param {number} gapSize\n * @param {number} curveFactor\n */\nconst __constructPath = (pathData, matrix, visitedLeftBordersMatrix, startingPosition, startingBorderDirection, origin, squareSize, gapSize, curveFactor) => {\n    // Pre: position's neighbour pixel at ehe given border direction is unset.\n    var isPathComplete = false;\n    const maxInterations = matrix.xSegmentCount * matrix.ySegmentCount * 4 + 1;\n    var i = 0;\n    var position = startingPosition;\n    var borderDirection = startingBorderDirection;\n    while (!isPathComplete && i++ < maxInterations) {\n        var x = position.xIndex;\n        var y = position.yIndex;\n        // console.log(\"x\", x, \"y\", y, \"borderDirection\", borderDirection);\n        // Get the pixel's box bounds.\n        const squareBox = getSquareBox(origin, squareSize, gapSize, x, y);\n        // Find next step when walking 'clockwise'\n        if (borderDirection === LEFT_BORDER) {\n            // Only track visits on left borders. By this we can detect non-visited holes :)\n            visitedLeftBordersMatrix.set(x, y, true);\n            // We want to expand the left border\n            const west = squareBox.getWestPoint();\n            // Pixel in the north?\n            if (y - 1 < 0 || matrix.get(x, y - 1) === false) {\n                // Northwise pixel is empty\n                //  -> construct round corner to right\n                addRoundCorner(pathData, west, squareBox.getNorthWestPoint(), squareBox.getNorthWestPoint(), squareBox.getNorthPoint(), curveFactor);\n                borderDirection = TOP_BORDER;\n                // Keep pixel position unchanged\n            }\n            else if (x - 1 >= 0 && matrix.get(x - 1, y - 1) === true) {\n                // Top neighbour pixel is set AND top-left pixel is set too.\n                // -> construct rounded edge to top-left.\n                const squareBoxNW = getSquareBox(origin, squareSize, gapSize, x - 1, y - 1);\n                addRoundCorner(pathData, west, squareBox.getNorthWestPoint(), squareBoxNW.getSouthEastPoint(), squareBoxNW.getSouthPoint(), curveFactor);\n                borderDirection = BOTTOM_BORDER;\n                position = { xIndex: x - 1, yIndex: y - 1 };\n            }\n            else {\n                // Straight to top\n                const squareBoxN = getSquareBox(origin, squareSize, gapSize, x, y - 1);\n                addStraightLine(pathData, squareBoxN.getWestPoint());\n                position = { xIndex: x, yIndex: y - 1 };\n                // Keep borderDirection: LEFT_BORDER\n                // isPathComplete = true; // TODO\n            }\n        }\n        else if (borderDirection === TOP_BORDER) {\n            // North pixel is definitely empty.\n            const north = squareBox.getNorthPoint();\n            if (x + 1 >= matrix.xSegmentCount || matrix.get(x + 1, y) === false) {\n                // Top border and right pixel is empty\n                //  --> create rounded corner to right south\n                addRoundCorner(pathData, north, squareBox.getNorthEastPoint(), squareBox.getNorthEastPoint(), squareBox.getEastPoint(), curveFactor);\n                borderDirection = RIGHT_BORDER;\n                // Keep pixel position unchanged\n            }\n            else if (y - 1 < 0 || matrix.get(x + 1, y - 1) === false) {\n                // Top border and right pixel is set, and north-east pixel is clear.\n                // -> linear path to right\n                const squareBoxE = getSquareBox(origin, squareSize, gapSize, x + 1, y);\n                addStraightLine(pathData, squareBoxE.getNorthPoint());\n                position = { xIndex: x + 1, yIndex: y };\n                // Keep borderDirection TOP\n            }\n            else {\n                // Last case: right neighbour is set and north-east pixel is set\n                //-> construct a rounded corner to east-north.\n                const squareBoxNE = getSquareBox(origin, squareSize, gapSize, x + 1, y - 1);\n                addRoundCorner(pathData, north, squareBox.getNorthEastPoint(), squareBoxNE.getSouthWestPoint(), squareBoxNE.getWestPoint(), curveFactor);\n                borderDirection = LEFT_BORDER;\n                position = { xIndex: x + 1, yIndex: y - 1 };\n                // isPathComplete = true; // TODO!!!\n            }\n        }\n        else if (borderDirection === RIGHT_BORDER) {\n            // East pixel is definitely empty.\n            var east = squareBox.getEastPoint();\n            if (y + 1 >= matrix.ySegmentCount || matrix.get(x, y + 1) === false) {\n                // South pixel is empty.\n                // -> construct rounded corner to south-east\n                addRoundCorner(pathData, east, squareBox.getSouthEastPoint(), squareBox.getSouthEastPoint(), squareBox.getSouthPoint(), curveFactor);\n                borderDirection = BOTTOM_BORDER;\n                // Keep pixel position unchanged\n            }\n            else if (x + 1 < matrix.xSegmentCount && y + 1 < matrix.ySegmentCount && matrix.get(x + 1, y + 1) === true) {\n                // South pixel is set AND right lower pixel is set, too.\n                // -> construct round corner to south-east.\n                const squareBoxSE = getSquareBox(origin, squareSize, gapSize, x + 1, y + 1);\n                addRoundCorner(pathData, east, squareBox.getSouthEastPoint(), squareBoxSE.getNorthWestPoint(), squareBoxSE.getNorthPoint(), curveFactor);\n                borderDirection = TOP_BORDER;\n                position = { xIndex: x + 1, yIndex: y + 1 };\n            }\n            else {\n                // South pixel is set and south-east pixel is clear.\n                // -> construct linear connection to south\n                const squareBoxS = getSquareBox(origin, squareSize, gapSize, x, y + 1);\n                addStraightLine(pathData, squareBoxS.getEastPoint());\n                position = { xIndex: x, yIndex: y + 1 };\n                // Keep borderDirection RIGHT\n            }\n        }\n        else if (borderDirection === BOTTOM_BORDER) {\n            // Pre: south pixel is definitely empty\n            const south = squareBox.getSouthPoint();\n            if (x - 1 < 0 || matrix.get(x - 1, y) === false) {\n                // Left pixel is empty\n                // -> construct round corner to west-north\n                addRoundCorner(pathData, south, squareBox.getSouthWestPoint(), squareBox.getSouthWestPoint(), squareBox.getWestPoint(), curveFactor);\n                borderDirection = LEFT_BORDER;\n            }\n            else if (x - 1 >= 0 && y + 1 < matrix.ySegmentCount && matrix.get(x - 1, y + 1) === true) {\n                // Left pixel AND left lower pixel are set\n                // -> construct rounded edge to south-west\n                const squareBoxSW = getSquareBox(origin, squareSize, gapSize, x - 1, y + 1);\n                addRoundCorner(pathData, south, squareBox.getSouthWestPoint(), squareBoxSW.getNorthEastPoint(), squareBoxSW.getEastPoint(), curveFactor);\n                borderDirection = RIGHT_BORDER;\n                position = { xIndex: x - 1, yIndex: y + 1 };\n            }\n            else {\n                // Left pixel is set AND south pixel is empty\n                // -> construct linear edge to left neighbour.\n                const squareBoxW = getSquareBox(origin, squareSize, gapSize, x - 1, y);\n                addStraightLine(pathData, squareBoxW.getSouthPoint());\n                position = { xIndex: x - 1, yIndex: y };\n                // Keep borderDirection BOTTOM\n            }\n        }\n        else {\n            console.warn(`[Error] Cannot construct full rounded path; 'borderDirection' has wrong value (${borderDirection}).`);\n            isPathComplete = true;\n        }\n        // End condition reached?\n        if (startingPosition.xIndex === position.xIndex &&\n            startingPosition.yIndex === position.yIndex &&\n            startingBorderDirection === borderDirection) {\n            pathData.push(\"Z\");\n            isPathComplete = true;\n        }\n    }\n};\n//# sourceMappingURL=pixelCornersToRoundPaths.js.map","/**\n * @requires Line\n * @requires Vertex\n *\n * @author   Ikaros Kappler\n * @date     2020-12-04\n * @modified 2020-12-07 Ported from vanilla JS to typescript.\n * @modified 2024-11-22 Added the `insideBoundsOnly` param to the `splitPolygonToNonIntersecting` algorithm.\n * @version  1.1.0\n */\nimport { Line } from \"../../Line\";\nimport { Vertex } from \"../../Vertex\";\n/**\n * This function cuts a given self-intersecting polygon into non-self-intersecting\n * sub polygons.\n *\n * The algorithm only works for non-self-overlapping polygons:\n * Please note that the union set of the sub polygons themselves will _not_ be disjunct if\n * the input polyon overlaps with itself!\n *\n * See this illustration for details:\n * ./demos/27-polygon-intersection-greinerhormann/splitting-polygon-types.png\n *\n * @name splitPolygonToNonIntersecting\n * @param {Array<Vertex>} vertices - The polygon as an array of vertices.\n * @param {number=10} maxDepth - Number of max recursive steps (default is 10).\n * @return {Array<Array<Vertex>>} A sequence of non-self-intersecting sub polygons.\n */\nexport const splitPolygonToNonIntersecting = (() => {\n    /**\n     * @param {Array<Vertex>} vertices\n     * @param {number=10} maxDepth\n     */\n    const splitPolygonToNonIntersecting = (vertices, maxDepth, insideBoundsOnly) => {\n        if (typeof maxDepth === \"undefined\")\n            maxDepth = 10;\n        return _splitPolygonToNonIntersecting(vertices, maxDepth, insideBoundsOnly);\n    };\n    const _splitPolygonToNonIntersecting = (vertices, maxDepth, insideBoundsOnly) => {\n        if (maxDepth <= 0) {\n            // aborting at max depth\n            return [vertices];\n        }\n        if (vertices.length <= 3) {\n            // No intersections possible\n            return [vertices];\n        }\n        const n = vertices.length;\n        const lineA = new Line(new Vertex(), new Vertex());\n        const lineB = new Line(new Vertex(), new Vertex());\n        for (var a = 0; a < vertices.length; a++) {\n            lineA.a.set(vertices[a]);\n            lineA.b.set(vertices[(a + 1) % n]);\n            for (var b = 0; b < vertices.length; b++) {\n                // Equal edges or neighbour edges intersect by definition.\n                // We ignore them.\n                if (a == b || a + 1 == b || a == b + 1 || (a == 0 && b + 1 == vertices.length) || (b == 0 && a + 1 == vertices.length))\n                    continue;\n                lineB.a.set(vertices[b]);\n                lineB.b.set(vertices[(b + 1) % n]);\n                const intersectionPoint = lineA.intersection(lineB);\n                if (intersectionPoint &&\n                    lineA.hasPoint(intersectionPoint, insideBoundsOnly) &&\n                    lineB.hasPoint(intersectionPoint, insideBoundsOnly)) {\n                    // Cut polygon into two here\n                    const split = splitPolygonAt(vertices, a, b, intersectionPoint);\n                    // Split has 2 elements.\n                    const leftCleaned = _splitPolygonToNonIntersecting(split[0], maxDepth - 1, insideBoundsOnly);\n                    const rightCleaned = _splitPolygonToNonIntersecting(split[1], maxDepth - 1, insideBoundsOnly);\n                    return leftCleaned.concat(rightCleaned);\n                }\n            }\n        }\n        // No intersection found:\n        //    just return a list with the original\n        //    polygon as its only element.\n        return [vertices];\n    };\n    // Pre: edgeIndexA < edgeIndexB && vertices.length >= 4\n    const splitPolygonAt = (vertices, edgeIndexA, edgeIndexB, intersectionPoint) => {\n        const first = [];\n        var second = [];\n        for (var i = 0; i < vertices.length; i++) {\n            if (i <= edgeIndexA)\n                first.push(vertices[i]);\n            if (i == edgeIndexA) {\n                first.push(intersectionPoint);\n                second.push(intersectionPoint); // clone???\n            }\n            if (i > edgeIndexA && i <= edgeIndexB)\n                second.push(vertices[i]);\n            if (i > edgeIndexB)\n                first.push(vertices[i]);\n        }\n        return [first, second];\n    };\n    return splitPolygonToNonIntersecting;\n})();\n//# sourceMappingURL=splitPolygonToNonIntersecting.js.map","/**\n * The Sutherland-Hodgman convex polygon clipping algorithm.\n *\n * Original version:\n *    https://rosettacode.org/wiki/Sutherland-Hodgman_polygon_clipping#JavaScript\n *\n * @author  Ikaros Kappler (ported to TypeScript with {x,y} vertices).\n * @date    2021-01-29\n * @version 1.0.0\n */\n/**\n * @param {XYCoords}\n * @param {XYCoords}\n **/\nconst inside = (cp1, cp2, p) => {\n    return (cp2.x - cp1.x) * (p.y - cp1.y) > (cp2.y - cp1.y) * (p.x - cp1.x);\n};\n/**\n * @param {XYCoords}\n * @param {XYCoords}\n * @param {XYCoords}\n * @param {XYCoords}\n */\nconst intersection = (cp1, cp2, s, e) => {\n    const dc = {\n        x: cp1.x - cp2.x,\n        y: cp1.y - cp2.y\n    };\n    const dp = {\n        x: s.x - e.x,\n        y: s.y - e.y\n    };\n    const n1 = cp1.x * cp2.y - cp1.y * cp2.x;\n    const n2 = s.x * e.y - s.y * e.x;\n    const n3 = 1.0 / (dc.x * dp.y - dc.y * dp.x);\n    return { x: (n1 * dp.x - n2 * dc.x) * n3,\n        y: (n1 * dp.y - n2 * dc.y) * n3\n    };\n};\n/**\n * @param {Array<XYCoords>} subjectPolygon - Can be any polygon.\n * @param {Array<XYCoords>} clipPolygon - Must be convex.\n */\nexport const sutherlandHodgman = (subjectPolygon, clipPolygon) => {\n    let cp1 = clipPolygon[clipPolygon.length - 1];\n    let cp2;\n    let s;\n    let e;\n    let outputList = subjectPolygon;\n    for (var j in clipPolygon) {\n        cp2 = clipPolygon[j];\n        var inputList = outputList;\n        outputList = [];\n        s = inputList[inputList.length - 1]; // last on the input list\n        for (var i in inputList) {\n            e = inputList[i];\n            if (inside(cp1, cp2, e)) {\n                if (!inside(cp1, cp2, s)) {\n                    outputList.push(intersection(cp1, cp2, s, e));\n                }\n                outputList.push(e);\n            }\n            else if (inside(cp1, cp2, s)) {\n                outputList.push(intersection(cp1, cp2, s, e));\n            }\n            s = e;\n        }\n        cp1 = cp2;\n    }\n    return outputList;\n};\n//# sourceMappingURL=sutherlandHodgman.js.map","/**\n * Calculate the inset of any non-self-overlapping polygon.\n *\n * The polygon may be\n *  - convex or non-convex\n *  - self-intersecting\n *\n * The algorithms will\n *  - first construct a general offset polygon which may be corrupt due to ouf-of-bounds or in illegal-area problems.\n *  - then dissect the possibly self-intersecting inset polygon into separate simple polygons.\n *  - then detect for each if it's out of bounds or in some illegal area.\n *  - keeping only the valid ones.\n *\n * @required sutherlandHodgman\n * @required splitPolygonToNonIntersecting\n *\n * @author   Ikaros Kappler\n * @date     2024-11-04 Ported the script to a class.\n * @modified 2024-12-02 Ported to Typescript.\n */\nimport { Line } from \"../../Line\";\nimport { Polygon } from \"../../Polygon\";\nimport { Vector } from \"../../Vector\";\nimport { splitPolygonToNonIntersecting } from \"./splitPolygonToNonIntersecting\";\nimport { sutherlandHodgman } from \"./sutherlandHodgman\";\nexport class PolygonInset {\n    /**\n     * Constructs a new PolygonInset instance with the underlying given polygon to work with.\n     *\n     * Please note that the algorithm will reverse the vertex order if the given polygon\n     * is not clockwise.\n     *\n     * @param {Polygon} polygon - The polygon to calculate the offset for.\n     */\n    constructor(polygon) {\n        /**\n         * The original polygon as a sequence of line objects. This is easier to use than a list of points.\n         */\n        this.originalPolygonLines = [];\n        /**\n         * The simple inset lines, directly generated by offsetting the original polygon lines by the given amount.\n         */\n        this.insetLines = [];\n        /**\n         * The cropped inset lines that makes up the first direct iteration of the inset polygon.\n         * This one will probably be self-intersecting.\n         */\n        this.insetPolygonLines = [];\n        /**\n         * The inset polygon split up into simple non-self-intersecting polygons.\n         * Represented as a list of vertex-lists. Each sub-list represents a single polygon.\n         */\n        this.splitPolygons = [];\n        this.polygon = polygon;\n    }\n    /**\n     * This is the main method.\n     *\n     * Call this with the required option params to compute your desired offset polygon(s).\n     *\n     * @param {number} options.innerPolygonOffset - The offset to use. Should be a positive number. Correct result for negative numbers are not guaranteed.\n     * @param {number?} options.maxPolygonSplitDepth - (default is the number of polygon.vertices) The maximum amount of recursive stepts to simplify the complex first iteration of the offset polygon.\n     * @param {number?} options.intersectionEpsilon - (default is 1.0) The epsilon to use for detecting overlapping polygons. This indicates a tolerance value, because directly adjecent polygons may have a little arithmetic intersection area.\n     * @returns {Array<Array<Vertex>>} A list of vertex-lists, each one representing a simple polygon from the offset-polygons.\n     */\n    computeOutputPolygons(options) {\n        var _a;\n        // No offset implies: no change.\n        if (options.innerPolygonOffset === 0) {\n            return [this.polygon.vertices]; // No change\n        }\n        // This algorithm only works with polygon in clockwise vertex order.\n        // If the polygon is not clockwise: revert.\n        PolygonInset._assertPolygonIsClockwise(this.polygon.vertices);\n        // The potential result polygons might overlap with other parts. These are not part of the desired\n        // result set and need to be filtered out.\n        // Define an intersection-epsilon: minimal critical overlaps might result of rounding errors and\n        // don't represent real overlaps.\n        const intersectionEpsilon = options.intersectionEpsilon;\n        // This will create a deep clone\n        this.optimizedPolygon = this.polygon.clone();\n        // In case the potential result polygons are self intersecting we need to split them apart later.\n        // Using the initial vertex number as the upper split limit should be safe here.\n        const maxPolygonSplitDepth = (_a = options === null || options === void 0 ? void 0 : options.maxPolygonSplitDepth) !== null && _a !== void 0 ? _a : this.optimizedPolygon.vertices.length;\n        // For calculations of initial inset rectagles we need the original polygon's lines.\n        this.originalPolygonLines = this.optimizedPolygon.getEdges();\n        this._collectInsetLines(this.originalPolygonLines, options.innerPolygonOffset);\n        this._collectInsetPolygonLines(this.insetLines);\n        this.insetRectanglePolygons = this._collectRectangularPolygonInsets(this.originalPolygonLines, this.insetLines);\n        // Optimize inset polygon AND the insetRectanglePolygons?\n        if (options.removeEars) {\n            // console.log(\"Remove ears\");\n            // This will modify both params!\n            PolygonInset._optimizeInsetPolygon(this.optimizedPolygon, this.insetRectanglePolygons);\n        }\n        // Create a naive first inset polygon for later optimization.\n        this.insetPolygon = PolygonInset.convertToBasicInsetPolygon(this.insetPolygonLines);\n        // // Optimize inset polygon AND the insetRectanglePolygons!\n        // if (options.removeEars) {\n        //   // This will modify both params!\n        //   PolygonInset._optimizeInsetPolygon(this.insetPolygon, this.insetRectanglePolygons);\n        // }\n        // The resulting polygon will likely intersect itself multiple times.\n        // For further calculations split apart into non-self-intersecting.\n        this.splitPolygons = splitPolygonToNonIntersecting(this.insetPolygon.vertices, maxPolygonSplitDepth, true); // insideBoundsOnly\n        // This method was initially meant to calculate inset-polygons only.\n        // But with a simple filter we COULD also create outer offset-polygons.\n        // Maybe this is a task for the future\n        // console.log(\"DEBUG\", DEBUG);\n        // DEBUG(\"TEST\");\n        if (options.innerPolygonOffset < 0) {\n            // return [this.polygon.vertices]; // No change\n        }\n        // console.log(\"splitPolygons.length\", this.splitPolygons.length);\n        // Assert all polygons are clockwise!\n        PolygonInset._assertAllPolygonsAreClockwise(this.splitPolygons);\n        this.filteredSplitPolygons = PolygonInset._filterInnerSplitPolygonsByCoverage(this.splitPolygons, this.insetRectanglePolygons, intersectionEpsilon);\n        // console.log(\"[0] filteredSplitPolygons.length\", this.filteredSplitPolygons.length);\n        this.filteredSplitPolygons = PolygonInset._filterInnerSplitPolygonsByOriginalBounds(this.filteredSplitPolygons, this.polygon);\n        // console.log(\"[1] filteredSplitPolygons.length\", this.filteredSplitPolygons.length);\n        return this.filteredSplitPolygons;\n    }\n    /**\n     * This method transforms each polygon line into a new line\n     * by moving it to the inside direction of the polygon (by the given `insetAmount`).\n     *\n     * @param {Array<Line>} polygonLines\n     * @param {number} insetAmount\n     * @return {Array<Line>} The transformed lines. The result array has the same length and order as the input array.\n     */\n    _collectInsetLines(polygonLines, insetAmount) {\n        const insetLines = []; // Array<Line>\n        for (var i = 0; i < polygonLines.length; i++) {\n            const line = polygonLines[i];\n            const perp = new Vector(line.a, line.b).perp();\n            const t = insetAmount / perp.length();\n            const offsetOnPerp = perp.vertAt(t);\n            const diff = line.a.difference(offsetOnPerp);\n            // Polygon is is clockwise order.\n            // Move line inside polygon\n            const movedLine = line.clone();\n            movedLine.a.add(diff);\n            movedLine.b.add(diff);\n            insetLines.push(movedLine);\n        }\n        this.insetLines = insetLines;\n        return insetLines;\n    }\n    /**\n     * For a sequence of inset polygon lines get the inset polygon by detecting\n     * useful intersections (by cropping or extending them).\n     *\n     * The returned lines resemble a new polygon.\n     *\n     * Please note that the returned polygon can be self-intersecting!\n     *\n     * @param {Array<Line>} insetLines\n     * @returns {Array<Line>} The cropped or exented inset polygon lines.\n     */\n    _collectInsetPolygonLines(insetLines) {\n        if (insetLines.length <= 1) {\n            return [];\n        }\n        const insetPolygonLines = [];\n        // Collect first intersection at beginning :)\n        const lastInsetLine = insetLines[insetLines.length - 1];\n        const firstInsetLine = insetLines[0];\n        let lastIntersectionPoint = lastInsetLine.intersection(firstInsetLine); // Must not be null\n        for (var i = 0; i < insetLines.length; i++) {\n            const insetLine = insetLines[i];\n            const nextInsetLine = insetLines[(i + 1) % insetLines.length];\n            // Find desired intersection\n            const intersection = insetLine.intersection(nextInsetLine);\n            if (intersection == null) {\n                console.warn(\"[collectInsetPolygon] WARN intersection line must not be null\", i, nextInsetLine);\n            }\n            else {\n                // By construction they MUST have any non-null intersection!\n                if (lastIntersectionPoint != null) {\n                    const resultLine = new Line(lastIntersectionPoint, intersection);\n                    insetPolygonLines.push(resultLine);\n                }\n            }\n            lastIntersectionPoint = intersection;\n        }\n        // Store intermediate result for later retrieval.\n        this.insetPolygonLines = insetPolygonLines;\n        return insetPolygonLines;\n    }\n    /**\n     * Converts two lists (same length) of original polygon lines and inset lines (interpreted as\n     * pairs) to a list of rectangular polyons.\n     *\n     * @static\n     * @param {Array<Line>} originalPolygonLines\n     * @param {Array<Line>} insetLines\n     * @returns {Array<Polygon>} A list of rectangular polygons; each returned polyon has exactly four vertices.\n     */\n    _collectRectangularPolygonInsets(originalPolygonLines, insetLines) {\n        // Convert to rectangle polygon\n        const insetRectanglePolygons = originalPolygonLines.map((polygonLine, index) => {\n            const rectPolygon = new Polygon([], false);\n            // Add in original order\n            rectPolygon.vertices.push(polygonLine.a.clone());\n            rectPolygon.vertices.push(polygonLine.b.clone());\n            // Add in reverse order\n            const insetLine = insetLines[index];\n            rectPolygon.vertices.push(insetLine.b.clone());\n            rectPolygon.vertices.push(insetLine.a.clone());\n            return rectPolygon;\n        });\n        return insetRectanglePolygons;\n    }\n    /**\n     * Converts a sequence of (hopefully adjacent) lines to a polygon by using all second line vertices `b`.\n     *\n     * @static\n     * @param insetPolygonLines\n     * @returns\n     */\n    static convertToBasicInsetPolygon(insetPolygonLines) {\n        const insetPolygon = new Polygon([], false);\n        insetPolygonLines.forEach((insetLine) => {\n            insetPolygon.vertices.push(insetLine.a);\n        });\n        return insetPolygon;\n    }\n    /**\n     * Filter split polygons: only keep those whose vertices are all contained inside the original polygon.\n     * Reason: scaling too much will result in excessive translation beyond the opposite bounds of the polygon (like more than 200% of possible insetting).\n     *\n     * @param {Array<Array<Vertex>>} splitPolygonsVertices\n     * @param {Polygon} originalPolygon\n     * @return {Array<Array<Vertex>>} The filtered polygon list.\n     */\n    static _filterInnerSplitPolygonsByOriginalBounds(splitPolygonsVertices, originalPolygon) {\n        return splitPolygonsVertices.filter((splitPolyVerts, _splitPolyIndex) => {\n            return splitPolyVerts.every((splitPVert) => {\n                return originalPolygon.containsVert(splitPVert);\n            });\n        });\n    }\n    /**\n     * Filter split polygons: only keep those that do not (signifiantly) interset with any rectangles.\n     *\n     * @static\n     * @param {Array<Array<Vertex>>} splitPolygonsVertices\n     * @param {Array<Polygon>} insetRectanglePolygons\n     * @param {number?=1.0} intersectionEpsilon - (optional, default is 1.0) A epsislon to define a tolerance for checking if two polygons intersect.\n     */\n    static _filterInnerSplitPolygonsByCoverage(splitPolygonsVertices, insetRectanglePolygons, intersectionEpsilon) {\n        // TEST: Add some jitter\n        // splitPolygonsVertices.forEach(split => {\n        //   split.forEach(vert => {\n        //     vert.x += (0.5 - Math.random()) * 0.01;\n        //     vert.y += (0.5 - Math.random()) * 0.01;\n        //   });\n        // });\n        splitPolygonsVertices.forEach((split, index) => {\n            const isCW = Polygon.utils.isClockwise(split);\n            if (!isCW) {\n                console.warn(\"------ split is not isClockwise!\", index, isCW);\n            }\n        });\n        insetRectanglePolygons.forEach((rect, index) => {\n            const isCW = rect.isClockwise();\n            if (!isCW) {\n                console.warn(\"------ rect is not isClockwise!\", index, isCW);\n            }\n        });\n        const eps = intersectionEpsilon === undefined || typeof intersectionEpsilon === \"undefined\" ? 1.0 : intersectionEpsilon;\n        return splitPolygonsVertices.filter((splitPolyVerts, _splitPolyIndex) => {\n            const intersectionTestCallback = PolygonInset._hasIntersectionCallback(splitPolyVerts, eps, _splitPolyIndex);\n            const intersectsWithAnyRect = insetRectanglePolygons.some(intersectionTestCallback);\n            return !intersectsWithAnyRect;\n        });\n    }\n    /**\n     * This private method will reverse each polygon's vertex order that's not clockwise.\n     *\n     * @param {Array<Vertex[]>} polygons\n     */\n    static _assertAllPolygonsAreClockwise(polygons) {\n        polygons.forEach((polygonVerts, _polyIndex) => {\n            // if (!Polygon.utils.isClockwise(polygonVerts)) {\n            //   polygonVerts.reverse(); // Attention: this happens in-place (Array.reverse is destructive!)\n            // }\n            PolygonInset._assertPolygonIsClockwise(polygonVerts);\n        });\n    }\n    /**\n     * This private method will revert the vertex order if the polygon is not clockwise.\n     *\n     * @param {Vertex[]} polygonVerts\n     */\n    static _assertPolygonIsClockwise(polygonVerts) {\n        if (!Polygon.utils.isClockwise(polygonVerts)) {\n            polygonVerts.reverse(); // Attention: this happens in-place (Array.reverse is destructive!)\n        }\n    }\n}\n/**\n * Optimize the inset polygon by removing critical `ear` edges.\n * Such an is identified by: the edge itself is completely located inside its neighbours inset rectangle.\n *\n * In this process multiple edges from the ear might be dropped and two adjacent edges get a new\n * common intersection point.\n *\n * Note: this method is not working as expected in all cases and quite experimental.\n *\n * @param insetPolygon\n * @param insetRectangles\n */\nPolygonInset._optimizeInsetPolygon = (insetPolygon, insetRectangles) => {\n    // Locate edge that can be removed:\n    var earEdgeIndex = -1;\n    var maxLimit = insetPolygon.vertices.length;\n    var i = 0;\n    while (i++ < maxLimit &&\n        insetPolygon.vertices.length > 3 &&\n        (earEdgeIndex = PolygonInset._locateExcessiveEarEdge(insetPolygon, insetRectangles)) != -1) {\n        // console.log(\"REMOVE EAR EDGE\", earEdgeIndex);\n        // As this is an ear edge: don't just remove the vertex.\n        //   i) Remove the vertex and calculate the new intersection point of neighbour edges.\n        //  ii) Update neightbour rectangles\n        var leftEdge = insetPolygon.getEdgeAt(earEdgeIndex - 2);\n        var rightEdge = insetPolygon.getEdgeAt(earEdgeIndex + 1);\n        var newIntersection = leftEdge.intersection(rightEdge);\n        newIntersection && rightEdge.a.set(newIntersection);\n        // Update rectangles\n        // ...\n        insetPolygon.vertices.splice(earEdgeIndex, 1);\n        insetRectangles.splice(earEdgeIndex, 1);\n    }\n    // TODO remove if not -1\n};\nPolygonInset._locateExcessiveEarEdge = (insetPolygon, insetRectangles) => {\n    for (var i = 0; i < insetPolygon.vertices.length; i++) {\n        const thisEdge = insetPolygon.getEdgeAt(i);\n        const leftIndex = i == 0 ? insetPolygon.vertices.length - 1 : i - 1;\n        // const rightIndex = i + 1 >= insetPolygon.vertices.length ? 0 : i + 1;\n        const leftRect = insetRectangles[leftIndex];\n        // const rightRect = insetRectangles[rightIndex];\n        const leftRectContainsThisEdge = PolygonInset._rectangleFullyContainsLine(leftRect, thisEdge);\n        if (leftRectContainsThisEdge) {\n            return i;\n        }\n        const leftEdge = insetPolygon.getEdgeAt(leftIndex);\n        const thisRect = insetRectangles[i];\n        const thisRectContainsLeftEdge = PolygonInset._rectangleFullyContainsLine(thisRect, leftEdge);\n        if (thisRectContainsLeftEdge) {\n            return i; // leftIndex;\n        }\n    }\n    return -1;\n};\n// Pre: rectangle.vertices.length === 4\nPolygonInset._rectangleFullyContainsLine = (rectangle, edge) => {\n    var rectWidth = rectangle.getEdgeAt(0).length();\n    var rectHeight = rectangle.getEdgeAt(1).length();\n    // Both line corners must be at least 1% within the rectangle limits.\n    const eps = Math.min(rectWidth, rectHeight) / 100;\n    const edgeLen = edge.length();\n    var epsPointA = edge.vertAt(0.01); // edgeLen * eps);\n    var epsPointB = edge.vertAt(0.99); // 1.0 - edgeLen * eps);\n    var centerPoint = edge.vertAt(0.5);\n    return rectangle.containsVerts([epsPointA, epsPointB, centerPoint]);\n};\n/**\n * For simplification I'm using a callback generator function here.\n *\n * @param splitPolyVerts\n * @param eps\n * @param _splitPolyIndex\n * @returns {Function} The callback for an `Array.some` parameter.\n */\nPolygonInset._hasIntersectionCallback = (splitPolyVerts, eps, _splitPolyIndex) => (rectanglePoly, _rectanglePolyIndex) => {\n    // const intersectionVerts: XYCoords[] = sutherlandHodgman(splitPolyVerts, rectanglePoly.vertices);\n    const intersectionVerts = sutherlandHodgman(rectanglePoly.vertices, splitPolyVerts);\n    // var intersection = GreinerHorman.intersection(sourcePolygon.vertices, clipPolygon.vertices);\n    // const uniqueIntersectionVerts = clearDuplicateVertices(intersectionVerts);\n    const intersectionAreaSize = Polygon.utils.area(intersectionVerts);\n    if (intersectionAreaSize < 0) {\n        console.warn(\"%cFound a polygon split with negative area. Counterclockwise against all odds?\", \"color: red; background: black;\", //  font-size: 30px\",\n        \"intersectionAreaSize\", intersectionAreaSize, \"_splitPolyIndex\", _splitPolyIndex, \"_rectanglePolyIndex\", _rectanglePolyIndex, \"intersectionVerts\", intersectionVerts\n        // \"uniqueIntersectionVerts\",\n        // uniqueIntersectionVerts\n        );\n    }\n    // if (intersectionAreaSize >= eps) {\n    //   console.log(\n    //     \"%cFound a polygon split for removal\",\n    //     \"color: orange; background: grey;\", //  font-size: 30px\",\n    //     \"intersectionAreaSize\",\n    //     intersectionAreaSize,\n    //     \"_splitPolyIndex\",\n    //     _splitPolyIndex,\n    //     \"_rectanglePolyIndex\",\n    //     _rectanglePolyIndex,\n    //     \"intersectionVerts\",\n    //     intersectionVerts\n    //     // \"uniqueIntersectionVerts\",\n    //     // uniqueIntersectionVerts\n    //   );\n    // }\n    // if (intersectionAreaSize < eps) {\n    //   // console.log(\"%cHello\", \"color: green; background: yellow; font-size: 30px\");\n    //   console.log(\n    //     \"Polygon split can be kept. Area is position but below epsilon.\",\n    //     \"intersectionAreaSize\",\n    //     intersectionAreaSize,\n    //     \"_splitPolyIndex\",\n    //     _splitPolyIndex,\n    //     \"_rectanglePolyIndex\",\n    //     _rectanglePolyIndex,\n    //     \"intersectionVerts\",\n    //     intersectionVerts\n    //     // \"uniqueIntersectionVerts\",\n    //     // uniqueIntersectionVerts\n    //   );\n    // }\n    return intersectionAreaSize >= eps;\n};\n//# sourceMappingURL=PolygonInset.js.map","/**\n * Find the outer hull outlines of a (not necessarily full connected) polygon tesellation.\n *\n * The method `findAllOutlinesGraph` will return a simple graph containing all vertices and edges\n * that belong to the outer hull.\n *\n * The method `findAllOutlinesPolygons` will detect connected paths inside the graph and return\n * an array of Polygons.\n *\n *\n * @require detectPaths\n *\n * @author  Ikaros Kappler\n * @date    2026-01-20\n * @version 1.0.0\n */\nimport { Line } from \"../../Line\";\nimport { Polygon } from \"../../Polygon\";\nimport { arrayFill } from \"./arrayFill\";\nimport { detectPaths } from \"./detectPaths\";\n/**\n * Convert any non-intersecting tesselation to a graph.\n * Adjadent tiles (polygons) will result in duplicate edges.\n *\n * @param {Polygon[]} polygons - The polygon tesselation to use.\n * @return {TesselationGraph} A tesselation graph.\n */\nexport const polygonTesselationToGraph = (polygons) => {\n    const vertices = [];\n    const edges = [];\n    // const vertexPolygonMapping: Array<number>[] = []; // Map polygon+vertex to graph vertices\n    for (var i = 0; i < polygons.length; i++) {\n        const polygon = polygons[i];\n        const polygonMapping = [];\n        // vertexPolygonMapping.push(polygonMapping);\n        // Add vertices\n        for (var j = 0; j < polygon.vertices.length; j++) {\n            const graphVertIndex = vertices.length;\n            vertices.push(polygon.vertices[j]);\n            polygonMapping.push(graphVertIndex);\n        }\n        // Now add edges\n        for (var j = 0; j < polygon.vertices.length; j++) {\n            const polyEdgeIndexA = j;\n            const polyEdgeIndexB = (j + 1) % polygon.vertices.length;\n            const grapgVertIndexA = polygonMapping[polyEdgeIndexA];\n            const grapgVertIndexB = polygonMapping[polyEdgeIndexB];\n            edges.push({ i: grapgVertIndexA, j: grapgVertIndexB });\n        }\n    }\n    return { vertices, edges };\n};\n/**\n * A class to calculate the tesselation's outer hull.\n */\nexport class PolygonTesselationOutlines {\n    /**\n     * @constructor\n     * @param {Polygon[]} polygons - The polygon tesselation to use.\n     * @param {PolygonTesselationOutlinesOptions} options - (optional)\n     */\n    constructor(polygons, options) {\n        var _a, _b;\n        this.polygons = polygons;\n        // this.tesselationGraph = tesselationToGraph(polygons);\n        this.tolerance = (_a = options === null || options === void 0 ? void 0 : options.tolerance) !== null && _a !== void 0 ? _a : PolygonTesselationOutlines.DEFAULT_TOLERANCE;\n        this.removeUnusedVertices = (_b = options === null || options === void 0 ? void 0 : options.removeUnusedVertices) !== null && _b !== void 0 ? _b : true;\n    }\n    /**\n     * Clears duplicate edges.\n     *\n     * Note: this works only for duplicates. Triplets will not be removed.\n     *\n     * @name __eliminateDuplicateEdges\n     * @private\n     * @memberof TesselationGraph\n     * @instance\n     * @param {TesselationGraph} tesselationGraph - The tesselation graph to remove duplicate edges from.\n     * @return {TesselationGraph} A new tesselation graph with cleaned up edges.\n     */\n    __eliminateDuplicateEdges(tesselationGraph) {\n        const newEdges = [];\n        for (var e = 0; e < tesselationGraph.edges.length; e++) {\n            const curEdge = tesselationGraph.edges[e];\n            if (!curEdge) {\n                continue;\n            }\n            const curA = tesselationGraph.vertices[curEdge.i];\n            const curB = tesselationGraph.vertices[curEdge.j];\n            for (var f = 0; f < tesselationGraph.edges.length; f++) {\n                if (e === f) {\n                    continue;\n                }\n                const otherEdge = tesselationGraph.edges[f];\n                if (!otherEdge) {\n                    continue;\n                }\n                const otherA = tesselationGraph.vertices[otherEdge.i];\n                const otherB = tesselationGraph.vertices[otherEdge.j];\n                if (this.__isEqualEdge(curA, curB, otherA, otherB)) {\n                    // Both edges are equal -> remove both\n                    tesselationGraph.edges[e] = null;\n                    tesselationGraph.edges[f] = null;\n                }\n            }\n        }\n        // return tesselationGraph; // TODO: create clean clone with new mapping\n        // Clear null-records.\n        return {\n            vertices: tesselationGraph.vertices,\n            edges: tesselationGraph.edges.filter((edge) => edge != null)\n        }; // TODO: create clean clone with new mapping\n    }\n    /**\n     * Locate some edge that adjacent to the given vertex index\n     *\n     * @name __locateEdgeWithVertIndex\n     * @private\n     * @memberof TesselationGraph\n     * @instance\n     * @param {number} vertIndex - The vertex index to find an edge for.\n     * @param {TesselationGraph} tesselationGraph - The tesselation graph to remove unused vertices from.\n     * @return {number} The edge index that's adjacent to the given vertex index.\n     * @return -1 if no such edge is found.\n     */\n    __locateEdgeWithVertIndex(vertIndex, tesselationGraph) {\n        return tesselationGraph.edges.findIndex((edge) => edge.i == vertIndex || edge.j == vertIndex);\n    }\n    /**\n     * Removes all unused vertices from the graph and re-matps the edges.\n     *\n     * @name __removeUnusedVertices\n     * @private\n     * @memberof TesselationGraph\n     * @instance\n     * @param {TesselationGraph} tesselationGraph - The tesselation graph to remove unused vertices from.\n     * @return {TesselationGraph} A new tesselation graph.\n     */\n    __removeUnusedVertices(tesselationGraph) {\n        // First remove un-used vertices and re-map indices.\n        const newVertices = [];\n        const indexMapping = arrayFill(tesselationGraph.vertices.length, -1);\n        for (var j = 0; j < tesselationGraph.vertices.length; j++) {\n            const edgeIndex = this.__locateEdgeWithVertIndex(j, tesselationGraph);\n            if (edgeIndex === -1) {\n                // No adjacent edge found -> vertex is not in use\n                // Ignore; index mapping remains to -1\n            }\n            else {\n                // Keep vertex\n                const newIndex = newVertices.length;\n                newVertices.push(tesselationGraph.vertices[j]);\n                indexMapping[j] = newIndex;\n            }\n        }\n        // Now re-map the egdes\n        const newEdges = [];\n        for (var j = 0; j < tesselationGraph.edges.length; j++) {\n            const edge = tesselationGraph.edges[j];\n            newEdges.push({ i: indexMapping[edge.i], j: indexMapping[edge.j] });\n        }\n        return { vertices: newVertices, edges: newEdges };\n    }\n    /**\n     * Creates a tesselation graph and removes all inner edges.\n     *\n     * @name findAllOutlinesGraph\n     * @private\n     * @memberof PolygonTesselationOutlines\n     * @instance\n     * @return {TesselationGraph} A tesselation graph containing the outer hull edges only.\n     */\n    findAllOutlinesGraph() {\n        // First build tesselation graph from polygons, containing all edges and vertices.\n        const tesselationGraph = polygonTesselationToGraph(this.polygons);\n        // Now eliminate all duplicate edges. By construction only inner edges are duplicates.\n        const outerHull = this.__eliminateDuplicateEdges(tesselationGraph);\n        // Only of requested remove unused vertices.\n        if (this.removeUnusedVertices) {\n            const cleanOuterHull = this.__removeUnusedVertices(outerHull);\n            return cleanOuterHull;\n        }\n        else {\n            return outerHull;\n        }\n    }\n    /**\n     * Convert any generic path to a polygon. Each path segment (start point and end point)\n     * are interpreted as a linear segment here.\n     *\n     * @name __convertGenericPathToPolygon\n     * @private\n     * @memberof PolygonTesselationOutlines\n     * @instance\n     * @param {GenericPath} path - The path to convert.\n     */\n    __convertGenericPathToPolygon(path) {\n        const vertices = [];\n        const n = path.getSegmentCount();\n        let isOpen = false;\n        for (var i = 0; i < n; i++) {\n            const segment = path.getSegmentAt(i);\n            vertices.push(segment.getStartPoint());\n            if (i > 0 && i + 1 >= n && !this.__isEqualPoint(segment.getEndPoint(), vertices[0])) {\n                isOpen = true;\n            }\n        }\n        return new Polygon(vertices, isOpen);\n    }\n    /**\n     * Creates a tesselation graph and removes all inner edges.\n     *\n     * @name findAllOutlinesPolygons\n     * @private\n     * @memberof PolygonTesselationOutlines\n     * @instance\n     * @param {TesselationGraph} tesselationGraph - Find all outlines on the tesselation graph.\n     */\n    findAllOutlinesPolygons(tesselationGraph) {\n        // Convert to real line segments:\n        const lineSegments = tesselationGraph.edges.map((edge) => new Line(tesselationGraph.vertices[edge.i], tesselationGraph.vertices[edge.j]));\n        // Now run the path detection.\n        const paths = detectPaths(lineSegments, this.tolerance);\n        // And now convert the generic paths back to polygons\n        // (we have put in line segments, so line segments must have returned)\n        return paths.map((path) => this.__convertGenericPathToPolygon(path));\n    }\n    /**\n     * Checks if two vertices are equal – regarding to the current tolerance setting.\n     *\n     * @name __isEqualPoint\n     * @private\n     * @memberof PolygonTesselationOutlines\n     * @instance\n     * @param {boolean} vertA - The first point.\n     * @param {boolean} vertB - The second point.\n     * @return True if the vertices are equal.\n     */\n    __isEqualPoint(vertA, vertB) {\n        return vertA.distance(vertB) < this.tolerance;\n    }\n    /**\n     * Checks if two edges (identified as two pairs of vertices) are equal – regarding to the\n     * current tolerance setting.\n     *\n     * @name __isEqualEdge\n     * @private\n     * @memberof PolygonTesselationOutlines\n     * @instance\n     * @param {boolean} edgeAvertA - The first edge's point A.\n     * @param {boolean} edgeAvertB - The first edge's point B.\n     * @param {boolean} edgeBvertA - The second edge's point A.\n     * @param {boolean} edgeBvertB - The second edge's point B.\n     * @return True if the edges are equal.\n     */\n    __isEqualEdge(edgeAvertA, edgeAvertB, edgeBvertA, edgeBvertB) {\n        return ((this.__isEqualPoint(edgeAvertA, edgeBvertA) && this.__isEqualPoint(edgeAvertB, edgeBvertB)) ||\n            (this.__isEqualPoint(edgeAvertA, edgeBvertB) && this.__isEqualPoint(edgeAvertB, edgeBvertA)));\n    }\n}\nPolygonTesselationOutlines.DEFAULT_TOLERANCE = 0.01;\n//# sourceMappingURL=PolygonTesselationOutlines.js.map","/**\n * A simple linear color gradient implementation.\n *\n * A color gradient is just an array of color objects paired with position values on the gradient.\n *\n * TODO: add `angle`\n *\n * @author  Ikaros Kappler\n * @version 1.0.0\n * @date    2025-08-05\n * @modified 2025-11-26 Fixing a bug in `ColorGradient.getColorAt(ratio)`: value at 1.0 caused runtime error.\n */\nimport { Color } from \"./Color\";\nconst RAD_TO_DEG = 180.0 / Math.PI;\nconst DEFAULT_COLORSET = [\n    { color: Color.Red, ratio: 0.0 },\n    { color: Color.Gold, ratio: 0.2 },\n    { color: Color.Yellow, ratio: 0.4 },\n    { color: Color.LimeGreen, ratio: 0.6 },\n    { color: Color.MediumBlue, ratio: 0.8 },\n    { color: Color.Purple, ratio: 1.0 }\n];\nexport class ColorGradient {\n    /**\n     * Creates a new ColorGradient with the given values. Please be sure that the values appear in the correct\n     * order regarding the `ratio` information. This will not be validated.\n     *\n     * @param {Array<ColorGradientItem>} values - The values to use.\n     * @param {number?} angle - (optional) An optional angle for the gradient; if no specified `PI/2.0` will be used (vertical from left to right).\n     */\n    constructor(values, angle) {\n        this.values = values;\n        // Default: left to right\n        this.angle = typeof angle === \"undefined\" ? Math.PI / 2.0 : angle;\n    }\n    /**\n     * Get a color gradient CSS value string from these gradient settings.\n     *\n     * @instance\n     * @memberof ColorGradientPicker\n     * @returns {string}\n     */\n    toColorGradientString() {\n        // Example:\n        //    linear-gradient(90deg,rgba(42, 123, 155, 1) 0%, rgba(87, 199, 133, 1) 38%, rgba(161, 210, 108, 1) 68%, rgba(237, 221, 83, 1) 100%)\n        // const buffer: Array<string | undefined> = [`linear-gradient( ${RAD_TO_DEG * this.angle}deg, `];\n        const buffer = [\n            `linear-gradient( ${typeof this.angle === \"number\" ? `${this.angle * RAD_TO_DEG}deg` : this.angle}, `\n        ];\n        for (var i = 0; i < this.values.length; i++) {\n            if (i > 0) {\n                buffer.push(\",\");\n            }\n            const colorValue = this.values[i] ? this.values[i].color.cssRGBA() : null;\n            buffer.push(colorValue);\n            const percentage = this.values[i].ratio;\n            buffer.push(`${typeof percentage === \"number\" ? `${percentage * 100}%` : percentage}`);\n        }\n        buffer.push(\")\");\n        return buffer.join(\" \");\n    }\n    /**\n     * Get the color at the specific relative position.\n     *\n     * @param {number} ratio - Any value between 0.0 and 1.0.\n     */\n    getColorAt(ratio) {\n        // Locate interval first\n        const intervalLocation = this.locateClosestRatio(ratio);\n        const leftItem = this.values[intervalLocation[0]];\n        const rightItem = this.values[intervalLocation[0] + 1];\n        if (!rightItem) {\n            return leftItem.color.clone();\n        }\n        const relativeInnerIntervalPosition = (ratio - leftItem.ratio) / (rightItem.ratio - leftItem.ratio);\n        return leftItem.color.clone().interpolate(rightItem.color, relativeInnerIntervalPosition);\n    }\n    /**\n     * Find that gradient record (index) that's value is closest to the given relative value. The function will return\n     * the closest value and the left index, indicating the containing interval index.\n     *\n     * @param {number} ratio - The value to look for.\n     * @returns {[number,number]} A pair of left interval boundary index and closest value.\n     */\n    locateClosestRatio(ratio) {\n        if (this.values.length === 0) {\n            console.warn(\"[Warn] All slider values array is empty. This should not happen, cannot proceed.\");\n            return [NaN, null]; // This should not happen: at least two values must be present in a gradient\n        }\n        // console.log(\"__locateClosestSliderValue\", \"allSliderValues\", allSliderValues);\n        let leftSliderIndex = 0;\n        let closestSliderValue = this.values[leftSliderIndex];\n        for (var i = 1; i < this.values.length; i++) {\n            const curVal = this.values[i];\n            if (Math.abs(curVal.ratio - ratio) < Math.abs(closestSliderValue.ratio - ratio)) {\n                closestSliderValue = curVal;\n                if (curVal.ratio > ratio) {\n                    leftSliderIndex = i - 1;\n                }\n                else {\n                    leftSliderIndex = i;\n                }\n            }\n        }\n        return [leftSliderIndex, closestSliderValue];\n    }\n    /**\n     * Try to convert the given anonymous item (usually and object) to a ColorGradient. This method should be used\n     * to restore items from JSON parse results to convert them into proper ColorGradient instances.\n     *\n     * @param {any} item\n     * @returns {ColorGradient}\n     */\n    static fromObject(item) {\n        if (typeof item !== \"object\") {\n            throw new Error(`Cannot instantiate ColorGradient from item: must be an object. (${typeof item})`);\n        }\n        if (!item.hasOwnProperty(\"values\")) {\n            throw new Error(\"Cannot instantiate ColorGradient from object: missing property 'values'.\");\n        }\n        const valuesObj = item.values;\n        if (!Array.isArray(valuesObj)) {\n            throw new Error(\"Cannot instantiate ColorGradient from object: property 'values' is not an array.\");\n        }\n        const values = valuesObj.map((element, index) => {\n            if (typeof element !== \"object\") {\n                throw new Error(`Cannot instantiate ColorGradient from object: item at index ${index} is not an object.`);\n            }\n            if (!element.hasOwnProperty(\"color\") || !element.hasOwnProperty(\"ratio\")) {\n                throw new Error(`Cannot instantiate ColorGradient from object: item at index ${index} is missing 'color' or 'ratio' property.`);\n            }\n            const tmpElement = element;\n            return { color: Color.makeRGB(tmpElement.color.r, tmpElement.color.g, tmpElement.color.b), ratio: tmpElement.ratio };\n        });\n        // More checks possible here ...\n        return new ColorGradient(values, item.angle);\n    }\n    /**\n     * Clone this linear color gradient. Returns a deep clone.\n     *\n     * @returns {ColorGradient}\n     */\n    clone() {\n        return new ColorGradient(this.values.map((item) => {\n            return { color: item.color, ratio: item.ratio };\n        }), this.angle);\n    }\n    /**\n     * Create a default color gradient with six color: red, orange, yellow, green, blue, purple.\n     * @returns\n     */\n    static createDefault() {\n        return new ColorGradient(DEFAULT_COLORSET.map((item) => ({ color: item.color, ratio: item.ratio })));\n    }\n    /**\n     * Create a basic color gradient from only two colors.\n     *\n     * @param {Color} startColor - The leftmost color.\n     * @param {Color} endColor - The rightmost color.\n     * @param {number?} angleInRadians - (optional) An optional angle for the gradient; if no specified `PI/2.0` will be used (vertical from left to right).\n     * @returns\n     */\n    static createFrom(startColor, endColor, angleInRadians) {\n        return new ColorGradient([\n            { ratio: 0.0, color: startColor },\n            { ratio: 1.0, color: endColor }\n        ], angleInRadians);\n    }\n}\nColorGradient.DEFAULT_COLORSET = DEFAULT_COLORSET;\n//# sourceMappingURL=ColorGradient.js.map","/**\n * @author   Ikaros Kappler\n * @date     2013-11-27\n * @modified 2014-04-05 Ikaros Kappler (member array outerTilePolygons added).\n * @modified 2015-03-19 Ikaros Kappler (added toSVG()).\n * @modified 2020-10-30 Refactored the this super class to work with PlotBoilerplate.\n * @modified 2020-11-11 Ported the class from vanilla JS to TypeScript.\n * @version  2.0.1-alpha\n * @name GirihTile\n **/\nimport { Bounds } from \"../../Bounds\";\nimport { Line } from \"../../Line\";\nimport { Polygon } from \"../../Polygon\";\nimport { Vertex } from \"../../Vertex\";\nexport var TileType;\n(function (TileType) {\n    TileType[\"UNKNOWN\"] = \"UNKNOWN\";\n    TileType[\"DECAGON\"] = \"DECAGON\";\n    TileType[\"PENTAGON\"] = \"PENTAGON\";\n    TileType[\"IRREGULAR_HEXAGON\"] = \"IRREGULAR_HEXAGON\";\n    TileType[\"RHOMBUS\"] = \"RHOMBUS\";\n    TileType[\"BOW_TIE\"] = \"BOW_TIE\";\n    // This is not part of the actual girih tile set!\n    TileType[\"PENROSE_RHOMBUS\"] = \"PENROSE_RHOMBUS\";\n})(TileType || (TileType = {}));\n/**\n * @classdesc This is a general tile superclass. All other tile classes extends this one.\n *\n * Rule:\n *  * the outer and the inner sub polygons must be inside the main polygon's bounds.\n *\n * @requires Bounds\n * @requires Polyon\n * @requires Vertex\n * @requires XYCoords\n */\nexport class GirihTile extends Polygon {\n    /**\n     * @constructor\n     * @memberof GirihTile\n     * @abstract class\n     * @param {Vertex} position   - The position of the tile.\n     * @param {number} edgeLength - The edge length (default is GirihTile.DEFAULT_EDGE_LENGTH).\n     * @param {TileType} tileType - One of `TileType.*` enum members.\n     **/\n    constructor(position, edgeLength, tileType) {\n        super([], false); // vertices, isOpen\n        if (typeof edgeLength === \"undefined\")\n            edgeLength = GirihTile.DEFAULT_EDGE_LENGTH;\n        if (typeof tileType == \"undefined\")\n            tileType = TileType.UNKNOWN;\n        this.edgeLength = edgeLength;\n        this.position = position;\n        this.rotation = 0.0; // angle;\n        this.symmetry = 10;\n        this.uniqueSymmetries = 10;\n        // An array of polygons.\n        // The inner tile polygons are those that do not share edges with the outer\n        // tile bounds (vertices are OK).\n        this.innerTilePolygons = [];\n        // A second array of polygons.\n        // The outer tile polygons are those that make up the whole tile area\n        // _together with the inner tile polygons (!)_; the union of the\n        // inner tile polygons and the outer tile polygons covers exactly\n        // the whole tile polygon.\n        // The intersection of both sets is empty.\n        // Outer tile polygon share at least one (partial) edge with the complete\n        // tile polygon (length > 0).\n        this.outerTilePolygons = [];\n        // this.imageProperties      = null;\n        this.textureSource = new Bounds(new Vertex(), new Vertex());\n        this.tileType = tileType;\n    }\n    /**\n     * Move this tile around (together will all inner polygons).\n     * As this function overrides Polygon.move(...), the returned\n     * instance (this) must be of type `Polygon`.\n     *\n     * @name move\n     * @instance\n     * @override\n     * @memberof GirihTile\n     * @param {XYCoords} amount\n     * @return {Polygon} this\n     */\n    move(amount) {\n        super.move.call(this, amount);\n        for (var i in this.innerTilePolygons)\n            this.innerTilePolygons[i].move(amount);\n        for (var i in this.outerTilePolygons)\n            this.outerTilePolygons[i].move(amount);\n        this.position.add(amount);\n        return this;\n    }\n    /**\n     * Find the adjacent tile (given by the template tile)\n     * Note that the tile itself will be modified (rotated and moved to the correct position).\n     *\n     * @name findAdjacentTilePosition\n     * @memberof GirihTile\n     * @instance\n     * @param {number} edgeIndex - The edge number of the you you want to find adjacency for.\n     * @param {Polygon} tile - The polygon (or tile) you want to find adjacency for at the specified edge.\n     * @return {IAdjacency|null} Adjacency information or null if the passed tile does not match.\n     */\n    findAdjacentTilePosition(edgeIndex, tile) {\n        const edgeA = new Line(this.vertices[edgeIndex % this.vertices.length], this.vertices[(edgeIndex + 1) % this.vertices.length]);\n        // Find adjacent edge\n        for (var i = 0; i < tile.vertices.length; i++) {\n            const edgeB = new Line(tile.vertices[i % tile.vertices.length].clone(), tile.vertices[(i + 1) % tile.vertices.length].clone());\n            // Goal: edgeA.a==edgeB.b && edgeA.b==edgeB.a\n            // So move edgeB\n            const offset = edgeB.b.difference(edgeA.a);\n            edgeB.add(offset);\n            if (edgeB.a.distance(edgeA.b) < GirihTile.epsilon) {\n                return { edgeIndex: i, offset: offset };\n            }\n        }\n        return null;\n    }\n    /**\n     * Find all possible adjacent tile positions (and rotations) for `neighbourTile`.\n     *\n     * @name transformTileToAdjacencies\n     * @memberof GirihTile\n     * @instance\n     * @param {number} baseEdgeIndex - The edge number of the you you want to find adjacencies for.\n     * @param {GirihTile} neighbourTile - The polygon (or tile) you want to find adjacencies for at the specified edge.\n     * @return {IAdjacency|null} Adjacency information or null if the passed tile does not match.\n     */\n    transformTileToAdjacencies(baseEdgeIndex, neighbourTile) {\n        // Find a rotation for that tile to match\n        let i = 0;\n        const foundAlignments = [];\n        let positionedTile = null;\n        while (i < neighbourTile.uniqueSymmetries) {\n            positionedTile = this.transformTilePositionToAdjacency(baseEdgeIndex, neighbourTile);\n            if (positionedTile != null) {\n                positionedTile = positionedTile.clone();\n                foundAlignments.push(positionedTile);\n            }\n            neighbourTile.rotate((Math.PI * 2) / neighbourTile.symmetry);\n            i++;\n        }\n        return foundAlignments;\n    }\n    /**\n     * Apply adjacent tile position to `neighbourTile`.\n     *\n     * @name transformTilePositionToAdjacencies\n     * @memberof GirihTile\n     * @instance\n     * @param {number} baseEdgeIndex - The edge number of the you you want to apply adjacent position for.\n     * @param {Polygon} neighbourTile - The polygon (or tile) you want to find adjacency for at the specified edge.\n     * @return {Polygon|null} the passed tile itself if adjacency was found, null otherwise.\n     */\n    transformTilePositionToAdjacency(baseEdgeIndex, neighbourTile) {\n        // Find the position for that tile to match (might not exist)\n        // { edgeIndex:number, offset:XYCoords }\n        var adjacency = this.findAdjacentTilePosition(baseEdgeIndex, neighbourTile);\n        if (adjacency != null) {\n            neighbourTile.move(adjacency.offset);\n            return neighbourTile;\n        }\n        return null;\n    }\n    /**\n     * Get the inner tile polygon at the given index.\n     * This function applies MOD to the index.\n     *\n     * @name getInnerTilePolygonAt\n     * @instance\n     * @memberof GirihTile\n     * @param {number} index\n     * @return {Polygon} The sub polygon (inner tile) at the given index.\n     **/\n    getInnerTilePolygonAt(index) {\n        if (index < 0)\n            return this.innerTilePolygons[this.innerTilePolygons.length - (Math.abs(index) % this.innerTilePolygons.length)];\n        else\n            return this.innerTilePolygons[index % this.innerTilePolygons.length];\n    }\n    /**\n     * Get the outer tile polygon at the given index.\n     * This function applies MOD to the index.\n     *\n     * @name getOuterTilePolygonAt\n     * @instance\n     * @memberof GirihTile\n     * @param {number} index\n     * @return {Polygon} The sub polygon (outer tile) at the given index.\n     **/\n    getOuterTilePolygonAt(index) {\n        if (index < 0)\n            return this.outerTilePolygons[this.outerTilePolygons.length - (Math.abs(index) % this.outerTilePolygons.length)];\n        else\n            return this.outerTilePolygons[index % this.outerTilePolygons.length];\n    }\n    /**\n     * Rotate this tile\n     * Note: this function behaves a bitdifferent than the genuine Polygon.rotate function!\n     *       Polygon has the default center of rotation at (0,0).\n     *       The GirihTile rotates around its center (position) by default.\n     *\n     * @name rotate\n     * @instance\n     * @memberof GirihTile\n     * @param {number} angle - The angle to use for rotation.\n     * @param {Vertex?} center - The center of rotation (default is this.position).\n     * @return {Polygon} this\n     **/\n    rotate(angle, center) {\n        if (typeof center === \"undefined\")\n            center = this.position;\n        super.rotate(angle, center);\n        for (var i in this.innerTilePolygons) {\n            this.innerTilePolygons[i].rotate(angle, center);\n        }\n        for (var i in this.outerTilePolygons) {\n            this.outerTilePolygons[i].rotate(angle, center);\n        }\n        this.rotation += angle;\n        return this;\n    }\n    /**\n     * This function locates the closest tile edge (polygon edge)\n     * to the passed point.\n     *\n     * Currently the edge distance to a point is measured by the\n     * euclidian distance from the edge's middle point.\n     *\n     * Idea: move this function to Polygon?\n     *\n     * @name locateEdgeAtPoint\n     * @instance\n     * @memberof GirihTile\n     * @param {XYCoords} point     - The point to detect the closest edge for.\n     * @param {number}   tolerance - The tolerance (=max distance) the detected edge\n     *                               must be inside.\n     * @return {nmber} the edge index (index of the starting vertex, so [index,index+1] is the edge ) or -1 if not found.\n     **/\n    locateEdgeAtPoint(point, tolerance) {\n        if (this.vertices.length == 0)\n            return -1;\n        const middle = new Vertex(0, 0);\n        let tmpDistance = 0;\n        let resultDistance = tolerance * 2; // definitely outside the tolerance :)\n        let resultIndex = -1;\n        for (var i = 0; i < this.vertices.length; i++) {\n            const vertI = this.getVertexAt(i);\n            const vertJ = this.getVertexAt(i + 1);\n            // Create a point in the middle of the edge\n            middle.x = vertI.x + (vertJ.x - vertI.x) / 2.0;\n            middle.y = vertI.y + (vertJ.y - vertI.y) / 2.0;\n            tmpDistance = middle.distance(point);\n            if (tmpDistance <= tolerance && (resultIndex == -1 || tmpDistance < resultDistance)) {\n                resultDistance = tmpDistance;\n                resultIndex = i;\n            }\n        }\n        return resultIndex;\n    }\n} // END class\n/**\n * An epsilon to use for detecting adjacent edges. 0.001 seems to be a good value.\n * Adjust if needed.\n *\n * @name epsilon\n * @member {number}\n * @memberof GirihTile\n * @type {number}\n * @static\n */\nGirihTile.epsilon = 0.001;\n/**\n * The default edge length.\n *\n * @name DEFAULT_EDGE_LENGTH\n * @member {number}\n * @memberof GirihTile\n * @type {number}\n * @readonly\n * @static\n */\nGirihTile.DEFAULT_EDGE_LENGTH = 58;\n//# sourceMappingURL=GirihTile.js.map","/**\n * @classdesc The bow tie tile from the Girih set.\n *\n * @requires Bounds\n * @requires GirihTile\n * @requires Polygon\n * @requires TileType\n * @requires Vertex\n *\n * @author Ikaros Kappler\n * @modified 2013-11-28\n * @modified 2014-04-05 Ikaros Kappler (member array outerTilePolygons added).\n * @modified 2015-03-19 Ikaros Kappler (added toSVG()).\n * @modified 2020-10-31 Refactored to work with PlotBoilerplate.\n * @modified 2020-11-13 Ported from vanilla JS to TypeScript.\n * @version 2.0.1-alpha\n * @file GirihBowtie\n * @public\n **/\nimport { GirihTile, TileType } from \"./GirihTile\";\nimport { Polygon } from \"../../Polygon\";\nimport { Vertex } from \"../../Vertex\";\nexport class GirihBowtie extends GirihTile {\n    /**\n     * @constructor\n     * @extends GirihTile\n     * @name GirihBowtie\n     * @param {Vertex} position\n     * @param {number} edgeLength\n     */\n    constructor(position, edgeLength) {\n        super(position, edgeLength, TileType.BOW_TIE);\n        // Overwrite the default symmetries:\n        //    the bow-tie tile has a 180° symmetry (5/10 * 360°)\n        this.uniqueSymmetries = 5;\n        // Init the actual decahedron shape with the passed size\n        let pointA = new Vertex(0, 0);\n        let pointB = pointA;\n        const startPoint = pointA;\n        let oppositePoint = null;\n        this.addVertex(pointB);\n        // TODO: notate in radians\n        var angles = [0.0,\n            72.0,\n            72.0,\n            216.0,\n            72.0\n        ];\n        var theta = 0.0;\n        for (var i = 0; i < angles.length; i++) {\n            theta += (180.0 - angles[i]);\n            pointA = pointB; // center of rotation\n            pointB = pointB.clone();\n            pointB.x -= this.edgeLength;\n            pointB.rotate(theta * (Math.PI / 180.0), pointA);\n            this.addVertex(pointB);\n            if (i == 2)\n                oppositePoint = pointB;\n        } // END for\n        // Move to center and position \n        const move = new Vertex((oppositePoint.x - startPoint.x) / 2.0, (oppositePoint.y - startPoint.y) / 2.0);\n        for (var i = 0; i < this.vertices.length; i++) {\n            this.vertices[i].add(position).sub(move);\n        }\n        this.textureSource.min.x = 288 / 500.0;\n        this.textureSource.min.y = 7 / 460.0;\n        this.textureSource.max.x = this.textureSource.min.x + 206 / 500.0;\n        this.textureSource.max.y = this.textureSource.min.y + 150 / 460.0;\n        this.baseBounds = this.getBounds();\n        this._buildInnerPolygons(this.edgeLength);\n        this._buildOuterPolygons(this.edgeLength); // Only call AFTER the inner polygons were created!\n    }\n    ;\n    /**\n     * @override\n     */\n    clone() {\n        return new GirihBowtie(this.position.clone(), this.edgeLength).rotate(this.rotation);\n    }\n    ;\n    _buildInnerPolygons(edgeLength) {\n        const indices = [1, 4];\n        for (var i = 0; i < indices.length; i++) {\n            const index = indices[i];\n            const middlePoint = this.getVertexAt(index).clone().scale(0.5, this.getVertexAt(index + 1));\n            const leftPoint = this.getVertexAt(index - 1).clone().scale(0.5, this.getVertexAt(index));\n            const rightPoint = this.getVertexAt(index + 1).clone().scale(0.5, this.getVertexAt(index + 2));\n            const innerPoint = middlePoint.clone().scale(0.38, this.position); // multiplyScalar( 0.38 );\n            const innerTile = new Polygon([]);\n            innerTile.addVertex(middlePoint);\n            innerTile.addVertex(rightPoint);\n            innerTile.addVertex(innerPoint);\n            innerTile.addVertex(leftPoint);\n            this.innerTilePolygons.push(innerTile);\n        }\n    }\n    ;\n    _buildOuterPolygons(edgeLength) {\n        // Add the outer four 'edges'\n        const indices = [0, 3];\n        for (var i = 0; i < indices.length; i++) {\n            const index = indices[i];\n            // The first/third triangle\n            const outerTileA = new Polygon();\n            outerTileA.addVertex(this.innerTilePolygons[i].getVertexAt(0).clone());\n            outerTileA.addVertex(this.getVertexAt(index + 2).clone());\n            outerTileA.addVertex(this.innerTilePolygons[i].getVertexAt(1).clone());\n            this.outerTilePolygons.push(outerTileA);\n            // The second/fourth triangle\n            const outerTileB = new Polygon();\n            outerTileB.addVertex(this.innerTilePolygons[i].getVertexAt(0).clone());\n            outerTileB.addVertex(this.getVertexAt(index + 1).clone());\n            outerTileB.addVertex(this.innerTilePolygons[i].getVertexAt(3).clone());\n            this.outerTilePolygons.push(outerTileB);\n        }\n        // Add the center polygon\n        const centerTile = new Polygon();\n        centerTile.addVertex(this.getVertexAt(0).clone());\n        centerTile.addVertex(this.innerTilePolygons[0].getVertexAt(3).clone());\n        centerTile.addVertex(this.innerTilePolygons[0].getVertexAt(2).clone());\n        centerTile.addVertex(this.innerTilePolygons[0].getVertexAt(1).clone());\n        centerTile.addVertex(this.getVertexAt(3).clone());\n        centerTile.addVertex(this.innerTilePolygons[1].getVertexAt(3).clone());\n        centerTile.addVertex(this.innerTilePolygons[1].getVertexAt(2).clone());\n        centerTile.addVertex(this.innerTilePolygons[1].getVertexAt(1).clone());\n        this.outerTilePolygons.push(centerTile);\n    }\n    ;\n}\n//# sourceMappingURL=GirihBowtie.js.map","/**\n * @classdesc The decagon tile from the Girih set.\n *\n * @requires GirihTile\n * @requires Polygon\n * @requires TileType\n * @requires Vertex\n *\n * @author   Ikaros Kappler\n * @date     2013-11-27\n * @date     2014-04-05 Ikaros Kappler (member array outerTilePolygons added).\n * @date     2015-03-19 Ikaros Kappler (added toSVG()).\n * @modified 2020-10-30 Refactored to work with PlotBoilerplate.\n * @modified 2020-11-13 Ported from vanilla JS to TypeScript.\n * @version  2.0.1-alpha\n * @file GirihDecacon\n * @public\n **/\nimport { GirihTile, TileType } from \"./GirihTile\";\nimport { Polygon } from \"../../Polygon\";\nexport class GirihDecagon extends GirihTile {\n    /**\n     * @constructor\n     * @extends GirihTile\n     * @name GirihDecagon\n     * @param {Vertex} position\n     * @param {number} edgeLength\n     */\n    constructor(position, edgeLength) {\n        super(position, edgeLength, TileType.DECAGON);\n        // Overwrite the default symmetries:\n        //    the decagon tile has a 36° symmetry (1/10 * 360°)\n        this.uniqueSymmetries = 1;\n        // Init the actual decahedron shape with the passed size:\n        // Divide the full circle into 10 sections (we want to make a regular decagon).\n        const theta = (Math.PI * 2) / 10.0;\n        // Compute the 'radius' using pythagoras\n        const radius = Math.sqrt(Math.pow(this.edgeLength / 2, 2)\n            +\n                Math.pow(1 / Math.tan(theta / 2) * this.edgeLength / 2, 2));\n        for (var i = 0; i < 10; i++) {\n            this.addVertex(position.clone().addY(-radius).rotate(theta / 2 + i * theta, position));\n        }\n        this.textureSource.min.x = 169 / 500.0;\n        this.textureSource.min.y = 140 / 460.0;\n        this.textureSource.max.x = this.textureSource.min.x + 313 / 500.0;\n        this.textureSource.max.y = this.textureSource.min.y + 297 / 460.0;\n        this.baseBounds = this.getBounds();\n        this._buildInnerPolygons(this.edgeLength);\n        this._buildOuterPolygons(this.edgeLength); // Important: call AFTER inner polygons were created!\n    }\n    ;\n    /**\n     * @override\n     */\n    clone() {\n        return new GirihDecagon(this.position.clone(), this.edgeLength).rotate(this.rotation);\n    }\n    ;\n    /**\n     * Build the inner polygons.\n     *\n     * @name _buildInnerPolygons\n     * @memberof GirihDecagon\n     * @private\n     * @param {number} edgeLength\n     */\n    _buildInnerPolygons(edgeLength) {\n        const centralStar = new Polygon();\n        for (var i = 0; i < 10; i++) {\n            const innerTile = new Polygon();\n            // Make polygon\n            const topPoint = this.getVertexAt(i).clone().scale(0.5, this.getVertexAt(i + 1));\n            const bottomPoint = topPoint.clone().scale(0.615, this.position);\n            const leftPoint = this.getVertexAt(i).clone().scale(0.69, this.position);\n            const rightPoint = this.getVertexAt(i + 1).clone().scale(0.69, this.position);\n            innerTile.addVertex(topPoint);\n            innerTile.addVertex(rightPoint);\n            innerTile.addVertex(bottomPoint);\n            innerTile.addVertex(leftPoint);\n            this.innerTilePolygons.push(innerTile);\n            centralStar.addVertex(leftPoint.clone());\n            centralStar.addVertex(bottomPoint.clone());\n        }\n        this.innerTilePolygons.push(centralStar);\n    }\n    ;\n    /**\n     * Build the outer polygons.\n     *\n     * @name _buildOuterPolygons\n     * @memberof GirihDecagon\n     * @private\n     * @param {number} edgeLength\n     */\n    _buildOuterPolygons(edgeLength) {\n        // DON'T include the inner star here!\n        for (var i = 0; i < 10; i++) {\n            const outerTile = new Polygon();\n            outerTile.addVertex(this.getVertexAt(i).clone());\n            outerTile.addVertex(this.innerTilePolygons[i].vertices[0].clone());\n            outerTile.addVertex(this.innerTilePolygons[i].vertices[3].clone());\n            outerTile.addVertex(this.getInnerTilePolygonAt(i == 0 ? 9 : i - 1).vertices[0].clone());\n            this.outerTilePolygons.push(outerTile);\n        }\n    }\n    ;\n}\n;\n//# sourceMappingURL=GirihDecagon.js.map","/**\n * @classdesc The irregular hexagon tile from the Girih set.\n *\n * @requires Bounds\n * @requires Circle\n * @requires GirihTile\n * @requires Line\n * @requires Polygon\n * @requires TileType\n * @requires Vertex\n *\n * @author Ikaros Kappler\n * @date 2013-11-28\n * @modified 2014-04-05 Ikaros Kappler (member array outerTilePolygons added).\n * @modified 2015-03-19 Ikaros Kappler (added toSVG()).\n * @modified 2020-10-31 Refactored to work with PlotBoilerplate.\n * @modified 2020-11-13 Ported from vanilla JS to TypeScript.\n * @version 2.0.1-alpha\n * @file GirihHexagon\n * @public\n **/\nimport { Circle } from \"../../Circle\";\nimport { GirihTile, TileType } from \"./GirihTile\";\nimport { Polygon } from \"../../Polygon\";\nimport { Vertex } from \"../../Vertex\";\nexport class GirihHexagon extends GirihTile {\n    /**\n     * @constructor\n     * @extends GirihTile\n     * @name GirihHexagon\n     * @param {Vertex} position\n     * @param {number} edgeLength\n     */\n    constructor(position, edgeLength) {\n        super(position, edgeLength, TileType.IRREGULAR_HEXAGON);\n        // Overwrite the default symmetries:\n        //    the hexagon tile has a 180° symmetry (5/10 * 360°)\n        this.uniqueSymmetries = 5;\n        // Init the actual decahedron shape with the passed size\n        let pointA = new Vertex(0, 0);\n        let pointB = pointA;\n        const startPoint = pointA;\n        let oppositePoint = null;\n        this.addVertex(pointB);\n        // TODO: use radians here\n        const angles = [0.0,\n            72.0,\n            144.0,\n            144.0,\n            72.0\n            // 144.0\n        ];\n        let theta = 0.0;\n        for (var i = 0; i < angles.length; i++) {\n            theta += (180.0 - angles[i]);\n            pointA = pointB; // center of rotation\n            pointB = pointB.clone();\n            pointB.x -= this.edgeLength;\n            pointB.rotate(theta * (Math.PI / 180.0), pointA);\n            this.addVertex(pointB);\n            if (i == 2)\n                oppositePoint = pointB;\n        }\n        // Center and move to desired position    \n        const move = new Vertex((oppositePoint.x - startPoint.x) / 2.0, (oppositePoint.y - startPoint.y) / 2.0);\n        for (var i = 0; i < this.vertices.length; i++) {\n            this.vertices[i].add(position).sub(move);\n        }\n        this.textureSource.min.x = 77 / 500.0;\n        this.textureSource.min.y = 11 / 460.0;\n        this.textureSource.max.x = this.textureSource.min.x + 205 / 500.0;\n        this.textureSource.max.y = this.textureSource.min.y + 150 / 460.0;\n        this.baseBounds = this.getBounds();\n        this._buildInnerPolygons(this.edgeLength);\n        this._buildOuterPolygons(this.edgeLength); // Only call AFTER the inner polygons were created!\n    }\n    ;\n    /**\n     * @override\n     */\n    clone() {\n        return new GirihHexagon(this.position.clone(), this.edgeLength).rotate(this.rotation);\n    }\n    ;\n    _buildInnerPolygons(edgeLength) {\n        // Connect all edges half-the-way\n        const innerTile = new Polygon();\n        innerTile.addVertex(this.vertices[0].clone().scale(0.5, this.vertices[1]));\n        innerTile.addVertex(this.vertices[1].clone().scale(0.5, this.vertices[2]));\n        // Compute the next inner polygon vertex by the intersection of two circles\n        const circleA = new Circle(innerTile.vertices[1], innerTile.vertices[0].distance(innerTile.vertices[1]));\n        const circleB = new Circle(this.vertices[2].clone().scale(0.5, this.vertices[3]), circleA.radius);\n        // TODO: the following piece of code occurs exactly four times.\n        // -> refactor! (DRY)\n        // There is definitely an intersection\n        let intersection = circleA.circleIntersection(circleB);\n        // The intersection is definitely not empty (by construction)\n        // One of the two points is inside the tile, the other is outside.\n        // Locate the inside point.\n        // Use the point that is closer to the center\n        if (this.position.distance(intersection.a) < this.position.distance(intersection.b))\n            innerTile.addVertex(intersection.a);\n        else\n            innerTile.addVertex(intersection.b);\n        innerTile.addVertex(circleB.center.clone());\n        // var i = 3;\n        // Move circles\n        circleA.center = circleB.center;\n        circleB.center = this.vertices[3].clone().scale(0.5, this.vertices[4]);\n        intersection = circleA.circleIntersection(circleB);\n        // The intersection is definitely not empty (by construction)\n        // There are two points again (one inside, one outside the tile)\n        // Use the point that is closer to the center\n        if (this.position.distance(intersection.a) < this.position.distance(intersection.b))\n            innerTile.addVertex(intersection.a);\n        else\n            innerTile.addVertex(intersection.b);\n        innerTile.addVertex(circleB.center.clone());\n        innerTile.addVertex(this.vertices[4].clone().scale(0.5, this.vertices[5]));\n        // Move circles  \n        circleA.center = innerTile.vertices[innerTile.vertices.length - 1];\n        circleB.center = this.vertices[5].clone().scale(0.5, this.vertices[0]);\n        intersection = circleA.circleIntersection(circleB);\n        // The intersection is definitely not empty (by construction)\n        // There are two points again (one inside, one outside the tile)\n        // Use the point that is closer to the center\n        if (this.position.distance(intersection.a) < this.position.distance(intersection.b))\n            innerTile.addVertex(intersection.a);\n        else\n            innerTile.addVertex(intersection.b);\n        innerTile.addVertex(circleB.center.clone());\n        // Move circles  \n        circleA.center = innerTile.vertices[innerTile.vertices.length - 1];\n        circleB.center = innerTile.vertices[0];\n        intersection = circleA.circleIntersection(circleB);\n        // The intersection is definitely not empty (by construction)\n        // There are two points again (one inside, one outside the tile)\n        // Use the point that is closer to the center\n        if (this.position.distance(intersection.a) < this.position.distance(intersection.b))\n            innerTile.addVertex(intersection.a);\n        else\n            innerTile.addVertex(intersection.b);\n        innerTile.addVertex(circleB.center.clone());\n        this.innerTilePolygons.push(innerTile);\n    }\n    ;\n    _buildOuterPolygons(edgeLength) {\n        // First add the two triangles at the 'ends' of the shape.\n        const indicesA = [0, 3]; //  6:2\n        const indicesB = [0, 5]; // 10:2\n        for (var i = 0; i < indicesA.length; i++) {\n            const indexA = indicesA[i];\n            const indexB = indicesB[i];\n            // The triangle\n            const outerTileX = new Polygon();\n            outerTileX.addVertex(this.getVertexAt(indexA + 1).clone());\n            outerTileX.addVertex(this.innerTilePolygons[0].getVertexAt(indexB).clone());\n            outerTileX.addVertex(this.innerTilePolygons[0].getVertexAt(indexB + 1).clone());\n            this.outerTilePolygons.push(outerTileX);\n            // The first 'kite'\n            const outerTileY = new Polygon();\n            outerTileY.addVertex(this.getVertexAt(indexA + 2).clone());\n            outerTileY.addVertex(this.innerTilePolygons[0].getVertexAt(indexB + 1).clone());\n            outerTileY.addVertex(this.innerTilePolygons[0].getVertexAt(indexB + 2).clone());\n            outerTileY.addVertex(this.innerTilePolygons[0].getVertexAt(indexB + 3).clone());\n            this.outerTilePolygons.push(outerTileY);\n            // The second 'kite'\n            const outerTileZ = new Polygon();\n            outerTileZ.addVertex(this.getVertexAt(indexA + 3).clone());\n            outerTileZ.addVertex(this.innerTilePolygons[0].getVertexAt(indexB + 3).clone());\n            outerTileZ.addVertex(this.innerTilePolygons[0].getVertexAt(indexB + 4).clone());\n            outerTileZ.addVertex(this.innerTilePolygons[0].getVertexAt(indexB + 5).clone());\n            this.outerTilePolygons.push(outerTileZ);\n        }\n    }\n    ;\n}\n//# sourceMappingURL=GirihHexagon.js.map","/**\n * @classdesc The penrose rhombus tile from the Girih set.\n * The penrose rhombus (angles 36° and 144°) is NOT part of the actual girih tile set!\n *\n * @requires Bounds\n * @requires GirihTile\n * @requires Polygon\n * @requires TileType\n * @requires Vertex\n *\n *\n * But it fits perfect into the girih as the angles are the same.\n * *\n * @author Ikaros Kappler\n * @date 2013-12-11\n * @modified 2014-04-05 Ikaros Kappler (member array outerTilePolygons added).\n * @modified 2015-03-19 Ikaros Kappler (added toSVG()).\n * @modified 2020-10-31 Refactored to work with PlotBoilerplate.\n * @modified 2020-11-13 Ported from vanilla JS to TypeScript.\n * @version 2.0.1-alpha\n * @file GirihPenroseRhombus\n * @public\n **/\nimport { Bounds } from \"../../Bounds\";\nimport { GirihTile, TileType } from \"./GirihTile\";\nimport { Polygon } from \"../../Polygon\";\nimport { Vertex } from \"../../Vertex\";\nexport class GirihPenroseRhombus extends GirihTile {\n    /**\n     * @constructor\n     * @extends GirihTile\n     * @name GirihPenroseRhombus\n     * @param {Vertex} position\n     * @param {number} edgeLength\n     */\n    constructor(position, edgeLength, addCenterPolygon) {\n        super(position, edgeLength, TileType.PENROSE_RHOMBUS);\n        // Overwrite the default symmetries:\n        //    the penrose-rhombus tile has a 180° symmetry (5/10 * 360°)\n        this.uniqueSymmetries = 5;\n        if (typeof addCenterPolygon === \"undefined\") {\n            addCenterPolygon = true; // Add by default\n        }\n        // Init the actual decahedron shape with the passed size\n        let pointA = new Vertex(0, 0);\n        let pointB = pointA;\n        this.addVertex(pointB);\n        const angles = [\n            0.0,\n            36.0, // 72.0,\n            144.0 // 108.0\n        ];\n        let theta = 0.0;\n        for (var i = 0; i < angles.length; i++) {\n            theta += 180.0 - angles[i];\n            pointA = pointB; // center of rotation\n            pointB = pointB.clone();\n            pointB.x += this.edgeLength;\n            pointB.rotate(theta * (Math.PI / 180.0), pointA);\n            this.addVertex(pointB);\n        }\n        // Move to center and position\n        const bounds = Bounds.computeFromVertices(this.vertices);\n        const move = new Vertex(bounds.width / 2.0 - (bounds.width - this.edgeLength), bounds.height / 2.0);\n        for (var i = 0; i < this.vertices.length; i++) {\n            this.vertices[i].add(move).add(position);\n        }\n        this.textureSource.min.x = 2 / 500.0;\n        this.textureSource.min.y = 8 / 460.0;\n        this.textureSource.max.x = this.textureSource.min.x + 173 / 500.0;\n        this.textureSource.max.y = this.textureSource.min.y + 56 / 460.0;\n        this.baseBounds = this.getBounds();\n        this._buildInnerPolygons(this.edgeLength, addCenterPolygon);\n        this._buildOuterPolygons(this.edgeLength, addCenterPolygon);\n    }\n    /**\n     * @override\n     */\n    clone() {\n        return new GirihPenroseRhombus(this.position.clone(), this.edgeLength, true).rotate(this.rotation);\n    }\n    _buildInnerPolygons(_edgeLength, addCenterPolygon) {\n        const indices = [0, 2];\n        const centerTile = new Polygon();\n        for (var i = 0; i < indices.length; i++) {\n            const innerTile = new Polygon();\n            const index = indices[i];\n            const left = this.getVertexAt(index)\n                .clone()\n                .scale(0.5, this.getVertexAt(index + 1));\n            const right = this.getVertexAt(index + 1)\n                .clone()\n                .scale(0.5, this.getVertexAt(index + 2));\n            const innerA = this.getVertexAt(index + 1)\n                .clone()\n                .scale(0.28, this.position);\n            const innerB = this.getVertexAt(index + 1)\n                .clone()\n                .scale(0.55, this.position);\n            innerTile.addVertex(left);\n            innerTile.addVertex(innerA);\n            innerTile.addVertex(right);\n            innerTile.addVertex(innerB);\n            centerTile.addVertex(this.getVertexAt(index)\n                .clone()\n                .scale(0.1775, this.getVertexAt(index + 2)));\n            centerTile.addVertex(innerA.clone());\n            this.innerTilePolygons.push(innerTile);\n        }\n        if (addCenterPolygon)\n            this.innerTilePolygons.push(centerTile);\n    }\n    _buildOuterPolygons(_edgeLength, centerPolygonExists) {\n        // Add left and right 'spikes'.\n        const indices = [0, 2];\n        for (var i = 0; i < indices.length; i++) {\n            const outerTile = new Polygon();\n            const index = indices[i];\n            const left = this.getVertexAt(index)\n                .clone()\n                .scale(0.5, this.getVertexAt(index + 1));\n            const right = this.getVertexAt(index + 1)\n                .clone()\n                .scale(0.5, this.getVertexAt(index + 2));\n            // const innerA:Vertex = this.getVertexAt( index+1 ).clone().scale( 0.28, this.position );\n            const innerB = this.getVertexAt(index + 1)\n                .clone()\n                .scale(0.55, this.position);\n            outerTile.addVertex(left.clone());\n            outerTile.addVertex(this.getVertexAt(index + 1).clone());\n            outerTile.addVertex(right.clone());\n            outerTile.addVertex(innerB.clone());\n            this.outerTilePolygons.push(outerTile);\n        }\n        // If the center polygon exists then the last outer polygon is split into two.\n        if (centerPolygonExists) {\n            // Two polygons\n            const indices = [0, 2];\n            for (var i = 0; i < indices.length; i++) {\n                const outerTile = new Polygon();\n                const index = indices[i];\n                outerTile.addVertex(this.getVertexAt(index).clone());\n                outerTile.addVertex(this.getVertexAt(index)\n                    .clone()\n                    .scale(0.5, this.getVertexAt(index + 1)));\n                outerTile.addVertex(this.innerTilePolygons[i].getVertexAt(1).clone());\n                outerTile.addVertex(this.getVertexAt(index)\n                    .clone()\n                    .scale(0.1775, this.getVertexAt(index + 2)));\n                outerTile.addVertex(this.innerTilePolygons[(i + 1) % 2].getVertexAt(1).clone());\n                outerTile.addVertex(this.getVertexAt(index - 1)\n                    .clone()\n                    .scale(0.5, this.getVertexAt(index)));\n                this.outerTilePolygons.push(outerTile);\n            }\n        }\n    }\n    /**\n     * If you want the center polygon not to be drawn the canvas handler needs to\n     * know the respective polygon index (inside the this.innerTilePolygons array).\n     **/\n    // TODO: IS THIS STILL REQUIRED\n    getCenterPolygonIndex() {\n        return 2;\n    }\n}\n//# sourceMappingURL=GirihPenroseRhombus.js.map","/**\n * @classdesc The pentagon tile from the Girih set.\n *\n * @requires Bounds\n * @requires GirihTile\n * @requires Polygon\n * @requires TileType\n * @requires Vertex\n *\n * @author Ikaros Kappler\n * @date 2013-11-27\n * @modified 2014-04-05 Ikaros Kappler (member array outerTilePolygons added).\n * @modified 2015-03-19 Ikaros Kappler (added toSVG()).\n * @modified 2020-10-31 Refactored to work with PlotBoilerplate.\n * @modified 2020-11-13 Ported from vanilla JS to TypeScript.\n * @version 2.0.1-alpha\n * @file GirihPentagon\n * @public\n **/\nimport { GirihTile, TileType } from \"./GirihTile\";\nimport { Polygon } from \"../../Polygon\";\nexport class GirihPentagon extends GirihTile {\n    /**\n     * @constructor\n     * @extends GirihTile\n     * @name GirihPentagon\n     * @param {Vertex} position\n     * @param {number} edgeLength\n     */\n    constructor(position, edgeLength) {\n        super(position, edgeLength, TileType.PENTAGON);\n        // Overwrite the default symmetries:\n        //    the pentagon tile has a 72° symmetry (2/10 * 360°)\n        this.uniqueSymmetries = 2;\n        // Init the actual pentagon shape with the passed size:\n        // Divide the full circle into 5 sections (we want to make a regular pentagon).\n        const theta = (Math.PI * 2) / 5.0;\n        // Compute the 'radius' using pythagoras\n        const radius = Math.sqrt(Math.pow(this.edgeLength / 2, 2)\n            +\n                Math.pow(1 / Math.tan(theta / 2) * this.edgeLength / 2, 2));\n        for (var i = 0; i < 5; i++) {\n            this.addVertex(position.clone().addY(-radius).rotate(theta / 2 + i * theta, position));\n        }\n        this.textureSource.min.x = 7 / 500.0;\n        this.textureSource.min.y = (303) / 460.0;\n        this.textureSource.max.x = this.textureSource.min.x + 157 / 500.0;\n        this.textureSource.max.y = this.textureSource.min.y + (150) / 460.0;\n        this.baseBounds = this.getBounds();\n        this._buildInnerPolygons(this.edgeLength);\n        this._buildOuterPolygons(this.edgeLength); // Only call AFTER the inner polygons were built!\n    }\n    ;\n    /**\n     * @override\n     */\n    clone() {\n        return new GirihPentagon(this.position.clone(), this.edgeLength).rotate(this.rotation);\n    }\n    ;\n    _buildInnerPolygons(edgeLength) {\n        // Connect all edges half-the-way\n        const innerTile = new Polygon();\n        for (var i = 0; i < this.vertices.length; i++) {\n            innerTile.addVertex(this.getVertexAt(i).clone().scale(0.5, this.getVertexAt(i + 1)));\n            // ... make linear approximation instead\n            innerTile.addVertex(this.getVertexAt(i + 1).clone().scale(0.5, this.position));\n        }\n        this.innerTilePolygons.push(innerTile);\n    }\n    ;\n    _buildOuterPolygons(edgeLength) {\n        for (var i = 0; i < this.vertices.length; i++) {\n            const indexA = i;\n            const indexB = i * 2;\n            // The triangle\n            const outerTile = new Polygon();\n            outerTile.addVertex(this.getVertexAt(indexA + 1).clone());\n            outerTile.addVertex(this.innerTilePolygons[0].getVertexAt(indexB).clone());\n            outerTile.addVertex(this.innerTilePolygons[0].getVertexAt(indexB + 1).clone());\n            outerTile.addVertex(this.innerTilePolygons[0].getVertexAt(indexB + 2).clone());\n            this.outerTilePolygons.push(outerTile);\n        }\n    }\n    ;\n}\n//# sourceMappingURL=GirihPentagon.js.map","/**\n * @classdesc The rhombus tile from the Girih set.\n *\n * @requires Bounds\n * @requires GirihTile\n * @requires Polygon\n * @requires TileType\n * @requires Vertex\n *\n *\n * @author Ikaros Kappler\n * @date 2013-11-28\n * @modified 2014-04-05 Ikaros Kappler (member array outerTilePolygons added).\n * @modified 2015-03-19 Ikaros Kappler (added toSVG()).\n * @modified 2020-10-31 Refactored to work with PlotBoilerplate.\n * @modified 2020-11-13 Ported from vanilla JS to TypeScript.\n * @version 2.0.1-alpha\n * @file GirihRhombus\n * @public\n **/\nimport { Bounds } from \"../../Bounds\";\nimport { Circle } from \"../../Circle\";\nimport { GirihTile, TileType } from \"./GirihTile\";\nimport { Polygon } from \"../../Polygon\";\nimport { Vertex } from \"../../Vertex\";\nexport class GirihRhombus extends GirihTile {\n    /**\n     * @constructor\n     * @extends GirihTile\n     * @name GirihRhombus\n     * @param {Vertex} position\n     * @param {number} edgeLength\n     */\n    constructor(position, edgeLength) {\n        super(position, edgeLength, TileType.RHOMBUS);\n        // Overwrite the default symmetries:\n        //    the rhombus tile has a 180° symmetry (5/10 * 360°)\n        this.uniqueSymmetries = 5;\n        // Init the actual rhombus shape with the passed size\n        let pointA = new Vertex(0, 0);\n        let pointB = pointA;\n        this.addVertex(pointB);\n        const angles = [0.0,\n            72.0,\n            108.0\n            // 72.0\n        ];\n        let theta = 0.0;\n        for (var i = 0; i < angles.length; i++) {\n            theta += (180.0 - angles[i]);\n            pointA = pointB; // center of rotation\n            pointB = pointB.clone();\n            pointB.x += this.edgeLength;\n            pointB.rotate(theta * (Math.PI / 180.0), pointA);\n            this.addVertex(pointB);\n        }\n        // Move to center    \n        const bounds = Bounds.computeFromVertices(this.vertices);\n        const move = new Vertex(bounds.width / 2.0 - (bounds.width - this.edgeLength), bounds.height / 2.0);\n        for (var i = 0; i < this.vertices.length; i++) {\n            this.vertices[i].add(move).add(this.position);\n        }\n        this.textureSource.min.x = 32 / 500.0;\n        this.textureSource.min.y = 188 / 460.0;\n        this.textureSource.max.x = this.textureSource.min.x + 127 / 500.0;\n        this.textureSource.max.y = this.textureSource.min.y + 92 / 460.0;\n        this.baseBounds = this.getBounds();\n        this._buildInnerPolygons();\n        this._buildOuterPolygons(); // Call only AFTER the inner polygons were built!\n    }\n    ;\n    /**\n     * @override\n     */\n    clone() {\n        return new GirihRhombus(this.position.clone(), this.edgeLength).rotate(this.rotation);\n    }\n    ;\n    _buildInnerPolygons() {\n        // Connect all edges half-the-way\n        const innerTile = new Polygon(); // [];\n        innerTile.addVertex(this.vertices[0].clone().scale(0.5, this.vertices[1]));\n        innerTile.addVertex(this.vertices[1].clone().scale(0.5, this.vertices[2]));\n        // Compute the next inner polygon vertex by the intersection of two circles\n        const circleA = new Circle(innerTile.vertices[1], innerTile.vertices[0].distance(innerTile.vertices[1]) * 0.73);\n        const circleB = new Circle(this.vertices[2].clone().scale(0.5, this.vertices[3]), circleA.radius);\n        // There is definitely an intersection\n        let intersection = circleA.circleIntersection(circleB);\n        // One of the two points is inside the tile, the other is outside.\n        // Locate the inside point.\n        if (this.containsVert(intersection.a))\n            innerTile.addVertex(intersection.b);\n        else\n            innerTile.addVertex(intersection.a);\n        innerTile.addVertex(circleB.center);\n        innerTile.addVertex(this.vertices[3].clone().scale(0.5, this.vertices[0]));\n        // Move circles\n        circleA.center = innerTile.vertices[4];\n        circleB.center = innerTile.vertices[0];\n        //window.alert( \"circleA=\" + circleA + \", circleB=\" + circleB );\n        intersection = circleA.circleIntersection(circleB);\n        // There are two points again (one inside, one outside the tile)\n        if (this.containsVert(intersection.a))\n            innerTile.addVertex(intersection.b);\n        else\n            innerTile.addVertex(intersection.a);\n        this.innerTilePolygons.push(innerTile);\n    }\n    ;\n    _buildOuterPolygons() {\n        const indicesA = [0, 2]; // 4:2\n        const indicesB = [0, 3]; // 6:2\n        for (var i = 0; i < indicesA.length; i++) {\n            const indexA = indicesA[i];\n            const indexB = indicesB[i];\n            // The triangle\n            const outerTileX = new Polygon();\n            outerTileX.addVertex(this.getVertexAt(indexA + 1).clone());\n            outerTileX.addVertex(this.innerTilePolygons[0].getVertexAt(indexB).clone());\n            outerTileX.addVertex(this.innerTilePolygons[0].getVertexAt(indexB + 1).clone());\n            this.outerTilePolygons.push(outerTileX);\n            // The first 'kite'\n            const outerTileY = new Polygon();\n            outerTileY.addVertex(this.getVertexAt(indexA + 2).clone());\n            outerTileY.addVertex(this.innerTilePolygons[0].getVertexAt(indexB + 1).clone());\n            outerTileY.addVertex(this.innerTilePolygons[0].getVertexAt(indexB + 2).clone());\n            outerTileY.addVertex(this.innerTilePolygons[0].getVertexAt(indexB + 3).clone());\n            this.outerTilePolygons.push(outerTileY);\n        }\n    }\n    ;\n}\n//# sourceMappingURL=GirihRhombus.js.map","/**\n * This file defines a Matrix4x4 class for 3d transformations.\n *\n * [ xx xy yz xw\n *   yx yy yz yw\n *   zx zy zz zw\n *   wx wy wz ww ]\n *\n * Original class found at\n *    https://www.migenius.com/articles/3d-transformations-part1-matrices\n * by Paul Arden\n *\n * @file Matrix4x4.js\n */\nexport class Matrix4x4 {\n    /**\n     * Generic class for representing 4x4 matrices.\n     * @constructor\n     * @param {Object} matrix - An object with the initial values for the Matrix4x4.\n     * Can be either an Object or Matrix4x4.\n     */\n    constructor(matrix) {\n        if (matrix) {\n            this.setFromObject(matrix);\n        }\n        else {\n            this.setIdentity();\n        }\n    }\n    /**\n     * Set matrix components from object\n     * @param {Object} mat - Object with each component of the matrix, all components must be present.\n     * @public\n     */\n    setFromObject(mat) {\n        this.xx = mat.xx;\n        this.xy = mat.xy;\n        this.xz = mat.xz;\n        this.xw = mat.xw;\n        this.yx = mat.yx;\n        this.yy = mat.yy;\n        this.yz = mat.yz;\n        this.yw = mat.yw;\n        this.zx = mat.zx;\n        this.zy = mat.zy;\n        this.zz = mat.zz;\n        this.zw = mat.zw;\n        this.wx = mat.wx;\n        this.wy = mat.wy;\n        this.wz = mat.wz;\n        this.ww = mat.ww;\n    }\n    // A vector {x,y,z,w=1}\n    apply4(vec4) {\n        return {\n            x: vec4.x * this.xx + vec4.y * this.xy + vec4.z * this.xz + vec4.w * this.xw,\n            y: vec4.x * this.yx + vec4.y * this.yy + vec4.z * this.yz + vec4.w * this.yw,\n            z: vec4.x * this.zx + vec4.y * this.zy + vec4.z * this.zz + vec4.w * this.zw,\n            w: vec4.x * this.wx + vec4.y * this.wy + vec4.z * this.wz + vec4.w * this.ww\n        };\n    }\n    apply3(vec3) {\n        const vec4 = Object.assign(Object.assign({}, vec3), { w: 1.0 });\n        var result4 = this.apply4(vec4);\n        // Divide by w: project result on the 4d sphere into 3d space.\n        return { x: result4.x / result4.w, y: result4.y / result4.w, z: result4.z / result4.w };\n    }\n    /**\n     * Set all matrix components to 0.\n     * @public\n     */\n    clear() {\n        this.xx = this.xy = this.xz = this.xw = this.yx = this.yy = this.yz = this.yw = this.zx = this.zy = this.zz = this.zw = this.wx = this.wy = this.wz = this.ww = 0;\n    }\n    /**\n     * Set matrix to the identity matrix.\n     * @public\n     */\n    setIdentity() {\n        this.clear();\n        this.xx = this.yy = this.zz = this.ww = 1;\n        return this;\n    }\n    /**\n     * Sets this matrix to a rotation matrix.\n     * @param {Vec3} axis - The vector to rotate around.\n     * @param {Number} angle - The angle to rotate in radians.\n     * @public\n     */\n    setRotation(axis, angle) {\n        this.setIdentity();\n        var c = Math.cos(angle);\n        var s = Math.sin(angle);\n        var t = 1 - c;\n        var X = axis.x;\n        var Y = axis.y;\n        var Z = axis.z;\n        this.xx = t * X * X + c;\n        this.xy = t * X * Y + s * Z;\n        this.xz = t * X * Z - s * Y;\n        this.yx = t * X * Y - s * Z;\n        this.yy = t * Y * Y + c;\n        this.yz = t * Y * Z + s * X;\n        this.zx = t * X * Z + s * Y;\n        this.zy = t * Y * Z - s * X;\n        this.zz = t * Z * Z + c;\n        return this;\n    }\n    /**\n     * Sets this matrix to a rotation matrix.\n     * @param {Number} x - Scaling factor in the x axis.\n     * @param {Number} y - Scaling factor in the y axis.\n     * @param {Number} z - Scaling factor in the z axis.\n     * @public\n     */\n    setScaling(x, y, z) {\n        this.setIdentity();\n        this.xx = x;\n        this.yy = y;\n        this.zz = z;\n        return this;\n    }\n    /**\n     * Sets the translation elements of this matrix while leaving the\n     * rest of the matrix untouched.\n     * @param {Number} x - Translation amount in the x axis.\n     * @param {Number} y - Translation amount in the y axis.\n     * @param {Number} z - Translation amount in the z axis.\n     */\n    setTranslation(x, y, z) {\n        this.setIdentity();\n        // There was an error in the original implementation.\n        //    See https://pages.mtu.edu/~shene/COURSES/cs3621/NOTES/geometry/geo-tran.html\n        // This is fixed:\n        this.xw = x;\n        this.yw = y;\n        this.zw = z;\n        return this;\n    }\n    /**\n     * Sets this matrix to the dot product between this matrix and the\n     * matrix specified by rhs.\n     * @param {Matrix4x4} matrix - The matrix on the right hand side of the dot product.\n     */\n    multiply(matrix) {\n        var _mat = new Matrix4x4(this);\n        this.xx = _mat.xx * matrix.xx + _mat.xy * matrix.yx + _mat.xz * matrix.zx + _mat.xw * matrix.wx;\n        this.xy = _mat.xx * matrix.xy + _mat.xy * matrix.yy + _mat.xz * matrix.zy + _mat.xw * matrix.wy;\n        this.xz = _mat.xx * matrix.xz + _mat.xy * matrix.yz + _mat.xz * matrix.zz + _mat.xw * matrix.wz;\n        this.xw = _mat.xx * matrix.xw + _mat.xy * matrix.yw + _mat.xz * matrix.zw + _mat.xw * matrix.ww;\n        this.yx = _mat.yx * matrix.xx + _mat.yy * matrix.yx + _mat.yz * matrix.zx + _mat.yw * matrix.wx;\n        this.yy = _mat.yx * matrix.xy + _mat.yy * matrix.yy + _mat.yz * matrix.zy + _mat.yw * matrix.wy;\n        this.yz = _mat.yx * matrix.xz + _mat.yy * matrix.yz + _mat.yz * matrix.zz + _mat.yw * matrix.wz;\n        this.yw = _mat.yx * matrix.xw + _mat.yy * matrix.yw + _mat.yz * matrix.zw + _mat.yw * matrix.ww;\n        this.zx = _mat.zx * matrix.xx + _mat.zy * matrix.yx + _mat.zz * matrix.zx + _mat.zw * matrix.wx;\n        this.zy = _mat.zx * matrix.xy + _mat.zy * matrix.yy + _mat.zz * matrix.zy + _mat.zw * matrix.wy;\n        this.zz = _mat.zx * matrix.xz + _mat.zy * matrix.yz + _mat.zz * matrix.zz + _mat.zw * matrix.wz;\n        this.zw = _mat.zx * matrix.xw + _mat.zy * matrix.yw + _mat.zz * matrix.zw + _mat.zw * matrix.ww;\n        this.wx = _mat.wx * matrix.xx + _mat.wy * matrix.yx + _mat.wz * matrix.zx + _mat.ww * matrix.wx;\n        this.wy = _mat.wx * matrix.xy + _mat.wy * matrix.yy + _mat.wz * matrix.zy + _mat.ww * matrix.wy;\n        this.wz = _mat.wx * matrix.xz + _mat.wy * matrix.yz + _mat.wz * matrix.zz + _mat.ww * matrix.wz;\n        this.ww = _mat.wx * matrix.xw + _mat.wy * matrix.yw + _mat.wz * matrix.zw + _mat.ww * matrix.ww;\n        return this;\n    }\n    /**\n     * Create the rotation matrix from the given axis and angle.\n     *\n     * @param {Vec3} axis - The axis to rotate around.\n     * @param {number} angle - The angle to use for rotation (in radians).\n     * @returns Matrix4x4\n     */\n    static makeRotationMatrix(axis, angle) {\n        return new Matrix4x4().setRotation(axis, angle);\n    }\n    /**\n     * Create the scaling matrix from the given x-, y- and z- scaling factors (use 1.0 for no scaling).\n     *\n     * @param {number} scaleX - The x scaling factor.\n     * @param {number} scaleY - The y scaling factor.\n     * @param {number} scaleZ - The z scaling factor.\n     * @returns Matrix4x4\n     */\n    static makeScalingMatrix(scaleX, scaleY, scaleZ) {\n        return new Matrix4x4().setScaling(scaleX, scaleY, scaleZ);\n    }\n    /**\n     * Create the translation matrix from the given x-, y- and z- translation amounts (use 0.0 for no translation).\n     *\n     * @param {number} translateX - The x translation amount.\n     * @param {number} translateY - The y translation amount.\n     * @param {number} translateZ - The z translation amount.\n     * @returns Matrix4x4\n     */\n    static makeTranslationMatrix(translateX, translateY, translateZ) {\n        return new Matrix4x4().setTranslation(translateX, translateY, translateZ);\n    }\n    /**\n     * Create a full transform matrix from the rotation, scaling and translation params.\n     *\n     * @param {number} rotateX - The rotation angle around the x axis.\n     * @param {number} rotateY - The rotation angle around the y axis.\n     * @param {number} rotateZ - The rotation angle around the z axis.\n     * @param {number} scaleX - The x scaling factor.\n     * @param {number} scaleY - The y scaling factor.\n     * @param {number} scaleZ - The z scaling factor.\n     * @param {number} translateX - The x translation amount.\n     * @param {number} translateY - The y translation amount.\n     * @param {number} translateZ - The z translation amount.\n     * @returns Matrix4x4\n     */\n    static makeTransformationMatrix(rotateX, rotateY, rotateZ, scaleX, scaleY, scaleZ, translateX, translateY, translateZ) {\n        var matrixRx = new Matrix4x4().setRotation({ x: 1, y: 0, z: 0 }, rotateX);\n        var matrixRy = new Matrix4x4().setRotation({ x: 0, y: 1, z: 0 }, rotateY);\n        var matrixRz = new Matrix4x4().setRotation({ x: 0, y: 0, z: 1 }, rotateZ);\n        var matrixS = new Matrix4x4().setScaling(scaleX, scaleY, scaleZ);\n        var matrixT0 = new Matrix4x4().setTranslation(translateX, translateY, translateZ);\n        var transformMatrix = new Matrix4x4()\n            .multiply(matrixRx)\n            .multiply(matrixRy)\n            .multiply(matrixRz)\n            .multiply(matrixS)\n            .multiply(matrixT0);\n        return transformMatrix;\n    }\n    /**\n     * Returns a deep copy of this matrix.\n     * @return {Matrix4x4} A deep copy of this matrix.\n     */\n    clone() {\n        return new Matrix4x4(this);\n    }\n    /**\n     * Returns a pretty print string representation of the matrix.\n     * @return {String} Pretty printed string of the matrix.\n     */\n    toJSON() {\n        // prettier-ignore\n        return (\"{\\n\" +\n            '\\t\"xx\": ' + this.xx + ', \"xy\": ' + this.xy + ', \"xz\": ' + this.xz + ', \"xw\": ' + this.xw + \",\\n\" +\n            '\\t\"yx\": ' + this.yx + ', \"yy\": ' + this.yy + ', \"yz\": ' + this.yz + ', \"yw\": ' + this.yw + \",\\n\" +\n            '\\t\"zx\": ' + this.zx + ', \"zy\": ' + this.zy + ', \"zz\": ' + this.zz + ', \"zw\": ' + this.zw + \",\\n\" +\n            '\\t\"wx\": ' + this.wx + ', \"wy\": ' + this.wy + ', \"wz\": ' + this.wz + ', \"ww\": ' + this.ww + \"\\n\" +\n            \"}\");\n    }\n}\n//# sourceMappingURL=Matrix4x4.js.map","export class Ref {\n    constructor(value) {\n        this.current = value;\n    }\n}\nexport const useRef = () => {\n    return new Ref(undefined);\n};\n//# sourceMappingURL=useRef.js.map","/**\n * A simple class for rendering color gradient dropdowns.\n *\n * As native dropdown do not support custom stylings in the way we need, we will implement\n * our own dropdown class.\n *\n * @author  Ikaros Kappler\n * @date    2025-08-19\n * @version 1.0.0\n */\nimport * as NoReact from \"noreact\";\nimport { Color } from \"../../datastructures/Color\";\nimport { ColorGradient } from \"../../datastructures/ColorGradient\";\nexport class ColorGradientSelector {\n    /**\n     * The constructor: creates a new color gradient picker in the given container.\n     * If no container or ID is given then a new unbound `container` will be created (DIV).\n     *\n     * Pass a container ID or nothing – in the latter case the constructor will create\n     * a new DIV element.\n     *\n     * @param {string?} containerID - (optional) If you want to use an existing container (should be a DIV).\n     */\n    constructor(options) {\n        this.isDropdownOpen = false;\n        this.css_buttonWidth = \"100px\";\n        this.css_buttonHeight = \"1.8em\";\n        this.css_buttonFontSize = \"0.725em\";\n        this.css_buttonFontSize_larger = \"1.0em\";\n        this.colorGradients = [];\n        // TODO: this does not really need to be a pair, does it?\n        this.colorGradientOptionRefs = [];\n        this.selectedGradientIndex = -1;\n        this.installedChangeListeners = [];\n        /**\n         * Adds custom styles (global STYLE tag).\n         *\n         * @private\n         */\n        this.__createCustomStylesElement = () => {\n            // Thanks to Ana Tudor\n            //    https://css-tricks.com/multi-thumb-sliders-particular-two-thumb-case/\n            return (NoReact.createElement(\"style\", null, `\n\n    #${this.elementID} button {\n      border: 0px solid lightgray;\n      padding: 0.25em;\n      /* background-color: rgba(255,255,255,0.9); */\n    }\n\n    #${this.elementID} .positioning-container button {\n      border-radius: 0;\n    }\n\n    #${this.elementID} .main-button:hover {\n      background-color: rgba(216,216,216,0.9);\n    }\n\n    #${this.elementID} .option-gradient-button:hover, #${this.elementID} .option-delete-button:hover {\n      background-color: rgba(216,216,216,0.9);\n    }\n\n\n    `));\n        };\n        options = options || {};\n        if (options.containerID) {\n            const cont = document.getElementById(options.containerID);\n            if (!cont) {\n                throw \"Cannot create ColorGradientPicker. Component ID does not exist.\";\n            }\n            this.container = cont;\n        }\n        else {\n            this.container = document.createElement(\"div\");\n        }\n        this.isMobileMode = Boolean(options.isMobileMode);\n        if (this.isMobileMode) {\n            this.css_buttonWidth = \"200px\";\n            this.css_buttonHeight = \"2.5em\";\n            this.css_buttonFontSize = \"1.25em\";\n            this.css_buttonFontSize_larger = \"1.45em\";\n        }\n        this.baseID = Math.floor(Math.random() * 65535);\n        this.elementID = `color-gradient-selector-${this.baseID}`;\n        this.colorGradients =\n            typeof options.initialGradients === \"undefined\" ? ColorGradientSelector.DEFAULT_COLOR_GRADIENTS : options.initialGradients;\n        this.selectedGradientIndex = typeof options.selectedGradientIndex === \"undefined\" ? 0 : options.selectedGradientIndex;\n        document.head.appendChild(this.__createCustomStylesElement());\n        this.container.append(this._render());\n    } // END constructor\n    // TODO: implement this?\n    setGradients(gradients, selectedIndex) {\n        // First empty the container\n        this.__removeAllChildNodes(this.positioningContainerRef.current);\n        this.colorGradients = [];\n        this.colorGradientOptionRefs = [];\n        this.selectedGradientIndex = selectedIndex;\n        // Re-render button array\n        gradients.map((grad) => {\n            this.addGradient(grad);\n        });\n    }\n    addGradient(gradient) {\n        // Render a new button\n        const index = this.colorGradients.length;\n        const refMainContainer = NoReact.useRef();\n        const refActionButton = NoReact.useRef();\n        const refDeleteButton = NoReact.useRef();\n        this.__renderOptionButton(gradient, index, refMainContainer, refActionButton, refDeleteButton);\n        this.colorGradients.push(gradient);\n        this.colorGradientOptionRefs.push({ mainButton: refActionButton, deleteButton: refDeleteButton });\n        // Add to container\n        this.positioningContainerRef.current.appendChild(refMainContainer.current);\n    }\n    // +---------------------------------------------------------------------------------\n    // | A helper function to remove all child nodes.\n    // +-------------------------------\n    __removeAllChildNodes(node) {\n        while (node.lastChild) {\n            node.removeChild(node.lastChild);\n        }\n    }\n    /**\n     * Adds a new color gradient change listener to this ColorGradientPicker.\n     *\n     * @param {ColorGradientChangeListener} listener - The listener to add.\n     * @returns {boolean} True, if the listener was added and did not exist before.\n     */\n    addChangeListener(listener) {\n        for (var i = 0; i < this.installedChangeListeners.length; i++) {\n            if (this.installedChangeListeners[i] === listener) {\n                return false;\n            }\n        }\n        this.installedChangeListeners.push(listener);\n        return true;\n    }\n    /**\n     *\n     * @param {ColorGradientChangeListener} listener The listener to remove.\n     * @returns {boolean} True, if the listener existed and has been removed.\n     */\n    removeChangeListener(listener) {\n        for (var i = 0; i < this.installedChangeListeners.length; i++) {\n            if (this.installedChangeListeners[i] === listener) {\n                this.installedChangeListeners.splice(i, 1);\n                return true;\n            }\n        }\n        return false;\n    }\n    getSelectedColorGradient() {\n        return this.colorGradients[this.selectedGradientIndex];\n    }\n    __fireChangeEvent() {\n        const newColorGradient = this.getSelectedColorGradient();\n        for (var i = 0; i < this.installedChangeListeners.length; i++) {\n            this.installedChangeListeners[i](newColorGradient, this.selectedGradientIndex, this);\n        }\n    }\n    /**\n     * Creates a handler for click events on the main button.\n     *\n     * @returns\n     */\n    __mainButtonClickHandler() {\n        const _self = this;\n        return (_evt) => {\n            // _self.mainButtonContainerRef.current.style.visibility = \"hidden\";\n            _self.positioningContainerRef.current.style.visibility = _self.isDropdownOpen ? \"hidden\" : \"visible\";\n            _self.isDropdownOpen = !_self.isDropdownOpen;\n        };\n    }\n    /**\n     * Creates a handler for click events on one of the option button in the dropdown.\n     *\n     * @returns\n     */\n    __optionButtonClickHandler() {\n        const _self = this;\n        return (evt) => {\n            _self.positioningContainerRef.current.style.visibility = \"hidden\";\n            _self.isDropdownOpen = false;\n            const targetButton = evt.currentTarget;\n            const clickedIndex_raw = targetButton.dataset[\"gradientIndex\"];\n            const clickedIndex = Number.parseInt(clickedIndex_raw);\n            console.log(\"clickedIndex\", clickedIndex, clickedIndex_raw, targetButton.dataset, targetButton);\n            if (Number.isNaN(clickedIndex)) {\n                // Stop here. This is not what we want.\n                return;\n            }\n            // Find child: and set selected.\n            _self.__setSelectedIndex(clickedIndex);\n            _self.__fireChangeEvent();\n        };\n    }\n    __optionButtonDeleteHandler() {\n        const _self = this;\n        return (evt) => {\n            if (this.colorGradientOptionRefs.length === 1) {\n                // Keep the last record\n                return;\n            }\n            const targetButton = evt.currentTarget;\n            const clickedIndex_raw = targetButton.dataset[\"gradientIndex\"];\n            const clickedIndex = Number.parseInt(clickedIndex_raw);\n            console.log(\"clickedIndex\", clickedIndex, clickedIndex_raw, targetButton.dataset, targetButton);\n            if (Number.isNaN(clickedIndex)) {\n                // Stop here. This is not what we want.\n                return;\n            }\n            // Find child: and remove from DOM\n            console.log(\"this.colorGradientOptionRefs\", this.colorGradientOptionRefs, \"clickedIndex\", clickedIndex);\n            const refPair = this.colorGradientOptionRefs[clickedIndex];\n            refPair.mainButton.current.parentElement.remove();\n            // Remove from logic\n            // Remove 1 element at the given index\n            this.colorGradients.splice(clickedIndex, 1);\n            this.colorGradientOptionRefs.splice(clickedIndex, 1);\n            // Update all following elements in the list.\n            this.__updateOptionDataSetIndices(clickedIndex);\n            if (this.selectedGradientIndex >= clickedIndex) {\n                // this.selectedGradientIndex--;\n                this.__setSelectedIndex(this.selectedGradientIndex);\n            }\n            console.log(\"All refs\", this.colorGradientOptionRefs);\n        };\n    }\n    /**\n     * Once a slider element was added or removed then the following indices must be updated.\n     *\n     * @param {number} startIndex - The slider index to start updating at.\n     */\n    __updateOptionDataSetIndices(startIndex) {\n        // Update all elements to the right of the new elelemt\n        for (var i = startIndex; i < this.colorGradientOptionRefs.length; i++) {\n            this.colorGradientOptionRefs[i].mainButton.current.dataset[\"gradientIndex\"] = `${i}`;\n            this.colorGradientOptionRefs[i].deleteButton.current.dataset[\"gradientIndex\"] = `${i}`;\n        }\n    }\n    __setSelectedIndex(newSelectedIndex) {\n        for (var i = 0; i < this.colorGradientOptionRefs.length; i++) {\n            const ref = this.colorGradientOptionRefs[i].mainButton;\n            // Find child: and set selected.\n            ref.current.querySelectorAll(\".option-gradient-radio-circle\")[0].innerHTML = newSelectedIndex === i ? \"🞊\" : \"🞅\";\n        }\n        this.selectedGradientIndex = newSelectedIndex;\n        const selectedGradient = this.colorGradients[this.selectedGradientIndex];\n        // Display new gradient in the main button\n        this.__setMainButtonGradient(selectedGradient);\n    }\n    /**\n     * Sets the backround color of the main button (of this dropdown) element.\n     *\n     * @param {ColorGradient} gradient - The gradient color to display. Must not be null.\n     */\n    __setMainButtonGradient(gradient) {\n        const colorDisplay = this.mainButtonContainerRef.current.querySelectorAll(\".main-button-gradient-display\")[0];\n        colorDisplay.style[\"background\"] = gradient.toColorGradientString();\n    }\n    /**\n     * Renders a new option button for the dropdown menu.\n     *\n     * @param {ColorGradient} gradient\n     * @returns {JsxElement}\n     */\n    __renderOptionButton(gradient, index, refMainContainer, refActionButton, refDelButton) {\n        return (NoReact.createElement(\"div\", { sx: { d: \"flex\", flexDirection: \"row\" }, ref: refMainContainer },\n            NoReact.createElement(\"button\", { className: \"option-gradient-button\", onClick: this.__optionButtonClickHandler(), style: {\n                    d: \"flex\",\n                    w: \"100%\",\n                    fontSize: this.css_buttonFontSize,\n                    minHeight: this.css_buttonHeight,\n                    maxHeight: this.css_buttonHeight\n                }, ref: refActionButton, \"data-gradientIndex\": `${index}` },\n                NoReact.createElement(\"div\", { className: \"option-gradient-radio-circle\", sx: { w: \"2em\", flexShrink: 2, alignContent: \"center\" } }, index === 0 ? \"🞊\" : \"🞅\"),\n                NoReact.createElement(\"div\", { sx: { w: \"calc( 100% - 2em )\", mr: \"1em\", background: gradient.toColorGradientString() } }, \"\\u00A0\")),\n            NoReact.createElement(\"button\", { classname: \"option-delete-button\", sx: { fontSize: this.css_buttonFontSize, minHeight: this.css_buttonHeight, maxHeight: this.css_buttonHeight }, onClick: this.__optionButtonDeleteHandler(), \"data-gradientIndex\": `${index}`, ref: refDelButton },\n                NoReact.createElement(\"div\", { sx: { w: \"2em\", flexShrink: 2, alignContent: \"center\" } }, \"\\uD83D\\uDDD1\"))));\n    }\n    /**\n     * Creates a new array of option buttons (refs).\n     * @returns\n     */\n    _renderAllOptionButtons() {\n        const _self = this;\n        // First clear all references\n        _self.colorGradientOptionRefs = [];\n        return this.colorGradients.map((colorGradient, index) => {\n            // console.log(\"num\", num, index);\n            const refMainContainer = NoReact.useRef();\n            const refActionButton = NoReact.useRef();\n            const refDelButton = NoReact.useRef();\n            _self.colorGradientOptionRefs.push({ mainButton: refActionButton, deleteButton: refDelButton });\n            return this.__renderOptionButton(colorGradient, index, refMainContainer, refActionButton, refDelButton);\n        });\n    }\n    /**\n     * Init the container contents.\n     *\n     * @private\n     */\n    _render() {\n        const _self = this;\n        // console.log(\"Rendering ...\", NoReact);\n        this.containerRef = NoReact.useRef();\n        this.mainButtonContainerRef = NoReact.useRef();\n        this.positioningContainerRef = NoReact.useRef();\n        const selectedGradient = this.colorGradients[this.selectedGradientIndex];\n        return (NoReact.createElement(\"div\", { id: this.elementID, className: \"color-gradient-selector\", style: { minWidth: this.css_buttonWidth, maxWidth: this.css_buttonWidth, pos: \"relative\" }, ref: this.containerRef },\n            NoReact.createElement(\"button\", { className: \"main-button\", ref: this.mainButtonContainerRef, style: {\n                    d: \"flex\",\n                    minWidth: this.css_buttonWidth,\n                    maxWidth: this.css_buttonWidth,\n                    minHeight: this.css_buttonHeight,\n                    maxHeight: this.css_buttonHeight\n                }, onClick: this.__mainButtonClickHandler() },\n                NoReact.createElement(\"div\", { className: \"main-button-gradient-display\", sx: { w: `calc( 100% - ${this.css_buttonFontSize} )`, background: selectedGradient.toColorGradientString() } }, \"\\u00A0\"),\n                NoReact.createElement(\"div\", { sx: { w: this.css_buttonHeight, flexShrink: 2, fontSize: this.css_buttonFontSize_larger } }, \"\\u25BE\")),\n            NoReact.createElement(\"div\", { className: \"positioning-container\", ref: this.positioningContainerRef, style: {\n                    minWidth: this.css_buttonWidth,\n                    maxHeight: \"25vh\",\n                    overflowY: \"auto\",\n                    v: \"hidden\",\n                    d: \"flex\",\n                    fd: \"column\",\n                    pos: \"absolute\",\n                    l: 0,\n                    zIndex: 999\n                } }, _self._renderAllOptionButtons())));\n    } // END function render()\n}\nColorGradientSelector.DEFAULT_COLOR_GRADIENTS = [\n    ColorGradient.createDefault(),\n    ColorGradient.createFrom(Color.Red, Color.Green),\n    ColorGradient.createFrom(Color.Blue, Color.Gold)\n];\n//# sourceMappingURL=ColorGradientSelector.js.map","/**\n * Internal helper function used to get 'float' properties from elements.\n * Used to determine border withs and paddings that were defined using CSS.\n */\nexport const getFProp = (elem, propName) => {\n    return parseFloat(globalThis.getComputedStyle(elem, null).getPropertyValue(propName));\n};\n//# sourceMappingURL=getFProp.js.map","/**\n * Interfaces and class for automatically handling Bézier curves.\n *\n * @requires AlloyFinger\n * @requires BezierPath\n * @requires CubicBezierPath\n * @requires KeyHandler\n * @requires MouseHandler\n * @requires PlotBoilerplate\n * @requires VertEvent\n * @requires Vertex\n * @requires XMouseEvent\n * @requires XYCoords\n *\n *\n * @author   Ikaros Kappler\n * @date     2020-07-31\n * @modified 2020-08-03 Ported this class from vanilla JS to Typescript.\n * @modified 2020-08-12 Added a distance check before handling the click/tap event.\n * @modified 2021-01-03 Changed property to `autoAdjustPaths` in the HandlerOptions interface (typo).\n * @modified 2021-01-03 Added following new functions: `addPathVertexDragStartListeners`, `removePathVertexDragStartListeners`, `addPathVertexDragEndListeners` and `removePathVertexDragEndListeners`.\n * @modified 2021-03-31 Fixed the issue with the new AlloyFinger (Typescript).\n * @modified 2022-02-03 Changing the element to catch events (eventCatcher instead of canvas).\n * @modified 2024-03-10 Fixing some types for Typescript 5 compatibility.\n * @modified 2025-04-14 Added the `BezierPathInteractionHelper.drawHandleLines` method.\n * @modified 2025-04-14 Fixing correct event types for touch events in `BezierPathInteractionHelper`.\n * @modified 2025-04-14 BezierPathInteractionHelper: Changed default value of `HelperOptions.autoAdjustPaths` from `true` to `false`.\n * @modified 2025-05-05 Added optional params `draw` and `fill` to BezierPathInteractionHelper.drawHandleLines` method.\n * @modified 2025-05-05 Class `BezierPathInteractionHelper` now implementing `IShapeInteractionHelper`.\n * @modified 2025-05-07 Tweaking performance of `BezierPathInteractionHelper`: only triggering redraw now when mouse move within given detect range.\n * @version  1.2.1\n *\n * @file BezierPathInteractionHelper\n * @public\n **/\n// I would like to use AlloyFinger from the node_modules, but it seems\n// AlloyTeam has forgotten to publish their d.ts file.\nimport AlloyFinger from \"alloyfinger-typescript\";\nimport { BezierPath } from \"../../BezierPath\";\nimport { KeyHandler } from \"../../KeyHandler\";\nimport { MouseHandler } from \"../../MouseHandler\";\nimport { PlotBoilerplate } from \"../../PlotBoilerplate\";\nimport { Vertex } from \"../../Vertex\";\n/**\n * @classdesc A helper for adding vertices to and remove vertices from Bézier paths.\n * By default the 'delete' key is used to remove vertices or paths.\n *\n * For convenience this helper is capable of handling multiple paths which are kept\n * in an array.\n *\n * [Demo](https://www.plotboilerplate.io/repo/demos/23-bezier-point-distance/ \"Demo\")\n *\n * @public\n **/\nexport class BezierPathInteractionHelper {\n    /**\n     * Pre: all paths must have been added to the PlotBoilerplate's drawable buffer (use the add(Drawable) function).\n     *\n     * The move callback accepts four params:\n     *   * The point on the closest curve (Vertex)\n     *   * The mouse or touch position (Vertex)\n     *   * The curve position (float t)\n     *   * The curve index on the array (integer)\n     *\n     *\n     * @constructor\n     * @name BezierPathInteractionHelper\n     * @param {PlotBoilerplate} pb\n     * @param {Array<BezierPath>} paths\n     * @param {boolean} options.autoAdjustPaths - If true then inner path points will be auto-adjusted to keep the curve smooth.\n     * @param {boolean} options.allowPathRemoval - If true then full paths can be removed (by removing selected vertices).\n     * @param {number} maxDetectDistance - The max detection distance. No events will be fired if the mouse/touch pointer is outside this range (default is Number.MAX_VALUE).\n     * @param {function(number,Vertex,Vertex,number)} options.onPointerMoved (pathIndex,pathPoint,pointer,t)\n     * @param {function(number,number,BezierPath,BezierPath)} options.onVertexInserted (pathIndex,insertIndex,newPath,oldPath)\n     * @param {function(number,number[],BezierPath,BezierPath)} options.onVerticesDeleted (pathIndex,removedVertexIndices,newPath,oldPath)\n     * @param {function(number,BezierPath)} options.onPathRemoved (pathIndex,oldPath)\n     **/\n    constructor(pb, paths, options) {\n        options = options || {};\n        this.pb = pb;\n        this.paths = [];\n        this.onPointerMoved =\n            typeof options.onPointerMoved === \"function\"\n                ? options.onPointerMoved\n                : (i, a, b, t) => { };\n        this.onVertexInserted =\n            typeof options.onVertexInserted === \"function\"\n                ? options.onVertexInserted\n                : (i, j, n, o) => { };\n        this.onVerticesDeleted =\n            typeof options.onVerticesDeleted === \"function\"\n                ? options.onVerticesDeleted\n                : (i, r, n, o) => { };\n        this.onPathRemoved = typeof options.onPathRemoved === \"function\" ? options.onPathRemoved : (i, o) => { };\n        this.autoAdjustPaths = typeof options.autoAdjustPaths === \"boolean\" ? options.autoAdjustPaths : false; // true;\n        this.allowPathRemoval = typeof options.allowPathRemoval === \"boolean\" ? options.allowPathRemoval : true;\n        this.maxDetectDistance = typeof options.maxDetectDistance === \"number\" ? options.maxDetectDistance : Number.MAX_VALUE;\n        this.mouseIsOver = false;\n        this.currentPathIndex = -1;\n        this.currentDistance = Number.MAX_VALUE;\n        this.currentT = 0.0;\n        this.currentA = new Vertex(0, 0); // Position on the curve\n        this.currentB = new Vertex(0, 0); // Mouse/Touch position\n        // Rebuild the array to avoid outside manipulations.\n        for (var i = 0; i < paths.length; i++) {\n            this.addPath(paths[i]);\n        }\n        this._mouseEnterListener = () => {\n            this.mouseIsOver = true;\n        };\n        this._mouseLeaveListener = () => {\n            this.mouseIsOver = false;\n            this._clearMoveEvent();\n        };\n        this._mouseHandler = this._installMouseListener();\n        this._touchHandler = this._installTouchListener();\n        this._keyHandler = this._installKeyListener();\n        // Paths might have changed by auto-adjustment.\n        if (this.autoAdjustPaths) {\n            pb.redraw();\n        }\n    }\n    /**\n     * Manually add a path to this helper.\n     * Note that if `autoAdjustPaths==true` then listeners will be installed to the path's vertices to\n     * keep the path smooth at all times.\n     *\n     * @method addPath\n     * @instance\n     * @memberof BezierPathInteractionHelper\n     * @param {BezierPath} path - The path to add.\n     * @return {boolean} Duplicate path instances cannot be added; function will return false if path already exists.\n     **/\n    addPath(path) {\n        const pathIndex = this._locatePath(path);\n        if (pathIndex != -1)\n            return false;\n        this.paths.push(path);\n        if (this.autoAdjustPaths)\n            BezierPathInteractionHelper.setPathAutoAdjust(path);\n        return true;\n    }\n    /**\n     * Manually remove a path from this helper.\n     * Note that this method ignores the `allowPathRemoval` option.\n     *\n     * @method removePath\n     * @instance\n     * @memberof BezierPathInteractionHelper\n     * @param {BezierPath} path - The path to remove.\n     * @return {boolean} Returns false if the path could not be found.\n     **/\n    removePath(path) {\n        const pathIndex = this._locatePath(path);\n        if (pathIndex == -1)\n            return false;\n        this.removePathAt(pathIndex);\n        return true;\n    }\n    /**\n     * Remove the path at the given index.\n     *\n     * @method removePathAt\n     * @instance\n     * @memberof BezierPathInteractionHelper\n     * @param {number} pathIndex - The index of the path (must be inside bounds, see `this.paths` array).\n     * @return {void}\n     **/\n    removePathAt(pathIndex) {\n        const path = this.paths[pathIndex];\n        this.paths = this.paths.filter((value, index) => index != pathIndex);\n        this._removeDefaultPathListeners(path);\n        this.pb.remove(path, false, true); // Remove with vertices\n        this.onPathRemoved(pathIndex, path);\n    }\n    /**\n     * Update the inner status by running the distance calculation again with the current settings.\n     *\n     * Call this if any of the properties changed (like maxDetecDistance).\n     *\n     * @method update\n     * @instance\n     * @memberof BezierPathInteractionHelper\n     * @return {void}\n     **/\n    update() {\n        // Just re-run the calculation with the recent mouse/touch position\n        this._handleMoveEvent(this.currentB.x, this.currentB.y);\n    }\n    /**\n     * Draw grey handle lines.\n     *\n     * @param {DrawLib<any>} draw - (optional) The draw library to use. If not provided then `pb.draw` will be used.\n     * @param {DrawLib<any>} fill - (optional) The fill library to use. If not provided then `pb.fill` will be used.\n     */\n    drawHandleLines(draw, fill) {\n        draw = draw || this.pb.draw;\n        fill = fill || this.pb.fill;\n        this.paths.forEach((path) => {\n            path.bezierCurves.forEach((curve) => {\n                this.pb.draw.line(curve.startPoint, curve.startControlPoint, \"rgba(64,192,128,0.333)\", 1.0, {\n                    dashOffset: 0.0,\n                    dashArray: [4, 2]\n                });\n                this.pb.draw.line(curve.endPoint, curve.endControlPoint, \"rgba(64,192,128,0.333)\", 1.0, {\n                    dashOffset: 0.0,\n                    dashArray: [4, 2]\n                });\n            });\n        });\n    }\n    /**\n     * This function should invalidate any installed listeners and invalidate this object.\n     * After calling this function the object might not hold valid data any more and\n     * should not be used any more.\n     *\n     * @method destroy\n     * @instance\n     * @memberof BezierPathInteractionHelper\n     * @return {void}\n     **/\n    destroy() {\n        for (var i = 0; i < this.paths.length; i++) {\n            this._removeDefaultPathListeners(this.paths[i]);\n            // removePathVertexDragStartListeners(this.paths[i], listener);\n        }\n        this.paths = [];\n        this.pb.eventCatcher.removeEventListener(\"mouseenter\", this._mouseEnterListener);\n        this.pb.eventCatcher.removeEventListener(\"mouseleave\", this._mouseLeaveListener);\n        this._mouseHandler.destroy();\n        this._keyHandler.destroy();\n    }\n    // +---------------------------------------------------------------------------------\n    // | A helper function to locate a given path instance inside the array.\n    // |\n    // | @return The index of the path or -1 if not found.\n    // +-------------------------------\n    _locatePath(path) {\n        for (var i = 0; i < this.paths.length; i++) {\n            if (this.paths[i] == path)\n                return i;\n        }\n        return -1;\n    }\n    // +---------------------------------------------------------------------------------\n    // | Handle deletion of any selecte vertex and/or paths.\n    // | Note that this function will trigger a `redraw`.\n    // +-------------------------------\n    _handleDelete() {\n        const pathDeleteIndices = this._handleSingleVertexDelete();\n        // Remove enqueued paths\n        if (this.allowPathRemoval) {\n            // Remove paths starting with the last (!) index.\n            for (var i = pathDeleteIndices.length - 1; i >= 0; i--) {\n                this.removePathAt(pathDeleteIndices[i]);\n            }\n        }\n        this.pb.redraw();\n    }\n    // +---------------------------------------------------------------------------------\n    // | This function removes all selected vertices on the paths without deleting\n    // | full paths (at least two path vertices remaining).\n    // |\n    // | Returned (sorted) array contains indices of those paths that should\n    // | be deleted completely.\n    // +-------------------------------\n    _handleSingleVertexDelete() {\n        // Check all path points (on all paths) for deletion.\n        // Note: whole paths are not meant to be removed this way.\n        //       Keep track of their indices (ascending order) for later removal.\n        const pathDeleteIndices = [];\n        for (var p = 0; p < this.paths.length; p++) {\n            const allVerticesSelected = this._handleDeleteOnPath(p);\n            if (allVerticesSelected)\n                pathDeleteIndices.push(p);\n        }\n        return pathDeleteIndices;\n    }\n    // +---------------------------------------------------------------------------------\n    // | This function removes all selected vertices on the given path (index)\n    // | without deleting the full path (at least two path vertices remaining).\n    // |\n    // | Returns true if path should be fully removed, false otherwise.\n    // +-------------------------------\n    _handleDeleteOnPath(pathIndex) {\n        const path = this.paths[pathIndex];\n        const newCurves = [];\n        const deletedVertIndices = [];\n        // Find first non-selected path point\n        let curveIndex = 0;\n        while (curveIndex < path.bezierCurves.length && path.bezierCurves[curveIndex].startPoint.attr.isSelected) {\n            deletedVertIndices.push(curveIndex), curveIndex++;\n        }\n        // All points selected? Enqueue for deletion.\n        if (curveIndex == path.bezierCurves.length) {\n            // Indicate: path removal required.\n            return true;\n        }\n        // Only keep those curves that have no selected path point (=delete selected)\n        let curStart = path.bezierCurves[curveIndex].startPoint;\n        let curStartControl = path.bezierCurves[curveIndex].startControlPoint;\n        for (var i = curveIndex; i < path.bezierCurves.length; i++) {\n            if (!path.bezierCurves[i].endPoint.attr.isSelected) {\n                newCurves.push([\n                    curStart.clone(),\n                    path.bezierCurves[i].endPoint.clone(),\n                    curStartControl.clone(),\n                    path.bezierCurves[i].endControlPoint.clone()\n                ]);\n                if (i + 1 < path.bezierCurves.length) {\n                    curStart = path.bezierCurves[i].endPoint;\n                    curStartControl = path.bezierCurves[i + 1].startControlPoint;\n                }\n            }\n            else {\n                // TODO: remove drag listener from removed vertex!\n                deletedVertIndices.push(i);\n            }\n        }\n        // Do not remove the whole path.\n        // Do not replace the path if no vertices were deleted.\n        if (newCurves.length != 0 && newCurves.length != path.bezierCurves.length) {\n            const newPath = BezierPath.fromArray(newCurves);\n            const oldPath = this.paths[pathIndex];\n            this._replacePathAt(pathIndex, newPath);\n            this.onVerticesDeleted(pathIndex, deletedVertIndices, newPath, oldPath);\n            // Indicate: no path removal required\n            return false;\n        }\n        else {\n            // Indicate full path removal if no curve would be left.\n            return newCurves.length == 0;\n        }\n    }\n    // +---------------------------------------------------------------------------------\n    // | This function replaces a path at the given index with a new one (after change\n    // | of vertex count).\n    // +-------------------------------\n    _replacePathAt(pathIndex, newPath) {\n        const oldPath = this.paths[pathIndex];\n        this.pb.remove(oldPath, false, true); // Remove with vertices\n        oldPath.destroy();\n        this._removeDefaultPathListeners(oldPath);\n        BezierPathInteractionHelper.setPathAutoAdjust(newPath);\n        this.paths[pathIndex] = newPath;\n        this.pb.add(newPath);\n    }\n    // +---------------------------------------------------------------------------------\n    // | Touch and mouse events should call this fuction when the pointer was moved.\n    // +-------------------------------\n    _handleMoveEvent(posX, posY) {\n        const oldA = this.currentA.clone();\n        const oldB = this.currentB.clone();\n        const oldDistance = this.currentDistance;\n        const point = this.pb.transformMousePosition(posX, posY);\n        this.currentB.set(point);\n        this._updateMinDistance();\n        // Always fire even if nothing visually changed?\n        if (this.currentDistance <= this.maxDetectDistance && this.mouseIsOver && this.pb.getDraggedElementCount() == 0) {\n            this.onPointerMoved(this.currentPathIndex, this.currentA, this.currentB, this.currentT);\n        }\n        else {\n            this.onPointerMoved(-1, null, null, 0.0);\n        }\n        // Only redraw when moving inside the detection distance\n        if ((this.currentDistance <= this.maxDetectDistance ||\n            (this.currentDistance > this.maxDetectDistance && oldDistance <= this.maxDetectDistance)) &&\n            (!oldA.equals(this.currentA) || !oldB.equals(this.currentB))) {\n            this.pb.redraw();\n        }\n    }\n    // +---------------------------------------------------------------------------------\n    // | This is called when the mouse pointer leaves the canvas or\n    // | when the touch progress ends.\n    // +-------------------------------\n    _clearMoveEvent() {\n        this.onPointerMoved(-1, null, null, 0.0);\n        this.pb.redraw();\n    }\n    // +---------------------------------------------------------------------------------\n    // | Called once upon initialization.\n    // +-------------------------------\n    _installTouchListener() {\n        var _self = this;\n        const afProps = {\n            touchStart: function (_event) {\n                _self.mouseIsOver = true;\n            },\n            touchMove: function (event) {\n                if (_self.pb.getDraggedElementCount() == 0 && event.touches.length > 0) {\n                    _self._handleMoveEvent(event.touches[0].clientX, event.touches[0].clientY);\n                }\n            },\n            touchEnd: function (_event) {\n                _self.mouseIsOver = false;\n                _self._clearMoveEvent();\n            }\n        };\n        if (window[\"createAlloyFinger\"]) {\n            return window[\"createAlloyFinger\"](this.pb.eventCatcher ? this.pb.eventCatcher : this.pb.eventCatcher, afProps);\n        }\n        else {\n            return new AlloyFinger(this.pb.eventCatcher ? this.pb.eventCatcher : this.pb.eventCatcher, afProps);\n        }\n    }\n    // +---------------------------------------------------------------------------------\n    // | Called once upon initialization.\n    // +-------------------------------\n    _installMouseListener() {\n        var _self = this;\n        var mouseHandler = new MouseHandler(this.pb.eventCatcher)\n            .up(function (e) {\n            if (e.params.wasDragged)\n                return;\n            if (_self._keyHandler.isDown(\"shift\"))\n                return;\n            if (_self.currentDistance > _self.maxDetectDistance || !_self.mouseIsOver)\n                return;\n            const path = _self.paths[_self.currentPathIndex];\n            const vertex = _self.pb.getVertexNear(e.params.pos, PlotBoilerplate.DEFAULT_CLICK_TOLERANCE);\n            if (vertex)\n                return;\n            // Check if there is already a path point at the given split position\n            const pathPoint = path.getPointAt(_self.currentT);\n            const pointNear = _self.pb.getVertexNear(_self.pb.revertMousePosition(pathPoint.x, pathPoint.y), 6.0);\n            if (pointNear) {\n                for (var i = 0; i < path.bezierCurves.length; i++) {\n                    if (path.bezierCurves[i].startPoint.distance(pointNear) <= 6.0 ||\n                        path.bezierCurves[i].endPoint.distance(pointNear) <= 6.0) {\n                        // console.log(\"There is already a path point near this position.\");\n                        return;\n                    }\n                }\n            }\n            //console.log('Inserting vertex at', _self.currentT );\n            const leftPath = path.getSubPathAt(0.0, _self.currentT);\n            const rightPath = path.getSubPathAt(_self.currentT, 1.0);\n            const newCurves = [];\n            for (var i = 0; i < leftPath.bezierCurves.length; i++) {\n                newCurves.push(leftPath.bezierCurves[i]);\n            }\n            for (var i = 0; i < rightPath.bezierCurves.length; i++) {\n                newCurves.push(rightPath.bezierCurves[i]);\n            }\n            const newPath = BezierPath.fromArray(newCurves);\n            const oldPath = _self.paths[_self.currentPathIndex];\n            _self._replacePathAt(_self.currentPathIndex, newPath);\n            _self.onVertexInserted(_self.currentPathIndex, leftPath.bezierCurves.length, newPath, oldPath);\n        })\n            .move(function (e) {\n            _self.mouseIsOver = true;\n            _self._handleMoveEvent(e.params.pos.x, e.params.pos.y);\n        });\n        this.pb.eventCatcher.addEventListener(\"mouseenter\", this._mouseEnterListener);\n        this.pb.eventCatcher.addEventListener(\"mouseleave\", this._mouseLeaveListener);\n        return mouseHandler;\n    }\n    // +---------------------------------------------------------------------------------\n    // | Called once upon initialization.\n    // |\n    // | @return {KeyHandler}\n    // +-------------------------------\n    _installKeyListener() {\n        var _self = this;\n        return new KeyHandler({ trackAll: true }).down(\"delete\", function () {\n            _self._handleDelete();\n        });\n    }\n    // +---------------------------------------------------------------------------------\n    // | Removes vertex listeners from all path points.\n    // |\n    // | @param {BezierPath} path - The path to remove vertex listeners from.\n    // +-------------------------------\n    _removeDefaultPathListeners(path) {\n        BezierPathInteractionHelper.removePathVertexDragListeners(path, this._updateMinDistance);\n    }\n    // +---------------------------------------------------------------------------------\n    // | Update the min distance from point `line.b` to the curve. And redraw.\n    // +-------------------------------\n    _updateMinDistance() {\n        if (this.paths.length == 0) {\n            return;\n        }\n        let pathIndex = -1;\n        let minDist = Number.MAX_VALUE;\n        let closestPoint = null;\n        let closestT = 0.0;\n        for (var i = 0; i < this.paths.length; i++) {\n            let path = this.paths[i];\n            let t = path.getClosestT(this.currentB);\n            let point = path.getPointAt(t);\n            let dist = point.distance(this.currentB);\n            if (dist < minDist) {\n                pathIndex = i;\n                minDist = dist;\n                closestT = t;\n                closestPoint = point;\n            }\n        }\n        this.currentT = closestT;\n        this.currentPathIndex = pathIndex;\n        this.currentDistance = minDist;\n        closestPoint && this.currentA.set(closestPoint);\n    }\n    // +---------------------------------------------------------------------------------\n    // | Sets all vertices on the given path to `bezierAutoAdjust=true`.\n    // |\n    // | @static\n    // +-------------------------------\n    static setPathAutoAdjust(path) {\n        for (var i = 0; i < path.bezierCurves.length; i++) {\n            const curve = path.bezierCurves[i];\n            path.adjustPredecessorControlPoint(i, true, // obtainHandleLength\n            false // updateArcLength  (we will do this after the loop)\n            );\n            if (i > 0 || path.adjustCircular)\n                curve.startPoint.attr.bezierAutoAdjust = true;\n        }\n        path.updateArcLengths();\n    }\n    /**\n     * A helper function to add drag-start listeners to all vertices of the given path.\n     *\n     * @static\n     * @method addPathVertexDragStartListeners\n     * @memberof BezierPathInteractionHelper\n     * @param {BezierPath} path - The Bézier path to add vertex listeners to.\n     * @param {function} vertexDragStartListener - The drag listeners to add to each path vertex.\n     * @return void\n     **/\n    static addPathVertexDragStartListeners(path, vertexDragStartListener) {\n        for (var i = 0; i < path.bezierCurves.length; i++) {\n            const curve = path.bezierCurves[i];\n            curve.startPoint.listeners.addDragStartListener(vertexDragStartListener);\n            curve.startControlPoint.listeners.addDragStartListener(vertexDragStartListener);\n            curve.endControlPoint.listeners.addDragStartListener(vertexDragStartListener);\n            if (i + 1 == path.bezierCurves.length && !path.adjustCircular)\n                curve.endPoint.listeners.addDragStartListener(vertexDragStartListener);\n            // if( i+1 == path.bezierCurves.length && !path.adjustCircular )\n            // BezierPathIntractionHelper._addVertsDragListener( [curve.startPoint, curve.startControlPoint, curve.endPoint, curve.endControlPoint ], vertexDragListener );\n        }\n    }\n    /**\n     * A helper function to remove drag-start listeners to all vertices of the given path.\n     *\n     * @static\n     * @method removePathVertexDragStartListeners\n     * @memberof BezierPathInteractionHelper\n     * @param {BezierPath} path - The Bézier path to remove vertex listeners from.\n     * @param {function} vertexDragListener - The drag listeners to remove from each path vertex.\n     * @return void\n     **/\n    static removePathVertexDragStartListeners(path, vertexDragStartListener) {\n        for (var i = 0; i < path.bezierCurves.length; i++) {\n            const curve = path.bezierCurves[i];\n            curve.startPoint.listeners.removeDragStartListener(vertexDragStartListener);\n            curve.startControlPoint.listeners.removeDragStartListener(vertexDragStartListener);\n            curve.endControlPoint.listeners.removeDragStartListener(vertexDragStartListener);\n            if (i + 1 == path.bezierCurves.length && !path.adjustCircular)\n                curve.endPoint.listeners.removeDragStartListener(vertexDragStartListener);\n        }\n    }\n    /**\n     * A helper function to add drag listeners to all vertices of the given path.\n     *\n     * @static\n     * @method addPathVertexDragListeners\n     * @memberof BezierPathInteractionHelper\n     * @param {BezierPath} path - The Bézier path to add vertex listeners to.\n     * @param {function} vertexDragListener - The drag listeners to add to each path vertex.\n     * @return void\n     **/\n    static addPathVertexDragListeners(path, vertexDragListener) {\n        for (var i = 0; i < path.bezierCurves.length; i++) {\n            const curve = path.bezierCurves[i];\n            curve.startPoint.listeners.addDragListener(vertexDragListener);\n            curve.startControlPoint.listeners.addDragListener(vertexDragListener);\n            curve.endControlPoint.listeners.addDragListener(vertexDragListener);\n            if (i + 1 == path.bezierCurves.length && !path.adjustCircular)\n                curve.endPoint.listeners.addDragListener(vertexDragListener);\n            // if( i+1 == path.bezierCurves.length && !path.adjustCircular )\n            // BezierPathIntractionHelper._addVertsDragListener( [curve.startPoint, curve.startControlPoint, curve.endPoint, curve.endControlPoint ], vertexDragListener );\n        }\n    }\n    /**\n     * A helper function to remove drag listeners to all vertices of the given path.\n     *\n     * @static\n     * @method removePathVertexDragListeners\n     * @memberof BezierPathInteractionHelper\n     * @param {BezierPath} path - The Bézier path to remove vertex listeners from.\n     * @param {function} vertexDragListener - The drag listeners to remove from each path vertex.\n     * @return void\n     **/\n    static removePathVertexDragListeners(path, vertexDragListener) {\n        for (var i = 0; i < path.bezierCurves.length; i++) {\n            const curve = path.bezierCurves[i];\n            curve.startPoint.listeners.removeDragListener(vertexDragListener);\n            curve.startControlPoint.listeners.removeDragListener(vertexDragListener);\n            curve.endControlPoint.listeners.removeDragListener(vertexDragListener);\n            if (i + 1 == path.bezierCurves.length && !path.adjustCircular)\n                curve.endPoint.listeners.removeDragListener(vertexDragListener);\n        }\n    }\n    /**\n     * A helper function to add drag-end listeners to all vertices of the given path.\n     *\n     * @static\n     * @method addPathVertexDragEndListeners\n     * @memberof BezierPathInteractionHelper\n     * @param {BezierPath} path - The Bézier path to add vertex listeners to.\n     * @param {function} vertexDragEndListener - The drag listeners to add to each path vertex.\n     * @return void\n     **/\n    static addPathVertexDragEndListeners(path, vertexDragEndListener) {\n        for (var i = 0; i < path.bezierCurves.length; i++) {\n            const curve = path.bezierCurves[i];\n            curve.startPoint.listeners.addDragEndListener(vertexDragEndListener);\n            curve.startControlPoint.listeners.addDragEndListener(vertexDragEndListener);\n            curve.endControlPoint.listeners.addDragEndListener(vertexDragEndListener);\n            if (i + 1 == path.bezierCurves.length && !path.adjustCircular)\n                curve.endPoint.listeners.addDragEndListener(vertexDragEndListener);\n            // if( i+1 == path.bezierCurves.length && !path.adjustCircular )\n            // BezierPathIntractionHelper._addVertsDragListener( [curve.startPoint, curve.startControlPoint, curve.endPoint, curve.endControlPoint ], vertexDragListener );\n        }\n    }\n    /**\n     * A helper function to remove drag-end listeners to all vertices of the given path.\n     *\n     * @static\n     * @method removePathVertexDragEndListeners\n     * @memberof BezierPathInteractionHelper\n     * @param {BezierPath} path - The Bézier path to remove vertex listeners from.\n     * @param {function} vertexDragListener - The drag listeners to remove from each path vertex.\n     * @return void\n     **/\n    static removePathVertexDragEndListeners(path, vertexDragEndListener) {\n        for (var i = 0; i < path.bezierCurves.length; i++) {\n            const curve = path.bezierCurves[i];\n            curve.startPoint.listeners.removeDragEndListener(vertexDragEndListener);\n            curve.startControlPoint.listeners.removeDragEndListener(vertexDragEndListener);\n            curve.endControlPoint.listeners.removeDragEndListener(vertexDragEndListener);\n            if (i + 1 == path.bezierCurves.length && !path.adjustCircular)\n                curve.endPoint.listeners.removeDragEndListener(vertexDragEndListener);\n        }\n    }\n}\n//# sourceMappingURL=BezierPathInteractionHelper.js.map","/**\n * Split SVG path data `d` strings.\n *\n * As this helper function does not detect all possible path data strings it should cover the most daily use-cases.\n *\n * For more insight see\n *    https://www.w3.org/TR/SVG/paths.html\n *\n * @author   Ikaros Kappler\n * @date     2022-11-22\n * @modified 2022-12-21 Ported to Typescript\n * @version  0.0.1-alpha\n */\n/**\n * @name splitSVGPathData\n * @static\n * @param {string} dataString - The SVG path data to split. This should be some string\n **/\nexport const splitSVGPathData = (dataString) => {\n    // I used a modified version of this Josh Frank's SVG path data RexEx.\n    // Source\n    //    https://javascript.plainenglish.io/june-3-parsing-and-validating-svg-paths-with-regex-7bd0e245115\n    // const validCommand =\n    // /([ml](\\s?-?((\\d+(\\.\\d+)?)|(\\.\\d+)))[,\\s]?(-?((\\d+(\\.\\d+)?)|(\\.\\d+))))|([hv](\\s?-?((\\d+(\\.\\d+)?)|(\\.\\d+))))|(c(\\s?-?((\\d+(\\.\\d+)?)|(\\.\\d+)))([,\\s]?(-?((\\d+(\\.\\d+)?)|(\\.\\d+)))){5})|(q(\\s?-?((\\d+(\\.\\d+)?)|(\\.\\d+)))([,\\s]?(-?((\\d+(\\.\\d+)?)|(\\.\\d+)))){3}(\\s?t?(\\s?-?((\\d+(\\.\\d+)?)|(\\.\\d+)))[,\\s]?(-?((\\d+(\\.\\d+)?)|(\\.\\d+))))*)|(a(\\s?-?((\\d+(\\.\\d+)?)|(\\.\\d+)))([,\\s]?(-?((\\d+(\\.\\d+)?)|(\\.\\d+)))){2}[,\\s]?[01][,\\s]+[01][,\\s]+([,\\s]?(-?((\\d+(\\.\\d+)?)|(\\.\\d+)))){2})|(s(\\s?-?((\\d+(\\.\\d+)?)|(\\.\\d+)))([,\\s]?(-?((\\d+(\\.\\d+)?)|(\\.\\d+)))){3})|z/gi;\n    //\n    // My Version allows multiple param sets, too, like 'm|M (x y)+' or 'q|Q (x1 y1 x y)+'. Look at the plus.\n    const validCommand = /([ml]((\\s?-?((\\d+(\\.\\d+)?)|(\\.\\d+)))[,\\s]?(-?((\\d+(\\.\\d+)?)|(\\.\\d+))))+)|([hv]((\\s?-?((\\d+(\\.\\d+)?)|(\\.\\d+))))+)|(c((\\s?-?((\\d+(\\.\\d+)?)|(\\.\\d+)))([,\\s]?(-?((\\d+(\\.\\d+)?)|(\\.\\d+)))){5})+)|(q((\\s?-?((\\d+(\\.\\d+)?)|(\\.\\d+)))([,\\s]?(-?((\\d+(\\.\\d+)?)|(\\.\\d+)))){3})+(\\s?(t?(\\s?-?((\\d+(\\.\\d+)?)|(\\.\\d+)))[,\\s]?(-?((\\d+(\\.\\d+)?)|(\\.\\d+))))*)+)|(a((\\s?-?((\\d+(\\.\\d+)?)|(\\.\\d+)))([,\\s]?(-?((\\d+(\\.\\d+)?)|(\\.\\d+)))){2}[,\\s]?[01][,\\s]+[01][,\\s]+([,\\s]?(-?((\\d+(\\.\\d+)?)|(\\.\\d+)))){2})+)|(s(\\s?-?((\\d+(\\.\\d+)?)|(\\.\\d+)))([,\\s]?(-?((\\d+(\\.\\d+)?)|(\\.\\d+)))){3})|z/gi;\n    const dataElements = dataString.match(validCommand);\n    if (!dataElements) {\n        return null;\n    }\n    const result = [];\n    var i = 0;\n    while (i < dataElements.length) {\n        const token = dataElements[i];\n        // Ctwheels comment was really useful here\n        //    https://stackoverflow.com/questions/47801455/what-is-the-regex-that-properly-splits-svg-d-attributes-into-tokens\n        const dataRaw = token.match(/-?(?:\\d*\\.)?\\d+|[a-z]/gi);\n        if (dataRaw) {\n            result.push(dataRaw);\n        }\n        else {\n            // throw Error?\n        }\n        i++;\n    }\n    return result;\n}; // END splitSVGPathData\n//# sourceMappingURL=splitSVGPathData.js.map","/**\n * Parse SVG path data strings and convert to PlotBoilerplate path objects.\n *\n * As this parser function does not detect all possible path data strings it should cover the most daily use-cases.\n *\n * For more insight see\n *    https://www.w3.org/TR/SVG/paths.html\n *\n * @author  Ikaros Kappler\n * @date    2022-11-06\n * @modified 2022-12-21 (winter solstice) Porting this to Typescript.\n * @modified 2023-01-17 Handling multiple parameter sets now.\n * @version 0.0.2-alpha\n **/\nimport { CubicBezierCurve } from \"../../../CubicBezierCurve\";\nimport { Line } from \"../../../Line\";\nimport { VEllipseSector } from \"../../../VEllipseSector\";\nimport { Vertex } from \"../../../Vertex\";\nimport { splitSVGPathData } from \"./splitSVGPathData\";\nconst DEG_TO_RAD = Math.PI / 180;\n/**\n * Transform the given path data (translate and scale. rotating is not intended here).\n *\n * @date 2022-11-06\n *\n * @name parseSVGPathData\n * @static\n * @param {string} data - The data to parse.\n * @return An array of straight line segments (Line) or curve segments (CubicBezierCurve) representing the path.\n */\nexport const parseSVGPathData = (dataString) => {\n    const dataElements = splitSVGPathData(dataString);\n    if (!dataElements) {\n        return null;\n    }\n    // Array<PathSegments>\n    const result = [];\n    var i = 0;\n    const firstPoint = { x: NaN, y: NaN };\n    const lastPoint = { x: NaN, y: NaN };\n    const lastControlPoint = { x: NaN, y: NaN };\n    const lastQuadraticControlPoint = { x: NaN, y: NaN };\n    while (i < dataElements.length) {\n        // Could this also be SVGPathShorthandQuadraticCurveToCommand?\n        const data = dataElements[i];\n        const cmd = data[0];\n        // console.log(\"cmd\", cmd, \"data\", data);\n        switch (data[0]) {\n            case \"M\":\n                // MoveTo: M|m x y\n                _handleMove(data, false, firstPoint, lastPoint, lastControlPoint, result);\n                break;\n            case \"m\":\n                // MoveTo: M|m x y\n                _handleMove(data, true, firstPoint, lastPoint, lastControlPoint, result);\n                break;\n            case \"L\":\n                // LineTo L|l x y\n                _handleLineTo(data, false, firstPoint, lastPoint, lastControlPoint, result);\n                break;\n            case \"l\":\n                // LineTo L|l x y\n                _handleLineTo(data, true, firstPoint, lastPoint, lastControlPoint, result);\n                break;\n            case \"H\":\n                // HorizontalLineTo: H|h x\n                _handleHorizontalLineTo(data, false, firstPoint, lastPoint, lastControlPoint, result);\n                break;\n            case \"h\":\n                // HorizontalLineTo: H|h x\n                _handleHorizontalLineTo(data, true, firstPoint, lastPoint, lastControlPoint, result);\n                break;\n            case \"V\":\n                // VerticalLineTo: V|v y\n                _handleVerticalLineTo(data, false, firstPoint, lastPoint, lastControlPoint, result);\n                break;\n            case \"v\":\n                // VerticalLineTo: V|v y\n                _handleVerticalLineTo(data, true, firstPoint, lastPoint, lastControlPoint, result);\n                break;\n            case \"C\":\n                // CurveTo: C|c x1 y1 x2 y2 x y\n                _handleCubicBezierTo(data, false, firstPoint, lastPoint, lastControlPoint, result);\n                break;\n            case \"c\":\n                // CurveTo: C|c x1 y1 x2 y2 x y\n                _handleCubicBezierTo(data, true, firstPoint, lastPoint, lastControlPoint, result);\n                break;\n            case \"S\":\n                _handleShorthandCubicCurveTo(data, false, firstPoint, lastPoint, lastControlPoint, result);\n                break;\n            case \"s\":\n                _handleShorthandCubicCurveTo(data, true, firstPoint, lastPoint, lastControlPoint, result);\n                break;\n            case \"Q\":\n                // QuadraticCurveTo: Q|q x1 y1 x y\n                _handleQuadraticCurveTo(data, false, firstPoint, lastPoint, lastControlPoint, result);\n                break;\n            case \"q\":\n                // QuadraticCurveTo: Q|q x1 y1 x y\n                _handleQuadraticCurveTo(data, true, firstPoint, lastPoint, lastControlPoint, result);\n                break;\n            case \"A\":\n                // EllipticalArcTo: A|a rx ry x-axis-rotation large-arc-flag sweep-flag x y\n                _handleArcTo(data, false, firstPoint, lastPoint, lastControlPoint, result);\n                break;\n            case \"a\":\n                // EllipticalArcTo: A|a rx ry x-axis-rotation large-arc-flag sweep-flag x y\n                _handleArcTo(data, true, firstPoint, lastPoint, lastControlPoint, result);\n                break;\n            case \"z\":\n                _handleClosePath(data, false, firstPoint, lastPoint, lastControlPoint, result);\n                break;\n            case \"Z\":\n                // ClosePath: Z|z (no arguments)\n                _handleClosePath(data, true, firstPoint, lastPoint, lastControlPoint, result);\n                // i++;\n                break;\n            default:\n                if (cmd === \"T\") {\n                    throw \"T command only allowed after q command.\";\n                }\n                if (cmd === \"t\") {\n                    throw \"t command only allowed after q command.\";\n                }\n                throw \"Unknown SVG path command found: \" + cmd + \".\";\n        }\n        // Safepoint: continue reading token by token until something is recognized again\n        i++;\n    } // END while\n    return result;\n}; // END parseSVGPathData\n// Just update the current position\nconst _handleMove = (data, isRelative, firstPoint, lastPoint, lastControlPoint, _result) => {\n    if (data.length < 3) {\n        throw \"Unsufficient params for MOVE\";\n    }\n    // result.push( new)\n    if (isRelative && !isNaN(lastPoint.x) && !isNaN(lastPoint.y)) {\n        lastPoint.x += Number(data[1]);\n        lastPoint.y += Number(data[2]);\n        lastControlPoint.x = lastPoint.x;\n        lastControlPoint.y = lastPoint.y;\n    }\n    else {\n        lastPoint.x = Number(data[1]);\n        lastPoint.y = Number(data[2]);\n        lastControlPoint.x = lastPoint.x;\n        lastControlPoint.y = lastPoint.y;\n    }\n    // console.log(\"AFTER MOVE\", lastPoint);\n    if (isNaN(firstPoint.y)) {\n        firstPoint.x = lastPoint.x;\n        firstPoint.y = lastPoint.y;\n    }\n};\n// Draw a line segment from the current position\nconst _handleLineTo = (data, isRelative, firstPoint, lastPoint, lastControlPoint, result) => {\n    if (data.length < 3) {\n        throw \"Unsufficient params for LINETO\";\n    }\n    for (var i = 1; i + 1 < data.length; i += 2) {\n        const line = new Line(new Vertex(lastPoint), new Vertex(lastPoint));\n        if (isRelative) {\n            line.b.x += Number(data[i]);\n            line.b.y += Number(data[i + 1]);\n        }\n        else {\n            line.b.x = Number(data[i]);\n            line.b.y = Number(data[i + 1]);\n        }\n        result.push(line);\n        lastPoint.x = line.b.x;\n        lastPoint.y = line.b.y;\n        lastControlPoint.x = line.b.x;\n        lastControlPoint.y = line.b.y;\n        if (isNaN(firstPoint.y)) {\n            firstPoint.x = line.a.x;\n            firstPoint.y = line.a.y;\n        }\n        console.log(\"LINETO LINE\", i, line.toString());\n    }\n};\nconst _handleHorizontalLineTo = (data, isRelative, firstPoint, lastPoint, lastControlPoint, result) => {\n    //   console.log(\"Handle HORIZONTALLINETO\", data);\n    if (data.length < 2) {\n        throw \"Unsufficient params for HORIZONTALLINETO\";\n    }\n    for (var i = 1; i < data.length; i++) {\n        const line = new Line(new Vertex(lastPoint), new Vertex(lastPoint));\n        if (isRelative) {\n            line.b.x += Number(data[i]);\n            // line.b.y += Number(data[2]);\n        }\n        else {\n            line.b.x = Number(data[i]);\n            // line.b.y = Number(data[2]);\n        }\n        result.push(line);\n        lastPoint.x = line.b.x;\n        // lastPoint.y = line.b.y;\n        lastControlPoint.x = line.b.x;\n        if (isNaN(firstPoint.y)) {\n            firstPoint.x = line.a.x;\n            firstPoint.y = line.a.y;\n        }\n    }\n};\nconst _handleVerticalLineTo = (data, isRelative, firstPoint, lastPoint, lastControlPoint, result) => {\n    if (data.length < 2) {\n        throw \"Unsufficient params for VERTICALLINETO\";\n    }\n    for (var i = 1; i < data.length; i++) {\n        const line = new Line(new Vertex(lastPoint), new Vertex(lastPoint));\n        if (isRelative) {\n            line.b.y += Number(data[i]);\n        }\n        else {\n            line.b.y = Number(data[i]);\n        }\n        result.push(line);\n        // lastPoint.x = line.b.x;\n        lastPoint.y = line.b.y;\n        lastControlPoint.y = line.b.y;\n        if (isNaN(firstPoint.y)) {\n            firstPoint.x = line.a.x;\n            firstPoint.y = line.a.y;\n        }\n    }\n};\n// CurveTo: C|c x1 y1 x2 y2 x y\nconst _handleCubicBezierTo = (data, isRelative, firstPoint, lastPoint, lastControlPoint, result) => {\n    //   console.log(\"Handle CUBICBEZIERTO\", data);\n    if (data.length < 7) {\n        throw \"Unsufficient params for CUBICBEZIERTO\";\n    }\n    for (var i = 1; i + 5 < data.length; i += 6) {\n        const curve = new CubicBezierCurve(new Vertex(lastPoint), new Vertex(lastPoint), new Vertex(lastPoint), new Vertex(lastPoint));\n        if (isRelative) {\n            curve.startControlPoint.x += Number(data[i]);\n            curve.startControlPoint.y += Number(data[i + 1]);\n            curve.endControlPoint.x += Number(data[i + 2]);\n            curve.endControlPoint.y += Number(data[i + 3]);\n            curve.endPoint.x += Number(data[i + 4]);\n            curve.endPoint.y += Number(data[i + 5]);\n        }\n        else {\n            curve.startControlPoint.x = Number(data[i]);\n            curve.startControlPoint.y = Number(data[i + 1]);\n            curve.endControlPoint.x = Number(data[i + 2]);\n            curve.endControlPoint.y = Number(data[i + 3]);\n            curve.endPoint.x = Number(data[i + 4]);\n            curve.endPoint.y = Number(data[i + 5]);\n        }\n        result.push(curve);\n        lastPoint.x = curve.endPoint.x;\n        lastPoint.y = curve.endPoint.y;\n        lastControlPoint.x = curve.endControlPoint.x;\n        lastControlPoint.y = curve.endControlPoint.y;\n        if (isNaN(firstPoint.x)) {\n            firstPoint.x = curve.startPoint.x;\n            firstPoint.y = curve.startPoint.y;\n        }\n    }\n};\n// QuadraticCurveTo: Q|q x1 y1 x y\nconst _handleQuadraticCurveTo = (data, isRelative, firstPoint, lastPoint, lastControlPoint, result) => {\n    //   console.log(\"Handle QUADRATICBEZIERTO\", data);\n    if (data.length < 5) {\n        throw \"Unsufficient params for QUADRATICBEZIERTO\";\n    }\n    var i = 1;\n    var localLastQuadraticControlPoint = { x: 0, y: 0 };\n    // This loops runs at least once\n    while (i + 3 < data.length && data[i] !== \"t\" && data[i] !== \"T\") {\n        const curve = new CubicBezierCurve(new Vertex(lastPoint), new Vertex(lastPoint), new Vertex(lastPoint), new Vertex(lastPoint));\n        if (isRelative) {\n            curve.startControlPoint.x += curve.startPoint.x + (Number(data[i]) - curve.startControlPoint.x); // * 0.666;\n            curve.startControlPoint.y += curve.startPoint.y + (Number(data[i + 1]) - curve.startControlPoint.y); // * 0.666;\n            curve.endPoint.x += Number(data[i + 2]);\n            curve.endPoint.y += Number(data[i + 3]);\n            curve.endControlPoint.x = curve.startControlPoint.x;\n            curve.endControlPoint.y = curve.startControlPoint.y;\n        }\n        else {\n            curve.startControlPoint.x = curve.startPoint.x + (Number(data[i]) - curve.startControlPoint.x); // * 0.666;\n            curve.startControlPoint.y = curve.startPoint.y + (Number(data[i + 1]) - curve.startControlPoint.y); // * 0.666;\n            curve.endPoint.x = Number(data[i + 2]);\n            curve.endPoint.y = Number(data[i + 3]);\n            curve.endControlPoint.x = curve.startControlPoint.x;\n            curve.endControlPoint.y = curve.startControlPoint.y;\n        }\n        // var lastQuadraticControlPoint = { x: Number(data[1]), y: Number(data[2]) };\n        localLastQuadraticControlPoint = { x: curve.endControlPoint.x, y: curve.endControlPoint.y };\n        // Convert quadratic curve to cubic curve\n        curve.startControlPoint.x = curve.startPoint.x + (curve.startControlPoint.x - curve.startPoint.x) * 0.666;\n        curve.startControlPoint.y = curve.startPoint.y + (curve.startControlPoint.y - curve.startPoint.y) * 0.666;\n        curve.endControlPoint.x = curve.endPoint.x + (curve.endControlPoint.x - curve.endPoint.x) * 0.666;\n        curve.endControlPoint.y = curve.endPoint.y + (curve.endControlPoint.y - curve.endPoint.y) * 0.666;\n        result.push(curve);\n        lastPoint.x = curve.endPoint.x;\n        lastPoint.y = curve.endPoint.y;\n        lastControlPoint.x = curve.endControlPoint.x;\n        lastControlPoint.y = curve.endControlPoint.y;\n        if (isNaN(firstPoint.x)) {\n            firstPoint.x = curve.startPoint.x;\n            firstPoint.y = curve.startPoint.y;\n        }\n        i += 4;\n    } // END while\n    // 'T' or 't' command may follow\n    // if (data.length >= 8) {\n    if (i < data.length && (data[i] == \"t\" || data[i] === \"T\")) {\n        // TODO: think about this type cast!\n        const subData = data.slice(5);\n        // var lastQuadraticControlPoint = { x: Number(data[1]), y: Number(data[2]) };\n        if (subData[0] === \"T\") {\n            // _handleShorthandQuadraticCurveTo(subData, false, firstPoint, lastPoint, lastControlPoint, lastQuadraticControlPoint, result);\n            _handleShorthandQuadraticCurveTo(subData, false, firstPoint, lastPoint, lastControlPoint, localLastQuadraticControlPoint, result);\n        }\n        else if (subData[0] === \"t\") {\n            // _handleShorthandQuadraticCurveTo(subData, true, firstPoint, lastPoint, lastControlPoint, lastQuadraticControlPoint, result);\n            _handleShorthandQuadraticCurveTo(subData, true, firstPoint, lastPoint, lastControlPoint, localLastQuadraticControlPoint, result);\n        }\n    }\n};\n// This is a helper function and works only in combination with Quadratic Bézier Curves\n// T|t (x y)+\nconst _handleShorthandQuadraticCurveTo = (data, isRelative, firstPoint, lastPoint, lastControlPoint, lastQuadraticControlPoint, result) => {\n    if (data.length < 3) {\n        throw \"Unsufficient params for SHORTHANDQUADRATICCURVETO\";\n    }\n    var i = 1;\n    while (i + 1 < data.length) {\n        // Respect multiple 'T|t' commands here\n        if (data[i] === \"T\" || data[i] === \"t\") {\n            i++;\n            continue;\n        }\n        const curve = new CubicBezierCurve(new Vertex(lastPoint), new Vertex(lastPoint), new Vertex(lastPoint), new Vertex(lastPoint));\n        if (isRelative) {\n            curve.endPoint.x += Number(data[i]);\n            curve.endPoint.y += Number(data[i + 1]);\n            curve.startControlPoint.x += curve.startPoint.x - (lastQuadraticControlPoint.x - lastPoint.x);\n            curve.startControlPoint.y += curve.startPoint.y - (lastQuadraticControlPoint.y - lastPoint.y);\n        }\n        else {\n            curve.endPoint.x = Number(data[i]);\n            curve.endPoint.y = Number(data[i + 1]);\n            curve.startControlPoint.x = curve.startPoint.x - (lastQuadraticControlPoint.x - lastPoint.x);\n            curve.startControlPoint.y = curve.startPoint.y - (lastQuadraticControlPoint.y - lastPoint.y);\n        }\n        // First handle as symmetrical cubic curve\n        curve.endControlPoint.x = curve.startControlPoint.x;\n        curve.endControlPoint.y = curve.startControlPoint.y;\n        lastQuadraticControlPoint.y = curve.endControlPoint.y;\n        lastQuadraticControlPoint.x = curve.endControlPoint.x;\n        // Convert quadratic curve to cubic curve\n        var scaleFactor = 0.666; // i === 1 ? 0.666 : 1.0;\n        curve.startControlPoint.x = curve.startPoint.x + (curve.startControlPoint.x - curve.startPoint.x) * scaleFactor;\n        curve.startControlPoint.y = curve.startPoint.y + (curve.startControlPoint.y - curve.startPoint.y) * scaleFactor;\n        curve.endControlPoint.x = curve.endPoint.x + (curve.endControlPoint.x - curve.endPoint.x) * scaleFactor;\n        curve.endControlPoint.y = curve.endPoint.y + (curve.endControlPoint.y - curve.endPoint.y) * scaleFactor;\n        //   console.log(\"ADDING T CURVE\", curve);\n        result.push(curve);\n        lastPoint.x = curve.endPoint.x;\n        lastPoint.y = curve.endPoint.y;\n        lastControlPoint.x = curve.endControlPoint.x;\n        lastControlPoint.y = curve.endControlPoint.y;\n        if (isNaN(firstPoint.x)) {\n            firstPoint.x = curve.startPoint.x;\n            firstPoint.y = curve.startPoint.y;\n        }\n        i += 2;\n    }\n};\n// The S|s x2 y2 x y\nconst _handleShorthandCubicCurveTo = (data, isRelative, firstPoint, lastPoint, lastControlPoint, result) => {\n    //   console.log(\"Handle SHORTHANDCUBICBEZIERTO\", data);\n    if (data.length < 5) {\n        throw \"Unsufficient params for SHORTHANDCUBICBEZIERTO\";\n    }\n    const curve = new CubicBezierCurve(new Vertex(lastPoint), new Vertex(lastPoint), new Vertex(lastPoint), new Vertex(lastPoint));\n    if (isRelative) {\n        curve.startControlPoint.x = lastPoint.x - (lastControlPoint.x - lastPoint.x);\n        curve.startControlPoint.y = lastPoint.y - (lastControlPoint.y - lastPoint.y);\n        curve.endControlPoint.x += Number(data[1]);\n        curve.endControlPoint.y += Number(data[2]);\n        curve.endPoint.x += Number(data[3]);\n        curve.endPoint.y += Number(data[4]);\n    }\n    else {\n        curve.startControlPoint.x = lastPoint.x - (lastControlPoint.x - lastPoint.x);\n        curve.startControlPoint.y = lastPoint.y - (lastControlPoint.y - lastPoint.y);\n        curve.endControlPoint.x = Number(data[1]);\n        curve.endControlPoint.y = Number(data[2]);\n        curve.endPoint.x = Number(data[3]);\n        curve.endPoint.y = Number(data[4]);\n    }\n    result.push(curve);\n    lastPoint.x = curve.endPoint.x;\n    lastPoint.y = curve.endPoint.y;\n    lastControlPoint.x = curve.endControlPoint.x;\n    lastControlPoint.y = curve.endControlPoint.y;\n    if (isNaN(firstPoint.x)) {\n        firstPoint.x = curve.startPoint.x;\n        firstPoint.y = curve.startPoint.y;\n    }\n};\n// EllipticalArcTo: A|a rx ry x-axis-rotation large-arc-flag sweep-flag x y\nconst _handleArcTo = (data, isRelative, firstPoint, lastPoint, lastControlPoint, result) => {\n    if (data.length < 8) {\n        throw \"Unsufficient params for ARCTO\";\n    }\n    for (var i = 1; i + 6 < data.length; i += 7) {\n        const arcEndPoint = { x: Number(data[i + 5]), y: Number(data[i + 6]) };\n        if (isRelative) {\n            arcEndPoint.x += lastPoint.x;\n            arcEndPoint.y += lastPoint.y;\n        }\n        // console.log(\n        //   \"ARC\",\n        //   \"data.length\",\n        //   data.length,\n        //   \"i\",\n        //   i,\n        //   \"lastPoint.x\",\n        //   lastPoint.x, // x1\n        //   \"lastPoint.y\",\n        //   lastPoint.y, // y1\n        //   \"data[i]\",\n        //   Number(data[i]), // rx\n        //   \"data[i+1]\",\n        //   Number(data[i + 1]), // ry\n        //   \"data[i+2]\",\n        //   Number(data[i + 2]), // phi: number,\n        //   \"data[i+3]\",\n        //   Boolean(data[i + 3]), // fa: boolean,\n        //   \"data[i+4]\",\n        //   Boolean(data[i + 4]), // fs: boolean,\n        //   \"data[i+5]\",\n        //   arcEndPoint.x, // Number(data[6]), // x2: number,\n        //   \"data[i+6]\",\n        //   arcEndPoint.y // Number(data[7]) // y2: number\n        // );\n        // A 5 4 0 1 1 -10 -5\n        // TODO: respect relative/absolute here\n        const ellipseSector = VEllipseSector.ellipseSectorUtils.endpointToCenterParameters(lastPoint.x, lastPoint.y, Number(data[i]), Number(data[i + 1]), Number(data[i + 2]) * DEG_TO_RAD, Boolean(data[i + 3]), Boolean(data[i + 4]), arcEndPoint.x, arcEndPoint.y // Number(data[7]) // y2: number\n        );\n        //   console.log(\"ellipseSector\", ellipseSector);\n        const curves = ellipseSector.toCubicBezier(4); // 4 segments already seems to be a good approximation\n        for (var j = 0; j < curves.length; j++) {\n            result.push(curves[j]); // Destruct!\n        }\n        // result.push(ellipseSector.ellipse);\n        if (curves.length > 0) {\n            // console.log(\"curves\", curves);\n            const lastCurve = curves[curves.length - 1];\n            // lastPoint.x = lastCurve.endPoint.x;\n            // lastPoint.y = lastCurve.endPoint.y;\n            lastControlPoint.x = lastCurve.endControlPoint.x;\n            lastControlPoint.y = lastCurve.endControlPoint.y;\n            if (isNaN(firstPoint.x)) {\n                firstPoint.x = curves[0].startPoint.x;\n                firstPoint.y = curves[0].startPoint.y;\n            }\n        }\n        lastPoint.x = arcEndPoint.x;\n        lastPoint.y = arcEndPoint.y;\n    } // END for\n    // TODO: track first/last/control point\n};\nconst _handleClosePath = (_data, _isRelative, firstPoint, lastPoint, lastControlPoint, result) => {\n    //   console.log(\"Handle CLOSEPATH\", \"lastPoint\", lastPoint, \"firstPoint\", firstPoint);\n    const line = new Line(new Vertex(lastPoint), new Vertex(firstPoint));\n    result.push(line);\n    lastPoint.x = line.b.x;\n    lastPoint.y = line.b.y;\n    lastControlPoint.x = line.b.x;\n    lastControlPoint.y = line.b.y;\n};\n//# sourceMappingURL=parseSVGPathData.js.map","/**\n * A CSS gradient string parser.\n *\n * Source:\n *  https://stackoverflow.com/questions/20215440/parse-css-gradient-rule-with-javascript-regex\n * Thanks to Dean Taylor\n *\n * @date           2025-09-04\n * @OriginalAuthor Dean Taylor\n * @RefactoredBy   Ikaros Kappler, ported to Typescript.\n * @version        1.0.0\n */\nimport { Color } from \"../datastructures/Color\";\nimport { ColorGradient } from \"../datastructures/ColorGradient\";\n/**\n * The default implementation of `PositionToRatioConverter`.\n * @param positionString\n * @returns\n */\nexport const DefaultPositionConverter = (positionString) => {\n    if (typeof positionString === \"undefined\") {\n        throw new Error(\"Cannot parse positioning string `null`.\");\n    }\n    const tmp = positionString.trim();\n    if (tmp.length === 0) {\n        throw new Error('Cannot parse empty positioning string \"\".');\n    }\n    if (!tmp.endsWith(\"%\")) {\n        throw new Error(`Cannot parse positioning string, must end with '%': '${tmp}'`);\n    }\n    return Number.parseFloat(tmp) / 100.0;\n};\n/**\n * Utility combine multiple regular expressions.\n *\n * Source:\n *  https://stackoverflow.com/questions/20215440/parse-css-gradient-rule-with-javascript-regex\n * Thanks to Dean Taylor\n *\n * @param {Array<RegExp | string>} regexpList List of regular expressions or strings.\n * @param {string} flags Normal RegExp flags.\n */\nconst __combineRegExp = (regexpList, flags) => {\n    var source = \"\";\n    for (var i = 0; i < regexpList.length; i++) {\n        const regex = regexpList[i];\n        if (typeof regex === \"string\") {\n            source += regex;\n        }\n        else {\n            source += regex.source;\n        }\n    }\n    return new RegExp(source, flags);\n};\n/**\n * Generate the required regular expressions once.\n *\n * Regular Expressions are easier to manage this way and can be well described.\n *\n * @result {object} Object containing regular expressions.\n */\nconst __generateDefaultRegExpLib = () => {\n    // Note any variables with \"Capture\" in name include capturing bracket set(s).\n    const searchFlags = \"gi\", // ignore case for angles, \"rgb\" etc\n    rAngle = /(?:[+-]?\\d*\\.?\\d+)(?:deg|grad|rad|turn)/, // Angle +ive, -ive and angle types\n    rSideCornerCapture = /to\\s+((?:(?:left|right)(?:\\s+(?:top|bottom))?))/, // optional 2nd part\n    rComma = /\\s*,\\s*/, // Allow space around comma.\n    rColorHex = /\\#(?:[a-f0-9]{6}|[a-f0-9]{3})/, // 3 or 6 character form\n    rDigits3 = /\\(\\s*(?:\\d{1,3}\\s*,\\s*){2}\\d{1,3}\\s*\\)/, // \"(1, 2, 3)\"\n    rDigits4 = /\\(\\s*(?:\\d{1,3}\\s*,\\s*){2}\\d{1,3}\\s*,\\s*\\d*\\.?\\d+\\)/, // \"(1, 2, 3, 4)\"\n    rValue = /(?:[+-]?\\d*\\.?\\d+)(?:%|[a-z]+)?/, // \".9\", \"-5px\", \"100%\".\n    rKeyword = /[_a-z-][_a-z0-9-]*/, // \"red\", \"transparent\", \"border-collapse\".\n    rColor = __combineRegExp([\"(?:\", rColorHex, \"|\", \"(?:rgb|hsl)\", rDigits3, \"|\", \"(?:rgba|hsla)\", rDigits4, \"|\", rKeyword, \")\"], \"\"), rColorStop = __combineRegExp([rColor, \"(?:\\\\s+\", rValue, \"(?:\\\\s+\", rValue, \")?)?\"], \"\"), // Single Color Stop, optional %, optional length.\n    rColorStopList = __combineRegExp([\"(?:\", rColorStop, rComma, \")*\", rColorStop], \"\"), // List of color stops min 1.\n    rLineCapture = __combineRegExp([\"(?:(\", rAngle, \")|\", rSideCornerCapture, \")\"], \"\"), // Angle or SideCorner\n    rGradientSearch = __combineRegExp([\"(?:(\", rLineCapture, \")\", rComma, \")?(\", rColorStopList, \")\"], searchFlags), // Capture 1:\"line\", 2:\"angle\" (optional), 3:\"side corner\" (optional) and 4:\"stop list\".\n    rColorStopSearch = __combineRegExp([\"\\\\s*(\", rColor, \")\", \"(?:\\\\s+\", \"(\", rValue, \"))?\", \"(?:\", rComma, \"\\\\s*)?\"], searchFlags); // Capture 1:\"color\" and 2:\"position\" (optional).\n    return {\n        gradientSearch: rGradientSearch,\n        colorStopSearch: rColorStopSearch\n    };\n};\n/**\n * Actually parse the input gradient parameters string into an object for reusability.\n *\n *\n * @note Really this only supports the standard syntax not historical versions, see MDN for details\n *       https://developer.mozilla.org/en-US/docs/Web/CSS/linear-gradient\n *\n * @param {ColorGradientParserRegExpLib} regExpLib\n * @param {string} input Input string in the form \"to right bottom, #FF0 0%, red 20px, rgb(0, 0, 255) 100%\"\n * @returns {object|undefined} Object containing break down of input string including array of stop points.\n */\nexport var __parseGradient = (regExpLib, input) => {\n    var result;\n    var matchGradient, matchColorStop, stopResult;\n    // reset search position, because we reuse regex.\n    regExpLib.gradientSearch.lastIndex = 0;\n    matchGradient = regExpLib.gradientSearch.exec(input);\n    if (matchGradient !== null) {\n        result = {\n            original: matchGradient[0],\n            colorStopList: [],\n            line: null,\n            angle: null,\n            sideCorner: null\n        };\n        // Line (Angle or Side-Corner).\n        if (!!matchGradient[1]) {\n            result.line = matchGradient[1];\n        }\n        // Angle or undefined if side-corner.\n        if (!!matchGradient[2]) {\n            result.angle = matchGradient[2];\n        }\n        // Side-corner or undefined if angle.\n        if (!!matchGradient[3]) {\n            result.sideCorner = matchGradient[3];\n        }\n        // reset search position, because we reuse regex.\n        regExpLib.colorStopSearch.lastIndex = 0;\n        // Loop though all the color-stops.\n        matchColorStop = regExpLib.colorStopSearch.exec(matchGradient[4]);\n        while (matchColorStop !== null) {\n            stopResult = {\n                color: matchColorStop[1],\n                position: null\n            };\n            // Position (optional).\n            if (!!matchColorStop[2]) {\n                stopResult.position = matchColorStop[2];\n            }\n            result.colorStopList.push(stopResult);\n            // Continue searching from previous position.\n            matchColorStop = regExpLib.colorStopSearch.exec(matchGradient[4]);\n        }\n    }\n    // Can be undefined if match not found.\n    return result;\n};\n/**\n * The actual parser class.\n */\nexport class LinearColorGradientParser {\n    constructor(regExpLib) {\n        this.regExpLib = regExpLib || __generateDefaultRegExpLib();\n    }\n    parse(input, positionConverter) {\n        const result = this.parseRaw(input);\n        return LinearColorGradientParser.parseResultToColorGradient(result, positionConverter);\n    }\n    parseRaw(input) {\n        var result;\n        const rGradientEnclosedInBrackets = /.*gradient\\s*\\(((?:\\([^\\)]*\\)|[^\\)\\(]*)*)\\)/; // Captures inside brackets - max one additional inner set.\n        const match = rGradientEnclosedInBrackets.exec(input);\n        const bracketPos = input.indexOf(\"(\");\n        const gradientType = bracketPos === -1 ? null : input.substring(0, bracketPos).toLowerCase();\n        if (match !== null) {\n            // Get the parameters for the gradient\n            result = __parseGradient(this.regExpLib, match[1]);\n            result.gradientType = gradientType;\n            if (result.original.trim() !== match[1].trim()) {\n                // Did not match the input exactly - possible parsing error.\n                result.parseWarning = true;\n            }\n        }\n        else {\n            //   result = new Error(\"Failed to find gradient\");\n            throw new Error(\"Failed to find gradient\");\n        }\n        return result;\n    }\n    static parseResultToColorGradient(result, positionConverter) {\n        if (!result.gradientType || result.gradientType.toLowerCase() != \"linear-gradient\") {\n            throw new Error(`Cannot create linear gradient from type '${result.gradientType}'.`);\n        }\n        if (!result.colorStopList || result.colorStopList.length <= 1) {\n            throw new Error(`Cannot create linear gradient from color stop list of length '${result.colorStopList.length}'. Too few elements.`);\n        }\n        const colorStops = [];\n        const converter = positionConverter !== null && positionConverter !== void 0 ? positionConverter : DefaultPositionConverter;\n        for (var i = 0; i < result.colorStopList.length; i++) {\n            const stopListItem = result.colorStopList[i];\n            console.log(stopListItem);\n            const color = Color.parse(stopListItem.color);\n            // var position: number = LinearColorGradientParser.parsePosition(stopListItem.position);\n            var ratio;\n            if (typeof stopListItem.position === \"undefined\") {\n                // Try to auto-fill undefined positions by their index in the list.\n                ratio = i / (result.colorStopList.length - 1);\n            }\n            else {\n                ratio = converter(stopListItem.position);\n            }\n            colorStops.push({ color: color, ratio: ratio });\n        }\n        return new ColorGradient(colorStops, result.line);\n    }\n} // END class\n// var test_this_one = function (regExpLib, input) {\n//   var result,\n//     rGradientEnclosedInBrackets = /.*gradient\\s*\\(((?:\\([^\\)]*\\)|[^\\)\\(]*)*)\\)/, // Captures inside brackets - max one additional inner set.\n//     match = rGradientEnclosedInBrackets.exec(input);\n//   if (match !== null) {\n//     // Get the parameters for the gradient\n//     result = parseGradient(regExpLib, match[1]);\n//     if (result.original.trim() !== match[1].trim()) {\n//       // Did not match the input exactly - possible parsing error.\n//       result.parseWarning = true;\n//     }\n//   } else {\n//     result = \"Failed to find gradient\";\n//   }\n//   return result;\n// };\n//# sourceMappingURL=LinearColorGradientParser.js.map","/**\n * Refactored 3daddict's js-stl-parser.\n *\n * Found at\n *   https://github.com/3daddict/js-stl-parser/blob/master/index.js\n *\n * Refactored by Ikaros Kappler\n *\n * @date     2021-04-16\n * @modified 2024-03-09 Added type checks for Typescript 5 compatibility.\n * @version  0.0.2\n */\nclass Vertex {\n    constructor(x, y, z) {\n        this.x = x;\n        this.y = y;\n        this.z = z;\n    }\n}\n// Vertex Holder\nclass VertexHolder {\n    constructor(vertex1, vertex2, vertex3) {\n        this.vert1 = vertex1;\n        this.vert2 = vertex2;\n        this.vert3 = vertex3;\n    }\n}\n// transforming a Node.js Buffer into a V8 array buffer\nconst _toArrayBuffer = (buffer) => {\n    const ab = new ArrayBuffer(buffer.length);\n    const view = new Uint8Array(ab);\n    for (var i = 0; i < buffer.length; ++i) {\n        view[i] = buffer.charCodeAt(i);\n    }\n    return ab;\n};\n/**\n * @classdesc STLParser\n */\nexport class STLParser {\n    /**\n     * Create a new STLParser with the given callback fuction for facets.\n     *\n     * @param {function} handleFacet function(x,y,z)\n     * @constructor\n     * */\n    constructor(handleFacet) {\n        this.handleFacet = handleFacet;\n    }\n    /**\n     * Parse an stl string (ASCII).\n     * @name _parseSTLString\n     * @method _parseSTLString\n     * @memberof STLParser\n     * @param {string} stl\n     * @private\n     */\n    _parseSTLString(stl) {\n        // yes, this is the regular expression, matching the vertexes\n        // it was kind of tricky but it is fast and does the job\n        const vertexes = stl.match(/facet\\s+normal\\s+([-+]?\\b(?:[0-9]*\\.)?[0-9]+(?:[eE][-+]?[0-9]+)?\\b)\\s+([-+]?\\b(?:[0-9]*\\.)?[0-9]+(?:[eE][-+]?[0-9]+)?\\b)\\s+([-+]?\\b(?:[0-9]*\\.)?[0-9]+(?:[eE][-+]?[0-9]+)?\\b)\\s+outer\\s+loop\\s+vertex\\s+([-+]?\\b(?:[0-9]*\\.)?[0-9]+(?:[eE][-+]?[0-9]+)?\\b)\\s+([-+]?\\b(?:[0-9]*\\.)?[0-9]+(?:[eE][-+]?[0-9]+)?\\b)\\s+([-+]?\\b(?:[0-9]*\\.)?[0-9]+(?:[eE][-+]?[0-9]+)?\\b)\\s+vertex\\s+([-+]?\\b(?:[0-9]*\\.)?[0-9]+(?:[eE][-+]?[0-9]+)?\\b)\\s+([-+]?\\b(?:[0-9]*\\.)?[0-9]+(?:[eE][-+]?[0-9]+)?\\b)\\s+([-+]?\\b(?:[0-9]*\\.)?[0-9]+(?:[eE][-+]?[0-9]+)?\\b)\\s+vertex\\s+([-+]?\\b(?:[0-9]*\\.)?[0-9]+(?:[eE][-+]?[0-9]+)?\\b)\\s+([-+]?\\b(?:[0-9]*\\.)?[0-9]+(?:[eE][-+]?[0-9]+)?\\b)\\s+([-+]?\\b(?:[0-9]*\\.)?[0-9]+(?:[eE][-+]?[0-9]+)?\\b)\\s+endloop\\s+endfacet/g);\n        if (!vertexes) {\n            throw \"[STLParser] Failed to parse STL input; regex could not match.\";\n        }\n        ;\n        const _handleFacet = this.handleFacet;\n        vertexes.forEach((vert) => {\n            const preVertexHolder = new VertexHolder();\n            const vertValues = vert\n                .match(/vertex\\s+([-+]?\\b(?:[0-9]*\\.)?[0-9]+(?:[eE][-+]?[0-9]+)?\\b)\\s+([-+]?\\b(?:[0-9]*\\.)?[0-9]+(?:[eE][-+]?[0-9]+)?\\b)\\s+([-+]?\\b(?:[0-9]*\\.)?[0-9]+(?:[eE][-+]?[0-9]+)?\\b)\\s/g);\n            if (!vertValues) {\n                console.warn(\"[STLParser] Could not parse vertex values.\", vertValues);\n            }\n            else {\n                vertValues.forEach((vertex, i) => {\n                    const tempVertex = vertex.replace(\"vertex\", \"\").match(/[-+]?[0-9]*\\.?[0-9]+/g);\n                    if (!tempVertex) {\n                        console.warn(\"[STLParser] Failed to parse vertex value.\", tempVertex);\n                    }\n                    else {\n                        const preVertex = new Vertex(Number(tempVertex[0]), Number(tempVertex[1]), Number(tempVertex[2]));\n                        // preVertexHolder[\"vert\" + (i + 1)] = preVertex;\n                        switch (i) {\n                            case 0:\n                                preVertexHolder.vert1 = preVertex;\n                                break;\n                            case 1:\n                                preVertexHolder.vert2 = preVertex;\n                                break;\n                            case 2:\n                                preVertexHolder.vert3 = preVertex;\n                                break;\n                            default: console.warn(\"[STLParse] Warning, vertex component index unexpeced.\", i);\n                        }\n                    }\n                });\n            }\n            if (preVertexHolder.vert1 && preVertexHolder.vert2 && preVertexHolder.vert3) {\n                _handleFacet(preVertexHolder.vert1, preVertexHolder.vert2, preVertexHolder.vert3);\n            }\n            else {\n                console.warn(\"[STLParse] Warning, cannot add vertex to mesh. vertex not fully defined.\");\n            }\n        });\n    }\n    /**\n     * Parse binary STL data.\n     * @param {ArrayBuffer} buf\n     */\n    _parseSTLBinary(buf) {\n        // parsing an STL Binary File\n        // (borrowed some code from here: https://github.com/mrdoob/three.js/blob/master/examples/js/loaders/STLLoader.js)\n        const headerLength = 80;\n        const dataOffset = 84;\n        const faceLength = 12 * 4 + 2;\n        const le = true; // is little-endian\n        const dvTriangleCount = new DataView(buf, headerLength, 4);\n        const numTriangles = dvTriangleCount.getUint32(0, le);\n        for (var i = 0; i < numTriangles; i++) {\n            const dv = new DataView(buf, dataOffset + i * faceLength, faceLength);\n            const normal = new Vertex(dv.getFloat32(0, le), dv.getFloat32(4, le), dv.getFloat32(8, le));\n            const vertHolder = new VertexHolder();\n            for (var v = 3; v < 12; v += 3) {\n                var vert = new Vertex(dv.getFloat32(v * 4, le), dv.getFloat32((v + 1) * 4, le), dv.getFloat32((v + 2) * 4, le));\n                // vertHolder[\"vert\" + v / 3] = vert;\n                const vIndex = v / 3;\n                switch (vIndex) {\n                    case 1:\n                        vertHolder.vert1 = vert;\n                        break;\n                    case 2:\n                        vertHolder.vert2 = vert;\n                        break;\n                    case 3:\n                        vertHolder.vert3 = vert;\n                        break;\n                    default: console.warn(\"[STLParser] Warning, binary vertex component index unexpeced.\", vIndex);\n                }\n            }\n            if (vertHolder.vert1 && vertHolder.vert2 && vertHolder.vert3) {\n                this.handleFacet(vertHolder.vert1, vertHolder.vert2, vertHolder.vert3, normal);\n            }\n            else {\n                console.warn(\"[STLParser] Warning, cannot add binary vertex to mesh. vertex not fully defined.\");\n            }\n        }\n    }\n    /**\n     * Parse any, binary or ascii, STL data.\n     *\n     * @name parse\n     * @method parse\n     * @member\n     * @memberof STLParser\n     * @param {ArrayBstringuffer} binaryOrAsciiString\n     * @returns\n     */\n    parse(binaryOrAsciiString) {\n        var isAscii = true;\n        for (var i = 0, len = binaryOrAsciiString.length; i < len && isAscii; i++) {\n            if (binaryOrAsciiString.charCodeAt(i) > 127) {\n                isAscii = false;\n                break;\n            }\n        }\n        if (isAscii) {\n            this._parseSTLString(binaryOrAsciiString.toString());\n        }\n        else {\n            const buffer = _toArrayBuffer(binaryOrAsciiString);\n            this._parseSTLBinary(buffer);\n        }\n    }\n}\n//# sourceMappingURL=STLParser.js.map","/**\n * @date     2020-04-15\n * @author   Converted to a class by Ikaros Kappler\n * @modified 2020-08-19 Ported this class from vanilla JS to TypeScript.\n * @version  1.0.1\n *\n * @file CatmullRomPath\n * @public\n **/\nimport { CubicBezierCurve } from \"../../CubicBezierCurve\";\nimport { Vertex } from \"../../Vertex\";\n/**\n * @classdesc Compute the Catmull-Rom spline path from a sequence of points (vertices).\n *\n * For comparison to the HobbyCurve I wanted to add a Catmull-Rom path (to show that the\n * HobbyCurve is smoother).\n *\n * This demo implementation was inspired by this Codepen by Blake Bowen\n * https://codepen.io/osublake/pen/BowJed\n *\n * @requires CubicBezierCurve\n * @requires Vertex\n */\nexport class CatmullRomPath {\n    /**\n     * @constructor\n     * @name CatmullRomPath\n     * @param {Array<Vertex>=} vertices? - An optional array of vertices to initialize the path with.\n     **/\n    constructor(vertices) {\n        this.vertices = vertices ? vertices : [];\n    }\n    ;\n    /**\n     * Add a new point to the end of the vertex sequence.\n     *\n     * @name addPoint\n     * @memberof CatmullRomPath\n     * @instance\n     * @param {Vertex} p - The vertex (point) to add.\n     **/\n    addPoint(p) {\n        this.vertices.push(p);\n    }\n    ;\n    /**\n     * Generate a sequence of cubic Bézier curves from the point set.\n     *\n     * @name generateCurve\n     * @memberof CatmullRomPath\n     * @instance\n     * @param {boolean=} circular - Specify if the path should be closed.\n     * @param {number=1} tension - (default=0) An optional tension parameter.\n     * @return Array<CubicBezierCurve>\n     **/\n    generateCurve(circular, tension) {\n        if (typeof tension === 'undefined')\n            tension = 1.0;\n        if (circular)\n            return this.solveClosed(tension);\n        else\n            return this.solveOpen(tension);\n    }\n    ;\n    solveOpen(k) {\n        var curves = [];\n        if (k == null || typeof k === 'undefined')\n            k = 1;\n        var size = this.vertices.length;\n        var last = size - 2;\n        for (var i = 0; i < size - 1; i++) {\n            var p0 = i ? this.vertices[i - 1] : this.vertices[0];\n            var p1 = this.vertices[i + 0];\n            var p2 = this.vertices[i + 1];\n            var p3 = i !== last ? this.vertices[i + 2] : p2;\n            var cp1 = new Vertex(p1.x + (p2.x - p0.x) / 6 * k, p1.y + (p2.y - p0.y) / 6 * k);\n            var cp2 = new Vertex(p2.x - (p3.x - p1.x) / 6 * k, p2.y - (p3.y - p1.y) / 6 * k);\n            curves.push(new CubicBezierCurve(p1, p2, cp1, cp2));\n        }\n        return curves;\n    }\n    ; // END solveOpen\n    solveClosed(k) {\n        var curves = [];\n        if (k == null || typeof k === 'undefined')\n            k = 1;\n        var size = this.vertices.length;\n        var last = size - 1;\n        for (var i = 0; i < size; i++) {\n            var p0 = i ? this.vertices[i - 1] : this.vertices[last];\n            var p1 = this.vertices[i + 0];\n            var p2 = this.vertices[(i + 1) % size];\n            var p3 = this.vertices[(i + 2) % size];\n            var cp1 = new Vertex(p1.x + (p2.x - p0.x) / 6 * k, p1.y + (p2.y - p0.y) / 6 * k);\n            var cp2 = new Vertex(p2.x - (p3.x - p1.x) / 6 * k, p2.y - (p3.y - p1.y) / 6 * k);\n            curves.push(new CubicBezierCurve(p1, p2, cp1, cp2));\n        }\n        return curves;\n    }\n    ; // END solveClosed\n}\n; // END class\n//# sourceMappingURL=CatmullRomPath.js.map","/**\n * Easily handle circles (mouse or touch) with this circle helper.\n *\n * The circle has the center point and a second point to determine the radius.\n *\n * @author   Ikaros Kappler\n * @date     2020-09-07\n * @modified 2020-10-18 Ported to Typescript from vanilla JS.\n * @modified 2021-01-22 Removed `pb.redraw()` call from update handlers (changed vertices already triggered redraw).\n * @modified 2024-02-26 Removed the constructor param `pb` (unused).\n * @modified 2024-02-25 Added `circle` and `radiusPoint` attributes.\n * @modified 2024-03-10 Fixed some issues in the `destroy` method; listeners were not properly removed.\n * @modified 2025-05-05 Class `BezierPathInteractionHelper` now implementing `IShapeInteractionHelper`.\n * @version  1.2.1\n **/\n/**\n * @classdesc A helper for handling circles with an additional radius-control-point.\n */\nexport class CircleHelper {\n    /**\n     * The constructor.\n     *\n     * @constructor\n     * @name CircleHelper\n     * @param {Circle} circle - The circle to handle.\n     * @param {Vertex} radiusPoint - A point to define the radius (distance from center).\n     * @param {PlotBoilerplate} pb - The PlotBoilerplate which contains the circle and point.\n     **/\n    constructor(circle, radiusPoint) {\n        this.circle = circle;\n        this.radiusPoint = radiusPoint;\n        circle.center.listeners.addDragListener((this.centerHandler = this._handleDragCenter()));\n        radiusPoint.listeners.addDragListener((this.radiusHandler = this._handleDragRadiusPoint()));\n    }\n    //--- BEGIN --- Implement ISHapeInteractionHelper ---\n    /**\n     * Let this shape helper draw it's handle lines. It's up to the helper what they look like.\n     * @param {DrawLib<any>} draw - The draw library to use.\n     * @param {DrawLib<any>} fill - The fill library to use.\n     */\n    drawHandleLines(_draw, _fill) {\n        // NOOP\n    }\n    /**\n     * Destroy this circle helper.\n     * The listeners will be removed from the circle points.\n     *\n     * @method destroy\n     * @instance\n     * @memberof CircleHelper\n     */\n    destroy() {\n        this.circle.center.listeners.removeDragListener(this.centerHandler);\n        this.radiusPoint.listeners.removeDragListener(this.radiusHandler);\n    }\n    //--- END --- Implement ISHapeInteractionHelper ---\n    /**\n     * Creates a new drag handler for the circle's center point.\n     *\n     * @private\n     * @method _handleDragCenter\n     * @instance\n     * @memberof CircleHelper\n     * @returns A new event handler.\n     */\n    _handleDragCenter() {\n        const _self = this;\n        return (evt) => {\n            _self.radiusPoint.add(evt.params.dragAmount);\n        };\n    }\n    /**\n     * Creates a new drag handler for the circle's radius control point.\n     *\n     * @private\n     * @method _handleDragCenter\n     * @instance\n     * @memberof CircleHelper\n     * @returns A new event handler.\n     */\n    _handleDragRadiusPoint() {\n        const _self = this;\n        return (_evt) => {\n            _self.circle.radius = _self.circle.center.distance(_self.radiusPoint);\n        };\n    }\n}\n//# sourceMappingURL=CircleHelper.js.map","/**\n * @author   Ikaros Kappler\n * @modified 2021-01-22\n * @version  1.0.0\n */\n/**\n * @classdesc A helper for handling circles with an additional radius-control-point.\n */\nexport class CircleSectorHelper {\n    /**\n     * The constructor.\n     *\n     * @constructor\n     * @name CircleSectorHelper\n     * @param {CircleSector} circleSector - The circle sector to handle.\n     * @param {Vertex} controlPointStart - A point to define the radius and start angle (distance and angle from center).\n     * @param {Vertex} controlPointEnd - A point to define the radius and end angle (distance and angle from center).\n     * @param {PlotBoilerplate} pb - The PlotBoilerplate which contains the circle sector and both points.\n     **/\n    constructor(circleSector, controlPointStart, controlPointEnd, pb) {\n        this.circleSector = circleSector;\n        this.controlPointStart = controlPointStart;\n        this.controlPointEnd = controlPointEnd;\n        this.circleSector.circle.center.listeners.addDragListener((this.centerListener = this._handleDragCenter()));\n        this.controlPointStart.listeners.addDragListener((this.radiusStartListener = this._handleDragStartControlPoint()));\n        this.controlPointEnd.listeners.addDragListener((this.radiusEndListener = this._handleDragEndControlPoint()));\n    }\n    /**\n     * Creates a new drag handler for the circle sector's center point.\n     *\n     * @private\n     * @method handleDragCenter\n     * @instance\n     * @memberof CircleSectorHelper\n     * @returns A new event handler.\n     */\n    _handleDragCenter() {\n        const _self = this;\n        return (e) => {\n            _self.controlPointStart.add(e.params.dragAmount);\n            _self.controlPointEnd.add(e.params.dragAmount);\n        };\n    }\n    /**\n     * Creates a new drag handler for the circle sector's start control point.\n     *\n     * @private\n     * @method _handleDragStartControlPoint\n     * @instance\n     * @memberof CircleSectorHelper\n     * @returns A new event handler.\n     */\n    _handleDragStartControlPoint() {\n        const _self = this;\n        return (e) => {\n            _self.circleSector.circle.radius = _self.circleSector.circle.center.distance(_self.controlPointStart);\n            _self.controlPointEnd.set(_self.circleSector.circle.vertAt(_self.circleSector.endAngle));\n            _self.circleSector.startAngle = _self.circleSector.circle.center.angle(_self.controlPointStart);\n        };\n    }\n    /**\n     * Creates a new drag handler for the circle sector's end control point.\n     *\n     * @private\n     * @method _handleDragEndControlPoint\n     * @instance\n     * @memberof CircleSectorHelper\n     * @returns A new event handler.\n     */\n    _handleDragEndControlPoint() {\n        const _self = this;\n        return (e) => {\n            _self.circleSector.circle.radius = _self.circleSector.circle.center.distance(_self.controlPointEnd);\n            _self.controlPointStart.set(_self.circleSector.circle.vertAt(_self.circleSector.startAngle));\n            _self.circleSector.endAngle = _self.circleSector.circle.center.angle(_self.controlPointEnd);\n        };\n    }\n    //--- BEGIN --- Implement IShapeInteractionHelper ---\n    /**\n     * Draw grey handle lines.\n     *\n     * @param {DrawLib<any>} draw - The draw library instance to use.\n     * @param {DrawLib<any>} fill - The fill library instance to use.\n     */\n    drawHandleLines(draw, fill) {\n        draw.line(this.circleSector.circle.center, this.controlPointStart, \"rgba(64,192,128,0.333)\", 1.0, {\n            dashOffset: 0.0,\n            dashArray: [4, 2]\n        });\n        draw.line(this.circleSector.circle.center, this.controlPointEnd, \"rgba(64,192,128,0.333)\", 1.0, {\n            dashOffset: 0.0,\n            dashArray: [4, 2]\n        });\n    }\n    /**\n     * Destroy this circle helper.\n     * The listeners will be removed from the circle sector's points.\n     *\n     * @method destroy\n     * @instance\n     * @memberof CircleSectorHelper\n     */\n    destroy() {\n        this.circleSector.circle.center.listeners.removeDragListener(this.centerListener);\n        this.controlPointStart.listeners.removeDragListener(this.radiusStartListener);\n        this.controlPointEnd.listeners.removeDragListener(this.radiusEndListener);\n    }\n}\n//# sourceMappingURL=CircleSectorHelper.js.map","/**\n * Approach for a 'simple' color gradient picker for my PlotBoilerplate library.\n *\n * As it turned out a bit more complex in the end – due to the fact that color gradient\n * picking is not a super simple task – so I used JSX here. Thus a JSX library is required\n * to get this running: NoReact.\n *\n *\n * @author   Ikaros Kappler\n * @date     2025-06-27\n * @modified 2025-09-10 Fixing a color select bug on MacOS.\n * @version  1.0.0\n */\nimport * as NoReact from \"noreact\";\nimport { Color } from \"../../datastructures/Color\";\nimport { ColorGradient } from \"../../datastructures/ColorGradient\";\nexport class ColorGradientPicker {\n    /**\n     * The constructor: creates a new color gradient picker in the given container.\n     * If no container or ID is given then a new unbound `container` will be created (DIV).\n     *\n     * Pass a container ID or nothing – in the latter case the constructor will create\n     * a new DIV element.\n     *\n     * @param {string?} containerID - (optional) If you want to use an existing container (should be a DIV).\n     * @param {boolean?} isMobileMode - (optional) If `true` then the elements are rendered in double size.\n     */\n    constructor(containerID, isMobileMode) {\n        this._sliderElementRefs = [];\n        this.sliderMin = 0;\n        this.sliderMax = 100;\n        // Only used during initialization!\n        this.isMobileMode = false;\n        this.css_indicatorWidth_num = 1.0;\n        this.css_indicatorWidth = \"1em\";\n        this.css_indicatorHeight = \"1em\";\n        this.css_thumbWidth = \"0.5em\";\n        this.css_thumbHeight = \"1.333em\";\n        this.css_containerHeight = \"20px\";\n        this.installedChangeListeners = [];\n        this.__mouseDownPosition = null;\n        /**\n         * Creates a callback function for range slider.\n         *\n         * @returns\n         */\n        this.__createSliderChangeHandler = () => {\n            const _self = this;\n            return (e) => {\n                const targetSlider = e.target;\n                // console.log(\"Clicked\", targetSlider ? targetSlider.getAttribute(\"id\") : null);\n                if (!targetSlider) {\n                    return false;\n                }\n                const currentSliderValue = Number.parseFloat(targetSlider.value);\n                const rangeSliderIndexRaw = targetSlider.dataset[\"rangeSliderIndex\"];\n                // console.log(\"rangeSliderIndexRaw\", rangeSliderIndexRaw);\n                if (!rangeSliderIndexRaw) {\n                    return false;\n                }\n                const rangeSliderIndex = Number.parseInt(rangeSliderIndexRaw);\n                var leftSliderValue = this.__getSliderValue(rangeSliderIndex - 1, _self.sliderMin);\n                var rightSliderValue = this.__getSliderValue(rangeSliderIndex + 1, _self.sliderMax);\n                if (leftSliderValue >= currentSliderValue) {\n                    targetSlider.value = `${leftSliderValue}`;\n                    _self.__updateBackgroundGradient();\n                    _self.__updateColorIndicator(rangeSliderIndex);\n                    return false;\n                }\n                else if (rightSliderValue <= currentSliderValue) {\n                    targetSlider.value = `${rightSliderValue}`;\n                    _self.__updateBackgroundGradient();\n                    _self.__updateColorIndicator(rangeSliderIndex);\n                    return false;\n                }\n                else {\n                    _self.__updateBackgroundGradient();\n                    _self.__updateColorIndicator(rangeSliderIndex);\n                    return true;\n                }\n            };\n        };\n        /**\n         * Adds custom styles (global STYLE tag).\n         *\n         * @private\n         */\n        this.__createCustomStylesElement = () => {\n            // Thanks to Ana Tudor\n            //    https://css-tricks.com/multi-thumb-sliders-particular-two-thumb-case/\n            return (NoReact.createElement(\"style\", null, `\n    #${this.elementID} {\n      margin-top: 1em;\n    }\n\n    #${this.elementID} input[type='range'] {\n\n      -webkit-appearance: none;\n\n      grid-column: 1;\n      grid-row: 2;\n      \n      /* same as before */\n      background: none; /* get rid of white Chrome background */\n      color: #000;\n      font: inherit; /* fix too small font-size in both Chrome & Firefox */\n      margin: 0;\n      pointer-events: none; /* let clicks pass through */\n    }\n\n    #${this.elementID} input[type='range']::-webkit-slider-runnable-track {\n      -webkit-appearance: none;\n\n      background: none; /* get rid of Firefox track background */\n      height: 100%;\n      width: 100%;\n\n      pointer-events: none;\n    }\n\n    #${this.elementID} input[type='range']::-webkit-slider-thumb {\n      -webkit-appearance: none;\n      background: currentcolor;\n      border: none; /* get rid of Firefox thumb border */\n      border-radius: 6px; /* get rid of Firefox corner rounding */\n      pointer-events: auto; /* catch clicks */\n      width: ${this.css_thumbWidth}; \n      height: ${this.css_thumbHeight};\n    }\n\n    #${this.elementID} input[type='range']:focus::-webkit-slider-thumb {\n      border: 2px solid white;\n    }\n\n    #${this.elementID} input[type='range']::-moz-range-track {\n      -webkit-appearance: none;\n      background: none; /* get rid of Firefox track background */\n      height: 100%;\n      width: 100%;\n      pointer-events: none;\n    }\n\n    #${this.elementID} input[type='range']::-moz-range-thumb {\n      /* -webkit-appearance: none; */\n      background: currentcolor;\n      border: none; /* get rid of Firefox thumb border */\n      border-radius: 6px; /* get rid of Firefox corner rounding */\n      pointer-events: auto; /* catch clicks */\n      width: ${this.css_thumbWidth}; \n      height: ${this.css_thumbHeight};\n    }\n\n    #${this.elementID} input[type='range']:focus::-moz-range-thumb {\n      border: 2px solid white;\n    }\n\n    #${this.elementID} input[type='range'] {\n      /* same as before */\n      z-index: 1;\n    }\n    \n    #${this.elementID} input[type='range']:focus {\n        z-index: 2;\n        /* outline: dotted 1px orange; */\n        color: darkorange;\n    }\n\n    body.darkmode #${this.elementID} .color-remove-button {    \n      background-color: #1e2937;\n      color: grey;\n    }\n\n    body.darkmode #${this.elementID} .color-remove-button:hover,\n    body.darkmode #${this.elementID} .color-remove-button:active {    \n      background-color: rgba(216,216,216,0.9);\n    }\n\n    `));\n        };\n        if (containerID) {\n            const cont = document.getElementById(containerID);\n            if (!cont) {\n                throw \"Cannot create ColorGradientPicker. Component ID does not exist.\";\n            }\n            this.container = cont;\n        }\n        else {\n            this.container = document.createElement(\"div\");\n        }\n        this.baseID = Math.floor(Math.random() * 65535);\n        this.elementID = `color-gradient-picker-${this.baseID}`;\n        this.colorGradient = ColorGradient.createDefault();\n        this.isMobileMode = Boolean(isMobileMode);\n        if (isMobileMode) {\n            // Double size :)\n            this.css_indicatorWidth_num = 2.0;\n            this.css_indicatorWidth = \"2em\";\n            this.css_indicatorHeight = \"2em\";\n            this.css_thumbWidth = \"1.0em\";\n            this.css_thumbHeight = \"2.666em\";\n            this.css_containerHeight = \"40px\";\n        }\n        document.head.appendChild(this.__createCustomStylesElement());\n        this.container.append(this._render());\n        this.__initializeDataSets();\n        this.__updateColorIndicator(0);\n        this.__updateBackgroundGradient();\n    } // END constructor\n    setGradient(gradient, fireChangeEvent) {\n        // We are lazy: just throw away everything and rebuild all.\n        this.__removeAllChildNodes(this.container);\n        this.colorGradient = gradient;\n        this.container.append(this._render());\n        this.__initializeDataSets();\n        this.__updateColorIndicator(0);\n        this.__updateBackgroundGradient();\n        if (fireChangeEvent) {\n            this.__fireChangeEvent();\n        }\n    }\n    // +---------------------------------------------------------------------------------\n    // | A helper function to remove all child nodes.\n    // +-------------------------------\n    __removeAllChildNodes(node) {\n        while (node.lastChild) {\n            node.removeChild(node.lastChild);\n        }\n    }\n    // +---------------------------------------------------------------------------------\n    // | Used during initialization: define dataset values for each slider.\n    // +-------------------------------\n    __initializeDataSets() {\n        for (var i = 0; i < this._sliderElementRefs.length; i++) {\n            const sliderColor = this.colorGradient.values[i].color;\n            // console.log(\"Setting up slider color data set\", i, sliderColor, sliderColor.cssRGB(), sliderColor.cssHEX());\n            this._sliderElementRefs[i].current.dataset.colorValue = sliderColor.cssRGB();\n            this._sliderElementRefs[i].current.dataset.colorValueHEX = sliderColor.cssHEX();\n        }\n    }\n    /**\n     * Adds a new color gradient change listener to this ColorGradientPicker.\n     *\n     * @param {ColorGradientChangeListener} listener - The listener to add.\n     * @returns {boolean} True, if the listener was added and did not exist before.\n     */\n    addChangeListener(listener) {\n        for (var i = 0; i < this.installedChangeListeners.length; i++) {\n            if (this.installedChangeListeners[i] === listener) {\n                return false;\n            }\n        }\n        this.installedChangeListeners.push(listener);\n        return true;\n    }\n    /**\n     *\n     * @param {ColorGradientChangeListener} listener The listener to remove.\n     * @returns {boolean} True, if the listener existed and has been removed.\n     */\n    removeChangeListener(listener) {\n        for (var i = 0; i < this.installedChangeListeners.length; i++) {\n            if (this.installedChangeListeners[i] === listener) {\n                this.installedChangeListeners.splice(i, 1);\n                return true;\n            }\n        }\n        return false;\n    }\n    /**\n     * Fires a change event to all installed listeners.\n     */\n    __fireChangeEvent() {\n        const newColorGradient = this.getColorGradient();\n        for (var i = 0; i < this.installedChangeListeners.length; i++) {\n            this.installedChangeListeners[i](newColorGradient, this);\n        }\n    }\n    /**\n     * Creates a new color range input element.\n     *\n     * @private\n     * @param {number} baseID\n     * @param index\n     * @param sliderMin\n     * @param sliderMax\n     * @param initialValue\n     * @param initialColor\n     * @returns\n     */\n    __createColorRangeInput(index, sliderMin, sliderMax, initialValue, initialColor) {\n        const sliderHandler = this.__createSliderChangeHandler();\n        const ref = NoReact.useRef();\n        // this._sliderElementRefs.push(ref);\n        this._sliderElementRefs.splice(index, 0, ref);\n        // console.log(\"new _sliderElementRefs\", this._sliderElementRefs);\n        // Update all elements to the right of the new elelemt\n        this.__updateSliderDataSetIndices(index + 1);\n        return (NoReact.createElement(\"input\", { id: `rage-slider-${this.baseID}-${index}`, type: \"range\", min: sliderMin, max: sliderMax, value: initialValue, style: { pos: \"absolute\", l: \"0px\", t: \"0px\", w: \"100%\", h: \"60%\" }, \"data-range-slider-index\": `${index}`, \"data-colorValue\": initialColor.cssRGB(), \"data-colorValueHEX\": initialColor.cssHEX(), onChange: sliderHandler, onClick: sliderHandler, ref: ref }));\n    }\n    /**\n     * Get the absolute length of this range, in slider units.\n     * @returns\n     */\n    getRangeLength() {\n        return this.sliderMax - this.sliderMin;\n    }\n    /**\n     * Handles color value changes.\n     *\n     * @returns\n     */\n    __colorChangeHandler() {\n        const _self = this;\n        return (_evt) => {\n            // console.log(\"__colorChangeHandler\");\n            const activeSliderIndex_raw = this.colorInputRef.current.dataset.activeSliderIndex;\n            if (!activeSliderIndex_raw) {\n                console.warn(\"Cannot update color indicator; no active range slider set. This is likely a program error and should not happen.\");\n                return false;\n            }\n            const activeSliderIndex = Number.parseInt(activeSliderIndex_raw);\n            if (Number.isNaN(activeSliderIndex) || activeSliderIndex < 0 || activeSliderIndex >= _self._sliderElementRefs.length) {\n                console.warn(\"Cannot update color indicator; active index invalid or out of bounds. This is likely a program error and should not happen.\", activeSliderIndex);\n                return false;\n            }\n            const newColor = _self.colorInputRef.current.value;\n            const rangeSlider = _self._sliderElementRefs[activeSliderIndex].current;\n            rangeSlider.dataset.colorValue = newColor;\n            // rangeSlider.dataset[\"colorValue\"] = newColor;\n            this.colorIndicatorColorButtonRef.current.style[\"background-color\"] = newColor;\n            _self.__updateBackgroundGradient();\n            _self.__fireChangeEvent();\n            return true;\n        };\n    }\n    /**\n     * Removed the current color slider from the DOM and highlights the left neighbour.\n     *\n     * @returns {boolean} True if the element could be successfully removed.\n     */\n    __handleRemoveColor() {\n        // const colorInput : HTMLInputElement | null = evt.target;\n        // console.log(\"__colorChangeHandler\");\n        const activeSliderIndex_raw = this.colorInputRef.current.dataset.activeSliderIndex;\n        if (!activeSliderIndex_raw) {\n            console.warn(\"Cannot remove color indicator; no active range slider set.\");\n            return false;\n        }\n        const activeSliderIndex = Number.parseInt(activeSliderIndex_raw);\n        if (Number.isNaN(activeSliderIndex) || activeSliderIndex < 0 || activeSliderIndex >= this._sliderElementRefs.length) {\n            console.warn(\"Cannot remove color indicator; active index invalid or out of bounds.\", activeSliderIndex);\n            return false;\n        }\n        if (activeSliderIndex === 0 || activeSliderIndex + 1 === this.getRangeLength()) {\n            console.warn(\"Cannot remove color indicator; leftmost and rightmost slider must not be removed.\", activeSliderIndex);\n            return false;\n        }\n        const sliderElementRef = this._sliderElementRefs[activeSliderIndex];\n        sliderElementRef.current.remove();\n        this._sliderElementRefs.splice(activeSliderIndex, 1);\n        // Update all elements to the right of the removed elelemt\n        this.__updateSliderDataSetIndices(activeSliderIndex);\n        // Set left element active\n        this.__updateColorIndicator(activeSliderIndex - 1);\n        this.__updateBackgroundGradient();\n        this.__fireChangeEvent();\n        return true;\n    }\n    /**\n     * Once a slider element was added or removed then the following indices must be updated.\n     *\n     * @param {number} startIndex - The slider index to start updating at.\n     */\n    __updateSliderDataSetIndices(startIndex) {\n        // Update all elements to the right of the new elelemt\n        for (var i = startIndex; i < this._sliderElementRefs.length; i++) {\n            this._sliderElementRefs[i].current.setAttribute(\"data-range-slider-index\", `${i}`);\n            this._sliderElementRefs[i].current.setAttribute(\"id\", `rage-slider-${this.baseID}-${i}`);\n        }\n    }\n    /**\n     * To avoid too many sliders added on each click, check if the mouse was moved in the meantime (detect drag event).\n     *\n     * @returns\n     */\n    __containerMouseDownHandler() {\n        const _self = this;\n        return (event) => {\n            _self.__mouseDownPosition = { x: event.clientX, y: event.clientY };\n            // console.log(\"__containerMouseDownHandler _self.__mouseDownPosition\", _self.__mouseDownPosition);\n        };\n    }\n    /**\n     * Creates a handler for click events on the container. If the click event is far\n     * enough from existing sliders, then it can be added.\n     *\n     * @returns\n     */\n    __containerClickHandler() {\n        const _self = this;\n        const maxDifference = _self.getRangeLength() * 0.03;\n        return (evt) => {\n            // console.log(\"Container click handler\");\n            const relativeValue = _self.__clickEventToRelativeValue(evt);\n            if (relativeValue < 0 || relativeValue > 1.0) {\n                // Clicked somewhere outside the range\n                return;\n            }\n            // Check if element was moved in the meantime\n            if (_self.__mouseDownPosition && Math.abs(_self.__mouseDownPosition.x - evt.clientX) >= 10.0) {\n                // Ignore event if mouse was moved more than 10 pixels between down- and up-event\n                // console.log(\"Mouse was moved more than 10 px. Cancelling.\");\n                _self.__mouseDownPosition = null;\n                return;\n            }\n            const absoluteValue = this.__relativeToAbsolute(relativeValue);\n            // console.log(\"click\", \"relativeValue\", relativeValue, \"absoluteValue\", absoluteValue);\n            // Check if click position (ratio) is far enough away from any slider\n            const [leftSliderIndex, closestSliderValue] = _self.__locateClosestSliderValue(absoluteValue);\n            const diff = Math.abs(closestSliderValue - absoluteValue);\n            if (diff >= maxDifference) {\n                // console.log(\"Add slider here\");\n                _self.__addSliderAt(absoluteValue, leftSliderIndex);\n            }\n            else {\n                // console.debug(\"Don't add slider here.\");\n            }\n            // Finally clear mousedown-position\n            _self.__mouseDownPosition = null;\n        };\n    }\n    /**\n     * Find that slider (index) that's value is closest to the given absolute value. The function will return\n     * the closest value and the left index, indicating the containing interval index.\n     *\n     * @param {number} absoluteValue - The value to look for.\n     * @returns {[number,number]} A pair of left slider index and closest value.\n     */\n    __locateClosestSliderValue(absoluteValue) {\n        // As the colorGradient always reflects the slider values we can just ust the color gradient itself to search.\n        const relativeValue = this.__absoluteToRelative(absoluteValue);\n        const colorGradientEntry = this.colorGradient.locateClosestRatio(relativeValue);\n        return [colorGradientEntry[0], this.__relativeToAbsolute(colorGradientEntry[1].ratio)];\n    }\n    /**\n     * Convert the click event to the relative x value in [0..1].\n     *\n     * @param {MouseEvent} evt - The mouse event.\n     * @returns {number} The relative x value.\n     */\n    __clickEventToRelativeValue(evt) {\n        const target = evt.target;\n        const rect = target.getBoundingClientRect();\n        const x = evt.clientX - rect.left; //x position within the element.\n        const width = rect.width; // target.clientWidth;\n        const relativeValue = x / width;\n        // console.log(\"width\", width, \"x\", x, \"relativeValue\", relativeValue);\n        return relativeValue;\n    }\n    /**\n     * Adds a slider at the given interval index.\n     *\n     * @param {number} absoluteValue - The absolute new slider value.\n     * @param {number} leftSliderIndex - The new slider's position (interval index).\n     */\n    __addSliderAt(absoluteValue, leftSliderIndex) {\n        // console.log(\"__addSliderAt\", \"absoluteValue\", absoluteValue, \"leftSliderIndex\", leftSliderIndex);\n        const leftSlider = this._sliderElementRefs[leftSliderIndex].current;\n        // const colorAtPosition = this.__getSliderColorAt(relativeValue);\n        const newColor = this.__getSliderColorAt(absoluteValue);\n        const newSliderIndex = leftSliderIndex + 1;\n        const _newSlider = this.__createColorRangeInput(newSliderIndex, this.sliderMin, this.sliderMax, absoluteValue, newColor // initialColor: string\n        );\n        const sliderRef = this._sliderElementRefs[newSliderIndex];\n        leftSlider.after(sliderRef.current);\n        sliderRef.current.dataset.colorValue = newColor.cssRGB();\n        sliderRef.current.dataset.colorValueHEX = newColor.cssHEX();\n        // No visible change, but let's reflect this in the output gradient anyway\n        this.__updateBackgroundGradient();\n        // Highlight the newly added range slider\n        this.__updateColorIndicator(newSliderIndex);\n        this.__fireChangeEvent();\n    }\n    /**\n     * Get the slider color at the given absolute value. That value must be inside the [MIN_VALUE, MAX_VALUE] interval.\n     * @param absoluteValue\n     * @returns\n     */\n    __getSliderColorAt(absoluteValue) {\n        // console.log(\"__getSliderColorAt\", \"absoluteValue\", absoluteValue);\n        // Locate interval\n        const leftIndex = this.__locateIntervalAt(absoluteValue);\n        const leftSliderValue = this.__getSliderValue(leftIndex, NaN);\n        const rightSliderValue = this.__getSliderValue(leftIndex + 1, NaN);\n        if (Number.isNaN(leftSliderValue) || Number.isNaN(rightSliderValue)) {\n            console.warn(`[Warn] Failed to determine left/right slider values at indices ${leftIndex} or ${rightSliderValue}. Cannot proceed for absolute value ${absoluteValue}.`);\n            return null;\n        }\n        const leftColorString = this.__getSliderColorString(leftIndex, null);\n        const rightColorString = this.__getSliderColorString(leftIndex + 1, null);\n        if (!leftColorString || !rightColorString) {\n            console.warn(`[Warn] Failed to determine left/right color string values at indices ${leftIndex} or ${rightSliderValue}. Cannot proceed for absolute value ${absoluteValue}.`);\n            return null;\n        }\n        const positionInsideInterval = (absoluteValue - leftSliderValue) / (rightSliderValue - leftSliderValue);\n        // console.log(\"leftColorString\", leftColorString, \"rightColorString\", rightColorString);\n        const leftColorObject = Color.parse(leftColorString);\n        const rightColorObject = Color.parse(rightColorString);\n        const newColor = leftColorObject.interpolate(rightColorObject, positionInsideInterval);\n        return newColor;\n    }\n    /**\n     * Locate the slider interval that contains the given (absolute) slider value. The given value must be\n     * somewhere between MIN_VALUE and MAX_VALUE (usually between 0 and 100 in the default configuraion.).\n     *\n     * @param {number} absoluteValue - The absolute value to search for.\n     * @returns {number} The left slider inder the containing interval is starting with – or -1 if out of bounds.\n     */\n    __locateIntervalAt(absoluteValue) {\n        for (var i = 0; i + 1 < this._sliderElementRefs.length; i++) {\n            if (this.__getSliderValue(i, this.sliderMin) <= absoluteValue &&\n                absoluteValue < this.__getSliderValue(i + 1, this.sliderMax)) {\n                return i;\n            }\n        }\n        return -1;\n    }\n    /**\n     * Converts a relative value in [0..1] to [min..max].\n     * @param relativeValue\n     */\n    __relativeToAbsolute(relativeValue) {\n        return this.sliderMin + (this.sliderMax - this.sliderMin) * relativeValue;\n    }\n    /**\n     * Converts a relative value in [0..1] to [min..max].\n     * @param relativeValue\n     */\n    __absoluteToRelative(absolute) {\n        return (absolute - this.sliderMin) / (this.sliderMax - this.sliderMin);\n    }\n    /**\n     * Get the value of the n-th rangel slider.\n     *\n     * @param {number} sliderIndex\n     * @param {number} fallback\n     * @returns\n     */\n    __getSliderValue(sliderIndex, fallback) {\n        if (sliderIndex < 0 || sliderIndex >= this._sliderElementRefs.length) {\n            return fallback;\n        }\n        return Number.parseFloat(this._sliderElementRefs[sliderIndex].current.value);\n    }\n    /**\n     * Get all current slider values as an array.\n     * @returns\n     */\n    __getAllSliderValues() {\n        return this._sliderElementRefs.map((ref, index) => this.__getSliderValue(index, NaN));\n    }\n    /**\n     * Updates the container's background to display the configured color gradient.\n     *\n     * @private\n     */\n    __updateBackgroundGradient() {\n        // const colorGradient = this.getColorGradient();\n        this.colorGradient = new ColorGradient(this.__getAllSliderValues().map((sliderValue, sliderIndex) => ({\n            color: this.__getSliderColor(sliderIndex, null),\n            ratio: this.__absoluteToRelative(sliderValue)\n        })), this.colorGradient.angle);\n        this.containerRef.current.style[\"background\"] = this.colorGradient.toColorGradientString();\n    }\n    /**\n     * After changes this function updates the color indicator button.\n     *\n     * @param {number} rangeSliderIndex - The new active slider index.\n     */\n    __updateColorIndicator(rangeSliderIndex) {\n        const colorValue = this.__getSliderColorHEXString(rangeSliderIndex, \"#808080\");\n        const ratio = this.__getSliderPercentage(rangeSliderIndex);\n        // Set left offset of color input container\n        this.colorInputContainerRef.current.style[\"left\"] = `calc( ${ratio * 100}% + ${(1.0 - ratio) * this.css_indicatorWidth_num * 0.5}em - ${ratio * this.css_indicatorWidth_num * 0.5}em)`;\n        // Also set offset of colot input element (safari will open the native color dialog at this position)\n        this.colorInputRef.current.style[\"left\"] = `calc( ${ratio * 100}% + ${(1.0 - ratio) * this.css_indicatorWidth_num * 0.5}em - ${ratio * this.css_indicatorWidth_num * 0.5}em)`;\n        this.colorIndicatorColorButtonRef.current.style[\"background-color\"] = colorValue;\n        this.colorInputRef.current.value = colorValue;\n        // console.log(\"Setting new color value\", this.colorInputRef.current.value, colorValue);\n        this.colorInputRef.current.dataset.activeSliderIndex = `${rangeSliderIndex}`;\n        if (rangeSliderIndex <= 0 || rangeSliderIndex + 1 >= this._sliderElementRefs.length) {\n            this.colorIndicatorRemoveButtonRef.current.style[\"visibility\"] = \"hidden\";\n        }\n        else {\n            this.colorIndicatorRemoveButtonRef.current.style[\"visibility\"] = \"visible\";\n        }\n    }\n    /**\n     * Get a color gradient CSS value string from the current editor settings.\n     *\n     * @instance\n     * @memberof ColorGradientPicker\n     * @returns {ColorGradient}\n     */\n    getColorGradient() {\n        return this.colorGradient;\n    }\n    /**\n     * Get the configured color value of the n-th rangel slider.\n     *\n     * @param {number} sliderIndex\n     * @param {string} fallback\n     * @returns\n     */\n    __getSliderColorString(sliderIndex, fallback) {\n        if (sliderIndex < 0 || sliderIndex >= this._sliderElementRefs.length) {\n            return fallback;\n        }\n        const colorValue = this._sliderElementRefs[sliderIndex].current.dataset.colorValue;\n        return colorValue ? colorValue : fallback;\n    }\n    /**\n     * Get the configured color value of the n-th rangel slider.\n     *\n     * @param {number} sliderIndex\n     * @param {string} fallback\n     * @returns\n     */\n    __getSliderColorHEXString(sliderIndex, fallback) {\n        if (sliderIndex < 0 || sliderIndex >= this._sliderElementRefs.length) {\n            return fallback;\n        }\n        const colorValue = this._sliderElementRefs[sliderIndex].current.dataset.colorValueHEX;\n        return colorValue ? colorValue : fallback;\n    }\n    /**\n     * Get get color of this gradient picker at the given slider index.\n     *\n     * @param {number} sliderIndex - The index to get the slider color from. Something between 0 and _sliderElementRefs.length.\n     * @param {Color} fallback\n     * @returns\n     */\n    __getSliderColor(sliderIndex, fallback) {\n        if (sliderIndex < 0 || sliderIndex >= this._sliderElementRefs.length) {\n            return fallback;\n        }\n        const colorValueString = this._sliderElementRefs[sliderIndex].current.dataset[\"colorValue\"];\n        const colorValue = Color.parse(colorValueString);\n        return colorValue ? colorValue : fallback;\n    }\n    /**\n     * Get the slider's value in a mapped range of 0.0 ... 1.0.\n     *\n     * @param sliderIndex\n     * @returns\n     */\n    __getSliderPercentage(sliderIndex) {\n        const sliderValue = this.__getSliderValue(sliderIndex, 0.0);\n        const percentage = (this.sliderMin + sliderValue) / (this.sliderMax - this.sliderMin);\n        return percentage;\n    }\n    /**\n     * Init the container contents.\n     *\n     * @private\n     */\n    _render() {\n        const _self = this;\n        // console.log(\"Rendering ...\", NoReact);\n        this._sliderElementRefs = [];\n        this.colorIndicatorColorButtonRef = NoReact.useRef();\n        this.colorIndicatorRemoveButtonRef = NoReact.useRef();\n        this.colorInputRef = NoReact.useRef();\n        this.colorInputContainerRef = NoReact.useRef();\n        this.containerRef = NoReact.useRef();\n        /**\n         * This helper method is called when the tiny color button below the active slider is clicked. The method\n         * triggers the colorInput dialog to be triggered.\n         *\n         * @param {Event} evt\n         */\n        const handleIndicatorButtonClick = (evt) => {\n            evt.preventDefault(); // Prevent other inputs to react to this event.\n            evt.stopPropagation();\n            // But fake a click on the input element\n            // console.log(\"Current selected color: \" + _self.colorInputRef.current.value);\n            _self.colorInputRef.current.click();\n        };\n        /**\n         * This helper method is called when the remove-color button is clicked. It removes the\n         * currently active color slider – if possible (leftmost and rightmost slider cannot be removed).\n         * @param evt\n         */\n        const handleRemoveColorButtonClick = (evt) => {\n            evt.preventDefault(); // Prevent other inputs to react to this event.\n            evt.stopPropagation();\n            _self.__handleRemoveColor();\n        };\n        return (NoReact.createElement(\"div\", { id: this.elementID, style: {\n                d: \"flex\",\n                fd: \"column\",\n                w: \"100%\",\n                h: this.css_containerHeight,\n                pos: \"relative\",\n                mb: this.isMobileMode ? \"5em\" : \"3em\"\n            }, ref: this.containerRef, onMouseDown: this.__containerMouseDownHandler(), onClick: this.__containerClickHandler() },\n            this.colorGradient.values.map((colorGradientItem, index) => {\n                const initialValue = _self.__relativeToAbsolute(colorGradientItem.ratio);\n                return this.__createColorRangeInput(index, this.sliderMin, this.sliderMax, initialValue, colorGradientItem.color);\n            }),\n            NoReact.createElement(\"div\", { style: { w: \"100%\" } },\n                NoReact.createElement(\"input\", { id: `color-indicator-input-${this.baseID}`, type: \"color\", style: { v: \"hidden\", pos: \"absolute\", l: 0 }, \n                    // data-active-slider-index=\"\"\n                    ref: this.colorInputRef, onInput: this.__colorChangeHandler() }),\n                NoReact.createElement(\"div\", { ref: this.colorInputContainerRef, style: {\n                        pos: \"absolute\",\n                        b: \"0px\",\n                        l: \"0%\",\n                        d: \"flex\",\n                        fd: \"column\",\n                        transform: \"translate(0%, 100%)\"\n                    } },\n                    NoReact.createElement(\"button\", { id: `color-indicator-button-${this.baseID}`, className: \"color-indicator-button\", style: {\n                            backgroundColor: \"grey\",\n                            borderRadius: \"50%\",\n                            border: \"1px solid grey\",\n                            w: this.css_indicatorWidth, // \"1em\",\n                            h: this.css_indicatorHeight, // \"1em\",\n                            transform: \"translate(-50%, 0%)\"\n                        }, onClick: handleIndicatorButtonClick, ref: this.colorIndicatorColorButtonRef }),\n                    NoReact.createElement(\"button\", { id: `color-remove-button-${this.baseID}`, className: \"color-remove-button\", style: {\n                            borderRadius: \"10%\",\n                            border: \"1px solid grey\",\n                            w: this.css_indicatorWidth, // \"1em\",\n                            h: this.css_indicatorHeight, // \"1em\",\n                            transform: \"translate(-50%, 50%)\",\n                            lineHeight: \"0.5em\",\n                            p: 0\n                        }, onClick: handleRemoveColorButtonClick, ref: this.colorIndicatorRemoveButtonRef },\n                        NoReact.createElement(\"span\", { style: { fontSize: this.isMobileMode ? \"1.0em\" : \"0.5em\" } }, \"\\uD83D\\uDDD1\"))))));\n    } // END function render()\n}\n//# sourceMappingURL=ColorGradientPicker.js.map","/**\n * A DataGrid2d implementation on a linear array of triplets/Vector3.\n *\n * @author   Ikaros Kappler\n * @date     2023-10-28\n * @modified 2023-11-04 Converted to a Typescript class.\n * @version  1.0.0\n **/\nexport class DataGrid2dListAdapter {\n    /**\n     * Create a new DataGrid2d from the given\n     * @throws Error if xSegmentCount*ySegmentCount is larger than the capacity of the array/list.\n     * @param list\n     * @param xSegmentCount\n     * @param ySegmentCount\n     */\n    constructor(list, xSegmentCount, ySegmentCount) {\n        if (xSegmentCount * ySegmentCount > list.length) {\n            throw `Cannot create DataGrid2dListAdapter, the list (length ${list.length}) does not provide enough items for ${xSegmentCount}x${ySegmentCount} required entries.`;\n        }\n        // this.canvas = document.getElementById(canvasId);\n        this.xSegmentCount = xSegmentCount;\n        this.ySegmentCount = ySegmentCount;\n        this._dataList = list;\n    }\n    getIndicesFromBufferIndex(bufferIndex) {\n        return { xIndex: Math.floor(bufferIndex % this.xSegmentCount), yIndex: Math.floor(bufferIndex / this.xSegmentCount) };\n    }\n    getCoordsFromBufferIndex(bufferIndex) {\n        var index = this.getIndicesFromBufferIndex(bufferIndex);\n        // Note that the xSegmentCount and ySegmentCount counts plane squares, each consisting of four vertices\n        index.xRel = index.xIndex / (this.xSegmentCount - 1);\n        index.yRel = index.yIndex / (this.ySegmentCount - 1);\n        return index;\n    }\n    coordinateIndicesToBufferIndex(xIndex, yIndex) {\n        return yIndex * this.xSegmentCount + xIndex;\n    }\n    /**\n     * @override\n     */\n    getMinDataValue() {\n        return this.minDataValue;\n    }\n    /**\n     * @override\n     */\n    getMaxDataValue() {\n        return this.maxDataValue;\n    }\n    /**\n     * @override\n     */\n    getDataValueAt(xIndex, yIndex, isDebug) {\n        // var bufferIndex = yIndex * this.xSegmentCount + xIndex;\n        var bufferIndex = this.coordinateIndicesToBufferIndex(xIndex, yIndex);\n        // if (isDebug) {\n        //   console.log(\"xIndex\", xIndex, \"yIndex\", yIndex, \"bufferIndex\", bufferIndex);\n        // }\n        if (bufferIndex > this._dataList.length) {\n            console.error(\"ERR buffer index is out of bounds! xIndex\", xIndex, \"yIndex\", yIndex, \"bufferIndex\", bufferIndex);\n        }\n        if (!this._dataList[bufferIndex]) {\n            console.error(\"ERR buffer element is null! xIndex\", xIndex, \"yIndex\", yIndex, \"bufferIndex\", bufferIndex);\n        }\n        return this._dataList && bufferIndex < this._dataList.length ? this._dataList[bufferIndex].z : null;\n    }\n    /**\n     * @override\n     */\n    getDataFace4At(xIndex, yIndex, buffer) {\n        // buffer: array[2][2]\n        buffer[0][0] = this.getDataValueAt(xIndex, yIndex);\n        buffer[1][0] = this.getDataValueAt(xIndex + 1, yIndex);\n        buffer[1][1] = this.getDataValueAt(xIndex + 1, yIndex + 1);\n        buffer[0][1] = this.getDataValueAt(xIndex, yIndex + 1);\n    }\n}\n//# sourceMappingURL=DataGrid2dListAdapter.js.map","/**\n * @modified_by Ikaros Kappler\n * @date_init   2012-10-17\n * @date        2017-07-31\n * @modified    2020-08-17 Ported from vanilla JS to TypeScript.\n * @version     2.0.1\n **/\nimport { Triangle } from \"../../Triangle\";\nimport { Vertex } from \"../../Vertex\";\nimport { Line as Edge } from \"../../Line\";\n// TODO: cleanup? This seems not to be used.\n// const EPSILON : number = 1.0e-6;\n/**\n * @classdesc A Delaunay pointset triangulation implementation.  Inspired by\n *    http://www.travellermap.com/tmp/delaunay.htm\n *\n * License: Public Domain\n *          Original C++ code by Joshua Bell\n *\n * @requires Triangle\n * @requires Line\n * @requires Vertex\n */\nexport class Delaunay {\n    constructor(pointList) {\n        this.pointList = pointList;\n    }\n    triangulate() {\n        return this.Triangulate(this.pointList);\n    }\n    ////////////////////////////////////////////////////////////////////////////////\n    //\n    // Delaunay Triangulation Code, by Joshua Bell\n    //\n    // Inspired by: http://www.codeguru.com/cpp/data/mfc_database/misc/article.php/c8901/\n    //\n    // This work is hereby released into the Public Domain. To view a copy of the public \n    // domain dedication, visit http://creativecommons.org/licenses/publicdomain/ or send \n    // a letter to Creative Commons, 171 Second Street, Suite 300, San Francisco, \n    // California, 94105, USA.\n    //\n    ////////////////////////////////////////////////////////////////////////////////\n    //------------------------------------------------------------\n    // Triangulate\n    //\n    // Perform the Delaunay Triangulation of a set of vertices.\n    //\n    // vertices: Array of Vertex objects\n    //\n    // returns: Array of Triangles\n    //------------------------------------------------------------\n    Triangulate(vertices) {\n        const triangles = [];\n        // First, create a \"supertriangle\" that bounds all vertices  \n        var st = this.createBoundingTriangle(vertices);\n        triangles.push(st);\n        // begin the triangulation one vertex at a time\n        for (var i in vertices) {\n            // NOTE: This is O(n^2) - can be optimized by sorting vertices\n            // along the x-axis and only considering triangles that have \n            // potentially overlapping circumcircles\n            this.AddVertex(vertices[i], triangles);\n        }\n        // Remove triangles that shared edges with \"supertriangle\"\n        for (var i in triangles) {\n            var triangle = triangles[i];\n            if (triangle.a == st.a || triangle.a == st.b || triangle.a == st.c ||\n                triangle.b == st.a || triangle.b == st.b || triangle.b == st.c ||\n                triangle.c == st.a || triangle.c == st.b || triangle.c == st.c) {\n                delete triangles[i];\n            }\n        }\n        return triangles;\n    }\n    ; // Triangulate\n    // Internal: create a triangle that bounds the given vertices, with room to spare\n    createBoundingTriangle(vertices) {\n        // NOTE: There's a bit of a heuristic here. If the bounding triangle \n        // is too large and you see overflow/underflow errors. If it is too small \n        // you end up with a non-convex hull.\n        var minx, miny, maxx, maxy;\n        for (var i in vertices) {\n            var vertex = vertices[i];\n            if (minx === undefined || vertex.x < minx) {\n                minx = vertex.x;\n            }\n            if (miny === undefined || vertex.y < miny) {\n                miny = vertex.y;\n            }\n            if (maxx === undefined || vertex.x > maxx) {\n                maxx = vertex.x;\n            }\n            if (maxy === undefined || vertex.y > maxy) {\n                maxy = vertex.y;\n            }\n        }\n        var dx = (maxx - minx) * 10;\n        var dy = (maxy - miny) * 10;\n        var stv0 = new Vertex(minx - dx, miny - dy * 3);\n        var stv1 = new Vertex(minx - dx, maxy + dy);\n        var stv2 = new Vertex(maxx + dx * 3, maxy + dy);\n        return new Triangle(stv0, stv1, stv2);\n    }\n    ; // END createBoundingTriangle\n    // Internal: update triangulation with a vertex \n    AddVertex(vertex, triangles) {\n        var edges = [];\n        // Remove triangles with circumcircles containing the vertex\n        for (var i in triangles) {\n            var triangle = triangles[i];\n            if (triangle.inCircumcircle(vertex)) {\n                edges.push(new Edge(triangle.a, triangle.b));\n                edges.push(new Edge(triangle.b, triangle.c));\n                edges.push(new Edge(triangle.c, triangle.a));\n                delete triangles[i];\n            }\n        }\n        edges = this.mkUniqueEdges(edges);\n        // Create new triangles from the unique edges and new vertex\n        for (var i in edges) {\n            // console.log( 'adding triangle' );\n            var edge = edges[i];\n            triangles.push(new Triangle(edge.a, edge.b, vertex));\n        }\n    }\n    ; // END AddVertex\n    // Internal: remove duplicate edges from an array\n    mkUniqueEdges(edges) {\n        // TODO: This is O(n^2), make it O(n) with a hash or some such\n        const uniqueEdges = [];\n        for (var i in edges) {\n            let edge1 = edges[i];\n            let unique = true;\n            for (var j in edges) {\n                if (i != j) {\n                    let edge2 = edges[j];\n                    if ((edge1.a == edge2.a && edge1.b == edge2.b) ||\n                        (edge1.a == edge2.b && edge1.b == edge2.a)) {\n                        unique = false;\n                        break;\n                    }\n                }\n            }\n            if (unique) {\n                uniqueEdges.push(edge1);\n            }\n        }\n        return uniqueEdges;\n    }\n    ; // END mkUniqueEdges\n}\n; // END class\n//# sourceMappingURL=delaunay.js.map","/**\n * A basic IO handler for file drop (Drag-and-drop).\n *\n * Example use:\n * ```javascript\n *  var body = document.getElememtByTagName(\"body\")[0];\n *  var fileDrop = new FileDrop(body);\n *    fileDrop.onFileJSONDropped(function (jsonObject) {\n *    console.log(\"jsonObject\", jsonObject);\n *  });\n * ```\n *\n * @author   Ikaros Kappler\n * @date     2021-10-13\n * @modified 2022-01-31 (ported from the ngdg project, then generalized)\n * @modified 2023-01-03 Fixing some minor type issues and adding SVG reading capabilities.\n * @version  2.1.0\n */\nexport class FileDrop {\n    /**\n     *\n     * @param {HTMLElement} element - The element you wish to operate as the drop zone (like <body/>).\n     */\n    constructor(element) {\n        /**\n         * Internally handle a drop event.\n         *\n         * @param {DragEvent} event\n         * @returns {void}\n         */\n        this.handleDropEvent = (event) => {\n            event.preventDefault();\n            event.stopPropagation();\n            this.element.style.opacity = \"1.0\";\n            if (!event.dataTransfer || !event.dataTransfer.files || event.dataTransfer.files.length === 0) {\n                // No files were dropped\n                return;\n            }\n            if (event.dataTransfer.files.length > 1) {\n                // Multiple file drop is not nupported\n                return;\n            }\n            // if (!this.fileDroppedCallbackJSON) {\n            //   // No handling callback defined.\n            //   return;\n            // }\n            if (event.dataTransfer.files[0]) {\n                const file = event.dataTransfer.files[0];\n                // console.log(\"file\", file);\n                if (file.type.match(/json.*/) && this.fileDroppedCallbackJSON !== null) {\n                    var reader = new FileReader();\n                    reader.onload = (readEvent) => {\n                        if (!readEvent.target) {\n                            console.warn(\"Cannot process JSON ProgressEvent data: target is null.\");\n                            return;\n                        }\n                        // Finished reading file data.\n                        const jsonObject = JSON.parse(readEvent.target.result);\n                        // TODO: what happens on fail?\n                        this.fileDroppedCallbackJSON && this.fileDroppedCallbackJSON(jsonObject);\n                    };\n                    reader.readAsText(file); // start reading the file data.\n                }\n                else if (file.type.match(/text\\/plain.*/) && this.fileDroppedCallbackText) {\n                    var reader = new FileReader();\n                    reader.onload = (readEvent) => {\n                        if (!readEvent.target) {\n                            console.warn(\"Cannot process Text ProgressEvent data: target is null.\");\n                            return;\n                        }\n                        // Finished reading file data.\n                        this.fileDroppedCallbackText && this.fileDroppedCallbackText(readEvent.target.result);\n                    };\n                    reader.readAsText(file); // start reading the file data.\n                }\n                else if (this.fileDroppedCallbackBinary) {\n                    var reader = new FileReader();\n                    reader.onload = (readEvent) => {\n                        if (!readEvent.target) {\n                            console.warn(\"Cannot process Binary ProgressEvent data: target is null.\");\n                            return;\n                        }\n                        // Finished reading file data.\n                        this.fileDroppedCallbackBinary &&\n                            this.fileDroppedCallbackBinary(new Blob([readEvent.target.result]), file);\n                    };\n                    reader.readAsBinaryString(file); // start reading the file data.\n                }\n                else if (this.fileDroppedCallbackSVG) {\n                    var reader = new FileReader();\n                    reader.onload = (readEvent) => {\n                        if (!readEvent.target) {\n                            console.warn(\"Cannot process SVG ProgressEvent data: target is null.\");\n                            return;\n                        }\n                        const parser = new DOMParser();\n                        const doc = parser.parseFromString(readEvent.target.result, \"image/svg+xml\");\n                        // Finished reading file data.\n                        this.fileDroppedCallbackSVG && this.fileDroppedCallbackSVG(doc);\n                    };\n                    reader.readAsText(file); // start reading the file data.\n                }\n            }\n        };\n        /**\n         * Toggles the drop sensitive element's opacity to 0.5.\n         *\n         * @param {DragEvent} event - The event.\n         */\n        this.handleDragOverEvent = (event) => {\n            event.preventDefault();\n            event.stopPropagation();\n            this.element.style.opacity = \"0.5\";\n        };\n        /**\n         * Restored the drop sensitive element's opacity back to 1.0.\n         *\n         * @param {DragEvent} event - The event.\n         */\n        this.handleDragLeaveEvent = (event) => {\n            event.preventDefault();\n            event.stopPropagation();\n            this.element.style.opacity = \"1.0\";\n        };\n        this.element = element;\n        // Init the drop listeners\n        element.addEventListener(\"drop\", this.handleDropEvent.bind(this));\n        element.addEventListener(\"dragover\", this.handleDragOverEvent.bind(this));\n        element.addEventListener(\"dragleave\", this.handleDragLeaveEvent.bind(this));\n    }\n    /**\n     * Install the JSON (MIME type json*) file drop callback. Note than only one callback can be installed\n     * in this implementation. Calling this method multiple times will overwrite previously\n     * installed listeners.\n     *\n     * The callback will receive the dropped file content as an object (parsed JSON).\n     *\n     * @param {(data:object)=>void} callback\n     */\n    onFileJSONDropped(callback) {\n        this.fileDroppedCallbackJSON = callback;\n    }\n    /**\n     * Install the text file (MIME type text/plain) drop callback. Note than only one callback can be installed\n     * in this implementation. Calling this method multiple times will overwrite previously\n     * installed listeners.\n     *\n     * The callback will receive the dropped file content as a string.\n     *\n     * @param {(data:object)=>void} callback\n     */\n    onFileTextDropped(callback) {\n        this.fileDroppedCallbackText = callback;\n    }\n    // TODO: docs\n    onFileSVGDropped(callback) {\n        this.fileDroppedCallbackSVG = callback;\n    }\n    onFileBinaryDropped(callback) {\n        this.fileDroppedCallbackBinary = callback;\n    }\n    /**\n     * Removes all listeners (drop, dragover and dragleave).\n     */\n    destroy() {\n        this.element.removeEventListener(\"drop\", this.handleDropEvent);\n        this.element.removeEventListener(\"dragover\", this.handleDragOverEvent);\n        this.element.removeEventListener(\"dragleave\", this.handleDragLeaveEvent);\n    }\n}\n//# sourceMappingURL=FileDrop.js.map","/**\n * Adapted from the 3D geometry datastuctured from demo-33 (depth mesh).\n *\n * Refactored the strucure into a class.\n *\n * @author   Ikaros Kappler\n * @date     2025-11-14\n * @modified 2025-11-17 Moved `getBounds` and `normalizeGeometry` from helper functions to this class.\n * @version  1.0.0\n */\nexport class GeometryMesh {\n    constructor(vertices, edges) {\n        this.vertices = vertices || [];\n        this.edges = edges || [];\n    }\n    normalize() {\n        // Desired bounds is a max bounding box. The object will be scaled keeping aspect ratio\n        // in that way that the largest axis size touches the desired bounds.\n        var desiredBounds = { min: { x: -1, y: -1, z: -1 }, max: { x: 1, y: 1, z: 1 } };\n        var bounds = this.getGeometryBounds();\n        var sizeX = bounds.max.x - bounds.min.x;\n        var sizeY = bounds.max.y - bounds.min.y;\n        var sizeZ = bounds.max.z - bounds.min.z;\n        // Scale uniform so the dimension with the max expansion fits into [-1,1]\n        var maxDimension = Math.max(sizeX, sizeY, sizeZ);\n        var desiredSizeX = (desiredBounds.max.x - desiredBounds.min.x) / maxDimension;\n        var desiredSizeY = (desiredBounds.max.y - desiredBounds.min.y) / maxDimension;\n        var desiredSizeZ = (desiredBounds.max.z - desiredBounds.min.z) / maxDimension;\n        for (var i in this.vertices) {\n            var vert = this.vertices[i]; // TODO: Check if this is safe\n            vert.x = desiredBounds.min.x + (bounds.max.x - vert.x) * desiredSizeX;\n            vert.y = desiredBounds.min.y + (bounds.max.y - vert.y) * desiredSizeY;\n            vert.z = desiredBounds.min.z + (bounds.max.z - vert.z) * desiredSizeZ;\n        }\n    }\n    getGeometryBounds() {\n        // var min = new Vert3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);\n        // var max = new Vert3(Number.MIN_VALUE, Number.MIN_VALUE, Number.MIN_VALUE);\n        var min = { x: Number.MAX_VALUE, y: Number.MAX_VALUE, z: Number.MAX_VALUE };\n        var max = { x: Number.MIN_VALUE, y: Number.MIN_VALUE, z: Number.MIN_VALUE };\n        for (var i in this.vertices) {\n            var vert = this.vertices[i];\n            min.x = Math.min(vert.x, min.x);\n            min.y = Math.min(vert.y, min.y);\n            min.z = Math.min(vert.z, min.z);\n            max.x = Math.max(vert.x, max.x);\n            max.y = Math.max(vert.y, max.y);\n            max.z = Math.max(vert.z, max.z);\n        }\n        return { min: min, max: max, width: max.x - min.x, height: max.y - min.y, depth: max.z - min.z };\n    }\n}\n//# sourceMappingURL=GeometryMesh.js.map","/**\n * @author   Ikaros Kappler\n * @date     2020-11-24\n * @modified 2020-11-25 Ported to TypeScript from vanilla JS.\n * @modified 2024-03-10 Fixed some types for Typescript 5 compatibility.\n * @modified 2026-01-06 Added method `Girih.locateContainingTileAndEdge` to locate tile/edge pairs.\n * @modified 2026-01-12 Added method `Girih.getTileByCenter` to locate tiles by position.\n * @modified 2026-01-18 Added method `Girih.removeAllTiles`.\n * @version  1.1.0\n * @file     Girih\n **/\nimport { Vertex } from \"../../Vertex\";\nimport { GirihBowtie } from \"./GirihBowtie\";\nimport { GirihDecagon } from \"./GirihDecagon\";\nimport { GirihHexagon } from \"./GirihHexagon\";\nimport { GirihPenroseRhombus } from \"./GirihPenroseRhombus\";\nimport { GirihPentagon } from \"./GirihPentagon\";\nimport { GirihRhombus } from \"./GirihRhombus\";\n/**\n * @classdesc The Girih datastructure for generating patterns.\n *\n * @requires Vertex\n * @requires GirihTile\n * @requires GirihBowtie\n * @requires GirihDecagon\n * @requires GirihHexagon\n * @requires GirihPenroseRhombus\n * @requires GirihPentagon\n * @requires GirihRhombus\n */\nexport class Girih {\n    /**\n     * Create a new empty Girih pattern.\n     *\n     * @constructor\n     * @memberof Girih\n     * @param {number} edgeLength\n     */\n    constructor(edgeLength) {\n        this.edgeLength = edgeLength;\n        // Initialize templates, one for each Girih tile type.\n        // The template array will be filled on initialization (see below).\n        this.TILE_TEMPLATES = [];\n        // The set of all Girih tiles in scene\n        this.tiles = [];\n        this.initTemplates(edgeLength);\n    }\n    /**\n     * Initialize the TILE_TEMPLATES array.\n     *\n     * @name initTemplates\n     * @private\n     * @memberof Girih\n     * @instance\n     * @param {number} edgeLength - The edge length to use for the template tiles.\n     * @return {void}\n     */\n    initTemplates(edgeLength) {\n        // Positions actually don't matter here.\n        // Tiles will be moved to correct position conerning adjacency.\n        var decagon = new GirihDecagon(new Vertex(0, 0), edgeLength);\n        var pentagon = new GirihPentagon(new Vertex(0, 0), edgeLength);\n        var hexagon = new GirihHexagon(new Vertex(0, 0), edgeLength);\n        var bowtie = new GirihBowtie(new Vertex(0, 0), edgeLength);\n        var rhombus = new GirihRhombus(new Vertex(0, 0), edgeLength);\n        var penrose = new GirihPenroseRhombus(new Vertex(0, 0), edgeLength, true); // Add center polygon\n        // Add tiles to array and put them in the correct adjacency position.\n        this.TILE_TEMPLATES.push(decagon);\n        this.TILE_TEMPLATES.push(decagon.transformTilePositionToAdjacency(2, pentagon));\n        this.TILE_TEMPLATES.push(pentagon.transformTilePositionToAdjacency(1, penrose));\n        this.TILE_TEMPLATES.push(penrose.transformTilePositionToAdjacency(3, hexagon));\n        this.TILE_TEMPLATES.push(decagon.transformTilePositionToAdjacency(5, bowtie));\n        this.TILE_TEMPLATES.push(pentagon.transformTilePositionToAdjacency(4, rhombus));\n    }\n    /**\n     * Add a new tile to this Girih pattern.\n     *\n     * @name addTile\n     * @memberof Girih\n     * @instance\n     * @param {GirihTile} tile - The tile to add (instance must not already be part of this pattern).\n     * @return {void}\n     */\n    addTile(tile) {\n        this.tiles.push(tile);\n    }\n    /**\n     * Remove the tile at given array position. The index must be inside valid bounds.\n     *\n     * @name removeTile\n     * @memberof Girih\n     * @instance\n     * @param {number} index - The index in the `tiles` Array.\n     * @return {void}\n     */\n    removeTileAt(index) {\n        this.tiles.splice(index, 1);\n    }\n    /**\n     * Remove all tiles.\n     *\n     * @name removeAllTiles\n     * @memberof Girih\n     * @instance\n     * @return {void}\n     */\n    removeAllTiles() {\n        this.tiles.splice(0, this.tiles.length);\n    }\n    /**\n     * Replace all current tiles with the given ones.\n     *\n     * @param tiles\n     */\n    replaceTiles(tiles) {\n        this.tiles.splice(0, this.tiles.length);\n        for (var i in tiles) {\n            this.addTile(tiles[i]);\n        }\n    }\n    /**\n     * Find the tile with the given center.\n     *\n     * @name getTileByCenter\n     * @memberof Girih\n     * @instance\n     * @param {XYCoords} center - The center point to look for.\n     * @return {GirihTile} The tile or null if not found.\n     */\n    getTileByCenter(center) {\n        for (var i = 0; i < this.tiles.length; i++) {\n            const pos = this.tiles[i].position;\n            if (pos === center || (pos.x == center.x && pos.y == center.y)) {\n                return this.tiles[i];\n            }\n        }\n        return null;\n    }\n    /**\n     * Find that tile (index) which contains the given position. First match will be returned.\n     *\n     * @name locateContainingTile\n     * @memberof Girih\n     * @instance\n     * @param {Vertex} position\n     * @return {number} The index of the containing tile or -1 if none was found.\n     **/\n    locateConatiningTile(position) {\n        for (var i = 0; i < this.tiles.length; i++) {\n            if (this.tiles[i].containsVert(position))\n                return i;\n        }\n        return -1;\n    }\n    /**\n     * Find find a tile-edge-pair (indices) that contain the given position. First match will be returned.\n     *\n     * @name locateContainingTileAndEdge\n     * @memberof Girih\n     * @instance\n     * @param {Vertex} position\n     * @return {{ tileIndex: number; edgeIndex: number }} The index of the containing tile and edge or null if none was found.\n     **/\n    locateContainingTileAndEdge(position) {\n        var containedTileIndex = this.locateConatiningTile(position);\n        // Reset currently highlighted tile/edge (if re-detected nothing changed in the end)\n        var hoverTileIndex = -1;\n        var hoverEdgeIndex = -1;\n        // Find Girih edge nearby ...\n        if (containedTileIndex == -1) {\n            return null;\n        }\n        var i = containedTileIndex;\n        do {\n            var tile = this.tiles[i];\n            // May be -1\n            hoverEdgeIndex = tile.locateEdgeAtPoint(position, this.edgeLength / 2);\n            if (hoverEdgeIndex != -1) {\n                hoverTileIndex = i;\n            }\n            i++;\n        } while (i < this.tiles.length && containedTileIndex == -1 && hoverEdgeIndex == -1);\n        if (hoverTileIndex == -1) {\n            hoverTileIndex = containedTileIndex;\n        }\n        // Find the next possible tile to place?\n        if (hoverTileIndex == -1 || hoverEdgeIndex == -1) {\n            return null;\n        }\n        return { tileIndex: hoverTileIndex, edgeIndex: hoverEdgeIndex };\n    }\n    /**\n     * Turn the tile the mouse is hovering over.\n     * The turnCount is ab abstract number: -1 for one turn left, +1 for one turn right.\n     * The turning angle is defined by the tile with the lowest turn symmetry: the Decagon,\n     * so angle is 36°.\n     *\n     * @name turnTile\n     * @memberof Girih\n     * @instance\n     * @param {number} tileIndex - The index of the tile to rotate.\n     * @param {number} turnCount - A discrete number indicating the number of turn steps.\n     * @return {void}\n     */\n    turnTile(tileIndex, turnCount) {\n        if (tileIndex == -1)\n            // TODO: still required?\n            return;\n        const tile = this.tiles[tileIndex];\n        tile.rotate((turnCount * Math.PI * 2) / tile.symmetry);\n    }\n    /**\n     * Move that tile the mouse is hovering over.\n     * The move amounts are abstract numbers, 1 indicating one unit along each axis.\n     *\n     * @name moveTile\n     * @memberof Girih\n     * @instance\n     * @param {number} tileIndex - The index of the tile to rotate.\n     * @param {number} moveXAmount - The amount to move along the x axis (in pixels).\n     * @param {number} moveYAmount - The amount to move along the y axis (in pixels).\n     * @return {void}\n     */\n    moveTile(tileIndex, moveXAmount, moveYAmount) {\n        if (tileIndex == -1)\n            // TODO: still required?\n            return;\n        const tile = this.tiles[tileIndex];\n        tile.move({ x: moveXAmount * 10, y: moveYAmount * 10 });\n    }\n    /**\n     * Find all possible adjadent tiles and their locations (type, rotation and offset). The\n     * function will return an array of all possible tiles matching at the given tile and edge.\n     *\n     * @name findPossibleAdjacentTiles\n     * @memberof Girih\n     * @instance\n     * @param {number} tileIndex - The index of the tile to rotate.\n     * @param {number} edgeIndex - The index of the tile's edge.\n     * @return {Array<GirihTile>} - An array of possible adjecent tiles (already positioned and rotated).\n     */\n    findPossibleAdjacentTiles(tileIndex, edgeIndex) {\n        var adjTiles = [];\n        if (tileIndex == -1 || edgeIndex == -1)\n            // TODO: still required?\n            return [];\n        let template = null;\n        for (var i in this.TILE_TEMPLATES) {\n            template = this.TILE_TEMPLATES[i].clone();\n            // Find all rotations and positions for that tile to match\n            const foundTiles = this.tiles[tileIndex].transformTileToAdjacencies(edgeIndex, template);\n            if (foundTiles.length != 0) {\n                adjTiles = adjTiles.concat(foundTiles);\n            }\n        }\n        // Set pointer to save range.\n        // previewTilePointer = Math.min( adjTiles.length-1, previewTiilePointer );\n        return adjTiles;\n    }\n} // END class Girih\n//# sourceMappingURL=Girih.js.map","/**\n * Approach to observe objects from other scripts to be initialized.\n *\n * @author  Ikaros Kappler\n * @date    2024-07-08\n * @version 1.0.0\n */\nexport class InitializationObserver {\n    constructor(timeout, timeoutMessage) {\n        this._acceptRejectPairs = [];\n        this._timeoutMessage = timeoutMessage !== null && timeoutMessage !== void 0 ? timeoutMessage : null;\n        globalThis.setTimeout(() => {\n            var _a;\n            if (this._isInitialized) {\n                return; // NOOP\n            }\n            // else\n            if (!this._timeoutMessage) {\n                console.warn(\"Failed to initialize object. Reason unknown.\");\n            }\n            this._fireReject((_a = this._timeoutMessage) !== null && _a !== void 0 ? _a : null);\n        }, timeout);\n    }\n    accept(value) {\n        if (this._isInitialized) {\n            return;\n        }\n        this._isInitialized = true;\n        this._initializedValue = value;\n        this._fireAccept(value);\n    }\n    _fireAccept(value) {\n        this._acceptRejectPairs.forEach(pair => {\n            pair.accept(value);\n        });\n    }\n    _fireReject(error) {\n        this._acceptRejectPairs.forEach(pair => {\n            pair.reject(error);\n        });\n    }\n    waitForInitialized() {\n        const _self = this;\n        // If the value is already present, then accept immediately\n        if (_self._isInitialized) {\n            return new Promise((accept, reject) => {\n                accept(_self._initializedValue);\n            });\n        }\n        else {\n            return new Promise((accept, reject) => {\n                _self._acceptRejectPairs.push({ accept, reject });\n            });\n        }\n    }\n}\n//# sourceMappingURL=InitializationObserver.js.map","/**\n * A wrapper for Lissajous figure params.\n *\n * @author   Ikaros Kappler\n * @date     2018-11-22\n * @modified 2025-10-29 Ported to typescript from demo 13-lissajous.\n * @version  1.0.0\n */\nimport { Vertex } from \"../Vertex\";\nexport class LissajousFigure {\n    /**\n     * Create a new figure with the given settings.\n     * @param {number} freqA - The 'horizontal' frequency.\n     * @param {number} freqB - The 'vertical' frequency.\n     * @param {number} phaseA - The 'horizonal' phase shift.\n     * @param {number} phaseB - The 'vertical' phase shift.\n     */\n    constructor(freqA, freqB, phaseA, phaseB) {\n        this.freqA = freqA;\n        this.freqB = freqB;\n        this.phaseA = phaseA;\n        this.phaseB = phaseB;\n    }\n    /**\n     * Get the point at the given abstract time.\n     *\n     * The result is periodic in 0..TWO_PI.\n     *\n     * @param {number} t - The timing value (for example milliseconds).\n     * @returns {Vertex} The x-y-position on the Lissajous figure at the given time.\n     */\n    getPointAt(t) {\n        return new Vertex(Math.sin(this.phaseA + this.freqA * t), Math.sin(this.phaseB + this.freqB * t));\n    }\n    toPolyLine(stepSize) {\n        const polyLine = [];\n        let pA = new Vertex(0, 0);\n        stepSize = Math.abs(stepSize);\n        for (var t = 0; t <= 2 * Math.PI; t += stepSize) {\n            pA = this.getPointAt(t);\n            polyLine.push(pA.clone());\n        }\n        return polyLine;\n    }\n    toQuadraticBezierApproximation(stepSize\n    // scale: number\n    // alternating: boolean\n    ) {\n        const result = [];\n        let pA = new Vertex(0, 0);\n        let pB = new Vertex(0, 0);\n        stepSize = Math.abs(stepSize);\n        let p1 = new Vertex(0, 0);\n        let dx1 = this.freqA;\n        let dy1 = this.freqB;\n        pA = this.getPointAt(stepSize);\n        let x2, y2, dx2, dy2, det, x3, y3;\n        var i = 0;\n        for (var t = stepSize; t <= 2 * Math.PI + 2 * stepSize; t += stepSize) {\n            x2 = Math.sin(this.phaseA + this.freqA * t);\n            y2 = Math.sin(this.phaseB + this.freqB * t);\n            dx2 = this.freqA * Math.cos(this.phaseA + this.freqA * t);\n            dy2 = this.freqB * Math.cos(this.phaseB + this.freqB * t);\n            det = dx1 * dy2 - dy1 * dx2;\n            if (Math.abs(det) > 0.1) {\n                x3 = ((x2 * dy2 - y2 * dx2) * dx1 - (p1.x * dy1 - p1.y * dx1) * dx2) / det;\n                y3 = ((x2 * dy2 - y2 * dx2) * dy1 - (p1.x * dy1 - p1.y * dx1) * dy2) / det;\n                // pB.set(scale * x2, scale * y2 * (alternating ? -1 : 1));\n                // pB.set(scale * x2, scale * y2);\n                pB.set(x2, y2);\n                // pB.set(x2, y2);\n                if (i > 0) {\n                    //   pb.draw.quadraticBezier(pA, new Vertex(scale * x3, scale * y3), pB, \"rgba(0,108,255,1.0)\", 2);\n                    //   result.push([pA.clone(), new Vertex(scale * x3, scale * y3), pB.clone()]);\n                    result.push([pA.clone(), new Vertex(x3, y3), pB.clone()]);\n                }\n            }\n            else {\n                // pB.set(scale * x2, scale * y2);\n                pB.set(x2, y2);\n                if (i > 0) {\n                    //   pb.draw.line(pA, pB, \"rgba(0,192,192,0.8)\", 2);\n                    result.push([pA.clone(), pB.clone()]);\n                }\n            }\n            p1.set(x2, y2);\n            dx1 = dx2;\n            dy1 = dy2;\n            pA.set(pB);\n            i++;\n        } // END for\n        return result;\n    }\n}\n//# sourceMappingURL=LissajousFigure.js.map","/**\n * Algorithm:\n *  Input Circles\n *      -> filter out fully contained circles\n *      -> build outer containing circles (given by detect radius)\n *      -> find radical lines\n *\n * This implementation currently does not detect any holes.\n *\n * @author  Ikaros Kappler\n * @version 1.0.0\n * @date    2024-03-01\n */\nimport { Circle } from \"../../Circle\";\nimport { CircleIntersections } from \"./CircleIntersections\";\nexport class Metaballs {\n    constructor(inputCircles) {\n        this.circleIsFullyContained = []; // Array<boolean>\n        this.inputCircles = [];\n        this.circlesOfInterest = [];\n        this.containingCircles = [];\n        // Array< { baseCircleIndexA, baseCircleIndexB,\n        //          baseCircleA, baseCircleB,\n        //          circleA, circleB,\n        //          inverseCircleA, inverseCircleB,\n        //          doIntersect, circlePointsA:[], circlePointsB:[] } >\n        this.inverseCirclesPairs = [];\n        this.inputCircles = inputCircles;\n    }\n    rebuild(options) {\n        this.detectContainmentStatus();\n        this.rebuildContainingCircles(options);\n        this.inverseCirclesPairs = [];\n        const radicalLineMatrix = CircleIntersections.buildRadicalLineMatrix(this.containingCircles);\n        for (var i = 0; i < this.containingCircles.length; i++) {\n            var circleA = this.containingCircles[i];\n            var centerCircleA = this.circlesOfInterest[i];\n            for (var j = i + 1; j < this.containingCircles.length; j++) {\n                var radicalLine = radicalLineMatrix[i][j];\n                if (radicalLine == null) {\n                    // The two circles do not have an intersection.\n                    // console.log(\"Circles\", i, j, \"do not have any intersections\");\n                    continue;\n                }\n                var circleB = this.containingCircles[j];\n                var centerCircleB = this.circlesOfInterest[j];\n                // But if they have -> compute. outer circle(s).\n                // They are symmetrical.\n                var inverseCircle1 = new Circle(radicalLine.a, options.metaRadiusAddon);\n                var inverseCircle2 = new Circle(radicalLine.b, options.metaRadiusAddon);\n                var doIntersect = inverseCircle1.circleIntersection(inverseCircle2) != null;\n                // console.log(\"doIntersect\", doIntersect);\n                // Now find the intersection points between inner and outer circles.\n                // We will need them later.\n                var circlePointsA = [\n                    centerCircleA.closestPoint(inverseCircle1.center),\n                    centerCircleA.closestPoint(inverseCircle2.center)\n                ];\n                var circlePointsB = [\n                    centerCircleB.closestPoint(inverseCircle1.center),\n                    centerCircleB.closestPoint(inverseCircle2.center)\n                ];\n                this.inverseCirclesPairs.push({\n                    baseCircleIndexA: i,\n                    baseCircleIndexB: j,\n                    baseCircleA: this.circlesOfInterest[i],\n                    baseCircleB: this.circlesOfInterest[j],\n                    circleA: circleA,\n                    inverseCircleA: inverseCircle1,\n                    circleB: circleB,\n                    inverseCircleB: inverseCircle2,\n                    doIntersect: doIntersect,\n                    circlePointsA: circlePointsA,\n                    circlePointsB: circlePointsB\n                });\n            } // END for j\n        } // END for i\n    }\n    //   public getInnerPath;\n    checkCircleFullyContained(circleIndex) {\n        for (var i = 0; i < this.inputCircles.length; i++) {\n            if (circleIndex == i) {\n                continue;\n            }\n            if (this.inputCircles[i].containsCircle(this.inputCircles[circleIndex])) {\n                return true;\n            }\n        }\n        return false;\n    }\n    detectContainmentStatus() {\n        this.circleIsFullyContained = [];\n        this.circlesOfInterest = [];\n        for (var i = 0; i < this.inputCircles.length; i++) {\n            this.circleIsFullyContained[i] = this.checkCircleFullyContained(i);\n            if (!this.circleIsFullyContained[i]) {\n                this.circlesOfInterest.push(this.inputCircles[i]);\n            }\n        }\n    }\n    rebuildContainingCircles(options) {\n        this.containingCircles = [];\n        for (var i = 0; i < this.circlesOfInterest.length; i++) {\n            var containingCircle = new Circle(this.circlesOfInterest[i].center, this.circlesOfInterest[i].radius + options.metaRadiusAddon);\n            this.containingCircles.push(containingCircle);\n        }\n    }\n}\n//# sourceMappingURL=Metaballs.js.map","/**\n * A simple wavefront OBJ parser.\n *\n * Inspired by\n *    https://webglfundamentals.org/webgl/lessons/webgl-load-obj.html\n *\n * @param {*} handleVert\n * @param {*} handleFace\n *\n * @author Ikaros Kappler\n * @date 2021-04-21\n * @version 0.0.1\n */\nexport class OBJParser {\n    constructor(handleVert, handleFace) {\n        this.handleVert = handleVert;\n        this.handleFace = handleFace;\n    }\n    _seekEOL(byteView, curPosition) {\n        // Seek line break character (13)\n        while (curPosition < byteView.length && byteView[curPosition] !== 13 && byteView[curPosition] !== 10) {\n            curPosition++;\n        }\n        return curPosition;\n    }\n    _handleLine(line, lineNo) {\n        if (line === \"\" || line.startsWith(\"#\")) {\n            return;\n        }\n        var split = line.split(/\\s+/g);\n        if (split[0] === \"v\") {\n            // Parse string of form\n            // 'v x y z'\n            if (split.length < 4) {\n                console.warn(\"Parse error in line \" + lineNo + \": too few arguments\", line);\n                return;\n            }\n            // Assume all params are proper numbers.\n            this.handleVert(Number(split[1]), Number(split[2]), Number(split[3]));\n        }\n        else if (split[0] === \"f\") {\n            // Parse string of form\n            // 'f vA vB vC' or 'f vA/tA vB/tB vC/tC' or 'f vA/tA/nA vB/tB/nB vC/tC/nC'\n            if (split.length < 4) {\n                console.warn(\"Parse error in line \" + lineNo + \": too few arguments\", line);\n                return;\n            }\n            // Split each face argument into parts (vert-index/texture-coordindate/normal)\n            var faceParams = [];\n            for (var i = 1; i < 4; i++) {\n                var faceSplit = split[i].split(\"/\");\n                faceParams.push(Number(faceSplit[0]));\n            }\n            this.handleFace(faceParams[0], faceParams[1], faceParams[2]);\n        }\n    }\n    parse(arrayBuffer) {\n        const byteView = new Int8Array(arrayBuffer);\n        var curStart = 0;\n        var curEnd = 0;\n        var lineNo = 0;\n        do {\n            curEnd = this._seekEOL(byteView, curStart);\n            var lineBuffer = byteView.slice(curStart, curEnd); // .toString();\n            var line = String.fromCharCode.apply(null, lineBuffer);\n            this._handleLine(line.trim(), lineNo);\n            curStart = curEnd + 1;\n            lineNo++;\n        } while (curEnd < arrayBuffer.byteLength);\n    }\n}\n//# sourceMappingURL=OBJParser.js.map","/**\n * Wraps a Record<string,string> and adds type conversion methods (developed this in\n * some other project) and added this here (2023-10-28).\n *\n * @author   Ikars Kappler\n * @version  1.0.0\n * @date     2023-03-13\n * @modified 2024-08-26 Added the `hasParam` method.\n * @modified 2026-05-22 Added the `isValueAllowed` function param to the getter methods.\n */\nexport class Params {\n    constructor(baseParams) {\n        this.baseParams = baseParams;\n    }\n    hasParam(name) {\n        return this.baseParams.hasOwnProperty(name);\n    }\n    getString(name, fallback, isValueAllowed) {\n        let value = this.baseParams[name];\n        if (typeof value === \"undefined\" || !value || (value = value.trim()).length === 0) {\n            return fallback;\n        }\n        if (isValueAllowed && !isValueAllowed(value)) {\n            return fallback;\n        }\n        return value;\n    }\n    getNumber(name, fallback, isValueAllowed) {\n        let value = this.baseParams[name];\n        if (typeof value === \"undefined\" || !value || (value = value.trim()).length === 0) {\n            return fallback;\n        }\n        var numericValue = Number(value);\n        if (isValueAllowed && !isValueAllowed(numericValue)) {\n            return fallback;\n        }\n        return numericValue;\n    }\n    getBoolean(name, fallback) {\n        let value = this.baseParams[name];\n        if (typeof value === \"undefined\" || !value || (value = value.trim()).length === 0) {\n            return fallback;\n        }\n        value = value.toLocaleLowerCase();\n        if (value === \"1\" || value === \"on\" || value === \"yes\" || value === \"y\" || value === \"hi\" || value == \"high\") {\n            return true;\n        }\n        else if (value === \"0\" || value === \"off\" || value === \"no\" || value === \"n\" || value === \"lo\" || value == \"low\") {\n            return false;\n        }\n        else {\n            return Boolean(value);\n        }\n    }\n}\n//# sourceMappingURL=Params.js.map","/**\n * Easily handle triangles with this triangle interaction helper: always keep your\n * triangles equilateral.\n *\n * @author   Ikaros Kappler\n * @date     2025-05-05\n * @version  1.0.0\n **/\nimport { Vector } from \"../../Vector\";\n/**\n * @classdesc A helper for handling circles with an additional radius-control-point.\n */\nexport class TriangleHelper {\n    /**\n     * The constructor.\n     *\n     * @constructor\n     * @name TriangleHelper\n     * @param {Triangle} triangle - The triangle to handle.\n     * @param {Vertex} radiusPoint - A point to define the radius (distance from center).\n     * @param {PlotBoilerplate} pb - The PlotBoilerplate which contains the circle and point.\n     **/\n    constructor(triangle, setInitiallyEquilateral) {\n        this.triangle = triangle;\n        triangle.a.listeners.addDragListener((this.handlerA = this._handleTrianglePoint(this.triangle.a, this.triangle.b, this.triangle.c)));\n        triangle.b.listeners.addDragListener((this.handlerB = this._handleTrianglePoint(this.triangle.b, this.triangle.c, this.triangle.a)));\n        triangle.c.listeners.addDragListener((this.handlerC = this._handleTrianglePoint(this.triangle.c, this.triangle.a, this.triangle.b)));\n        // Trigger to set equilateral\n        if (setInitiallyEquilateral) {\n            this.handlerC(null); // We know by construction that _here_ the param is optional!\n        }\n    }\n    //--- BEGIN --- Implement ISHapeInteractionHelper ---\n    /**\n     * Let this shape helper draw it's handle lines. It's up to the helper what they look like.\n     * @param {DrawLib<any>} draw - The draw library to use.\n     * @param {DrawLib<any>} fill - The fill library to use.\n     */\n    drawHandleLines(_draw, _fill) {\n        // NOOP\n    }\n    /**\n     * Destroy this circle helper.\n     * The listeners will be removed from the circle points.\n     *\n     * @method destroy\n     * @instance\n     * @memberof TriangleHelper\n     */\n    destroy() {\n        this.triangle.a.listeners.removeDragListener(this.handlerA);\n        this.triangle.b.listeners.removeDragListener(this.handlerB);\n        this.triangle.c.listeners.removeDragListener(this.handlerC);\n    }\n    //--- END --- Implement ISHapeInteractionHelper ---\n    /**\n     * Creates a new drag handler for the circle's radius control point.\n     *\n     * @private\n     * @method _handleDragCenter\n     * @instance\n     * @memberof TriangleHelper\n     * @returns A new event handler.\n     */\n    _handleTrianglePoint(vertex1, vertex2, vertex3) {\n        const _self = this;\n        return (_evt) => {\n            //   _self.circle.radius = _self.circle.center.distance(_self.radiusPoint);\n            // Calculate new side length: set equialateral\n            const vec = new Vector(vertex1, vertex2);\n            const mid = vec.vertAt(0.5);\n            const perp = vec.perp().add(mid).sub(vec.a);\n            perp.setLength((vec.length() * Math.sqrt(3)) / 2); // The height of a equilateral triangle\n            vertex3.set(perp.b);\n        };\n    }\n}\n//# sourceMappingURL=TriangleHelper.js.map","/**\n * A helper for VEllipses.\n *\n * @author   Ikaros Kappler\n * @date     2025-03-31\n * @modified 2025-04-02 Adding `VEllipseHelper.drawHandleLines()`.\n * @modified 2025-04-09 Adding `VEllipseHelper.destroy()`.\n * @modified 2025-05-05 Fixed a typo in the `VEllipseHelper.destroy` method (was named `detroy`).\n * @modified 2025-05-05 `VEllipseHelper` is now implementing `IShapeInteractionHelper`.\n * @version  1.0.1\n */\nimport { Line } from \"../../Line\";\nexport class VEllipseHelper {\n    constructor(ellipse, rotationControlPoint) {\n        this.ellipse = ellipse;\n        this.rotationControlPoint = rotationControlPoint;\n        // const rotationControlLine: Line = new Line(ellipse.center, rotationControlPoint);\n        this._rotationControlLine = new Line(ellipse.center, rotationControlPoint);\n        // +---------------------------------------------------------------------\n        // | Listen for the center to be moved.\n        // +-------------------------------------------\n        // ellipse.center.listeners.addDragListener((event: VertEvent) => {\n        //   rotationControlPoint.add(event.params.dragAmount);\n        // });\n        ellipse.center.listeners.addDragListener((this._centerPointHandler = this._handleDragCenterPoint()));\n        // +---------------------------------------------------------------------\n        // | Listen for rotation changes.\n        // +-------------------------------------------\n        // rotationControlPoint.listeners.addDragListener((_event: VertEvent) => {\n        //   var newRotation = rotationControlLine.angle();\n        //   var rDiff = newRotation - ellipse.rotation;\n        //   ellipse.rotation = newRotation;\n        //   ellipse.axis.rotate(rDiff, ellipse.center);\n        // });\n        rotationControlPoint.listeners.addDragListener((this._rotationPointHandler = this._handleRotationCenterPoint()));\n    }\n    _handleDragCenterPoint() {\n        const _self = this;\n        return (event) => {\n            _self.rotationControlPoint.add(event.params.dragAmount);\n        };\n    }\n    _handleRotationCenterPoint() {\n        const _self = this;\n        return (_event) => {\n            var newRotation = _self._rotationControlLine.angle();\n            var rDiff = newRotation - _self.ellipse.rotation;\n            _self.ellipse.rotation = newRotation;\n            _self.ellipse.axis.rotate(rDiff, _self.ellipse.center);\n        };\n    }\n    /**\n     * Draw grey handle lines.\n     *\n     * @param {DrawLib<any>} draw - The draw library instance to use.\n     * @param {DrawLib<any>} fill - The fill library instance to use.\n     */\n    drawHandleLines(draw, fill) {\n        // Draw rotation handle line\n        draw.line(this.ellipse.center, this.rotationControlPoint, \"rgba(192,64,128,0.333)\", 1.0, {\n            dashOffset: 0.0,\n            dashArray: [4, 2]\n        });\n        // Draw helper box\n        draw.setCurrentId(`${this.ellipse.uid}_e0`);\n        draw.setCurrentClassName(`${this.ellipse.className}-v-line`);\n        draw.line(this.ellipse.center.clone().add(0, this.ellipse.signedRadiusV()).rotate(this.ellipse.rotation, this.ellipse.center), this.ellipse.axis, \"rgba(64,128,192,0.333)\", 1.0, {\n            dashOffset: 0.0,\n            dashArray: [4, 2]\n        });\n        draw.setCurrentId(`${this.ellipse.uid}_e1`);\n        draw.setCurrentClassName(`${this.ellipse.className}-h-line`);\n        draw.line(this.ellipse.center.clone().add(this.ellipse.signedRadiusH(), 0).rotate(this.ellipse.rotation, this.ellipse.center), this.ellipse.axis, \"rgba(64,128,192,0.333)\", 1.0, {\n            dashOffset: 0.0,\n            dashArray: [4, 2]\n        });\n    }\n    destroy() {\n        this.ellipse.center.listeners.removeDragListener(this._centerPointHandler);\n        this.rotationControlPoint.listeners.removeDragListener(this._rotationPointHandler);\n    }\n}\n//# sourceMappingURL=VEllipseHelper.js.map","/**\n * A helper for VEllipseSectors.\n *\n * @author   Ikaros Kappler\n * @date     2021-03-24\n * @modified 2025-04-02 Adding `VEllipseSectorHelper.drawHandleLines`.\n * @modified 2025-04-07 Modifying the calculation of `startAngle` and `endAngle` from the rotation control point: wrapping result into [0,TWO_PI).\n * @modified 2025-04-09 Adding the `VEllipseSectorHelper.destroy` method.\n * @modified 2025-05-05 `VEllipseSectorHelper` is now implementing `IShapeInteractionHelper`.\n * @version  1.1.0\n */\nimport { Line } from \"../../Line\";\nimport { geomutils } from \"../../geomutils\";\nexport class VEllipseSectorHelper {\n    constructor(sector, startAngleControlPoint, endAngleControlPoint, rotationControlPoint) {\n        this.sector = sector;\n        this.startAngleControlPoint = startAngleControlPoint;\n        this.endAngleControlPoint = endAngleControlPoint;\n        this.rotationControlPoint = rotationControlPoint;\n        // const rotationControlLine: Line = new Line(sector.ellipse.center, rotationControlPoint);\n        this._rotationControlLine = new Line(sector.ellipse.center, rotationControlPoint);\n        // const startAngleControlLine: Line = new Line(sector.ellipse.center, startAngleControlPoint);\n        this._startAngleControlLine = new Line(sector.ellipse.center, startAngleControlPoint);\n        // const endAngleControlLine: Line = new Line(sector.ellipse.center, endAngleControlPoint);\n        this._endAngleControlLine = new Line(sector.ellipse.center, endAngleControlPoint);\n        // +---------------------------------------------------------------------\n        // | Listen for the center to be moved.\n        // +-------------------------------------------\n        sector.ellipse.center.listeners.addDragListener((this._centerHandler = this._handleDragCenterPoint()));\n        // +---------------------------------------------------------------------\n        // | Listen for rotation changes.\n        // +-------------------------------------------\n        rotationControlPoint.listeners.addDragListener((this._rotationHandler = this._handleDragRotationControlPoint()));\n        // +---------------------------------------------------------------------\n        // | Listen for start angle changes.\n        // +-------------------------------------------\n        startAngleControlPoint.listeners.addDragListener((this._startAngleHandler = this._handleDragStartAngleControlPoint()));\n        // +---------------------------------------------------------------------\n        // | Listen for end angle changes.\n        // +-------------------------------------------\n        endAngleControlPoint.listeners.addDragListener((this._endAngleHandler = this._handleDragEndAngleControlPoint()));\n    }\n    /**\n     * Creates a new drag handler for the circle sector's start control point.\n     *\n     * @private\n     * @method _handleDragStartControlPoint\n     * @instance\n     * @memberof CircleSectorHelper\n     * @returns A new event handler.\n     */\n    _handleDragCenterPoint() {\n        const _self = this;\n        return (event) => {\n            _self.startAngleControlPoint.add(event.params.dragAmount);\n            _self.endAngleControlPoint.add(event.params.dragAmount);\n            _self.rotationControlPoint.add(event.params.dragAmount);\n        };\n    }\n    _handleDragRotationControlPoint() {\n        const _self = this;\n        return (event) => {\n            const newRotation = _self._rotationControlLine.angle();\n            const rDiff = newRotation - _self.sector.ellipse.rotation;\n            _self.sector.ellipse.rotation = newRotation;\n            _self.sector.ellipse.axis.rotate(rDiff, _self.sector.ellipse.center);\n            _self.startAngleControlPoint.rotate(rDiff, _self.sector.ellipse.center);\n            _self.endAngleControlPoint.rotate(rDiff, _self.sector.ellipse.center);\n        };\n    }\n    _handleDragStartAngleControlPoint() {\n        const _self = this;\n        return (_event) => {\n            // sector.startAngle = startAngleControlLine.angle() - sector.ellipse.rotation;\n            _self.sector.startAngle = geomutils.mapAngleTo2PI(_self._startAngleControlLine.angle() - _self.sector.ellipse.rotation);\n        };\n    }\n    _handleDragEndAngleControlPoint() {\n        const _self = this;\n        return (event) => {\n            _self.sector.endAngle = geomutils.mapAngleTo2PI(_self._endAngleControlLine.angle() - _self.sector.ellipse.rotation);\n        };\n    }\n    /**\n     * Draw grey handle lines.\n     *\n     * @param {DrawLib<any>} draw - The draw library instance to use.\n     * @param {DrawLib<any>} fill - The fill library instance to use.\n     */\n    drawHandleLines(draw, fill) {\n        draw.line(this.sector.ellipse.center, this.startAngleControlPoint, \"rgba(64,192,128,0.333)\", 1.0, {\n            dashOffset: 0.0,\n            dashArray: [4, 2]\n        });\n        draw.line(this.sector.ellipse.center, this.endAngleControlPoint, \"rgba(64,192,128,0.333)\", 1.0, {\n            dashOffset: 0.0,\n            dashArray: [4, 2]\n        });\n        // Draw rotation handle line\n        draw.line(this.sector.ellipse.center, this.rotationControlPoint, \"rgba(192,64,128,0.333)\", 1.0, {\n            dashOffset: 0.0,\n            dashArray: [4, 2]\n        });\n        // Draw helper box\n        draw.line(this.sector.ellipse.center\n            .clone()\n            .add(0, this.sector.ellipse.signedRadiusV())\n            .rotate(this.sector.ellipse.rotation, this.sector.ellipse.center), this.sector.ellipse.axis, \"rgba(64,128,192,0.333)\", 1.0, {\n            dashOffset: 0.0,\n            dashArray: [4, 2]\n        });\n        draw.line(this.sector.ellipse.center\n            .clone()\n            .add(this.sector.ellipse.signedRadiusH(), 0)\n            .rotate(this.sector.ellipse.rotation, this.sector.ellipse.center), this.sector.ellipse.axis, \"rgba(64,128,192,0.333)\", 1.0, {\n            dashOffset: 0.0,\n            dashArray: [4, 2]\n        });\n    } // END drawHandleLines\n    /**\n     * Destroy this VEllipseHandler which means: all listeners are being removed.\n     */\n    destroy() {\n        this.sector.ellipse.center.listeners.removeDragListener(this._centerHandler);\n        this.rotationControlPoint.listeners.removeDragListener(this._rotationHandler);\n        this.startAngleControlPoint.listeners.removeDragListener(this._startAngleHandler);\n        this.endAngleControlPoint.listeners.removeDragListener(this._endAngleHandler);\n    }\n}\n//# sourceMappingURL=VEllipseSectorHelper.js.map","/**\n * Resize a given array to a desired number of elements by adding or removing some.\n *\n * @author  Ikaros Kappler\n * @date    2024-02-07\n * @version 1.0.0\n */\nexport const arrayResize = (arr, desiredSize, factoryFn) => {\n    if (arr.length === desiredSize) {\n        // No change required\n        return;\n    }\n    while (arr.length < desiredSize) {\n        arr.push(factoryFn());\n    }\n    if (arr.length > desiredSize) {\n        arr.splice(desiredSize);\n    }\n};\n//# sourceMappingURL=arrayResize.js.map","/**\n * Randomize a given array in-place.\n *\n * @author Ikaros Kappler\n * @date 2022-10-09\n * @version 1.0.0\n **/\nexport const arrayShuffle = (arr) => {\n    arr.sort(() => Math.random() - 0.5);\n};\n//# sourceMappingURL=arrayShuffle.js.map","/**\n * @requires Vertex\n *\n * @author Ikaros Kappler\n * @date 2020-12-20\n */\n/**\n * Remove all duplicate neighbours from the given polygon.\n *\n * Imagagine a polygon:\n * [ [0,0], [10,10], [10,10], [10,10], [20,20], [10,10], [30,30], [0,0] ]\n *\n * The returned vertex array will then be:\n * [ [10,10], [20,20], [10,10], [30,30], [0,0] ]\n *\n * Duplicate neighbours (and only neightours) of a run of any length will be removed.\n *\n * @method clearPolygonDuplicateVertices\n * @param {Array<Vertex>} vertices - The polygon vertices to use.\n * @param {number=0} epsilon - The epsilon area to use around each vertex to check equality.\n * @return {Array<Vertex>}\n */\nexport const clearPolygonDuplicateVertices = (vertices, epsilon) => {\n    const n = vertices.length;\n    if (n === 0)\n        return [];\n    // Find following up sequence of vertices that are inside the epsilon sphere.\n    if (typeof epsilon === \"undefined\")\n        epsilon = 0;\n    // Check if the verts a i and j are considered equal\n    const equalVerts = (i, j) => {\n        const vertA = vertices[i % n];\n        const vertB = vertices[j % n];\n        return (epsilon === 0 && vertA.x === vertB.x && vertA.y === vertB.y)\n            || (epsilon !== 0 && vertA.distance(vertB) <= epsilon);\n    };\n    // Find the next vertex in the list, starting from 'index', that is different\n    const findEndOfRun = (index) => {\n        var b = index;\n        while (equalVerts(index, b + 1) && b < index + n) {\n            b++;\n        }\n        return b;\n    };\n    var start = findEndOfRun(0);\n    // console.log('starting at', start );\n    var i = 0;\n    const result = [];\n    for (var j = i + 1; j <= n; j++) {\n        if (!equalVerts(start + i, start + j)) {\n            result.push(vertices[(start + j) % n]);\n            i = j;\n        }\n    }\n    return result;\n};\n//# sourceMappingURL=clearPolygonDuplicateVertices.js.map","/**\n * The name says it.\n *\n * @requires Vertex\n *\n * @author   Ikaros Kappler\n * @date     2020-12-20\n * @modified 2021-02-09 Ported to TypeScript.\n * @version  1.0.0\n */\nimport { Vertex } from \"../Vertex\";\nexport const cloneVertexArray = (vertices) => {\n    const result = [];\n    for (var i = 0; i < vertices.length; i++) {\n        result.push(new Vertex(vertices[i].x, vertices[i].y));\n    }\n    return result;\n};\n//# sourceMappingURL=cloneVertexArray.js.map","/**\n * A helper function to generate randmoized non-intersecting polygons.\n *\n * @author  Ikaros Kappler\n * @date    2025-03-23 (ported to Typescript from a helper script from 2024)\n * @version 1.0.0\n */\nimport { Polygon } from \"../Polygon\";\nimport { Vertex } from \"../Vertex\";\n/**\n * @param numVertices\n * @returns\n */\nexport const createRandomizedPolygon = (numVertices, viewport, createClockwise) => {\n    const polygon = new Polygon();\n    for (var i = 0; i < numVertices; i++) {\n        const vert = new Vertex(viewport.getMinDimension() * 0.33, 0.0);\n        vert.rotate(((Math.PI * 2) / numVertices) * i);\n        vert.addXY(viewport.width * 0.1 * (1.0 - Math.random() * 2), viewport.height * 0.1 * (1.0 - Math.random() * 2));\n        polygon.addVertex(vert);\n    }\n    if (createClockwise && !polygon.isClockwise()) {\n        // Reverse\n        polygon.vertices = polygon.vertices.reverse();\n    }\n    return polygon;\n};\n//# sourceMappingURL=createRandomizedPolygon.js.map","/**\n * @author   Ikaros Kappler\n * @date     2018-04-07\n * @modified 2018-04-11 Using VoronoiCells now (was array before).\n * @modified 2020-08-15 Ported from vanilla JS to TypeScript.\n * @version  1.0.2\n **/\nimport { VoronoiCell } from \"../datastructures/VoronoiCell\";\n/**\n * @classdesc Create the voronoi diagram from the given delaunay triangulation (they are dual graphs).\n *\n * @requires VoronoiCell\n * @requires Triangle\n */\nexport class delaunay2voronoi {\n    constructor(pointList, triangles) {\n        this.failedTriangleSets = [];\n        this.hasErrors = false;\n        this.pointList = pointList;\n        this.triangles = triangles;\n    }\n    ;\n    // +---------------------------------------------------------------------------------\n    // | Convert the triangle set to the Voronoi diagram.\n    // +-------------------------------\n    build() {\n        const voronoiDiagram = [];\n        for (var p in this.pointList) {\n            var point = this.pointList[p];\n            // Find adjacent triangles for first point\n            var adjacentSubset = [];\n            for (var t in this.triangles) {\n                if (this.triangles[t].a.equals(point) || this.triangles[t].b.equals(point) || this.triangles[t].c.equals(point))\n                    adjacentSubset.push(this.triangles[t]);\n            }\n            var path = this.subsetToPath(adjacentSubset);\n            if (path) // There may be errors\n                voronoiDiagram.push(new VoronoiCell(path, point));\n        }\n        return voronoiDiagram;\n    }\n    ;\n    // +---------------------------------------------------------------------------------\n    // | Re-order a tiangle subset so the triangle define a single path.\n    // |\n    // | It is required that all passed triangles are connected to a\n    // | path. Otherwise this function will RAISE AN EXCEPTION.\n    // |\n    // | The function has a failsafe recursive call for the case the first\n    // | element in the array is inside the path (no border element).\n    // +-------------------------------\n    subsetToPath(triangleSet, startPosition, tryOnce) {\n        if (triangleSet.length == 0)\n            return [];\n        if (typeof startPosition === 'undefined')\n            startPosition = 0;\n        let t = startPosition;\n        const result = [triangleSet[t]];\n        const visited = [t];\n        let i = 0;\n        while (result.length < triangleSet.length && i < triangleSet.length) {\n            let u = (startPosition + i) % triangleSet.length;\n            if (t != u && visited.indexOf(u) == -1 && triangleSet[t].isAdjacent(triangleSet[u])) {\n                result.push(triangleSet[u]);\n                visited.push(u);\n                t = u;\n                i = 0;\n            }\n            else {\n                i++;\n            }\n        }\n        // If not all triangles were used the passed set is NOT CIRCULAR.\n        // But in this case the triangle at position t is at one end of the path :)\n        // -> Restart with t.\n        if (result.length < triangleSet.length) {\n            if (tryOnce) {\n                // Possibility A (try to fix this): split the triangle set into two arrays and restart with each.\n                // Possibility B (no fix for this): throw an error and terminate.\n                // Possibility C (temp solution): Store the error for later reporting and continue.\n                // this.failedTriangleSets.push( triangleSet );\n                this.failedTriangleSets = triangleSet;\n                this.hasErrors = true;\n                // throw \"Error: this triangle set is not connected: \" + JSON.stringify(triangleSet);\n                return null;\n            }\n            else {\n                // Triangle inside path found. Rearrange.\n                return this.subsetToPath(triangleSet, t, true);\n            }\n        }\n        else {\n            return result;\n        }\n    }\n    ;\n}\n; // END delaunay2voronoi\n//# sourceMappingURL=delaunay2voronoi.js.map","/**\n * @author  Ikaros Kappler\n * @date    2021-11-07\n * @modified 2023-09-25 Ported to Typescript and added system darkmode detection.\n * @version 1.1.0\n *\n * @param {Record<string,string>} GUP\n * @returns {boolean}\n */\nexport const detectDarkMode = (GUP) => {\n    var isDarkmode = false;\n    // Respect overrides\n    if (typeof GUP !== \"undefined\" && GUP.hasOwnProperty(\"darkmode\") && GUP[\"darkmode\"]) {\n        // const overrideValue = PlotBoilerplate.utils.fetch.bool(GUP, \"darkmode\", null);\n        const overrideValue = !!JSON.parse(GUP[\"darkmode\"]);\n        if (overrideValue !== null) {\n            isDarkmode = overrideValue;\n        }\n    }\n    else if (globalThis.matchMedia && globalThis.matchMedia(\"(prefers-color-scheme: dark)\").matches) {\n        // dark mode by system\n        isDarkmode = true;\n    }\n    else {\n        // else: dark mode by daytime\n        const hours = new Date().getHours();\n        const isDayTime = hours > 6 && hours < 18;\n        isDarkmode = !isDayTime;\n    }\n    // console.log(\"Adding darkmode to <body>\", isDarkmode);\n    if (isDarkmode && document.body) {\n        // Add darkmode class to <body> tag\n        document.body.classList.add(\"darkmode\");\n    }\n    return isDarkmode;\n};\n//# sourceMappingURL=detectDarkMode.js.map","/**\n * @author  Ikaros Kappler\n * @date    2022-01-10\n * @version 1.0.0\n */\n/**\n * In an array of vertices find the first occurence of a specific vertex, using\n * and epsilon tolerance.\n *\n * @param {Array<Vertex>} vertexList - The vertex array to search in.\n * @param {XYCoords} vertex - A vertex/position to search for. This can be any x-y-tuple and does not\n *                              necessarily need to be an instance of Vertex.\n * @param {number} epsilon - The epsilon tolerance to use (should be >= 0). This is a required param to avoid excessive\n *                              is-undef checking if this function runs in a loop.\n * @returns {boolean} - The first index of a vertex that matched or -1 if no such vertex could be found.\n */\nexport const findInVertexArray = (vertexList, vertex, epsilon) => {\n    for (var i = 0; i < vertexList.length; i++) {\n        if (vertexList[i].distance(vertex) < epsilon) {\n            return i;\n        }\n    }\n    return -1;\n};\n//# sourceMappingURL=findInVertexArray.js.map","import { getFProp } from \"./getFProp\";\nexport const getAvailableContainerSpace = (element) => {\n    // const _self: PlotBoilerplate = this;\n    const container = element.parentNode; // Element | Document | DocumentFragment;\n    // var canvas : HTMLCanvasElement = _self.canvas;\n    // _self.canvas.style.display = \"none\";\n    /* var\n    padding : number = parseFloat( globalThis.getComputedStyle(container, null).getPropertyValue('padding') ) || 0,\n    border : number = parseFloat( globalThis.getComputedStyle(_self.canvas, null).getPropertyValue('border-width') ) || 0,\n    pl : number = parseFloat( globalThis.getComputedStyle(container, null).getPropertyValue('padding-left') ) || padding,\n    pr : number = parseFloat( globalThis.getComputedStyle(container, null).getPropertyValue('padding-right') ) || padding,\n    pt : number = parseFloat( globalThis.getComputedStyle(container, null).getPropertyValue('padding-top') ) || padding,\n    pb : number = parseFloat( globalThis.getComputedStyle(container, null).getPropertyValue('padding-bottom') ) || padding,\n    bl : number = parseFloat( globalThis.getComputedStyle(_self.canvas, null).getPropertyValue('border-left-width') ) || border,\n    br : number = parseFloat( globalThis.getComputedStyle(_self.canvas, null).getPropertyValue('border-right-width') ) || border,\n    bt : number = parseFloat( globalThis.getComputedStyle(_self.canvas, null).getPropertyValue('border-top-width') ) || border,\n    bb : number = parseFloat( globalThis.getComputedStyle(_self.canvas, null).getPropertyValue('border-bottom-width') ) || border;\n    */\n    var padding = getFProp(container, \"padding\") || 0, border = getFProp(element, \"border-width\") || 0, pl = getFProp(container, \"padding-left\") || padding, pr = getFProp(container, \"padding-right\") || padding, pt = getFProp(container, \"padding-top\") || padding, pb = getFProp(container, \"padding-bottom\") || padding, bl = getFProp(element, \"border-left-width\") || border, br = getFProp(element, \"border-right-width\") || border, bt = getFProp(element, \"border-top-width\") || border, bb = getFProp(element, \"border-bottom-width\") || border;\n    var w = container.clientWidth;\n    var h = container.clientHeight;\n    // _self.canvas.style.display = \"block\";\n    return { width: w - pl - pr - bl - br, height: h - pt - pb - bt - bb };\n};\n//# sourceMappingURL=getAvailableContainerSpace.js.map","/**\n * @requires lil-gui\n *\n * @author   Ikaros Kappler\n * @date     2021-12-13\n * @modified 2022-01-10\n * @modified 2024-06-25 Ported to typescript and moved to utils/dom (was located inside demos before).\n * @modified 2024-10-02 Added a transition time.\n * @version  1.1.1\n */\n/**\n * @param {GUI} gui - The GUI (compatible with dat.gui and lil-gui).\n * @param {boolean} guiDoubleSize - True or false.\n * @param {Record<string,string>} cssProps - The CSS props to use.\n */\nconst applyGuiSize = (gui, guiDoubleSize, cssProps) => {\n    if (cssProps && cssProps.hasOwnProperty(\"transformOrigin\")) {\n        gui.domElement.style[\"transform-origin\"] = cssProps[\"transformOrigin\"];\n    }\n    else {\n        gui.domElement.style[\"transform-origin\"] = \"100% 0%\";\n    }\n    const transform = cssProps && cssProps.hasOwnProperty(\"transform\") ? cssProps[\"transform\"] + \" \" : \"\";\n    // console.log(\"transform\", transform);\n    if (guiDoubleSize) {\n        gui.domElement.style[\"transform\"] = transform + \"scale(2.0)\";\n    }\n    else {\n        gui.domElement.style[\"transform\"] = transform + \"scale(1.0)\";\n    }\n};\nexport const guiSizeToggler = (gui, config, cssProps) => {\n    gui.domElement.style[\"transition\"] = \"transform 0.5s\";\n    return {\n        update: function () {\n            applyGuiSize(gui, Boolean(config.guiDoubleSize), cssProps);\n        }\n    };\n};\n//# sourceMappingURL=guiSizeToggler.js.map","/**\n * `gup` = \"Get URL/URI Params\".\n *\n * This function simply taktes the location string from the broser bar and retrieves all GET params\n * as a record of string mappings.\n *\n * You can pass that result into the `Params` class to get proper type conversion for numbers and booleans.\n *\n * Ported to typescript.\n * @date 2021-05-21\n * @modified 2024-03-10 Fixed some type for Typescript 5 compatibility.\n * @modified 2024-08-26 Decoding URI components in GET params.\n */\n// Get the URI GET params as an assoc.\n//\n// A nicer version with regex\n// Found at\n//    https://stackoverflow.com/questions/979975/how-to-get-the-value-from-the-get-parameters?utm_medium=organic&utm_source=google_rich_qa&utm_campaign=google_rich_qa\nexport const gup = () => {\n    const vars = {};\n    globalThis.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi, (_m, key, value) => {\n        const keyName = key;\n        return (vars[decodeURIComponent(keyName)] = value);\n    });\n    return vars;\n};\n//# sourceMappingURL=gup.js.map"],"names":["VertexAttr","constructor","key","this","draggable","selectable","isSelected","visible","model","UIDGenerator","next","current","VertexListeners","vertex","click","drag","dragStart","dragEnd","addClickListener","listener","_addListener","removeClickListener","_removeListener","addDragListener","removeDragListener","addDragStartListener","removeDragStartListener","addDragEndListener","removeDragEndListener","fireClickEvent","e","_fireEvent","fireDragEvent","fireDragStartEvent","fireDragEndEvent","removeAllListeners","_self","listeners","ve","i","params","newListener","Error","push","oldListener","length","splice","Circle","center","radius","className","uid","setRadius","move","amount","add","containsPoint","point","circleUtils","containsCircle","circle","epsilon","Number","isNaN","distance","Math","abs","lineDistance","line","getClosestPoint","vertAt","angle","tangentAt","pointA","Vector","Vertex","perp","getBounds","Bounds","clone","subXY","addXY","circleIntersection","p0","p1","d","a","h","sqrt","p2","scale","x3","x","y","y3","x4","y4","Line","lineIntersection","b","interA","interB","transA","sub","transB","diff","difference","dist","det","distSquared","belowSqrt","sign","lineIntersections","inVectorBoundsOnly","intersectioLine","filter","vert","hasPoint","lineIntersectionTangents","map","radicalAxis","circleB","helperCircle","createRadicalAxisHelperCircle","intersectionLineA","intersectionLineB","intersection","console","error","lineA","lineB","firstRadicalAxisPoint","secondRadicalAxisPoint_mirrored","closestPoint","tangentsFromPoint","centerDistance","tangentLength","log","fromICircle","obj","destroy","isDestroyed","cos","sin","circleCenter","circleRadius","geomutils","dist4","circleA","circleConnectLine","set","bisector","bisectorLength","max","setLength","circleDistance","Triangle","c","calcCircumcircle","fromArray","arr","getArea","utils","signedArea","getCentroid","scaleToCentroid","factor","centroid","bounds","getCircumcircle","getMinimumEnclosingCircle","circleAB","VertTuple","vtutils","circleBC","circleCA","circumCircle","isAdjacent","tri","equals","getThirdVertex","vert1","vert2","getVertices","tmpCircle","radius_squared","inCircumcircle","v","dx","dy","Polygon","locateLineIntersecion","intersectionTuple","polyLine","getEdgeAt","edgeIndex","moveTo","modIndex","toPolygon","determinant","p","pointIsInTriangle","getIncircularTriangle","lineC","bisector1","nsectAngle","bisector2","circleIntersA","circleIntersB","circleIntersC","getIncircle","getIncenter","toString","EPSILON","max3","min3","p0x","p0y","p1x","p1y","p2x","p2y","px","py","area","s","t","A","B","C","D","E","F","G","min","mapAngleTo2PI","new_angle","asin","PI","x1","y1","x2","y2","pow","dotProduct","vertA","vertB","pA","pB","pC","n","triangle","lineAB","lineAC","insideAngle","clockwise","scaleFactor","result","rotate","wrapMax","wrapMinMax","tuple","NaN","attr","setX","setY","invX","invY","amountX","amountY","addX","addY","subX","subY","eqX","eqY","origin","atan2","scaleXY","lerp","target","lerpAbs","u","step","factors","len","ZERO","multiplyScalar","scalar","round","inv","computeFromVertices","findClosestPoint","pointB","findFarestPoint","precision","toFixed","randomVertex","viewPort","random","buildArrowHead","zA","zB","headlen","scaleX","scaleY","warn","vertices","arrayToJSON","JSON","stringify","undefined","factory","revert","tmp","normalize","newA","v0","v1","denominator","colinear","getClosestT","l2","dist2","insideBoundsOnly","pointDistance","w","cx","cy","super","inverse","numerator1","numerator2","getOrthogonal","linePoint","startPoint","getStartPoint","getEndPoint","getStartTangent","getEndTangent","reverse","intersections","intrsctn","isOpen","addVertex","addVertexAt","index","vertIndex","getVertexAt","getEdges","lines","getInnerAngleAt","p3","isAcute","isAngleAcute","zero","p2mp1","p3mp2","p2mp1_len","p3mp2_len","lengthProduct","acos","containsVert","inside","j","xi","yi","xj","yj","containsVerts","verts","every","containsPolygon","polygon","lineSegment","isClockwise","perimeter","getMeanCenter","cur","lineIntersectionTangentsIndices","closestLineIntersection","closestInterSectionIndex","closestLineIntersectionIndex","allIntersections","closestIntersection","MAX_VALUE","curDist","curVert","getInterpolationPolygon","interpolationCount","nextVert","lerpAmount","getEvenDistributionPolygon","pointCount","polygonPoint","stepSize","polygonIndex","nextPolygonPoint","segmentLength","loopMax","curSegmentU","newPoint","elimitateColinearEdges","tolerance","eps","slice","areColinear","vertC","toQuadraticBezierData","qbezier","cc0","cc1","edgeCenter","limit","toQuadraticBezierSVGString","qdata","buffer","join","toCubicBezierData","threshold","cbezier","aCenter","bCenter","a2","b0","toCubicBezierSVGString","toCubicBezierPath","pathdata","BezierPath","total","l","sum","intersectionPoints","width","height","getWidth","getHeight","getScaled","getCenter","newMin","newMax","getMoved","moveAmount","getNorthPoint","getSouthPoint","getWestPoint","getEastPoint","getNorthWestPoint","getNorthEastPoint","getSouthEastPoint","getSouthWestPoint","getMinDimension","getMaxDimension","randomPoint","horizontalSafeArea","verticalSafeArea","absHorizontalSafeArea","absVerticalSafeArea","xMin","xMax","yMin","yMax","computeFromBoundsSet","boundingBoxes","fromDimension","CubicBezierCurve","endPoint","startControlPoint","endControlPoint","START_POINT","START_CONTROL_POINT","END_CONTROL_POINT","END_POINT","curveIntervals","segmentCache","segmentLengths","updateArcLengths","moveCurvePoint","pointID","moveControlPoint","getStartControlPoint","getEndControlPoint","translate","getLength","arcLength","curveStep","newLength","tmpLength","getPointAt","tPrev","tNext","iteration","locateIntervalByDistance","tStart","tEnd","stepCount","minIndex","minDist","tDiff","xMinMax","cubicPolyMinMax","xl","xh","yMinMax","yl","yh","getPointByID","id","evaluateT","getPoint","getTangentAt","t2","nt2","tX","tY","trimStart","uValue","trimStartAt","convertU2T","subCurbePoints","getSubCurvePointsAt","trimEnd","trimEndAt","getSubCurve","uStart","uEnd","getSubCurveAt","getTangent","getPerpendicular","getPerpendicularAt","tangentVector","lineIntersectionTs","intersectionTangents","vec","bx","bezierCoeffs","by","poly","Array","cubicRoots","root","curve","isInstance","toJSON","prettyFormat","fromJSON","jsonString","parse","fromObject","isArray","polyX","cubicPoly","disc","t1","startVec","endVec","S","T","Q","R","ts","sgn","th","sort","coeffs","totalArcLength","adjustCircular","bezierCurves","addCurve","adjustSuccessorControlPoint","locateCurveByStartPoint","locateCurveByEndPoint","locateCurveByStartControlPoint","locateCurveByEndControlPoint","getCurveCount","getCurveAt","curveIndex","anchor","scaleFactors","curveT","uMin","uTemp","relativeU","uResult","_locateUIndex","bCurve","uPart","reduce","accu","curCurve","concat","path","uBefore","getSubPathAt","startT","endT","startU","endU","uStartResult","uEndResult","firstT","lastT","firstCurve","curves","adjustPredecessorControlPoint","obtainHandleLength","mainCurve","neighbourCurve","adjustNeighbourControlPoint","_mainCurve","mainPoint","mainControlPoint","neighbourPoint","neighbourControlPoint","obtainHandleLengths","_updateArcLengths","mainHandleBounds","neighbourHandleBounds","mainHandleLength","neighbourHandleLength","POSITIVE_INFINITY","NEGATIVE_INFINITY","getEvenDistributionVertices","toPathPoints","fromCurve","bPath","lastCurve","toReducedListRepresentation","digits","fromReducedListRepresentation","listJSON","pointArray","fromReducedList","bezierPath","CircleSector","startAngle","endAngle","circleBounds","candidates","containsAngle","wrappedAngle","wrappedStart","wrappedEnd","angleAt","circleSectorIntersection","sector","radicalLine","thisIntersectionAngleA","thisIntersectionAngleB","thatIntersectionAngleA","thatIntersectionAngleB","centerOfOriginalGap","resultSector","ray","ellipseIntersections","tmpLine","intersectionPoint","lineAngle","describeSVGPath","options","circleSectorUtils","describeSVGArc","polarToCartesian","centerX","centerY","moveToStart","end","start","firstHalf","secondHalf","largeArcFlag","sweepFlag","pathData","RAD_TO_DEG","drawutilssvg","svgNode","offset","canvasSize","fillShapes","drawConfig","isSecondary","gNode","bufferGNode","nodeDefs","bufferNodeDefs","nodeStyle","Boolean","drawlibConfiguration","cache","Map","setSize","bufferedNodeDefs","addStyleDefs","addDefsNode","createSVGNode","appendChild","rebuildStyleDefs","keys","bezier","ellipse","ellipseSector","circleSector","vector","image","text","rules","k","drawSettings","color","lineWidth","customStyleDefs","forEach","value","innerHTML","addCustomStyleDefs","defs","findElement","nodeName","node","get","toUpperCase","delete","document","createElementNS","makeNode","curId","blendMode","style","_bindFillDraw","strokeOptions","_configureNode","_bindNode","bindingParent","parentNode","_addCSSClasses","curClassName","setAttribute","fillMode","applyStrokeOpts","copyInstance","setConfiguration","configuration","setCurrentId","setCurrentClassName","beginDrawCycle","renderTime","clear","childNodes","child","getAttribute","removeAllChildNodes","endDrawCycle","replaceChild","tmpGNode","tmpDefsNode","dashArray","nodeSupportsLineDash","tagName","dashArayElem","dashOffset","lineJoin","nodeSupportsLineJoin","lineCap","nodeSupportsLineCap","_x","_y","makeLineNode","arrow","headLength","group","arrowHeadBasePosition","arrowHead","makeArrowHeadNode","cubicBezierArrow","makeCubicBezierNode","position","size","alpha","setImageSize","naturalWidth","ratioX","ratioY","naturalHeight","addEventListener","event","src","texturedPoly","textureImage","textureSize","polygonPosition","rotation","rotatedScalingOrigin","clipPathNode","clipPathId","imageNode","pathNode","clipNode","cubicBezier","cubicBezierPath","handle","square","handleLine","dot","circleArc","arcData","radiusX","radiusY","rect","grid","sizeX","sizeY","ceil","raster","diamondHandle","squareHandle","circleHandle","crosshair","cross","polyline","_a","_b","_c","lineHeight","fontSize","textAlign","transformOrigin","textNode","fontFamily","fontStyle","fontWeight","label","inplace","copyPathData","transformPathData","lastChild","removeChild","createSvg","data","_stx","_sty","_sx","_sy","_slp","includes","classNameOverride","makePathNode","pathString","arrowHeadBasePositionBuffer","HEAD_XML","drawutils","context","ctx","_d","setLineDash","dashArrayElem","lineDashOffset","_fillOrDraw","fillStyle","fill","strokeStyle","stroke","globalCompositeOperation","save","beginPath","lineTo","restore","complete","globalAlpha","drawImage","basePolygonBounds","targetTextureSize","targetTextureOffset","helpers","clipPoly","closePath","bezierCurveTo","quadraticBezier","controlPoint","quadraticCurveTo","arc","asSegment","relX","relY","font","indexOf","fillText","strokeText","Path2D","clearRect","canvas","fillRect","clip","drawutilsgl","gl","_zindex","glutils","GLU","_vertShader","compileShader","vertCode","VERTEX_SHADER","_fragShader","fragCode","FRAGMENT_SHADER","_program","makeProgram","vertex_buffer","createBuffer","_x2rel","_y2rel","copy","Float32Array","bindBuffer","ARRAY_BUFFER","bufferData","STATIC_DRAW","coord","getAttribLocation","vertexAttribPointer","FLOAT","enableVertexAttribArray","viewport","uRotationVector","getUniformLocation","uniform2fv","drawArrays","LINES","TRIANGLE_FAN","clearColor","enable","DEPTH_TEST","COLOR_BUFFER_BIT","DEPTH_BUFFER_BIT","vbuffer","shaderCode","shaderType","shader","createShader","shaderSource","getShaderParameter","COMPILE_STATUS","getShaderInfoLog","deleteShader","vertShader","fragShader","program","createProgram","attachShader","linkProgram","useProgram","detachShader","Grid","baseLog","base","num","mapRasterScale","adjustFactor","gf","floor","KeyHandler","downListeners","pressListeners","upListeners","keyStates","element","globalThis","trackAllKeys","trackAll","installListeners","fireEvent","hasListener","lis","keyCode","fireDownEvent","handler","firePressEvent","fireUpEvent","key2code","KEY_CODES","_keyDownListener","_keyPressListener","_keyUpListener","releaseListeners","removeEventListener","down","press","up","isDown","break","backspace","tab","enter","shift","ctrl","alt","pause","capslock","hangul","hanja","escape","conversion","spacebar","pageup","pagedown","home","leftarrow","uparrow","rightarrow","downarrow","select","print","execute","printscreen","insert","help","f","g","m","o","q","r","z","windows","leftcommand","chromebooksearch","rightwindowkey","windowsmenu","rightcommant","sleep","numpad0","numpad1","numpad2","numpad3","numpad4","numpad5","numpad6","numpad7","numpad8","numpad9","multiply","numpadperiod","subtract","decimalpoint","divide","f1","f2","f3","f4","f5","f6","f7","f8","f9","f10","f11","f12","f13","f14","f15","f16","f17","f18","f19","f20","f21","f22","f23","f24","numlock","scrolllock","$","pagebackward","pageforward","refresh","closingparen","minus","decreasevolumelevel","increasevolumelevel","previous","stop","email","mute","unmute","semicolon","equal","comma","dash","period","forwardslash","openbracket","backslash","closebracket","singlequote","altgr","XF86Forward","XF86Back","alphanumeric","hiragana","katakana","kanji","unlocktrackpad","toggletouchpad","XMouseEvent","MouseEvent","XWheelEvent","WheelEvent","MouseHandler","name","mouseDownPos","mouseDragPos","mouseButton","installed","handlers","mousemove","mkParams","relPos","mouseup","button","mousedown","wheel","offsetX","offsetY","eventName","rel","xEvent","isTouchEvent","pos","leftButton","middleButton","rightButton","draggedFrom","wasDragged","dragAmount","listenFor","unlistenFor","callback","throwAlreadyInstalled","PBImage","upperLeft","lowerRight","PBText","getLen","getRotateAngle","v2","mr","getAngle","HandlerAdmin","el","del","dispatch","_args","apply","arguments","wrapFunc","handlerAdmin","AlloyFinger","option","querySelector","bind","cancel","preV","pinchStartLen","zoom","isDoubleTap","noop","touchStart","multipointStart","multipointEnd","pinch","swipe","tap","doubleTap","longTap","singleTap","pressMove","twoFingerPressMove","touchMove","touchEnd","touchCancel","_cancelAllHandler","cancelAll","delta","last","now","tapTimeout","singleTapTimeout","longTapTimeout","swipeTimeout","preTapPosition","evt","touches","Date","pageX","pageY","clearTimeout","_cancelLongTap","_cancelSingleTap","_preventTap","setTimeout","afEvent","currentX","currentY","sCurrentX","sCurrentY","sx2","deltaX","deltaY","sy2","movedX","movedY","preventDefault","changedTouches","self","direction","_swipeDirection","on","off","VEllipse","axis","radiusH","signedRadiusH","radiusV","signedRadiusV","getExtremePoints","t_x1","t_x2","x_x1","y_x1","x_x2","y_x2","x_max","x_min","t_y1","t_y2","x_y1","y_y1","x_y2","y_y2","y_max","y_min","r1","r2","ux","uy","vx","vy","bbox_halfwidth","bbox_halfheight","normalAt","foci","getFoci","angleA","centerAngle","endPointA","endPointB","resultVector","rh","rv","sdiff","getEquidistantVertices","angles","equidistantVertAngles","ellipseCopy","rayCopy","rotationAmount","scalingFactors","toCubicBezier","quarterSegmentCount","segmentCount","curAngle","nextAngle","startTangent","endTangent","startDiff","endDiff","phiToTheta","phi","tanPhi","tan","tanPhi2","atan","theta","VEllipseSector","sAngle","eAngle","ellipseSectorUtils","normalizeAngle","r2d","fullEllipsePointCount","ellipseAngles","startIndex","findClosestToStartAngle","ea","endpointToCenterParameters","rx","ry","fa","fs","sinphi","cosphi","prx","pry","L","M","_cx","_cy","__setFunctionName","prefix","description","Object","defineProperty","configurable","PlotBoilerplate","config","contentChangeListeners","_gui","bezierAutoAdjust","fetch","fullSize","val","fitToParent","bool","rasterGrid","drawRaster","rasterScaleX","rasterScaleY","rasterAdjustFactor","drawOrigin","autoAdjustOffset","offsetAdjustXPercent","offsetAdjustYPercent","backgroundColor","redrawOnResize","defaultCanvasWidth","DEFAULT_CANVAS_WIDTH","defaultCanvasHeight","DEFAULT_CANVAS_HEIGHT","canvasWidthFactor","canvasHeightFactor","cssScaleX","cssScaleY","cssUniformScale","saveFile","hooks","setToRetina","_setToRetina","autoDetectRetina","enableSVGExport","preClear","func","preDraw","postDraw","enableMouse","enableTouch","enableKeys","enableMouseWheel","enableZoom","enablePan","enableGL","isBackdropFiltersEnabled","drawVertices","drawBezierHandleLines","drawBezierHandlePoints","drawHandleLines","drawHandlePoints","drawGrid","pathVertex","controlVertex","selectedVertex","canvasElement","toLowerCase","eventCatcher","getContext","draw","parentElement","createElement","left","top","cursor","body","title","selectPolygon","draggedElements","drawables","_saveFile","resizeCanvas","installInputListeners","updateCSSscale","redraw","focus","pb","tosvgDraw","tosvgFill","drawAll","svgCode","XMLSerializer","serializeToString","blob","Blob","type","_saveAs","pixelRatio","devicePixelRatio","isPanning","isInPanningMode","fitToView","canvasCenter","canvasRatio","ratio","setOffset","newUniformZoom","setZoom","setConsole","con","_e","setCSSscale","addContentChangeListener","removeContentChangeListener","_fireContentChanged","addedDrawables","removedDrawables","drawable","doNotFireEvent","enableBezierPathAutoAdjust","remove","removeWithVertices","wasRemoved","removeVertex","removeAll","keepVertices","triggerRedraw","getVertexNear","pixelPosition","pixelTolerance","locatePointNear","transformMousePosition","typeName","vindex","gScale","gSize","cs","_handleColor","drawDrawables","drawDrawable","df","drawSelectPolygon","clearSelection","getFProp","elem","propName","parseFloat","getComputedStyle","getPropertyValue","getAvailableContainerSpace","container","display","padding","border","pl","pr","pt","bl","br","bt","bb","clientWidth","clientHeight","_f","_g","_setSize","HTMLCanvasElement","SVGElement","adjustOffset","innerWidth","documentElement","innerHeight","space","selectVerticesInPolygon","Draggable","VERTEX","setVIndex","handleClick","DEFAULT_CLICK_TOLERANCE","keyHandler","paths","pindex","cindex","pid","revertMousePosition","getDraggedElementCount","mouseDownHandler","draggablePoint","mouseDragHandler","oldDragAmount","mouseUpHandler","mouseWheelHandler","zoomStep","we","newOffset","zoomFactorX","zoomFactorY","interactionPos","oldPos","newPos","newOffsetX","newOffsetY","getBoundingClientRect","touchMovePos","touchDownPos","draggedElement","multiTouchStartScale","clearTouch","afProps","clientX","clientY","DEFAULT_TOUCH_TOLERANCE","draggingVertex","fakeEvent","stopPropagation","trans","touchItem0","item","touchItem1","fingerA","fingerB","window","createAlloyFinger","createGUI","props","getGUI","isVertex","safeMergeByKeys","extension","hasOwnProperty","typ","extVal","removeProperty","transform","fallback","NGons","ngon","nstar","radiusA","radiusB","Grad","dot2","dot3","grad3","F2","G2","F3","G3","fade","SVGPathUtils","mkCircularRingSector","innerRadius","outerRadius","innerStart","innerEnd","outerStart","outerEnd","isLargeArcRequired","innerLargeArcFlag","outerLargeArcFlag","Color","cssRGB","cssRGBA","red","green","blue","setRed","setBlue","Converter","RGBToHSL","setAlpha","setGreen","setHue","HSLToRGB","setSaturation","setLuminance","cssHSL","cssHSLA","hue","saturation","lightness","cssHEX","saturate","parseInt","desaturate","lighten","darken","fadein","fadeout","spin","makeRGB","args","sanitized","Sanitizer","RGB","makeHSL","HSL","makeHEX","startsWith","substr","Validator","checkHEX","str","trim","substring","parts","match","cssColorKey","CSS_COLORS","prevKey","curKey","cssColor","col","interpolate","charCodeAt","hue2rgb","MediumVioletRed","DeepPink","PaleVioletRed","HotPink","LightPink","Pink","DarkRed","Red","Firebrick","Crimson","IndianRed","LightCoral","Salmon","DarkSalmon","LightSalmon","OrangeRed","Tomato","DarkOrange","Coral","Orange","DarkKhaki","Gold","Khaki","PeachPuff","Yellow","PaleGoldenrod","Moccasin","PapayaWhip","LightGoldenrodYellow","LemonChiffon","LightYellow","Maroon","Brown","SaddleBrown","Sienna","Chocolate","DarkGoldenrod","Peru","RosyBrown","Goldenrod","SandyBrown","Tan","Burlywood","Wheat","NavajoWhite","Bisque","BlanchedAlmond","Cornsilk","Indigo","Purple","DarkMagenta","DarkViolet","DarkSlateBlue","BlueViolet","DarkOrchid","Fuchsia","Magenta","SlateBlue","MediumSlateBlue","MediumOrchid","MediumPurple","Orchid","Violet","Plum","Thistle","Lavender","MidnightBlue","Navy","DarkBlue","MediumBlue","Blue","RoyalBlue","SteelBlue","DodgerBlue","DeepSkyBlue","CornflowerBlue","SkyBlue","LightSkyBlue","LightSteelBlue","LightBlue","PowderBlue","Teal","DarkCyan","LightSeaGreen","CadetBlue","DarkTurquoise","MediumTurquoise","Turquoise","Aqua","Cyan","Aquamarine","PaleTurquoise","LightCyan","DarkGreen","Green","DarkOliveGreen","ForestGreen","SeaGreen","Olive","OliveDrab","MediumSeaGreen","LimeGreen","Lime","SpringGreen","MediumSpringGreen","DarkSeaGreen","MediumAquamarine","YellowGreen","LawnGreen","Chartreuse","LightGreen","GreenYellow","PaleGreen","MistyRose","AntiqueWhite","Linen","Beige","WhiteSmoke","LavenderBlush","OldLace","AliceBlue","Seashell","GhostWhite","Honeydew","FloralWhite","Azure","MintCream","Snow","Ivory","White","Black","DarkSlateGray","DimGray","SlateGray","Gray","LightSlateGray","DarkGray","Silver","LightGray","Gainsboro","DeepPurple","WebColors","shuffleWebColors","order","WebColorsContrast","WebColorsMalachite","arrayFill","count","initialValue","matrixFill","countA","countB","CircularIntervalSet","intervals","removeAt","intersect","CircleIntersections","findOuterPartitions","circles","intervalSets","maxSetLength","usedIntervals","pathList","findOuterPartition","findOuterPartitionsAsSectors","partitions","partitionsAsArcs","pathAsArcs","interval","buildRadicalLineMatrix","radicalLines","tmpRadLine","findInnerCircles","innerCircleIndices","findOuterCircleIntervals","intersectionMatrix","handleCircleInterval","intLocation","randomUnusedInterval","findAdjacentInterval","radicalLineToInterval","angleB","intervalSet","usedIntervalSetRecords","curInterval","curEndPoint","clearDuplicateVertices","containsElementFrom","isCloseTo","fromIndex","GenericPath","startSegment","segments","getSegmentCount","getSegmentAt","newPath","newSegments","getAllStartEndPoints","segment","locateUnvisitedSegment","isSegmentVisited","hasPredecessor","visited","getAdjacentSegment","currentSegment","nextSegment","detectAdjacentPath","currentSegmentIndex","detectPaths","hasSuccessor","initVisitationArray","resultPaths","nextSegmentIndex","ContourLineDetection","dataGrid","debugMode","rawLinearPathSegments","detectContourPaths","criticalHeightValue","closeGapType","CLOSE_GAP_TYPE_NONE","heightFace","ySegmentCount","xSegmentCount","getDataFace4At","findHeightFaceIntersectionLines","pointEliminationEpsilon","useTriangles","CLOSE_GAP_TYPE_ABOVE","CLOSE_GAP_TYPE_BELOW","xExtremes","nextX","nextY","detectAboveBelowLerpSegment","yExtremes","onRawSegmentsDetected","pathSegments","pathDetectEpsilon","pathSegment","findHeight4FaceIntersectionLine","xIndex","yIndex","heightValue","heightValueA","heightValueB","heightValueC","heightValueD","points","isBetween","lerpValueByHeight","getLerpRatio","findHeighteFace3IntersectionLine","xIndexA","yIndexA","xIndexB","yIndexB","xIndexC","yIndexC","getDataValueAt","areBothValuesOnRequiredPlaneSide","interpLine","valueA","valueB","criticalValue","valA","valB","curValue","comparison","getTangentTriangle4","vertD","findCircleIntersections","convexHull","HobbyPath","addPoint","generateCurve","circular","omega","controlPoints","hobbyControls","startControlPoints","endControlPoints","ds","succ","pred","gamma","beta","sherman","thomas","rho","rotateAngle","hypot","sa","sb","ca","cb","s5","cc","dd","den","Td","Tu","CubicSplinePath","xs","ys","controlsX","naturalControlsClosed","controlsY","naturalControlsOpen","coords","VoronoiCell","triangles","sharedVertex","toPathArray","toPathSVGString","_calcOpenEdgePoint","neigh","edgePoint","_findOuterEdgePoint","perpendicular","neighbour","BLACK","WHITE","DataGrid2dArrayMatrix","_matrix","setAll","find","condition","xRel","yRel","getMinDataValue","minDataValue","getMaxDataValue","maxDataValue","isDebug","matrix","parseBooleanMatrix","split","charAt","getSquareBox","squareSize","gapSize","lerpFactor","addRoundCorner","controlA","controlB","curveFactor","addStraightLine","__constructPath","visitedLeftBordersMatrix","startingPosition","startingBorderDirection","isPathComplete","maxInterations","borderDirection","squareBox","west","squareBoxNW","squareBoxN","north","squareBoxE","squareBoxNE","east","squareBoxSE","squareBoxS","south","squareBoxSW","squareBoxW","splitPolygonToNonIntersecting","_splitPolygonToNonIntersecting","maxDepth","splitPolygonAt","leftCleaned","rightCleaned","edgeIndexA","edgeIndexB","first","second","cp1","cp2","dc","dp","n1","n2","n3","sutherlandHodgman","subjectPolygon","clipPolygon","outputList","inputList","PolygonInset","originalPolygonLines","insetLines","insetPolygonLines","splitPolygons","computeOutputPolygons","innerPolygonOffset","_assertPolygonIsClockwise","intersectionEpsilon","optimizedPolygon","maxPolygonSplitDepth","_collectInsetLines","_collectInsetPolygonLines","insetRectanglePolygons","_collectRectangularPolygonInsets","removeEars","_optimizeInsetPolygon","insetPolygon","convertToBasicInsetPolygon","_assertAllPolygonsAreClockwise","filteredSplitPolygons","_filterInnerSplitPolygonsByCoverage","_filterInnerSplitPolygonsByOriginalBounds","polygonLines","insetAmount","offsetOnPerp","movedLine","lastInsetLine","firstInsetLine","lastIntersectionPoint","insetLine","nextInsetLine","resultLine","polygonLine","rectPolygon","splitPolygonsVertices","originalPolygon","splitPolyVerts","_splitPolyIndex","splitPVert","isCW","intersectionTestCallback","_hasIntersectionCallback","some","polygons","polygonVerts","_polyIndex","insetRectangles","earEdgeIndex","maxLimit","_locateExcessiveEarEdge","leftEdge","rightEdge","newIntersection","thisEdge","leftIndex","leftRect","_rectangleFullyContainsLine","thisRect","rectangle","edge","epsPointA","epsPointB","centerPoint","rectanglePoly","_rectanglePolyIndex","intersectionVerts","intersectionAreaSize","polygonTesselationToGraph","edges","polygonMapping","graphVertIndex","polyEdgeIndexA","polyEdgeIndexB","grapgVertIndexA","grapgVertIndexB","PolygonTesselationOutlines","DEFAULT_TOLERANCE","removeUnusedVertices","__eliminateDuplicateEdges","tesselationGraph","curEdge","curA","curB","otherEdge","otherA","otherB","__isEqualEdge","__locateEdgeWithVertIndex","findIndex","__removeUnusedVertices","newVertices","indexMapping","newIndex","newEdges","findAllOutlinesGraph","outerHull","__convertGenericPathToPolygon","__isEqualPoint","findAllOutlinesPolygons","lineSegments","edgeAvertA","edgeAvertB","edgeBvertA","edgeBvertB","DEFAULT_COLORSET","ColorGradient","values","toColorGradientString","colorValue","percentage","getColorAt","intervalLocation","locateClosestRatio","leftItem","rightItem","relativeInnerIntervalPosition","leftSliderIndex","closestSliderValue","curVal","valuesObj","tmpElement","createDefault","createFrom","startColor","endColor","angleInRadians","TileType","GirihTile","edgeLength","tileType","DEFAULT_EDGE_LENGTH","UNKNOWN","symmetry","uniqueSymmetries","innerTilePolygons","outerTilePolygons","textureSource","call","findAdjacentTilePosition","tile","edgeA","edgeB","transformTileToAdjacencies","baseEdgeIndex","neighbourTile","foundAlignments","positionedTile","transformTilePositionToAdjacency","adjacency","getInnerTilePolygonAt","getOuterTilePolygonAt","locateEdgeAtPoint","middle","tmpDistance","resultDistance","resultIndex","vertI","vertJ","GirihBowtie","BOW_TIE","oppositePoint","baseBounds","_buildInnerPolygons","_buildOuterPolygons","indices","middlePoint","leftPoint","rightPoint","innerPoint","innerTile","outerTileA","outerTileB","centerTile","GirihDecagon","DECAGON","centralStar","topPoint","bottomPoint","outerTile","GirihHexagon","IRREGULAR_HEXAGON","indicesA","indicesB","indexA","indexB","outerTileX","outerTileY","outerTileZ","GirihPenroseRhombus","addCenterPolygon","PENROSE_RHOMBUS","_edgeLength","right","innerA","innerB","centerPolygonExists","getCenterPolygonIndex","GirihPentagon","PENTAGON","GirihRhombus","RHOMBUS","Matrix4x4","setFromObject","setIdentity","mat","xx","xy","xz","xw","yx","yy","yz","yw","zx","zy","zz","zw","wx","wy","wz","ww","apply4","vec4","apply3","vec3","assign","result4","setRotation","X","Y","Z","setScaling","setTranslation","_mat","makeRotationMatrix","makeScalingMatrix","scaleZ","makeTranslationMatrix","translateX","translateY","translateZ","makeTransformationMatrix","rotateX","rotateY","rotateZ","matrixRx","matrixRy","matrixRz","matrixS","matrixT0","Ref","useRef","ColorGradientSelector","isDropdownOpen","css_buttonWidth","css_buttonHeight","css_buttonFontSize","css_buttonFontSize_larger","colorGradients","colorGradientOptionRefs","selectedGradientIndex","installedChangeListeners","__createCustomStylesElement","NoReact.createElement","elementID","containerID","cont","getElementById","isMobileMode","baseID","initialGradients","DEFAULT_COLOR_GRADIENTS","head","append","_render","setGradients","gradients","selectedIndex","__removeAllChildNodes","positioningContainerRef","grad","addGradient","gradient","refMainContainer","NoReact.useRef","refActionButton","refDeleteButton","__renderOptionButton","mainButton","deleteButton","addChangeListener","removeChangeListener","getSelectedColorGradient","__fireChangeEvent","newColorGradient","__mainButtonClickHandler","_evt","visibility","__optionButtonClickHandler","targetButton","currentTarget","clickedIndex_raw","dataset","clickedIndex","__setSelectedIndex","__optionButtonDeleteHandler","__updateOptionDataSetIndices","newSelectedIndex","querySelectorAll","selectedGradient","__setMainButtonGradient","mainButtonContainerRef","refDelButton","sx","flexDirection","ref","onClick","minHeight","maxHeight","flexShrink","alignContent","background","classname","_renderAllOptionButtons","colorGradient","containerRef","minWidth","maxWidth","overflowY","fd","zIndex","BezierPathInteractionHelper","onPointerMoved","onVertexInserted","onVerticesDeleted","onPathRemoved","autoAdjustPaths","allowPathRemoval","maxDetectDistance","mouseIsOver","currentPathIndex","currentDistance","currentT","currentA","currentB","addPath","_mouseEnterListener","_mouseLeaveListener","_clearMoveEvent","_mouseHandler","_installMouseListener","_touchHandler","_installTouchListener","_keyHandler","_installKeyListener","_locatePath","setPathAutoAdjust","removePath","pathIndex","removePathAt","_removeDefaultPathListeners","update","_handleMoveEvent","_handleDelete","pathDeleteIndices","_handleSingleVertexDelete","_handleDeleteOnPath","newCurves","deletedVertIndices","curStart","curStartControl","oldPath","_replacePathAt","posX","posY","oldA","oldB","oldDistance","_updateMinDistance","_event","mouseHandler","pathPoint","pointNear","leftPath","rightPath","removePathVertexDragListeners","closestT","addPathVertexDragStartListeners","vertexDragStartListener","removePathVertexDragStartListeners","addPathVertexDragListeners","vertexDragListener","addPathVertexDragEndListeners","vertexDragEndListener","removePathVertexDragEndListeners","splitSVGPathData","dataString","dataElements","dataRaw","DEG_TO_RAD","_handleMove","isRelative","firstPoint","lastPoint","lastControlPoint","_result","_handleLineTo","_handleHorizontalLineTo","_handleVerticalLineTo","_handleCubicBezierTo","_handleQuadraticCurveTo","localLastQuadraticControlPoint","subData","_handleShorthandQuadraticCurveTo","lastQuadraticControlPoint","_handleShorthandCubicCurveTo","_handleArcTo","arcEndPoint","_handleClosePath","_data","_isRelative","DefaultPositionConverter","positionString","endsWith","__combineRegExp","regexpList","flags","source","regex","RegExp","__parseGradient","regExpLib","input","matchGradient","matchColorStop","stopResult","gradientSearch","lastIndex","exec","original","colorStopList","sideCorner","colorStopSearch","LinearColorGradientParser","rComma","rValue","rColor","rColorStop","rColorStopList","rLineCapture","__generateDefaultRegExpLib","positionConverter","parseRaw","parseResultToColorGradient","bracketPos","gradientType","parseWarning","colorStops","converter","stopListItem","VertexHolder","vertex1","vertex2","vertex3","vert3","tension","solveClosed","solveOpen","radiusPoint","centerHandler","_handleDragCenter","radiusHandler","_handleDragRadiusPoint","_draw","_fill","controlPointStart","controlPointEnd","centerListener","radiusStartListener","_handleDragStartControlPoint","radiusEndListener","_handleDragEndControlPoint","_sliderElementRefs","sliderMin","sliderMax","css_indicatorWidth_num","css_indicatorWidth","css_indicatorHeight","css_thumbWidth","css_thumbHeight","css_containerHeight","__mouseDownPosition","__createSliderChangeHandler","targetSlider","currentSliderValue","rangeSliderIndexRaw","rangeSliderIndex","leftSliderValue","__getSliderValue","rightSliderValue","__updateBackgroundGradient","__updateColorIndicator","__initializeDataSets","setGradient","fireChangeEvent","sliderColor","colorValueHEX","getColorGradient","__createColorRangeInput","initialColor","sliderHandler","__updateSliderDataSetIndices","onChange","getRangeLength","__colorChangeHandler","activeSliderIndex_raw","colorInputRef","activeSliderIndex","newColor","colorIndicatorColorButtonRef","__handleRemoveColor","__containerMouseDownHandler","__containerClickHandler","maxDifference","relativeValue","__clickEventToRelativeValue","absoluteValue","__relativeToAbsolute","__locateClosestSliderValue","__addSliderAt","__absoluteToRelative","colorGradientEntry","leftSlider","__getSliderColorAt","newSliderIndex","sliderRef","after","__locateIntervalAt","leftColorString","__getSliderColorString","rightColorString","positionInsideInterval","leftColorObject","rightColorObject","absolute","sliderIndex","__getAllSliderValues","sliderValue","__getSliderColor","__getSliderColorHEXString","__getSliderPercentage","colorInputContainerRef","colorIndicatorRemoveButtonRef","colorValueString","mb","onMouseDown","colorGradientItem","onInput","borderRadius","list","_dataList","getIndicesFromBufferIndex","bufferIndex","getCoordsFromBufferIndex","coordinateIndicesToBufferIndex","pointList","triangulate","Triangulate","st","createBoundingTriangle","AddVertex","minx","miny","maxx","maxy","stv0","stv1","stv2","Edge","mkUniqueEdges","uniqueEdges","edge1","unique","edge2","handleDropEvent","opacity","dataTransfer","files","file","fileDroppedCallbackJSON","reader","FileReader","onload","readEvent","jsonObject","readAsText","fileDroppedCallbackText","fileDroppedCallbackBinary","readAsBinaryString","fileDroppedCallbackSVG","doc","DOMParser","parseFromString","handleDragOverEvent","handleDragLeaveEvent","onFileJSONDropped","onFileTextDropped","onFileSVGDropped","onFileBinaryDropped","desiredBounds","getGeometryBounds","sizeZ","maxDimension","desiredSizeX","desiredSizeY","desiredSizeZ","MIN_VALUE","depth","TILE_TEMPLATES","tiles","initTemplates","decagon","pentagon","hexagon","bowtie","rhombus","penrose","addTile","removeTileAt","removeAllTiles","replaceTiles","getTileByCenter","locateConatiningTile","locateContainingTileAndEdge","containedTileIndex","hoverTileIndex","hoverEdgeIndex","tileIndex","turnTile","turnCount","moveTile","moveXAmount","moveYAmount","findPossibleAdjacentTiles","adjTiles","template","foundTiles","timeout","timeoutMessage","_acceptRejectPairs","_timeoutMessage","_isInitialized","_fireReject","accept","_initializedValue","_fireAccept","pair","reject","waitForInitialized","Promise","freqA","freqB","phaseA","phaseB","toPolyLine","toQuadraticBezierApproximation","dx2","dy2","dx1","dy1","inputCircles","circleIsFullyContained","circlesOfInterest","containingCircles","inverseCirclesPairs","rebuild","detectContainmentStatus","rebuildContainingCircles","radicalLineMatrix","centerCircleA","centerCircleB","inverseCircle1","metaRadiusAddon","inverseCircle2","doIntersect","circlePointsA","circlePointsB","baseCircleIndexA","baseCircleIndexB","baseCircleA","baseCircleB","inverseCircleA","inverseCircleB","checkCircleFullyContained","circleIndex","containingCircle","handleVert","handleFace","_seekEOL","byteView","curPosition","_handleLine","lineNo","faceParams","faceSplit","arrayBuffer","Int8Array","curEnd","lineBuffer","String","fromCharCode","byteLength","baseParams","hasParam","getString","isValueAllowed","getNumber","numericValue","getBoolean","toLocaleLowerCase","perm","gradP","seed","simplex2","xin","yin","x0","y0","i1","j1","gi0","gi1","gi2","t0","simplex3","zin","z0","k1","i2","j2","k2","z1","z2","z3","gi3","t3","perlin2","x_init","y_init","n00","n01","n10","n11","perlin3","z_init","n000","n001","n010","n011","n100","n101","n110","n111","handleFacet","_parseSTLString","stl","vertexes","_handleFacet","preVertexHolder","vertValues","tempVertex","replace","preVertex","_parseSTLBinary","buf","le","numTriangles","DataView","getUint32","dv","normal","getFloat32","vertHolder","vIndex","binaryOrAsciiString","isAscii","ab","ArrayBuffer","view","Uint8Array","_toArrayBuffer","setInitiallyEquilateral","handlerA","_handleTrianglePoint","handlerB","handlerC","mid","rotationControlPoint","_rotationControlLine","_centerPointHandler","_handleDragCenterPoint","_rotationPointHandler","_handleRotationCenterPoint","newRotation","rDiff","startAngleControlPoint","endAngleControlPoint","_startAngleControlLine","_endAngleControlLine","_centerHandler","_rotationHandler","_handleDragRotationControlPoint","_startAngleHandler","_handleDragStartAngleControlPoint","_endAngleHandler","_handleDragEndAngleControlPoint","desiredSize","factoryFn","equalVerts","findEndOfRun","bestCircle","bestTriangle","_circle","numVertices","createClockwise","failedTriangleSets","hasErrors","build","voronoiDiagram","adjacentSubset","subsetToPath","triangleSet","startPosition","tryOnce","GUP","isDarkmode","overrideValue","matchMedia","matches","hours","getHours","classList","vertexList","pop","U","gui","cssProps","domElement","guiDoubleSize","applyGuiSize","vars","location","href","_m","decodeURIComponent","cmd","visitedLeftBorderMatrix","safetyLimit","nonVisitedPosition"],"mappings":"oEAqBO,MAAMA,EAUT,WAAAC,GAKI,IAAK,IAAIC,KAJTC,KAAKC,WAAY,EACjBD,KAAKE,YAAa,EAClBF,KAAKG,YAAa,EAClBH,KAAKI,SAAU,EACCP,EAAWQ,MACvBL,KAAKD,GAAOF,EAAWQ,MAAMN,EACpC,EASLF,EAAWQ,MAAQ,CACfJ,WAAW,EACXC,YAAY,EACZC,YAAY,EACZC,SAAS,GC5CN,MAAME,EACT,WAAOC,GACH,MAAO,GAAGD,EAAaE,SAC1B,EAELF,EAAaE,QAAU,ECQhB,MAAMC,EAQT,WAAAX,CAAYY,GACRV,KAAKW,MAAQ,GACbX,KAAKY,KAAO,GACZZ,KAAKa,UAAY,GACjBb,KAAKc,QAAU,GACfd,KAAKU,OAASA,CACjB,CAUD,gBAAAK,CAAiBC,GAEb,OADAP,EAAgBQ,aAAajB,KAAKW,MAAOK,GAClChB,IACV,CAeD,mBAAAkB,CAAoBF,GAEhB,OADAhB,KAAKW,MAAQF,EAAgBU,gBAAgBnB,KAAKW,MAAOK,GAClDhB,IACV,CAeD,eAAAoB,CAAgBJ,GAEZ,OADAP,EAAgBQ,aAAajB,KAAKY,KAAMI,GACjChB,IACV,CAeD,kBAAAqB,CAAmBL,GAEf,OADAhB,KAAKY,KAAOH,EAAgBU,gBAAgBnB,KAAKY,KAAMI,GAChDhB,IACV,CAUD,oBAAAsB,CAAqBN,GAEjB,OADAP,EAAgBQ,aAAajB,KAAKa,UAAWG,GACtChB,IACV,CAeD,uBAAAuB,CAAwBP,GAEpB,OADAhB,KAAKa,UAAYJ,EAAgBU,gBAAgBnB,KAAKa,UAAWG,GAC1DhB,IACV,CAUD,kBAAAwB,CAAmBR,GAGf,OADAP,EAAgBQ,aAAajB,KAAKc,QAASE,GACpChB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