mod constraints;
mod full;
mod order;
mod segments;
mod solve;
mod vpsc;
use alloc::collections::BTreeMap;
use alloc::vec::Vec;
use crate::geom::{Axis, Direction, Point, Rect};
use crate::graph::{RoutingGraph, VertexId};
use crate::nets::Net;
use crate::route::Route;
pub use constraints::{Constraint, Item, Kind};
use constraints::Object;
use segments::Segments;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Config {
pub separation: u32,
pub max_separation: u32,
pub placement: Placement,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
pub enum Placement {
#[default]
Spread,
Project,
}
impl Default for Config {
fn default() -> Self {
Self {
separation: 4,
max_separation: 8,
placement: Placement::Spread,
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Nudged {
pub routes: Vec<Vec<Point>>,
pub separation: Option<u32>,
pub overlaps: usize,
}
#[must_use]
pub fn nudge(
graph: &RoutingGraph,
obstacles: &[Rect],
routes: &[Route],
config: &Config,
) -> Nudged {
let nets: Vec<Net> = routes.iter().map(|r| Net::from_route(graph, r)).collect();
let (segments, separation) = run(graph, obstacles, &nets, *config);
let polylines: Vec<Vec<Point>> = routes
.iter()
.enumerate()
.map(|(i, r)| {
bend_vertices(graph, &r.vertices)
.into_iter()
.map(|v| segments.position(graph, i, v, &nets))
.collect()
})
.collect();
let overlaps = count_overlaps(&polylines);
Nudged {
routes: polylines,
separation: separation.map(|s| u32::try_from(s).unwrap_or(u32::MAX)),
overlaps,
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct FullNudged {
pub boxes: Vec<Rect>,
pub routes: Vec<Vec<Point>>,
}
#[must_use]
pub fn full(
graph: &RoutingGraph,
boxes: &[Rect],
routes: &[Route],
config: &Config,
) -> Option<FullNudged> {
let nets: Vec<Net> = routes.iter().map(|r| Net::from_route(graph, r)).collect();
let mut segments = Segments::new(graph, &nets);
let mut moved = boxes.to_vec();
let separation = i64::from(config.separation);
if !full::pass(
graph,
&mut moved,
&nets,
&mut segments,
Axis::Y,
separation,
&[],
) {
return None;
}
let kisses = kiss_arcs(graph, &nets, &segments);
if !full::pass(
graph,
&mut moved,
&nets,
&mut segments,
Axis::X,
separation,
&kisses,
) {
return None;
}
let polylines = routes
.iter()
.enumerate()
.map(|(i, r)| {
bend_vertices(graph, &r.vertices)
.into_iter()
.map(|v| segments.position(graph, i, v, &nets))
.collect()
})
.collect();
Some(FullNudged {
boxes: moved,
routes: polylines,
})
}
#[must_use]
pub fn nudge_nets(
graph: &RoutingGraph,
obstacles: &[Rect],
nets: &[Net],
config: &Config,
) -> (Vec<Vec<(Point, Point)>>, Option<u32>) {
let (segments, separation) = run(graph, obstacles, nets, *config);
let mut out = alloc::vec![Vec::new(); nets.len()];
for s in segments.list.iter().filter(|s| s.vertices.len() > 1) {
let a = segments.position(graph, s.net, s.low(), nets);
let b = segments.position(graph, s.net, s.high(), nets);
out[s.net].push((a, b));
}
(
out,
separation.map(|s| u32::try_from(s).unwrap_or(u32::MAX)),
)
}
#[must_use]
pub fn constraints(
graph: &RoutingGraph,
obstacles: &[Rect],
routes: &[Route],
axis: Axis,
) -> Vec<Constraint> {
let nets: Vec<Net> = routes.iter().map(|r| Net::from_route(graph, r)).collect();
let segments = Segments::new(graph, &nets);
let objects = pass_objects(graph, obstacles, &nets, &segments, axis, &[]);
let mut constraints = constraints::generate(&objects);
constraints.extend(shape_constraints(graph, &nets, &segments, axis));
constraints
}
fn shape_constraints(
graph: &RoutingGraph,
nets: &[Net],
segments: &Segments,
axis: Axis,
) -> Vec<Constraint> {
let mut out = Vec::new();
for (id, s) in segments.list.iter().enumerate() {
if s.axis != axis || s.fixed {
continue;
}
for &end in &s.vertices {
let across = s.forward().left();
for dir in [across, across.reverse()] {
if !nets[s.net].has_edge(end, dir) {
continue;
}
let Some(p) = segments.of_edge(graph, s.net, end, dir) else {
continue;
};
let perpendicular = &segments.list[p];
let far = if perpendicular.low() == end {
perpendicular.high()
} else if perpendicular.high() == end {
perpendicular.low()
} else {
continue;
};
let other = far_item(graph, nets, segments, p, far);
let (left, right) = if dir.is_positive() {
(Item::Segment(id), other)
} else {
(other, Item::Segment(id))
};
out.push(Constraint {
left,
right,
kind: Kind::Shape,
});
}
}
}
out
}
fn far_item(
graph: &RoutingGraph,
nets: &[Net],
segments: &Segments,
p: usize,
far: VertexId,
) -> Item {
let perpendicular = &segments.list[p];
let across = perpendicular.forward().left();
for dir in [across, across.reverse()] {
if nets[perpendicular.net].has_edge(far, dir) {
if let Some(q) = segments.of_edge(graph, perpendicular.net, far, dir) {
return Item::Segment(q);
}
}
}
match segments.terminal_point(perpendicular.net, far, perpendicular.axis.other()) {
Some(t) => Item::Segment(t),
None => Item::Bound(graph.point(far).coordinate(perpendicular.axis)),
}
}
#[must_use]
pub fn segment_lines(graph: &RoutingGraph, routes: &[Route]) -> Vec<(usize, Axis, i32)> {
let nets: Vec<Net> = routes.iter().map(|r| Net::from_route(graph, r)).collect();
let segments = Segments::new(graph, &nets);
segments
.list
.iter()
.zip(&segments.line)
.map(|(s, &l)| (s.net, s.axis, l))
.collect()
}
fn count_overlaps(polylines: &[Vec<Point>]) -> usize {
let mut count = 0;
for (i, a) in polylines.iter().enumerate() {
for b in &polylines[i + 1..] {
for pa in a.windows(2) {
for pb in b.windows(2) {
count += usize::from(collinear_overlap(pa[0], pa[1], pb[0], pb[1]));
}
}
}
}
count
}
fn collinear_overlap(a0: Point, a1: Point, b0: Point, b1: Point) -> bool {
let overlap = |p: i32, q: i32, r: i32, s: i32| p.min(q).max(r.min(s)) < p.max(q).min(r.max(s));
if a0.y == a1.y && b0.y == b1.y && a0.y == b0.y {
return overlap(a0.x, a1.x, b0.x, b1.x);
}
a0.x == a1.x && b0.x == b1.x && a0.x == b0.x && overlap(a0.y, a1.y, b0.y, b1.y)
}
fn bend_vertices(graph: &RoutingGraph, path: &[VertexId]) -> Vec<VertexId> {
let mut out = Vec::new();
for (i, &v) in path.iter().enumerate() {
let keep = i == 0
|| i + 1 == path.len()
|| Direction::between(graph.point(path[i - 1]), graph.point(v))
!= Direction::between(graph.point(v), graph.point(path[i + 1]));
if keep {
out.push(v);
}
}
out
}
fn run(
graph: &RoutingGraph,
obstacles: &[Rect],
nets: &[Net],
config: Config,
) -> (Segments, Option<i64>) {
let mut segments = Segments::new(graph, nets);
let first = pass(graph, obstacles, nets, &mut segments, Axis::Y, config, &[]);
let kisses = kiss_arcs(graph, nets, &segments);
let second = pass(
graph,
obstacles,
nets,
&mut segments,
Axis::X,
config,
&kisses,
);
let separation = match (first, second) {
(Some(a), Some(b)) => Some(a.min(b)),
(a, b) => a.or(b),
};
(segments, separation)
}
fn pass_objects(
graph: &RoutingGraph,
obstacles: &[Rect],
nets: &[Net],
segments: &Segments,
axis: Axis,
extra: &[(usize, usize)],
) -> Vec<Object> {
let terminal = segments.terminal_arcs(nets, axis);
let required = fixed_side_arcs(graph, obstacles, nets, segments, axis);
let ranks = order::line_ranks(graph, nets, segments, axis, (&required, &terminal), extra);
let mut objects = constraints::obstacle_objects(obstacles, axis.other());
for (id, s) in segments.list.iter().enumerate() {
if s.axis == axis {
objects.push(Object {
item: Item::Segment(id),
position: segments.line[id],
extent: segments.extent(graph, nets, id),
rank: ranks[id],
});
}
}
objects
}
fn fixed_side_arcs(
graph: &RoutingGraph,
obstacles: &[Rect],
nets: &[Net],
segments: &Segments,
axis: Axis,
) -> Vec<(usize, usize)> {
let across = axis.other();
let mut by_line: BTreeMap<i32, Vec<usize>> = BTreeMap::new();
for (id, s) in segments.list.iter().enumerate() {
if s.axis == axis {
by_line.entry(segments.line[id]).or_default().push(id);
}
}
let mut arcs = Vec::new();
for (&line, members) in &by_line {
for &m in members
.iter()
.filter(|&&m| !segments.list[m].fixed && segments.list[m].vertices.len() > 1)
{
let (lo, hi) = segments.extent(graph, nets, m);
let blocked = |high_side: bool| {
obstacles.iter().any(|r| {
let (a, b) = r.range(across);
let (c, d) = r.range(axis);
let touches = if high_side { a == line } else { b == line };
touches && c < hi && lo < d
})
};
let (low_blocked, high_blocked) = (blocked(false), blocked(true));
if low_blocked == high_blocked {
continue;
}
for &f in members.iter().filter(|&&f| {
segments.list[f].fixed && segments.list[f].net != segments.list[m].net
}) {
let (flo, fhi) = segments.extent(graph, nets, f);
let point = segments.list[f].vertices.len() == 1;
if flo.max(lo) < fhi.min(hi) || (point && lo <= flo && flo <= hi) {
arcs.push(if high_blocked { (m, f) } else { (f, m) });
}
}
}
}
arcs
}
fn pass(
graph: &RoutingGraph,
obstacles: &[Rect],
nets: &[Net],
segments: &mut Segments,
axis: Axis,
config: Config,
extra: &[(usize, usize)],
) -> Option<i64> {
let objects = pass_objects(graph, obstacles, nets, segments, axis, extra);
let mut constraints = constraints::generate(&objects);
constraints.extend(shape_constraints(graph, nets, segments, axis));
let (wall_low, wall_high) = walls(graph, obstacles, segments, axis.other(), config);
let scan_rank = scan_ranks(&objects, segments.list.len());
let movable: Vec<bool> = segments
.list
.iter()
.map(|s| s.axis == axis && !s.fixed)
.collect();
let lines = segments.line.clone();
let constant = |item: Item| -> i64 {
match item {
Item::Segment(i) => i64::from(lines[i]),
Item::ObstacleLow(i) => i64::from(obstacles[i].range(axis.other()).0),
Item::ObstacleHigh(i) => i64::from(obstacles[i].range(axis.other()).1),
Item::WallLow => wall_low,
Item::WallHigh => wall_high,
Item::Bound(c) => i64::from(c),
}
};
let problem = solve::Problem {
constraints: &constraints,
constant: &constant,
movable: &movable,
order: &scan_rank,
current: &lines,
separation: i64::from(config.separation),
max_separation: i64::from(config.max_separation),
project: config.placement == Placement::Project,
zig: &zig_segments(nets, segments),
};
let solution = problem.solve();
for (id, &m) in movable.iter().enumerate() {
if m {
segments.line[id] =
i32::try_from(solution.position[id]).expect("positions stay between the walls");
}
}
solution.separation
}
fn zig_segments(nets: &[Net], segments: &Segments) -> Vec<bool> {
segments
.list
.iter()
.map(|s| {
let across = s.forward().left();
let side = |v: VertexId| {
let arms = nets[s.net].arms_at(v);
match (arms.contains(across), arms.contains(across.reverse())) {
(true, false) => Some(true),
(false, true) => Some(false),
_ => None,
}
};
s.vertices.len() > 1
&& matches!((side(s.low()), side(s.high())), (Some(a), Some(b)) if a != b)
})
.collect()
}
fn scan_ranks(objects: &[Object], count: usize) -> Vec<usize> {
let mut keyed: Vec<(i64, u32, usize)> = objects
.iter()
.filter_map(|o| match o.item {
Item::Segment(id) => Some((i64::from(o.position), o.rank, id)),
_ => None,
})
.collect();
keyed.sort_unstable();
let mut rank = alloc::vec![0; count];
for (r, &(_, _, id)) in keyed.iter().enumerate() {
rank[id] = r;
}
rank
}
fn walls(
graph: &RoutingGraph,
obstacles: &[Rect],
segments: &Segments,
position_axis: Axis,
config: Config,
) -> (i64, i64) {
let coords = graph
.vertices()
.map(|v| graph.point(v).coordinate(position_axis))
.chain(obstacles.iter().flat_map(|r| {
let (a, b) = r.range(position_axis);
[a, b]
}));
let (lo, hi) = coords.fold((i64::MAX, i64::MIN), |(lo, hi), c| {
(lo.min(i64::from(c)), hi.max(i64::from(c)))
});
let count = i64::try_from(segments.list.len()).unwrap_or(i64::MAX / 4);
let margin = i64::from(config.separation.max(1)) * (count + 2);
(lo.saturating_sub(margin), hi.saturating_add(margin))
}
fn kiss_arcs(graph: &RoutingGraph, nets: &[Net], segments: &Segments) -> Vec<(usize, usize)> {
let mut ends: BTreeMap<VertexId, Vec<usize>> = BTreeMap::new();
for (id, s) in segments.list.iter().enumerate() {
if s.axis == Axis::X && s.vertices.len() > 1 {
ends.entry(s.low()).or_default().push(id);
ends.entry(s.high()).or_default().push(id);
}
}
let mut arcs = Vec::new();
for (&v, list) in &ends {
for (i, &a) in list.iter().enumerate() {
for &b in &list[i + 1..] {
if let Some(arc) = kiss(graph, nets, segments, v, a, b) {
arcs.push(arc);
}
}
}
}
arcs
}
fn kiss(
graph: &RoutingGraph,
nets: &[Net],
segments: &Segments,
v: VertexId,
a: usize,
b: usize,
) -> Option<(usize, usize)> {
let (sa, sb) = (&segments.list[a], &segments.list[b]);
let (na, nb) = (&nets[sa.net], &nets[sb.net]);
if sa.net == sb.net || na.terminals.contains(&v) || nb.terminals.contains(&v) {
return None;
}
let arm = |net: &Net, dirs: [Direction; 2]| dirs.into_iter().find(|&d| net.has_edge(v, d));
let (ha, hb) = (
arm(na, [Direction::Left, Direction::Right])?,
arm(nb, [Direction::Left, Direction::Right])?,
);
let (va, vb) = (
arm(na, [Direction::Up, Direction::Down])?,
arm(nb, [Direction::Up, Direction::Down])?,
);
if ha == hb
|| va == vb
|| na.arms_at(v).iter().count() != 2
|| nb.arms_at(v).iter().count() != 2
{
return None;
}
let xa = segments.line[segments.of_edge(graph, sa.net, v, va)?];
let xb = segments.line[segments.of_edge(graph, sb.net, v, vb)?];
let a_on_b_side = if hb == Direction::Right {
xa > xb
} else {
xa < xb
};
if !a_on_b_side {
return None;
}
Some(if vb == Direction::Up { (a, b) } else { (b, a) })
}