connector-routing 0.1.0

Connector routing for diagrams and schematics: many orthogonal connectors at once with bend, length and crossing costs, negotiated congestion, rip-up and reroute, and nudging
Documentation
//! Routing over the 1-bend visibility graph of Marriott, Stuckey and Wybrow (2014).
//!
//! Nodes are `(point, heading)` pairs: obstacle corners with a heading that runs along
//! one of the corner's sides ("hugging" the obstacle), plus the source. An edge joins
//! two nodes when an orthogonal path with at most one bend leads from the first,
//! moving in its heading, to the second, arriving in its heading. By the paper's
//! Theorems 1 and 2, every optimal route is topologically equivalent to an
//! obstacle-hugging route of the same length and bends whose intermediate segments
//! each pass such a corner, so a search over these edges finds the optimum while
//! exploring one representative per class of equivalent routes.
//!
//! The quadratic edge set is never stored: successors are generated by walking the
//! orthogonal visibility graph from the node along its heading and, at every vertex on
//! that ray, along both perpendicular directions.

use alloc::collections::BTreeMap;
use alloc::vec::Vec;

use heuristic_search::{Limits, Successors, a_star, heuristic_fn};

use crate::geom::{DirSet, Direction, Point};
use crate::graph::{RoutingGraph, VertexId};
use crate::route::Route;
use crate::scene::Scene;

use super::{Endpoints, NOT_MOVED, State, Weights, estimate};

/// The 1-bend graph of a scene for one connector.
struct OneBendGraph<'a> {
    /// The orthogonal visibility graph, walked to generate edges.
    graph: &'a RoutingGraph,
    /// The hugging headings at each obstacle corner that is a graph vertex.
    hugging: BTreeMap<Point, DirSet>,
    /// The connector's endpoints.
    endpoints: Endpoints,
    /// The objective weights.
    weights: Weights,
}

/// The headings that run along a side of a rectangle from each of its corners, in the
/// order of [`crate::Rect::corners`].
const ALONG: [[Direction; 2]; 4] = [
    [Direction::Right, Direction::Up],
    [Direction::Left, Direction::Up],
    [Direction::Left, Direction::Down],
    [Direction::Right, Direction::Down],
];

/// The hugging headings of every obstacle corner that is a vertex of the scene graph.
fn hugging_headings(scene: &Scene) -> BTreeMap<Point, DirSet> {
    let mut hugging: BTreeMap<Point, DirSet> = BTreeMap::new();
    for (_, rect) in scene.obstacles() {
        for (corner, along) in rect.corners().into_iter().zip(ALONG) {
            if scene.graph().vertex_at(corner).is_some() {
                *hugging.entry(corner).or_default() |= DirSet::only(along[0]) | along[1];
            }
        }
    }

    hugging
}

/// Adds the nodes the paper's construction misses when port directions force a turn
/// next to a port that no obstacle supports.
///
/// The proof of Theorem 1 slides the second segment towards the first, and the
/// second-to-last towards the last, until an obstacle stops it; without one it would
/// shrink the first or last segment to nothing and change the port direction. So:
///
/// - at the source, every vertex `w` reached from a vertex `b` on a source ray by a
///   perpendicular move in `p` becomes a node `(w, p)` (the end of the second segment);
/// - at the target, every vertex `b` on the ray back from the target against an arrival
///   heading `a` becomes a node `(b, p)` for both `p` perpendicular to `a`.
///
/// Extra nodes only add valid routes, so exactness is kept.
fn add_endpoint_nodes(
    graph: &RoutingGraph,
    endpoints: &Endpoints,
    nodes: &mut BTreeMap<Point, DirSet>,
) {
    for d in endpoints.source_directions.iter() {
        let mut ray = graph.neighbor(endpoints.source, d);
        while let Some(b) = ray {
            for p in [d.left(), d.right()] {
                let mut walk = graph.neighbor(b, p);
                while let Some(w) = walk {
                    *nodes.entry(graph.point(w)).or_default() |= DirSet::only(p);
                    walk = graph.neighbor(w, p);
                }
            }

            ray = graph.neighbor(b, d);
        }
    }

    for a in endpoints.target_directions.reversed().iter() {
        let mut ray = graph.neighbor(endpoints.target, a.reverse());
        while let Some(b) = ray {
            *nodes.entry(graph.point(b)).or_default() |= DirSet::only(a.left()) | a.right();
            ray = graph.neighbor(b, a.reverse());
        }
    }
}

/// The flag on a node's heading byte marking a node reached by a zero-length last leg
/// (a bend at the previous bend point). Such a node must not bend again in place, or the
/// route would reverse on the spot.
const IN_PLACE: u8 = 8;

/// The heading of a non-start state, without the [`IN_PLACE`] flag.
fn heading_of(state: State) -> Direction {
    Direction::from_index(usize::from(state.1 & 3))
}

/// `state` without the [`IN_PLACE`] flag, as the shared estimate expects.
fn plain(state: State) -> State {
    if state.1 == NOT_MOVED {
        state
    } else {
        (state.0, state.1 & 3)
    }
}

impl OneBendGraph<'_> {
    /// Emits every edge leaving `from` while moving in `heading`: straight along the
    /// ray, or with one bend at any vertex of the ray. A bend at `from` itself is
    /// allowed only if `bend_here`; the second leg may have zero length.
    fn edges_from(
        &self,
        from: VertexId,
        heading: Direction,
        bend_here: bool,
        emit: &mut impl FnMut(Direction, State, u64),
    ) {
        let start = self.graph.point(from);
        let mut bend_at = Some(from);
        while let Some(b) = bend_at {
            let at = self.graph.point(b);
            let run = start.manhattan(at);
            if b != from {
                self.emit_node(b, heading, run, 0, false, emit);
            }

            if b != from || bend_here {
                for turn in [heading.right(), heading.left()] {
                    self.emit_node(b, turn, run, 1, true, emit);
                    let mut next = self.graph.neighbor(b, turn);
                    while let Some(w) = next {
                        let length = run + at.manhattan(self.graph.point(w));
                        self.emit_node(w, turn, length, 1, false, emit);
                        next = self.graph.neighbor(w, turn);
                    }
                }
            }

            bend_at = self.graph.neighbor(b, heading);
        }
    }

    /// Emits the edge to `(w, heading)` if that is a node: a hugging or endpoint node,
    /// or a valid arrival at the target. `in_place` marks a zero-length last leg, which
    /// cannot be an arrival (the route did not move in `heading`).
    fn emit_node(
        &self,
        w: VertexId,
        heading: Direction,
        length: u64,
        bends: u64,
        in_place: bool,
        emit: &mut impl FnMut(Direction, State, u64),
    ) {
        let point = self.graph.point(w);
        let hugs = self
            .hugging
            .get(&point)
            .is_some_and(|set| set.contains(heading));
        let arrives = !in_place
            && w == self.endpoints.target
            && self
                .endpoints
                .target_directions
                .reversed()
                .contains(heading);
        if !hugs && !arrives {
            return;
        }

        let cost = self
            .weights
            .length
            .saturating_mul(length)
            .saturating_add(self.weights.bend.saturating_mul(bends));
        let mut index = u8::try_from(heading.index()).expect("four directions");
        if in_place {
            index |= IN_PLACE;
        }

        emit(heading, (w.0, index), cost);
    }
}

impl Successors for OneBendGraph<'_> {
    type State = State;
    type Action = Direction;
    type Cost = u64;

    fn successors(&self, state: &State, mut emit: impl FnMut(Direction, State, u64)) {
        let v = VertexId(state.0);
        if state.1 == NOT_MOVED {
            // The first leg must move in a port direction before any bend.
            for d in self.endpoints.source_directions.iter() {
                self.edges_from(v, d, false, &mut emit);
            }

            return;
        }

        self.edges_from(v, heading_of(*state), state.1 & IN_PLACE == 0, &mut emit);
    }
}

/// The optimal route between the endpoints over the 1-bend visibility graph of
/// `scene`, or `None` if there is none.
pub(crate) fn route(scene: &Scene, endpoints: Endpoints, weights: Weights) -> Option<Route> {
    let graph = scene.graph();
    let mut hugging = hugging_headings(scene);
    add_endpoint_nodes(graph, &endpoints, &mut hugging);
    let nodes = OneBendGraph {
        graph,
        hugging,
        endpoints,
        weights,
    };
    let arrivals = endpoints.target_directions.reversed();
    let target = endpoints.target.0;
    let goal = move |s: &State| {
        s.0 == target
            && (s.1 == NOT_MOVED || (s.1 & IN_PLACE == 0 && arrivals.contains(heading_of(*s))))
    };
    let heuristic = heuristic_fn(|s: &State| estimate(graph, &endpoints, weights, plain(*s)));
    let result = a_star(
        &nodes,
        (endpoints.source.0, NOT_MOVED),
        &goal,
        heuristic,
        Limits::NONE,
    );
    let solution = result.into_solution()?;
    let points = bend_points(graph, &solution.states);

    Route::from_points(graph, &points, solution.cost)
}

/// The polyline through a sequence of 1-bend nodes: each edge contributes its bend point
/// (where the heading changes) and its end.
fn bend_points(graph: &RoutingGraph, states: &[State]) -> Vec<Point> {
    let mut points = alloc::vec![graph.point(VertexId(states[0].0))];
    for pair in states.windows(2) {
        let from = graph.point(VertexId(pair[0].0));
        let to = graph.point(VertexId(pair[1].0));
        let heading = heading_of(pair[1]);
        let bend = match heading.axis() {
            // The last leg is horizontal, so the bend shares `to`'s y and `from`'s x.
            crate::geom::Axis::X => Point::new(from.x, to.y),
            crate::geom::Axis::Y => Point::new(to.x, from.y),
        };
        points.push(bend);
        points.push(to);
    }

    points
}