use alloc::vec::Vec;
use crate::geom::{Point, Rect, abs_diff};
use crate::route::Route;
use crate::search::{Weights, cost_of};
#[must_use]
pub fn invalidated_by(routes: &[Route], rect: Rect) -> Vec<usize> {
routes
.iter()
.enumerate()
.filter(|(_, r)| r.points.windows(2).any(|w| rect.blocks_segment(w[0], w[1])))
.map(|(i, _)| i)
.collect()
}
#[must_use]
pub fn may_improve(routes: &[Route], region: Rect, weights: Weights) -> Vec<usize> {
routes
.iter()
.enumerate()
.filter(|(_, r)| {
let (Some(&u), Some(&v)) = (r.points.first(), r.points.last()) else {
return false;
};
let bound = weights.length.saturating_mul(detour_through(u, v, ®ion));
bound < cost_of(weights, r.length, r.bends)
})
.map(|(i, _)| i)
.collect()
}
fn detour_through(u: Point, v: Point, region: &Rect) -> u64 {
let gap = |a: i32, b: i32, lo: i32, hi: i32| {
let (low, high) = (a.min(b), a.max(b));
if hi < low {
abs_diff(low, hi)
} else if lo > high {
abs_diff(lo, high)
} else {
0
}
};
let extra =
gap(u.x, v.x, region.min.x, region.max.x) + gap(u.y, v.y, region.min.y, region.max.y);
u.manhattan(v) + 2 * extra
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn detour_bound() {
let region = Rect::new(10, 10, 12, 12);
assert_eq!(
detour_through(Point::new(0, 0), Point::new(4, 0), ®ion),
4 + 2 * (6 + 10)
);
assert_eq!(
detour_through(Point::new(0, 0), Point::new(20, 20), ®ion),
40
);
}
}