UNPKG

@rxflow/manhattan

Version:

Manhattan routing algorithm for ReactFlow - generates orthogonal paths with obstacle avoidance

88 lines (81 loc) 2.18 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.Line = void 0; var _Point = require("./Point"); /** * Line class representing a line segment */ class Line { start; end; constructor(start, end) { this.start = start; this.end = end; } /** * Calculate intersection points with a rectangle * Returns an array of intersection points */ intersect(rect) { const intersections = []; // Define rectangle edges const edges = [ // Top edge { p1: new _Point.Point(rect.x, rect.y), p2: new _Point.Point(rect.x + rect.width, rect.y) }, // Right edge { p1: new _Point.Point(rect.x + rect.width, rect.y), p2: new _Point.Point(rect.x + rect.width, rect.y + rect.height) }, // Bottom edge { p1: new _Point.Point(rect.x, rect.y + rect.height), p2: new _Point.Point(rect.x + rect.width, rect.y + rect.height) }, // Left edge { p1: new _Point.Point(rect.x, rect.y), p2: new _Point.Point(rect.x, rect.y + rect.height) }]; // Check intersection with each edge for (const edge of edges) { const intersection = this.lineIntersection(this.start, this.end, edge.p1, edge.p2); if (intersection) { intersections.push(intersection); } } return intersections; } /** * Calculate intersection point between two line segments * Returns null if lines don't intersect */ lineIntersection(p1, p2, p3, p4) { const x1 = p1.x, y1 = p1.y; const x2 = p2.x, y2 = p2.y; const x3 = p3.x, y3 = p3.y; const x4 = p4.x, y4 = p4.y; const denom = (x1 - x2) * (y3 - y4) - (y1 - y2) * (x3 - x4); // Lines are parallel if (Math.abs(denom) < 1e-10) { return null; } const t = ((x1 - x3) * (y3 - y4) - (y1 - y3) * (x3 - x4)) / denom; const u = -((x1 - x2) * (y1 - y3) - (y1 - y2) * (x1 - x3)) / denom; // Check if intersection is within both line segments if (t >= 0 && t <= 1 && u >= 0 && u <= 1) { return new _Point.Point(x1 + t * (x2 - x1), y1 + t * (y2 - y1)); } return null; } } exports.Line = Line;