vibe-sketcherDocumentation

Source code for vibesketcher.render.orthogonal

"""Orthogonal connector routing around boxes (#247).

The method is that of M. Wybrow, K. Marriott and P. J. Stuckey,
"Orthogonal connector routing", in *Graph Drawing 2009*, LNCS 5849,
219-231 (2010), doi:10.1007/978-3-642-11805-0_22:

1. **Orthogonal visibility graph** (section 3). Every box is an obstacle,
   grown by a clearance. The interesting points are the corners of the grown
   boxes and the connection points just outside each box side. From each
   interesting point a horizontal and a vertical visibility segment run until
   they meet an obstacle or the drawing's bounding rectangle; the graph's
   vertices are the intersections of those segments, and its edges join
   neighbouring vertices along a segment. A path in this graph never enters a
   grown box.
2. **Shortest path with a bend penalty** (section 4). Each connector is the
   cheapest path from a connection point of its source box to one of its
   target box, where the cost is the length plus a fixed penalty per bend.
   It is Dijkstra's algorithm over (vertex, heading) states, so a bend is an
   edge of the search, and a U-turn is never taken. Ties are broken by the
   order the states were reached in, which is fixed, so the same boxes always
   give the same routes.
3. **Nudging** (section 5, simplified). Segments of different connectors
   that lie on the same line and overlap are spread across the channel,
   ordered by the side their connectors turn to at both ends so they do not
   cross needlessly. The spread stays inside the clearance, so a nudged
   segment still keeps out of every box. The paper solves a separation
   problem over all channels; here each shared run is spread on its own.

A connector leaves its source box perpendicular to a side, at the side's
midpoint, and ends perpendicular to a side of its target box, so its last
segment carries the arrowhead straight into the box.

Everything is in drawing points with y down. :func:`route` raises
:class:`NoRoute` when the boxes leave no orthogonal path; it never falls back
to a line through a box.
"""

from __future__ import annotations

import bisect
import heapq
import math
from collections.abc import Sequence
from typing import Final

__all__ = ["NoRoute", "Point", "Rect", "count_bends", "route"]

Point = tuple[float, float]
Rect = tuple[float, float, float, float]

_EPS: Final = 1e-6
#: Headings, in the fixed order the search tries them: east, south, west, north (y down).
_STEPS: Final = ((1, 0), (0, 1), (-1, 0), (0, -1))
_EAST, _SOUTH, _WEST, _NORTH = range(4)


[docs] class NoRoute(ValueError): """No orthogonal path joins two boxes without entering another; ``edge`` is its index.""" def __init__(self, edge: int) -> None: super().__init__(f"no orthogonal route for edge {edge}") self.edge = edge
def _key(x: float, y: float) -> tuple[float, float]: return round(x, 6), round(y, 6) def _inside(x: float, y: float, rect: Rect) -> bool: """Strictly inside ``rect``; the boundary is free space.""" return rect[0] + _EPS < x < rect[2] - _EPS and rect[1] + _EPS < y < rect[3] - _EPS def _ports(box: Rect, clearance: float, prefer: str) -> list[tuple[int, Point, Point]]: """(outward heading, point on the side, escape point) for the four sides. The sides are listed with the flow direction first, so a tie leaves a box the way the diagram reads: down and out of the bottom, or right and out of the right side. """ x0, y0, x1, y1 = box cx, cy = (x0 + x1) / 2, (y0 + y1) / 2 sides = { _SOUTH: ((cx, y1), (cx, y1 + clearance)), _NORTH: ((cx, y0), (cx, y0 - clearance)), _EAST: ((x1, cy), (x1 + clearance, cy)), _WEST: ((x0, cy), (x0 - clearance, cy)), } order = (_SOUTH, _EAST, _WEST, _NORTH) if prefer == "down" else (_EAST, _SOUTH, _NORTH, _WEST) return [(heading, *sides[heading]) for heading in order] def _aligned_ports( a: Rect, b: Rect, clearance: float ) -> list[tuple[tuple[int, Point, Point], tuple[int, Point, Point]]]: """Facing ports of two boxes that overlap along an axis, at the middle of the overlap. Two boxes one above the other whose spans overlap can be joined by one straight segment; a side midpoint would need a jog when their centres differ. Returns ((port on a), (port on b)) pairs. """ pairs = [] for axis in (0, 1): low, high = max(a[axis], b[axis]), min(a[axis + 2], b[axis + 2]) if high - low <= 2 * _EPS: continue mid = (low + high) / 2 other = 1 - axis if b[other] >= a[other + 2] - _EPS: # b after a along the other axis a_side, b_side = a[other + 2], b[other] a_heading = _SOUTH if other == 1 else _EAST elif a[other] >= b[other + 2] - _EPS: a_side, b_side = a[other], b[other + 2] a_heading = _NORTH if other == 1 else _WEST else: continue sign = _STEPS[a_heading][other] def point(along: float, across: float, axis: int = axis) -> Point: return (along, across) if axis == 0 else (across, along) pairs.append( ( (a_heading, point(mid, a_side), point(mid, a_side + sign * clearance)), ((a_heading + 2) % 4, point(mid, b_side), point(mid, b_side - sign * clearance)), ) ) return pairs class _Graph: """The orthogonal visibility graph: vertices and each one's nearest neighbour per heading.""" def __init__(self, obstacles: Sequence[Rect], points: Sequence[Point], bound: Rect) -> None: self.vertices: list[Point] = [] self.index: dict[tuple[float, float], int] = {} self.next: list[list[int]] = [] horizontal: set[tuple[float, float, float]] = set() vertical: set[tuple[float, float, float]] = set() for px, py in points: left, right = bound[0], bound[2] top, bottom = bound[1], bound[3] for x0, y0, x1, y1 in obstacles: if y0 + _EPS < py < y1 - _EPS: if x1 <= px + _EPS: left = max(left, x1) elif x0 >= px - _EPS: right = min(right, x0) if x0 + _EPS < px < x1 - _EPS: if y1 <= py + _EPS: top = max(top, y1) elif y0 >= py - _EPS: bottom = min(bottom, y0) horizontal.add((round(py, 6), round(left, 6), round(right, 6))) vertical.add((round(px, 6), round(top, 6), round(bottom, 6))) rows = sorted(horizontal) row_y = [r[0] for r in rows] on_row: dict[tuple[float, float, float], list[int]] = {r: [] for r in rows} for x, top, bottom in sorted(vertical): column: list[int] = [] start = bisect.bisect_left(row_y, top - _EPS) stop = bisect.bisect_right(row_y, bottom + _EPS) for row in rows[start:stop]: y, left, right = row if left - _EPS <= x <= right + _EPS: v = self._vertex(x, y) column.append(v) on_row[row].append(v) self._link(column, _SOUTH, axis=1) for row in rows: self._link(on_row[row], _EAST, axis=0) def _vertex(self, x: float, y: float) -> int: key = _key(x, y) found = self.index.get(key) if found is None: found = len(self.vertices) self.index[key] = found self.vertices.append(key) self.next.append([-1, -1, -1, -1]) return found def _link(self, members: list[int], forward: int, axis: int) -> None: """Join neighbouring vertices along one segment, keeping the nearest per heading.""" ordered = sorted(set(members), key=lambda v: self.vertices[v][axis]) backward = (forward + 2) % 4 for a, b in zip(ordered, ordered[1:], strict=False): gap = self.vertices[b][axis] - self.vertices[a][axis] if gap <= _EPS: continue here = self.next[a][forward] if here < 0 or self.vertices[here][axis] - self.vertices[a][axis] > gap: self.next[a][forward] = b there = self.next[b][backward] if there < 0 or self.vertices[b][axis] - self.vertices[there][axis] > gap: self.next[b][backward] = a def _simplify(points: list[Point]) -> list[Point]: """Drop repeated points and the middle point of three collinear ones.""" out: list[Point] = [] for p in points: if out and math.dist(out[-1], p) <= _EPS: continue if len(out) >= 2: a, b = out[-2], out[-1] if (abs(a[0] - b[0]) <= _EPS and abs(b[0] - p[0]) <= _EPS) or ( abs(a[1] - b[1]) <= _EPS and abs(b[1] - p[1]) <= _EPS ): out[-1] = p continue out.append(p) return out def _shortest( graph: _Graph, starts: list[tuple[int, int, Point]], goals: dict[int, list[tuple[int, Point]]], clearance: float, bend: float, ) -> list[Point] | None: """The cheapest path from a start (vertex, heading, side point) to a goal vertex. ``goals`` maps a vertex to its (inward heading, side point) pairs. The cost is length plus ``bend`` per change of heading, the final turn into the target box included. The search is A* (Hart, Nilsson and Raphael 1968, doi:10.1109/TSSC.1968.300136) with the Manhattan distance to the nearest goal plus the final stub as its estimate: every move is horizontal or vertical, so the estimate never exceeds the remaining cost and is consistent, and the path found is the cheapest one. """ targets = [graph.vertices[v] for v in goals] def estimate(v: int) -> float: x, y = graph.vertices[v] return clearance + min(abs(x - gx) + abs(y - gy) for gx, gy in targets) best: dict[tuple[int, int], float] = {} came: dict[tuple[int, int], tuple[int, int] | None] = {} first: dict[tuple[int, int], Point] = {} # (estimated total, insertion order, cost so far, vertex, heading, goal or -1) heap: list[tuple[float, int, float, int, int, int]] = [] seq = 0 for v, heading, side in starts: state = (v, heading) if clearance < best.get(state, math.inf): best[state] = clearance came[state] = None first[state] = side heapq.heappush(heap, (clearance + estimate(v), seq, clearance, v, heading, -1)) seq += 1 finished: tuple[tuple[int, int], Point] | None = None while heap: _f, _order, cost, v, heading, goal = heapq.heappop(heap) if goal >= 0: finished = ((v, heading), goals[v][goal][1]) break if cost > best.get((v, heading), math.inf) + _EPS: continue for k, (inward, _side) in enumerate(goals.get(v, ())): if inward == (heading + 2) % 4: continue total = cost + clearance + (bend if inward != heading else 0.0) heapq.heappush(heap, (total, seq, total, v, heading, k)) seq += 1 here = graph.vertices[v] for step in range(4): if step == (heading + 2) % 4: continue w = graph.next[v][step] if w < 0: continue there = graph.vertices[w] length = abs(there[0] - here[0]) + abs(there[1] - here[1]) total = cost + length + (bend if step != heading else 0.0) state = (w, step) if total < best.get(state, math.inf) - _EPS: best[state] = total came[state] = (v, heading) heapq.heappush(heap, (total + estimate(w), seq, total, w, step, -1)) seq += 1 if finished is None: return None final, end_side = finished chain: list[Point] = [end_side] walk: tuple[int, int] | None = final last = final while walk is not None: chain.append(graph.vertices[walk[0]]) last = walk walk = came[walk] chain.append(first[last]) return _simplify(chain[::-1]) def _sign(value: float) -> int: return 0 if abs(value) <= _EPS else (1 if value > 0 else -1) def _nudge( routes: list[list[Point]], ends: list[tuple[Rect, Rect]], clearance: float, spacing: float ) -> None: """Spread overlapping collinear segments of different connectors across their channel.""" # (axis of the segment's fixed coordinate, coordinate) -> [(start, end, route, segment)] lines: dict[tuple[int, float], list[tuple[float, float, int, int]]] = {} for r, points in enumerate(routes): for i in range(len(points) - 1): (ax, ay), (bx, by) = points[i], points[i + 1] if abs(ay - by) <= _EPS: lines.setdefault((1, round(ay, 6)), []).append((min(ax, bx), max(ax, bx), r, i)) else: lines.setdefault((0, round(ax, 6)), []).append((min(ay, by), max(ay, by), r, i)) shifts: list[tuple[int, int, int, float]] = [] for (axis, coordinate), members in sorted(lines.items()): members.sort() clusters: list[list[tuple[float, float, int, int]]] = [] reach = -math.inf for member in members: if clusters and member[0] < reach - _EPS: clusters[-1].append(member) reach = max(reach, member[1]) else: clusters.append([member]) reach = member[1] for cluster in clusters: if len({m[2] for m in cluster}) < 2: continue def turn( member: tuple[float, float, int, int], axis: int = axis, coordinate: float = coordinate, ) -> tuple[int, int]: # Which side the connector comes from and goes to: -1 toward smaller # coordinates (up or left), so it takes the upper or left place. _s, _e, r, i = member points = routes[r] total = 0 if i > 0: total += _sign(points[i - 1][axis] - coordinate) if i + 2 < len(points): total += _sign(points[i + 2][axis] - coordinate) return total, r ordered = sorted(cluster, key=turn) k = len(ordered) step = min(spacing, 1.8 * clearance / (k - 1)) for j, (_s, _e, r, i) in enumerate(ordered): shifts.append((r, i, axis, (j - (k - 1) / 2) * step)) for r, i, axis, offset in shifts: points = routes[r] for end in (i, i + 1): if end in (0, len(points) - 1): # A connection point slides along its side and stays on it. rect = ends[r][0] if end == 0 else ends[r][1] low, high = (rect[0], rect[2]) if axis == 0 else (rect[1], rect[3]) margin = min(0.25 * (high - low), clearance) value = points[end][axis] + offset offset = max(low + margin, min(high - margin, value)) - points[end][axis] for end in (i, i + 1): x, y = points[end] points[end] = (x + offset, y) if axis == 0 else (x, y + offset)
[docs] def count_bends(points: Sequence[Point]) -> int: """The number of bends of a polyline.""" return max(len(points) - 2, 0)
[docs] def route( boxes: Sequence[Rect], edges: Sequence[tuple[int, int]], *, clearance: float, bend: float, spacing: float, prefer: str = "down", ) -> list[list[Point]]: """Orthogonal polylines from box ``source`` to box ``target`` for each edge. Each starts on a side of the source box and ends on a side of the target box, perpendicular to both, and keeps ``clearance`` from every other box. ``bend`` is the cost of one bend in points of length; ``spacing`` is the widest gap between nudged parallel segments. Raises :class:`NoRoute`. """ grown = [ (x0 - clearance, y0 - clearance, x1 + clearance, y1 + clearance) for x0, y0, x1, y1 in boxes ] if not grown: return [] bound = ( min(r[0] for r in grown) - clearance, min(r[1] for r in grown) - clearance, max(r[2] for r in grown) + clearance, max(r[3] for r in grown) + clearance, ) candidates: dict[int, list[tuple[int, Point, Point]]] = {} for source, target in edges: for on_source, on_target in _aligned_ports(boxes[source], boxes[target], clearance): candidates.setdefault(source, []).append(on_source) candidates.setdefault(target, []).append(on_target) ports: dict[int, list[tuple[int, Point, Point]]] = {} points: list[Point] = [] for v in sorted({v for edge in edges for v in edge}): free: list[tuple[int, Point, Point]] = [] seen: set[tuple[int, tuple[float, float]]] = set() for heading, side, escape in candidates.get(v, []) + _ports(boxes[v], clearance, prefer): # On the graph's 1e-6 grid, so the stub is exactly perpendicular to the side. port = (heading, _key(*side), _key(*escape)) key = (heading, port[2]) if key not in seen and not any(_inside(*port[2], other) for other in grown): seen.add(key) free.append(port) ports[v] = free points.extend(port[2] for port in free) for x0, y0, x1, y1 in grown: for corner in ((x0, y0), (x1, y0), (x0, y1), (x1, y1)): if not any(_inside(*corner, other) for other in grown): points.append(corner) graph = _Graph(grown, points, bound) routes: list[list[Point]] = [] for k, (source, target) in enumerate(edges): starts = [ (graph.index[_key(*escape)], heading, side) for heading, side, escape in ports[source] ] goals: dict[int, list[tuple[int, Point]]] = {} for heading, side, escape in ports[target]: goals.setdefault(graph.index[_key(*escape)], []).append(((heading + 2) % 4, side)) found = _shortest(graph, starts, goals, clearance, bend) if starts and goals else None if found is None: raise NoRoute(k) routes.append(found) _nudge(routes, [(boxes[s], boxes[t]) for s, t in edges], clearance, spacing) return [_simplify(points_) for points_ in routes]