mod resources;
use alloc::vec::Vec;
use crate::Connector;
use crate::error::Error;
use crate::geom::Direction;
use crate::graph::VertexId;
use crate::route::Route;
use crate::scene::{PortId, Scene};
use crate::search::{EdgeCosts, Endpoints, Objective, Weights, endpoints, route_vertices};
pub(crate) use resources::Resources;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Config {
pub objective: Objective,
pub separation: u32,
pub crossing_penalty: u64,
pub max_iterations: u32,
pub history_increment: u64,
pub initial_present: u64,
}
impl Default for Config {
fn default() -> Self {
Self {
objective: Objective::Weighted {
length: 1,
bend: 10,
},
separation: 4,
crossing_penalty: 20,
max_iterations: 40,
history_increment: 1,
initial_present: 1,
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Routing {
pub routes: Vec<Route>,
pub iterations: u32,
pub overuse: u64,
pub crossings: u64,
}
struct Congestion<'a> {
resources: &'a Resources,
occupancy: Vec<u32>,
history: Vec<u64>,
present: u64,
straight: Vec<[u32; 2]>,
crossing_penalty: u64,
}
impl EdgeCosts for Congestion<'_> {
fn edge(&self, from: VertexId, dir: Direction, to: VertexId, length_cost: u64) -> u64 {
let uses = self.resources.of_edge(from, dir, to);
let total_width: u64 = uses.iter().map(|&(_, w)| u64::from(w)).sum();
let unit = length_cost.checked_div(total_width).unwrap_or(0);
uses.iter().fold(0_u64, |sum, &(r, width)| {
let r = r as usize;
let over =
u64::from((self.occupancy[r] + 1).saturating_sub(self.resources.capacity[r]));
let factor =
(1 + self.history[r]).saturating_mul(1 + self.present.saturating_mul(over));
sum.saturating_add(unit.saturating_mul(u64::from(width)).saturating_mul(factor))
})
}
fn pass(&self, at: VertexId, entry: Option<Direction>, exit: Direction) -> u64 {
if entry != Some(exit) {
return 0;
}
let perpendicular = match exit.axis() {
crate::geom::Axis::X => self.straight[at.index()][1],
crate::geom::Axis::Y => self.straight[at.index()][0],
};
self.crossing_penalty
.saturating_mul(u64::from(perpendicular))
}
}
impl Congestion<'_> {
fn apply(&mut self, graph: &crate::graph::RoutingGraph, route: &Route, add: bool) {
for pair in route.vertices.windows(2) {
let dir =
Direction::between(graph.point(pair[0]), graph.point(pair[1])).expect("aligned");
for &(r, _) in self.resources.of_edge(pair[0], dir, pair[1]) {
let slot = &mut self.occupancy[r as usize];
*slot = if add { *slot + 1 } else { *slot - 1 };
}
}
for triple in route.vertices.windows(3) {
let a = graph.point(triple[0]);
let b = graph.point(triple[1]);
let c = graph.point(triple[2]);
if Direction::between(a, b) == Direction::between(b, c) {
let axis = usize::from(a.y != b.y);
let slot = &mut self.straight[triple[1].index()][axis];
*slot = if add { *slot + 1 } else { *slot - 1 };
}
}
}
fn overuse(&self) -> u64 {
self.occupancy
.iter()
.zip(&self.resources.capacity)
.map(|(&used, &cap)| u64::from(used.saturating_sub(cap)))
.sum()
}
fn uses_overused(&self, graph: &crate::graph::RoutingGraph, route: &Route) -> bool {
route.vertices.windows(2).any(|pair| {
let dir =
Direction::between(graph.point(pair[0]), graph.point(pair[1])).expect("aligned");
self.resources
.of_edge(pair[0], dir, pair[1])
.iter()
.any(|&(r, _)| self.occupancy[r as usize] > self.resources.capacity[r as usize])
})
}
fn negotiate(&mut self, increment: u64) {
for (r, h) in self.history.iter_mut().enumerate() {
let over = self.occupancy[r].saturating_sub(self.resources.capacity[r]);
*h = h.saturating_add(increment.saturating_mul(u64::from(over)));
}
self.present = self.present.saturating_mul(2);
}
fn crossings(&self) -> u64 {
self.straight
.iter()
.map(|&[h, v]| u64::from(h) * u64::from(v))
.sum()
}
}
pub fn route_all(
scene: &Scene,
connectors: &[Connector<PortId>],
config: &Config,
) -> Result<Routing, Error> {
let ends: Vec<Endpoints> = connectors
.iter()
.map(|c| endpoints(scene, c.source, c.target))
.collect::<Result<_, _>>()?;
route_all_on(scene.graph(), &scene.rects(), &ends, config)
}
pub fn route_all_on(
graph: &crate::graph::RoutingGraph,
obstacles: &[crate::geom::Rect],
ends: &[Endpoints],
config: &Config,
) -> Result<Routing, Error> {
let weights = config.objective.weights(graph)?;
let ends = ends.to_vec();
let order = net_order(graph, &ends);
let resources = Resources::new(graph, obstacles, config.separation);
let mut congestion = Congestion {
resources: &resources,
occupancy: alloc::vec![0; resources.len()],
history: alloc::vec![0; resources.len()],
present: config.initial_present,
straight: alloc::vec![[0, 0]; graph.capacity()],
crossing_penalty: config.crossing_penalty,
};
let mut routes: Vec<Option<Route>> = alloc::vec![None; ends.len()];
let mut iterations = 0;
while iterations < config.max_iterations.max(1) {
iterations += 1;
let reroute: Vec<usize> = order
.iter()
.copied()
.filter(|&i| {
routes[i]
.as_ref()
.is_none_or(|r| congestion.uses_overused(graph, r))
})
.collect();
if reroute.is_empty() {
break;
}
for i in reroute {
reroute_one(graph, &mut congestion, &mut routes[i], ends[i], weights, i)?;
}
if congestion.overuse() == 0 {
break;
}
congestion.negotiate(config.history_increment);
}
Ok(Routing {
routes: routes.into_iter().flatten().collect(),
iterations,
overuse: congestion.overuse(),
crossings: congestion.crossings(),
})
}
#[must_use]
pub fn overuse(scene: &Scene, routes: &[Route], separation: u32) -> u64 {
overuse_on(scene.graph(), &scene.rects(), routes, separation)
}
#[must_use]
pub fn overuse_on(
graph: &crate::graph::RoutingGraph,
obstacles: &[crate::geom::Rect],
routes: &[Route],
separation: u32,
) -> u64 {
let resources = Resources::new(graph, obstacles, separation);
let mut congestion = Congestion {
resources: &resources,
occupancy: alloc::vec![0; resources.len()],
history: alloc::vec![0; resources.len()],
present: 0,
straight: alloc::vec![[0, 0]; graph.capacity()],
crossing_penalty: 0,
};
for route in routes {
congestion.apply(graph, route, true);
}
congestion.overuse()
}
fn reroute_one(
graph: &crate::graph::RoutingGraph,
congestion: &mut Congestion<'_>,
slot: &mut Option<Route>,
ends: Endpoints,
weights: Weights,
index: usize,
) -> Result<(), Error> {
if let Some(old) = slot.take() {
congestion.apply(graph, &old, false);
}
let route = route_vertices(graph, ends, weights, &*congestion)
.ok_or(Error::NoRoute { connector: index })?;
congestion.apply(graph, &route, true);
*slot = Some(route);
Ok(())
}
fn net_order(graph: &crate::graph::RoutingGraph, ends: &[Endpoints]) -> Vec<usize> {
let mut order: Vec<usize> = (0..ends.len()).collect();
order.sort_by_key(|&i| {
let span = graph
.point(ends[i].source)
.manhattan(graph.point(ends[i].target));
(core::cmp::Reverse(span), i)
});
order
}