reda_geometry/shape/rect.rs
1// Copyright (c) 2018-2020 Thomas Kramer.
2// SPDX-FileCopyrightText: 2018-2022 Thomas Kramer
3//
4// SPDX-License-Identifier: AGPL-3.0-or-later
5
6//! Data structures and functions for dealing with rectangles which consist of
7//! vertical and horizontal edges.
8use num_traits::{NumCast, One, Zero};
9use std::ops::{Add, Div, Sub};
10use crate::base::{cmp, Vec2};
11use crate::shape::Point;
12use crate::traits::{BoundingBox, Cast, MapPoint, TryBoundingBox};
13
14/// A rectangle which is oriented along the x an y axis and
15/// represented by its lower left and upper right corner.
16#[derive(Clone, Copy, Hash, Debug, PartialEq, Eq)]
17#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
18pub struct Rect<T> {
19 pub lower_left: Point<T>,
20 pub upper_right: Point<T>,
21}
22
23impl<T: PartialOrd + Copy> Rect<T> {
24 /// Construct the bounding box of the two points. Order does not matter.
25 ///
26 /// # Examples
27 ///
28 /// ```
29 /// use reda_geometry::prelude::*;
30 ///
31 /// // Create a rectangle based on two corner points.
32 /// let rect1 = Rect::new(Point::new(0, 0), Point::new(1, 2));
33 /// // Any type that implements `Into<Point<T>>` can be used for the corner points.
34 /// let rect2 = Rect::new((1, 2), (0, 0));
35 /// // Ordering of the corner points does not matter.
36 /// assert_eq!(rect1, rect2);
37 /// // Even though `(0, 0)` was passed as second argument it is recognized as lower left corner.
38 /// assert_eq!(rect2.lower_left(), Point::new(0, 0));
39 /// ```
40 pub fn new(c1: impl Into<Point<T>>, c2: impl Into<Point<T>>) -> Self {
41 let p1 = c1.into();
42 let p2 = c2.into();
43
44 let (x1, x2) = if p1.x < p2.x {
45 (p1.x, p2.x)
46 } else {
47 (p2.x, p1.x)
48 };
49
50 let (y1, y2) = if p1.y < p2.y {
51 (p1.y, p2.y)
52 } else {
53 (p2.y, p1.y)
54 };
55
56 Rect {
57 lower_left: Point::new(x1, y1),
58 upper_right: Point::new(x2, y2),
59 }
60 }
61}
62
63impl<T: Copy> Rect<T> {
64 /// Get the lower left corner.
65 #[inline]
66 pub fn lower_left(&self) -> Point<T> {
67 self.lower_left
68 }
69
70 /// Get the upper left corner.
71 #[inline]
72 pub fn upper_left(&self) -> Point<T> {
73 Point::new(self.lower_left.x, self.upper_right.y)
74 }
75
76 /// Get the upper right corner.
77 #[inline]
78 pub fn upper_right(&self) -> Point<T> {
79 self.upper_right
80 }
81
82 /// Get the lower right corner.
83 #[inline]
84 pub fn lower_right(&self) -> Point<T> {
85 Point::new(self.upper_right.x, self.lower_left.y)
86 }
87}
88
89impl<T: PartialOrd + Copy> Rect<T> {
90 /// Check if rectangle contains the point.
91 /// Inclusive boundaries.
92 ///
93 /// # Example
94 /// ```
95 /// use reda_geometry::prelude::*;
96 /// let rect = Rect::new((0, 0), (10, 20));
97 /// // Contains point somewhere in the center.
98 /// assert!(rect.contains_point(Point::new(5, 5)));
99 /// // Also contains point on the boundaries.
100 /// assert!(rect.contains_point(Point::new(0, 0)));
101 /// // Does not contain point outside of the rectangle.
102 /// assert!(!rect.contains_point(Point::new(10, 21)));
103 /// ```
104 pub fn contains_point(&self, p: Point<T>) -> bool {
105 self.lower_left.x <= p.x
106 && p.x <= self.upper_right.x
107 && self.lower_left.y <= p.y
108 && p.y <= self.upper_right.y
109 }
110
111 /// Check if rectangle contains the point.
112 /// Exclusive boundaries.
113 ///
114 /// # Example
115 /// ```
116 /// use reda_geometry::prelude::*;
117 /// let rect = Rect::new((0, 0), (10, 20));
118 /// // Contains point somewhere in the center.
119 /// assert!(rect.contains_point_exclusive(Point::new(5, 5)));
120 /// // Does not contain points on boundaries.
121 /// assert!(!rect.contains_point_exclusive(Point::new(0, 0)));
122 /// // Does not contain point outside of the rectangle.
123 /// assert!(!rect.contains_point_exclusive(Point::new(10, 21)));
124 /// ```
125 pub fn contains_point_exclusive(&self, p: Point<T>) -> bool {
126 self.lower_left.x < p.x
127 && p.x < self.upper_right.x
128 && self.lower_left.y < p.y
129 && p.y < self.upper_right.y
130 }
131
132 /// Check if rectangle contains other rectangle.
133 /// Inclusive boundaries.
134 ///
135 /// # Example
136 ///
137 /// ```
138 /// use reda_geometry::prelude::*;
139 ///
140 /// let outer = Rect::new((0, 0), (2, 2));
141 /// let inner = Rect::new((0, 0), (1, 1));
142 /// assert!(outer.contains_rectangle(&inner));
143 /// assert!(!inner.contains_rectangle(&outer));
144 /// ```
145 pub fn contains_rectangle(&self, other: &Self) -> bool {
146 self.contains_point(other.lower_left) && self.contains_point(other.upper_right)
147 }
148
149 /// Check if rectangle contains other rectangle.
150 /// Exclusive boundaries.
151 ///
152 /// # Example
153 ///
154 /// ```
155 /// use reda_geometry::prelude::*;
156 ///
157 /// let outer = Rect::new((0, 0), (3, 3));
158 /// let inner = Rect::new((1, 1), (2, 2));
159 /// assert!(outer.contains_rectangle_exclusive(&inner));
160 /// assert!(!inner.contains_rectangle_exclusive(&outer));
161 ///
162 /// let not_inner = Rect::new((0, 0), (1, 1)); // This shares the boundary with `outer`.
163 /// assert!(!outer.contains_rectangle_exclusive(¬_inner));
164 /// ```
165 pub fn contains_rectangle_exclusive(&self, other: &Self) -> bool {
166 self.contains_point_exclusive(other.lower_left)
167 && self.contains_point_exclusive(other.upper_right)
168 }
169
170 /// Test if the both rectangles touch each other, i.e. if they either share a boundary or are overlapping.
171 pub fn touches(&self, other: &Self) -> bool {
172 !(self.lower_left.x > other.upper_right.x
173 || self.lower_left.y > other.upper_right.y
174 || self.upper_right.x < other.lower_left.x
175 || self.upper_right.y < other.lower_left.y)
176 }
177
178 /// Compute the boolean intersection of two rectangles.
179 /// This function excludes the boundaries, hence a zero-area intersection is considered `None`.
180 /// See `intersection_inclusive_bounds()` zero-area intersections should be returned as `Some(rectangle)`.
181 ///
182 /// # Example
183 ///
184 /// ```
185 /// use reda_geometry::prelude::*;
186 ///
187 /// // Create two overlapping rectangles.
188 /// let a = Rect::new((0, 0), (2, 2));
189 /// let b = Rect::new((1, 1), (3, 3));
190 ///
191 /// // Compute the intersection.
192 /// assert_eq!(a.intersection(&b), Some(Rect::new((1, 1), (2, 2))));
193 ///
194 /// // Create a non-overlapping rectangle.
195 /// let c = Rect::new((100, 100), (200, 200));
196 /// // The intersection with a non-overlapping rectangle is `None`.
197 /// assert_eq!(a.intersection(&c), None);
198 /// ```
199 pub fn intersection(&self, other: &Self) -> Option<Self> {
200 let llx = cmp::max(self.lower_left.x, other.lower_left.x);
201 let lly = cmp::max(self.lower_left.y, other.lower_left.y);
202
203 let urx = cmp::min(self.upper_right.x, other.upper_right.x);
204 let ury = cmp::min(self.upper_right.y, other.upper_right.y);
205
206 if llx < urx && lly < ury {
207 Some(Rect::new((llx, lly), (urx, ury)))
208 } else {
209 None
210 }
211 }
212
213 /// Compute the boolean intersection of two rectangles and include the boundaries.
214 /// This allows to get zero-area intersection results for example if the two
215 /// rectangles touch on a boundary or one of the rectangle is already zero-area.
216 ///
217 /// # Example
218 ///
219 /// ```
220 /// use reda_geometry::prelude::*;
221 ///
222 /// // Create two rectangles which intersect in a single point.
223 /// let a = Rect::new((0, 0), (2, 2));
224 /// let b = Rect::new((2, 2), (3, 3));
225 ///
226 /// // Compute the intersection.
227 /// assert_eq!(a.intersection_inclusive_bounds(&b), Some(Rect::new((2, 2), (2, 2))));
228 ///
229 /// ```
230 pub fn intersection_inclusive_bounds(&self, other: &Self) -> Option<Self> {
231 let llx = cmp::max(self.lower_left.x, other.lower_left.x);
232 let lly = cmp::max(self.lower_left.y, other.lower_left.y);
233
234 let urx = cmp::min(self.upper_right.x, other.upper_right.x);
235 let ury = cmp::min(self.upper_right.y, other.upper_right.y);
236
237 if llx <= urx && lly <= ury {
238 Some(Rect::new((llx, lly), (urx, ury)))
239 } else {
240 None
241 }
242 }
243
244 /// Create the smallest `Rect` that contains the original `Rect` and the `point`.
245 ///
246 /// # Example
247 ///
248 /// ```
249 /// use reda_geometry::prelude::*;
250 ///
251 /// let r1 = Rect::new((0,0), (1,2));
252 ///
253 /// let r2 = r1.add_point(Point::new(10, 11));
254 ///
255 /// assert_eq!(r2, Rect::new((0,0), (10,11)));
256 ///
257 /// ```
258 pub fn add_point(&self, point: Point<T>) -> Self {
259 Rect::new(
260 Point::new(
261 cmp::min(self.lower_left.x, point.x),
262 cmp::min(self.lower_left.y, point.y),
263 ),
264 Point::new(
265 cmp::max(self.upper_right.x, point.x),
266 cmp::max(self.upper_right.y, point.y),
267 ),
268 )
269 }
270
271 /// Get the smallest `Rect` that contains both rectangles `self` and `rect`.
272 ///
273 /// # Example
274 ///
275 /// ```
276 /// use reda_geometry::prelude::*;
277 ///
278 /// let r1 = Rect::new((0,0), (1,2));
279 /// let r2 = Rect::new((4,5), (6,7));
280 ///
281 /// let r3 = r1.add_rect(&r2);
282 ///
283 /// assert_eq!(r3, Rect::new((0,0), (6,7)));
284 ///
285 /// ```
286 pub fn add_rect(&self, rect: &Self) -> Self {
287 self.add_point(rect.lower_left).add_point(rect.upper_right)
288 }
289}
290
291impl<T: Sub<Output = T> + Copy + Ord + Zero> Rect<T> {
292 /// Compute the shortest from the rectangle to the point `p`.
293 /// The distance is zero if the point is inside the rectangle.
294 ///
295 /// # Example
296 ///
297 /// ```
298 /// use reda_geometry::prelude::*;
299 ///
300 /// let r = Rect::new((0,0), (10, 10));
301 ///
302 /// assert_eq!(r.distance_to_point((5, 15).into()), Vec2::new(0, 5));
303 ///
304 /// // Distance to point inside the rectangle is zero.
305 /// assert_eq!(r.distance_to_point((5, 5).into()), Vec2::new(0, 0));
306 ///
307 /// ```
308 pub fn distance_to_point(&self, p: Point<T>) -> Vec2<T> {
309
310 let ll = self.lower_left();
311 let ul = self.upper_right();
312
313 // Compute x component of distance.
314 let dx_neg = (p.x - ll.x).min(Zero::zero());
315 let dx_pos = (p.x - ul.x).max(Zero::zero());
316 let dx = dx_neg + dx_pos;
317
318 // Compute y component of distance.
319 let dy_neg = (p.y - ll.y).min(Zero::zero());
320 let dy_pos = (p.y - ul.y).max(Zero::zero());
321 let dy = dy_neg + dy_pos;
322
323 Vec2::new(dx, dy)
324 }
325}
326
327impl<T: Copy + Sub<Output = T>> Rect<T> {
328 /// Compute the width of the rectangle.
329 #[inline]
330 pub fn width(&self) -> T {
331 self.upper_right.x - self.lower_left.x
332 }
333
334 /// Compute the height of the rectangle.
335 #[inline]
336 pub fn height(&self) -> T {
337 self.upper_right.y - self.lower_left.y
338 }
339}
340
341impl<T: Copy + Add<Output = T> + Div<Output = T> + One> Rect<T> {
342 /// Get the center point of the rectangle.
343 /// When using integer coordinates the resulting
344 /// coordinates will be truncated to the next integers.
345 pub fn center(&self) -> Point<T> {
346 let two = T::one() + T::one();
347 (self.lower_left() + self.upper_right()) / two
348 }
349}
350
351impl<T: Copy + Add<Output = T> + Sub<Output = T> + PartialOrd> Rect<T> {
352 /// Create an enlarged copy of this rectangle.
353 /// The vertical boundaries will be shifted towards the outside by `add_x`.
354 /// The horizontal boundaries will be shifted towards the outside by `add_y`.
355 pub fn sized(&self, add_x: T, add_y: T) -> Self {
356 Rect::new(
357 (self.lower_left.x - add_x, self.lower_left.y - add_y),
358 (self.upper_right.x + add_x, self.upper_right.y + add_y),
359 )
360 }
361
362 /// Create an enlarged copy of this rectangle.
363 pub fn sized_isotropic(&self, add: T) -> Self {
364 self.sized(add, add)
365 }
366}
367
368/// Iterate over all points of the rectangle.
369/// Starts with the lower left corner and iterates counter clock-wise.
370impl<'a, T> IntoIterator for &'a Rect<T>
371where
372 T: Copy,
373{
374 type Item = Point<T>;
375 type IntoIter = std::array::IntoIter<Self::Item, 4>;
376
377 fn into_iter(self) -> Self::IntoIter {
378 [
379 self.lower_left(),
380 self.lower_right(),
381 self.upper_right(),
382 self.upper_left(),
383 ]
384 .into_iter()
385 }
386}
387
388/// Iterate over all points of the rectangle.
389/// Starts with the lower left corner and iterates counter clock-wise.
390impl<T> IntoIterator for Rect<T>
391where
392 T: Copy,
393{
394 type Item = Point<T>;
395 type IntoIter = std::array::IntoIter<Self::Item, 4>;
396
397 fn into_iter(self) -> Self::IntoIter {
398 (&self).into_iter()
399 }
400}
401
402impl<T: Copy> MapPoint<T> for Rect<T> {
403 fn transform<F>(&self, transformate: F) -> Self
404 where
405 F: Fn(Point<T>) -> Point<T>
406 {
407 Self {
408 lower_left: transformate(self.lower_left),
409 upper_right: transformate(self.upper_right)
410 }
411 }
412}
413
414impl<T: Copy> BoundingBox<T> for Rect<T> {
415 fn bounding_box(&self) -> Rect<T> {
416 *self
417 }
418}
419
420impl<T: Copy> TryBoundingBox<T> for Rect<T> {
421 fn try_bounding_box(&self) -> Option<Rect<T>> {
422 Some(self.bounding_box())
423 }
424}
425
426impl<Src: Copy + NumCast, Dst: Copy + NumCast + PartialOrd> Cast<Src, Dst> for Rect<Src> {
427 type Output = Rect<Dst>;
428
429 fn try_cast(&self) -> Option<Self::Output> {
430 match (self.lower_left.try_cast(), self.upper_right.try_cast()) {
431 (Some(ll), Some(ur)) => Some(Rect::new(ll, ur)),
432 _ => None,
433 }
434 }
435}
436
437#[cfg(test)]
438mod tests {
439 use super::*;
440
441 #[test]
442 fn test_distance_to_point() {
443 let rect = Rect::new((10, 10), (20, 20));
444
445 assert_eq!(rect.distance_to_point((15, 15).into()).norm1(), 0);
446 assert_eq!(rect.distance_to_point((10, 10).into()).norm1(), 0);
447 assert_eq!(rect.distance_to_point((10, 20).into()).norm1(), 0);
448
449 assert_eq!(rect.distance_to_point((0, 0).into()).norm1(), 20);
450 assert_eq!(rect.distance_to_point((0, 5).into()).norm1(), 15);
451 assert_eq!(rect.distance_to_point((0, 10).into()).norm1(), 10);
452 assert_eq!(rect.distance_to_point((0, 15).into()).norm1(), 10);
453 assert_eq!(rect.distance_to_point((0, 20).into()).norm1(), 10);
454 assert_eq!(rect.distance_to_point((0, 25).into()).norm1(), 15);
455 }
456
457 #[test]
458 fn test_rect_intersection() {
459 let a = Rect::new((0, 0), (2, 4));
460 let b = Rect::new((1, 2), (3, 5));
461 assert_eq!(a.intersection(&b), Some(Rect::new((1, 2), (2, 4))));
462
463 let a = Rect::new((0, 0), (2, 2));
464 let b = Rect::new((1, 1), (3, 3));
465 assert_eq!(a.intersection(&b), Some(Rect::new((1, 1), (2, 2))));
466
467 let a = Rect::new((0, 0), (1, 1));
468 let b = Rect::new((2, 2), (3, 3));
469 assert_eq!(a.intersection(&b), None);
470
471 let a = Rect::new((0, 0), (2, 2));
472 let b = Rect::new((1, 2), (5, 5));
473 assert_eq!(a.intersection(&b), None);
474 }
475}