Skip to main content

connector_routing/
geom.rs

1//! Exact integer geometry: [`Point`], [`Rect`], [`Direction`], [`DirSet`] and [`Side`].
2//!
3//! Coordinates are `i32` within [`MAX_COORD`]; every derived quantity (differences,
4//! lengths, products) is computed in `i64` or wider, so no predicate can overflow or
5//! round.
6
7use core::fmt;
8use core::ops::{BitOr, BitOrAssign};
9
10/// The largest absolute coordinate the crate accepts.
11///
12/// `2^29` keeps coordinate differences within `2^30`, so the in-circle determinant of
13/// the constrained Delaunay triangulation (products of four differences, times a small
14/// constant) fits into `i128`, and leaves headroom for nudging margins.
15pub const MAX_COORD: i32 = 1 << 29;
16
17/// A point with integer coordinates.
18///
19/// `y` grows "up" in the documentation ([`Direction::Up`] is `+y`). Nothing depends on
20/// handedness, so screen coordinates with `y` growing down work unchanged.
21#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Default)]
22pub struct Point {
23    /// The horizontal coordinate.
24    pub x: i32,
25    /// The vertical coordinate.
26    pub y: i32,
27}
28
29impl Point {
30    /// Creates a point.
31    #[must_use]
32    pub const fn new(x: i32, y: i32) -> Self {
33        Self { x, y }
34    }
35
36    /// The Manhattan (L1) distance to `other`.
37    ///
38    /// # Examples
39    ///
40    /// ```
41    /// use connector_routing::Point;
42    ///
43    /// assert_eq!(Point::new(0, 0).manhattan(Point::new(3, -4)), 7);
44    /// ```
45    #[must_use]
46    pub fn manhattan(self, other: Self) -> u64 {
47        abs_diff(self.x, other.x) + abs_diff(self.y, other.y)
48    }
49
50    /// The squared Euclidean distance to `other`, exact.
51    #[must_use]
52    pub fn distance_squared(self, other: Self) -> u128 {
53        let dx = u128::from(abs_diff(self.x, other.x));
54        let dy = u128::from(abs_diff(self.y, other.y));
55
56        dx * dx + dy * dy
57    }
58
59    /// The coordinate along `axis`.
60    #[must_use]
61    pub fn coordinate(self, axis: Axis) -> i32 {
62        match axis {
63            Axis::X => self.x,
64            Axis::Y => self.y,
65        }
66    }
67
68    /// Whether both coordinates lie within [`MAX_COORD`].
69    #[must_use]
70    pub fn is_in_range(self) -> bool {
71        self.x.unsigned_abs() <= MAX_COORD.unsigned_abs()
72            && self.y.unsigned_abs() <= MAX_COORD.unsigned_abs()
73    }
74}
75
76impl fmt::Display for Point {
77    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
78        write!(f, "({}, {})", self.x, self.y)
79    }
80}
81
82/// `|a - b|` without overflow.
83#[must_use]
84pub(crate) fn abs_diff(a: i32, b: i32) -> u64 {
85    u64::from(a.abs_diff(b))
86}
87
88/// One of the two coordinate axes.
89#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
90pub enum Axis {
91    /// The horizontal axis; horizontal segments run along it.
92    X,
93    /// The vertical axis; vertical segments run along it.
94    Y,
95}
96
97impl Axis {
98    /// The other axis.
99    #[must_use]
100    pub const fn other(self) -> Self {
101        match self {
102            Self::X => Self::Y,
103            Self::Y => Self::X,
104        }
105    }
106}
107
108/// An axis-parallel direction of travel.
109#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
110pub enum Direction {
111    /// Towards larger `x`.
112    Right = 0,
113    /// Towards larger `y`.
114    Up = 1,
115    /// Towards smaller `x`.
116    Left = 2,
117    /// Towards smaller `y`.
118    Down = 3,
119}
120
121impl Direction {
122    /// All four directions, counter-clockwise from [`Direction::Right`].
123    pub const ALL: [Self; 4] = [Self::Right, Self::Up, Self::Left, Self::Down];
124
125    /// The direction with index `i` in [`Direction::ALL`]; `i` is taken modulo 4.
126    #[must_use]
127    pub const fn from_index(i: usize) -> Self {
128        Self::ALL[i % 4]
129    }
130
131    /// The index of this direction in [`Direction::ALL`].
132    #[must_use]
133    pub const fn index(self) -> usize {
134        self as usize
135    }
136
137    /// The opposite direction.
138    #[must_use]
139    pub const fn reverse(self) -> Self {
140        Self::from_index(self.index() + 2)
141    }
142
143    /// The direction after a quarter turn to the left (counter-clockwise).
144    #[must_use]
145    pub const fn left(self) -> Self {
146        Self::from_index(self.index() + 1)
147    }
148
149    /// The direction after a quarter turn to the right (clockwise).
150    #[must_use]
151    pub const fn right(self) -> Self {
152        Self::from_index(self.index() + 3)
153    }
154
155    /// The axis this direction moves along.
156    #[must_use]
157    pub const fn axis(self) -> Axis {
158        match self {
159            Self::Right | Self::Left => Axis::X,
160            Self::Up | Self::Down => Axis::Y,
161        }
162    }
163
164    /// Whether the direction moves towards larger coordinates.
165    #[must_use]
166    pub const fn is_positive(self) -> bool {
167        matches!(self, Self::Right | Self::Up)
168    }
169
170    /// The unit step `(dx, dy)` of this direction.
171    #[must_use]
172    pub const fn delta(self) -> (i32, i32) {
173        match self {
174            Self::Right => (1, 0),
175            Self::Up => (0, 1),
176            Self::Left => (-1, 0),
177            Self::Down => (0, -1),
178        }
179    }
180
181    /// The direction from `from` to `to` if they differ in exactly one coordinate.
182    #[must_use]
183    pub fn between(from: Point, to: Point) -> Option<Self> {
184        match (to.x.cmp(&from.x), to.y.cmp(&from.y)) {
185            (core::cmp::Ordering::Greater, core::cmp::Ordering::Equal) => Some(Self::Right),
186            (core::cmp::Ordering::Less, core::cmp::Ordering::Equal) => Some(Self::Left),
187            (core::cmp::Ordering::Equal, core::cmp::Ordering::Greater) => Some(Self::Up),
188            (core::cmp::Ordering::Equal, core::cmp::Ordering::Less) => Some(Self::Down),
189            _ => None,
190        }
191    }
192
193    /// The number of quarter turns from `self` to `other`: 0 straight, 1 a bend, 2 a
194    /// reversal.
195    #[must_use]
196    pub const fn turns_to(self, other: Self) -> u32 {
197        match (other.index() + 4 - self.index()) % 4 {
198            0 => 0,
199            2 => 2,
200            _ => 1,
201        }
202    }
203}
204
205/// A set of [`Direction`]s, such as the directions a port may be left in.
206#[derive(Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Default)]
207pub struct DirSet(u8);
208
209impl DirSet {
210    /// No direction.
211    pub const NONE: Self = Self(0);
212    /// Every direction.
213    pub const ALL: Self = Self(0b1111);
214    /// Only [`Direction::Right`].
215    pub const RIGHT: Self = Self::only(Direction::Right);
216    /// Only [`Direction::Up`].
217    pub const UP: Self = Self::only(Direction::Up);
218    /// Only [`Direction::Left`].
219    pub const LEFT: Self = Self::only(Direction::Left);
220    /// Only [`Direction::Down`].
221    pub const DOWN: Self = Self::only(Direction::Down);
222
223    /// The set containing only `dir`.
224    #[must_use]
225    pub const fn only(dir: Direction) -> Self {
226        Self(1 << dir.index())
227    }
228
229    /// Whether `dir` is in the set.
230    #[must_use]
231    pub const fn contains(self, dir: Direction) -> bool {
232        self.0 & (1 << dir.index()) != 0
233    }
234
235    /// Whether the set is empty.
236    #[must_use]
237    pub const fn is_empty(self) -> bool {
238        self.0 == 0
239    }
240
241    /// The set with every direction reversed.
242    #[must_use]
243    pub fn reversed(self) -> Self {
244        self.iter().fold(Self::NONE, |set, dir| set | dir.reverse())
245    }
246
247    /// The directions in the set, in the order of [`Direction::ALL`].
248    pub fn iter(self) -> impl Iterator<Item = Direction> {
249        Direction::ALL
250            .into_iter()
251            .filter(move |&d| self.contains(d))
252    }
253}
254
255impl BitOr for DirSet {
256    type Output = Self;
257
258    fn bitor(self, rhs: Self) -> Self {
259        Self(self.0 | rhs.0)
260    }
261}
262
263impl BitOr<Direction> for DirSet {
264    type Output = Self;
265
266    fn bitor(self, rhs: Direction) -> Self {
267        self | Self::only(rhs)
268    }
269}
270
271impl BitOrAssign for DirSet {
272    fn bitor_assign(&mut self, rhs: Self) {
273        self.0 |= rhs.0;
274    }
275}
276
277impl From<Direction> for DirSet {
278    fn from(dir: Direction) -> Self {
279        Self::only(dir)
280    }
281}
282
283impl fmt::Debug for DirSet {
284    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
285        f.debug_set().entries(self.iter()).finish()
286    }
287}
288
289/// A side of a rectangle.
290#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
291pub enum Side {
292    /// The side at `max.x`.
293    Right,
294    /// The side at `max.y`.
295    Top,
296    /// The side at `min.x`.
297    Left,
298    /// The side at `min.y`.
299    Bottom,
300}
301
302impl Side {
303    /// All four sides, in the order of the [`Direction`]s pointing out of them.
304    pub const ALL: [Self; 4] = [Self::Right, Self::Top, Self::Left, Self::Bottom];
305
306    /// The direction pointing out of the rectangle through this side.
307    #[must_use]
308    pub const fn outward(self) -> Direction {
309        match self {
310            Self::Right => Direction::Right,
311            Self::Top => Direction::Up,
312            Self::Left => Direction::Left,
313            Self::Bottom => Direction::Down,
314        }
315    }
316}
317
318/// A closed axis-aligned rectangle with positive width and height.
319///
320/// Routes may touch the boundary but never enter the open interior.
321#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
322pub struct Rect {
323    /// The corner with the smallest coordinates.
324    pub min: Point,
325    /// The corner with the largest coordinates; strictly greater than `min` on both axes.
326    pub max: Point,
327}
328
329impl Rect {
330    /// Creates the rectangle `[x0, x1] x [y0, y1]`, ordering the bounds.
331    ///
332    /// # Panics
333    ///
334    /// Panics if the rectangle has zero width or height. Use [`Rect::try_new`] to get
335    /// `None` instead.
336    ///
337    /// # Examples
338    ///
339    /// ```
340    /// use connector_routing::{Point, Rect};
341    ///
342    /// let r = Rect::new(10, 0, 0, 5);
343    /// assert_eq!(r.min, Point::new(0, 0));
344    /// assert_eq!(r.width(), 10);
345    /// ```
346    #[must_use]
347    pub fn new(x0: i32, y0: i32, x1: i32, y1: i32) -> Self {
348        Self::try_new(x0, y0, x1, y1).expect("a rectangle needs positive width and height")
349    }
350
351    /// Creates the rectangle `[x0, x1] x [y0, y1]`, or `None` if it is degenerate.
352    #[must_use]
353    pub fn try_new(x0: i32, y0: i32, x1: i32, y1: i32) -> Option<Self> {
354        let min = Point::new(x0.min(x1), y0.min(y1));
355        let max = Point::new(x0.max(x1), y0.max(y1));
356
357        (min.x < max.x && min.y < max.y).then_some(Self { min, max })
358    }
359
360    /// The width, `max.x - min.x`.
361    #[must_use]
362    pub fn width(&self) -> u64 {
363        abs_diff(self.max.x, self.min.x)
364    }
365
366    /// The height, `max.y - min.y`.
367    #[must_use]
368    pub fn height(&self) -> u64 {
369        abs_diff(self.max.y, self.min.y)
370    }
371
372    /// The low and high bound along `axis`.
373    #[must_use]
374    pub(crate) fn range(&self, axis: Axis) -> (i32, i32) {
375        (self.min.coordinate(axis), self.max.coordinate(axis))
376    }
377
378    /// The four corners, counter-clockwise from `min`.
379    #[must_use]
380    pub fn corners(&self) -> [Point; 4] {
381        [
382            self.min,
383            Point::new(self.max.x, self.min.y),
384            self.max,
385            Point::new(self.min.x, self.max.y),
386        ]
387    }
388
389    /// The centre, rounded towards negative infinity.
390    #[must_use]
391    pub fn center(&self) -> Point {
392        Point::new(
393            midpoint(self.min.x, self.max.x),
394            midpoint(self.min.y, self.max.y),
395        )
396    }
397
398    /// Whether `p` lies in the open interior.
399    #[must_use]
400    pub fn interior_contains(&self, p: Point) -> bool {
401        self.min.x < p.x && p.x < self.max.x && self.min.y < p.y && p.y < self.max.y
402    }
403
404    /// Whether `p` lies in the closed rectangle.
405    #[must_use]
406    pub fn contains(&self, p: Point) -> bool {
407        self.min.x <= p.x && p.x <= self.max.x && self.min.y <= p.y && p.y <= self.max.y
408    }
409
410    /// Whether `p` lies on the boundary.
411    #[must_use]
412    pub fn boundary_contains(&self, p: Point) -> bool {
413        self.contains(p) && !self.interior_contains(p)
414    }
415
416    /// The rectangle grown by `amount` on every side.
417    ///
418    /// # Panics
419    ///
420    /// Panics if a negative `amount` makes the rectangle degenerate.
421    #[must_use]
422    pub fn buffer(&self, amount: i32) -> Self {
423        Self::new(
424            self.min.x - amount,
425            self.min.y - amount,
426            self.max.x + amount,
427            self.max.y + amount,
428        )
429    }
430
431    /// The smallest rectangle containing both.
432    #[must_use]
433    pub fn union(&self, other: &Self) -> Self {
434        Self {
435            min: Point::new(self.min.x.min(other.min.x), self.min.y.min(other.min.y)),
436            max: Point::new(self.max.x.max(other.max.x), self.max.y.max(other.max.y)),
437        }
438    }
439
440    /// Whether the open interiors of the two rectangles intersect.
441    #[must_use]
442    pub fn interiors_overlap(&self, other: &Self) -> bool {
443        self.min.x < other.max.x
444            && other.min.x < self.max.x
445            && self.min.y < other.max.y
446            && other.min.y < self.max.y
447    }
448
449    /// Whether the closed axis-parallel segment from `a` to `b` meets the open interior.
450    ///
451    /// `a` and `b` must share one coordinate.
452    #[must_use]
453    pub fn blocks_segment(&self, a: Point, b: Point) -> bool {
454        let (lo, hi) = (
455            Point::new(a.x.min(b.x), a.y.min(b.y)),
456            Point::new(a.x.max(b.x), a.y.max(b.y)),
457        );
458        if lo.y == hi.y {
459            return self.min.y < lo.y
460                && lo.y < self.max.y
461                && lo.x < self.max.x
462                && self.min.x < hi.x;
463        }
464
465        self.min.x < lo.x && lo.x < self.max.x && lo.y < self.max.y && self.min.y < hi.y
466    }
467
468    /// The side that `p` lies on, if it lies on exactly one side (not a corner).
469    #[must_use]
470    pub fn side_of(&self, p: Point) -> Option<Side> {
471        let on_x = p.x == self.min.x || p.x == self.max.x;
472        let on_y = p.y == self.min.y || p.y == self.max.y;
473        if !self.contains(p) || on_x == on_y {
474            return None;
475        }
476
477        Some(
478            match (p.x == self.max.x, p.x == self.min.x, p.y == self.max.y) {
479                (true, _, _) => Side::Right,
480                (_, true, _) => Side::Left,
481                (_, _, true) => Side::Top,
482                _ => Side::Bottom,
483            },
484        )
485    }
486}
487
488/// `floor((a + b) / 2)` without overflow.
489#[must_use]
490pub(crate) fn midpoint(a: i32, b: i32) -> i32 {
491    i32::try_from((i64::from(a) + i64::from(b)).div_euclid(2)).expect("between two i32")
492}
493
494#[cfg(test)]
495mod tests {
496    //! Unit tests for directions, sets and rectangle predicates.
497
498    use super::*;
499
500    /// Turning left and right are inverse, and reversal is two turns.
501    #[test]
502    fn turns_compose() {
503        for d in Direction::ALL {
504            assert_eq!(d.left().right(), d);
505            assert_eq!(d.left().left(), d.reverse());
506            assert_eq!(d.turns_to(d), 0);
507            assert_eq!(d.turns_to(d.left()), 1);
508            assert_eq!(d.turns_to(d.right()), 1);
509            assert_eq!(d.turns_to(d.reverse()), 2);
510        }
511
512        assert_eq!(Direction::Right.left(), Direction::Up);
513    }
514
515    /// A segment along a boundary does not enter the interior; one through it does.
516    #[test]
517    fn segment_blocking_uses_open_interior() {
518        let r = Rect::new(0, 0, 10, 10);
519        assert!(!r.blocks_segment(Point::new(-5, 0), Point::new(15, 0)));
520        assert!(!r.blocks_segment(Point::new(10, -5), Point::new(10, 15)));
521        assert!(r.blocks_segment(Point::new(-5, 5), Point::new(1, 5)));
522        assert!(!r.blocks_segment(Point::new(-5, 5), Point::new(0, 5)));
523        assert!(r.blocks_segment(Point::new(5, 20), Point::new(5, 9)));
524    }
525
526    /// Reversing a set reverses every member.
527    #[test]
528    fn dirset_reverse() {
529        let set = DirSet::UP | Direction::Left;
530        assert_eq!(set.reversed(), DirSet::DOWN | Direction::Right);
531        assert_eq!(DirSet::ALL.iter().count(), 4);
532    }
533
534    /// Sides are found for side points and not for corners.
535    #[test]
536    fn side_of_points() {
537        let r = Rect::new(0, 0, 10, 4);
538        assert_eq!(r.side_of(Point::new(10, 2)), Some(Side::Right));
539        assert_eq!(r.side_of(Point::new(3, 4)), Some(Side::Top));
540        assert_eq!(r.side_of(Point::new(0, 0)), None);
541        assert_eq!(r.side_of(Point::new(5, 2)), None);
542    }
543}