Skip to main content

emath/
rect.rs

1use alloc::fmt;
2
3use crate::{Div, Mul, NumExt as _, Pos2, Rangef, Rot2, Vec2, fast_midpoint, lerp, pos2, vec2};
4use core::ops::{BitOr, BitOrAssign};
5
6/// A rectangular region of space.
7///
8/// Usually a [`Rect`] has a positive (or zero) size,
9/// and then [`Self::min`] `<=` [`Self::max`].
10/// In these cases [`Self::min`] is the left-top corner
11/// and [`Self::max`] is the right-bottom corner.
12///
13/// A rectangle is allowed to have a negative size, which happens when the order
14/// of `min` and `max` are swapped. These are usually a sign of an error.
15///
16/// Normally the unit is points (logical pixels) in screen space coordinates.
17///
18/// `Rect` does NOT implement `Default`, because there is no obvious default value.
19/// [`Rect::ZERO`] may seem reasonable, but when used as a bounding box, [`Rect::NOTHING`]
20/// is a better default - so be explicit instead!
21#[repr(C)]
22#[derive(Clone, Copy, Eq, PartialEq)]
23#[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))]
24#[cfg_attr(feature = "bytemuck", derive(bytemuck::Pod, bytemuck::Zeroable))]
25pub struct Rect {
26    /// One of the corners of the rectangle, usually the left top one.
27    pub min: Pos2,
28
29    /// The other corner, opposing [`Self::min`]. Usually the right bottom one.
30    pub max: Pos2,
31}
32
33impl Rect {
34    /// Infinite rectangle that contains every point.
35    pub const EVERYTHING: Self = Self {
36        min: pos2(-f32::INFINITY, -f32::INFINITY),
37        max: pos2(f32::INFINITY, f32::INFINITY),
38    };
39
40    /// The inverse of [`Self::EVERYTHING`]: stretches from positive infinity to negative infinity.
41    /// Contains no points.
42    ///
43    /// This is useful as the seed for bounding boxes.
44    ///
45    /// # Example:
46    /// ```
47    /// # use emath::*;
48    /// let mut rect = Rect::NOTHING;
49    /// assert!(rect.size() == Vec2::splat(-f32::INFINITY));
50    /// assert!(rect.contains(pos2(0.0, 0.0)) == false);
51    /// rect.extend_with(pos2(2.0, 1.0));
52    /// rect.extend_with(pos2(0.0, 3.0));
53    /// assert_eq!(rect, Rect::from_min_max(pos2(0.0, 1.0), pos2(2.0, 3.0)))
54    /// ```
55    pub const NOTHING: Self = Self {
56        min: pos2(f32::INFINITY, f32::INFINITY),
57        max: pos2(-f32::INFINITY, -f32::INFINITY),
58    };
59
60    /// An invalid [`Rect`] filled with [`f32::NAN`].
61    pub const NAN: Self = Self {
62        min: pos2(f32::NAN, f32::NAN),
63        max: pos2(f32::NAN, f32::NAN),
64    };
65
66    /// A [`Rect`] filled with zeroes.
67    pub const ZERO: Self = Self {
68        min: Pos2::ZERO,
69        max: Pos2::ZERO,
70    };
71
72    #[inline(always)]
73    pub const fn from_min_max(min: Pos2, max: Pos2) -> Self {
74        Self { min, max }
75    }
76
77    /// left-top corner plus a size (stretching right-down).
78    #[inline(always)]
79    pub fn from_min_size(min: Pos2, size: Vec2) -> Self {
80        Self {
81            min,
82            max: min + size,
83        }
84    }
85
86    #[inline(always)]
87    pub fn from_center_size(center: Pos2, size: Vec2) -> Self {
88        Self {
89            min: center - size * 0.5,
90            max: center + size * 0.5,
91        }
92    }
93
94    #[inline(always)]
95    pub fn from_x_y_ranges(x_range: impl Into<Rangef>, y_range: impl Into<Rangef>) -> Self {
96        let x_range = x_range.into();
97        let y_range = y_range.into();
98        Self {
99            min: pos2(x_range.min, y_range.min),
100            max: pos2(x_range.max, y_range.max),
101        }
102    }
103
104    /// Returns the bounding rectangle of the two points.
105    #[inline]
106    pub fn from_two_pos(a: Pos2, b: Pos2) -> Self {
107        Self {
108            min: pos2(a.x.min(b.x), a.y.min(b.y)),
109            max: pos2(a.x.max(b.x), a.y.max(b.y)),
110        }
111    }
112
113    /// A zero-sized rect at a specific point.
114    #[inline]
115    pub fn from_pos(point: Pos2) -> Self {
116        Self {
117            min: point,
118            max: point,
119        }
120    }
121
122    /// Bounding-box around the points.
123    pub fn from_points(points: &[Pos2]) -> Self {
124        let mut rect = Self::NOTHING;
125        for &p in points {
126            rect.extend_with(p);
127        }
128        rect
129    }
130
131    /// A [`Rect`] that contains every point to the right of the given X coordinate.
132    #[inline]
133    pub fn everything_right_of(left_x: f32) -> Self {
134        let mut rect = Self::EVERYTHING;
135        rect.set_left(left_x);
136        rect
137    }
138
139    /// A [`Rect`] that contains every point to the left of the given X coordinate.
140    #[inline]
141    pub fn everything_left_of(right_x: f32) -> Self {
142        let mut rect = Self::EVERYTHING;
143        rect.set_right(right_x);
144        rect
145    }
146
147    /// A [`Rect`] that contains every point below a certain y coordinate
148    #[inline]
149    pub fn everything_below(top_y: f32) -> Self {
150        let mut rect = Self::EVERYTHING;
151        rect.set_top(top_y);
152        rect
153    }
154
155    /// A [`Rect`] that contains every point above a certain y coordinate
156    #[inline]
157    pub fn everything_above(bottom_y: f32) -> Self {
158        let mut rect = Self::EVERYTHING;
159        rect.set_bottom(bottom_y);
160        rect
161    }
162
163    #[must_use]
164    #[inline]
165    pub fn with_min_x(mut self, min_x: f32) -> Self {
166        self.min.x = min_x;
167        self
168    }
169
170    #[must_use]
171    #[inline]
172    pub fn with_min_y(mut self, min_y: f32) -> Self {
173        self.min.y = min_y;
174        self
175    }
176
177    #[must_use]
178    #[inline]
179    pub fn with_max_x(mut self, max_x: f32) -> Self {
180        self.max.x = max_x;
181        self
182    }
183
184    #[must_use]
185    #[inline]
186    pub fn with_max_y(mut self, max_y: f32) -> Self {
187        self.max.y = max_y;
188        self
189    }
190
191    /// Expand by this much in each direction, keeping the center
192    #[must_use]
193    pub fn expand(self, amnt: f32) -> Self {
194        self.expand2(Vec2::splat(amnt))
195    }
196
197    /// Expand by this much in each direction, keeping the center
198    #[must_use]
199    pub fn expand2(self, amnt: Vec2) -> Self {
200        Self::from_min_max(self.min - amnt, self.max + amnt)
201    }
202
203    /// Scale up by this factor in each direction, keeping the center
204    #[must_use]
205    pub fn scale_from_center(self, scale_factor: f32) -> Self {
206        self.scale_from_center2(Vec2::splat(scale_factor))
207    }
208
209    /// Scale up by this factor in each direction, keeping the center
210    #[must_use]
211    pub fn scale_from_center2(self, scale_factor: Vec2) -> Self {
212        Self::from_center_size(self.center(), self.size() * scale_factor)
213    }
214
215    /// Shrink by this much in each direction, keeping the center
216    #[must_use]
217    pub fn shrink(self, amnt: f32) -> Self {
218        self.shrink2(Vec2::splat(amnt))
219    }
220
221    /// Shrink by this much in each direction, keeping the center
222    #[must_use]
223    pub fn shrink2(self, amnt: Vec2) -> Self {
224        Self::from_min_max(self.min + amnt, self.max - amnt)
225    }
226
227    #[must_use]
228    #[inline]
229    pub fn translate(self, amnt: Vec2) -> Self {
230        Self::from_min_size(self.min + amnt, self.size())
231    }
232
233    /// Rotate the bounds (will expand the [`Rect`])
234    #[must_use]
235    #[inline]
236    pub fn rotate_bb(self, rot: Rot2) -> Self {
237        let a = rot * self.left_top().to_vec2();
238        let b = rot * self.right_top().to_vec2();
239        let c = rot * self.left_bottom().to_vec2();
240        let d = rot * self.right_bottom().to_vec2();
241
242        Self::from_min_max(
243            a.min(b).min(c).min(d).to_pos2(),
244            a.max(b).max(c).max(d).to_pos2(),
245        )
246    }
247
248    #[must_use]
249    #[inline]
250    pub fn intersects(self, other: Self) -> bool {
251        self.min.x <= other.max.x
252            && other.min.x <= self.max.x
253            && self.min.y <= other.max.y
254            && other.min.y <= self.max.y
255    }
256
257    /// keep min
258    pub fn set_width(&mut self, w: f32) {
259        self.max.x = self.min.x + w;
260    }
261
262    /// keep min
263    pub fn set_height(&mut self, h: f32) {
264        self.max.y = self.min.y + h;
265    }
266
267    /// Keep size
268    pub fn set_center(&mut self, center: Pos2) {
269        *self = self.translate(center - self.center());
270    }
271
272    #[must_use]
273    #[inline(always)]
274    pub fn contains(&self, p: Pos2) -> bool {
275        self.min.x <= p.x && p.x <= self.max.x && self.min.y <= p.y && p.y <= self.max.y
276    }
277
278    #[must_use]
279    pub fn contains_rect(&self, other: Self) -> bool {
280        self.contains(other.min) && self.contains(other.max)
281    }
282
283    /// Return the given points clamped to be inside the rectangle
284    /// Panics if [`Self::is_negative`].
285    #[must_use]
286    pub fn clamp(&self, p: Pos2) -> Pos2 {
287        p.clamp(self.min, self.max)
288    }
289
290    /// Floor the rect coordinates
291    #[inline(always)]
292    pub fn floor(self) -> Self {
293        Self {
294            min: self.min.floor(),
295            max: self.max.floor(),
296        }
297    }
298
299    /// Round the rect coordinates
300    #[inline(always)]
301    pub fn round(self) -> Self {
302        Self {
303            min: self.min.round(),
304            max: self.max.round(),
305        }
306    }
307
308    /// Ceil the rect coordinates
309    #[inline(always)]
310    pub fn ceil(self) -> Self {
311        Self {
312            min: self.min.ceil(),
313            max: self.max.ceil(),
314        }
315    }
316
317    #[inline(always)]
318    pub fn extend_with(&mut self, p: Pos2) {
319        self.min = self.min.min(p);
320        self.max = self.max.max(p);
321    }
322
323    #[inline(always)]
324    /// Expand to include the given x coordinate
325    pub fn extend_with_x(&mut self, x: f32) {
326        self.min.x = self.min.x.min(x);
327        self.max.x = self.max.x.max(x);
328    }
329
330    #[inline(always)]
331    /// Expand to include the given y coordinate
332    pub fn extend_with_y(&mut self, y: f32) {
333        self.min.y = self.min.y.min(y);
334        self.max.y = self.max.y.max(y);
335    }
336
337    /// The union of two bounding rectangle, i.e. the minimum [`Rect`]
338    /// that contains both input rectangles.
339    #[inline(always)]
340    #[must_use]
341    pub fn union(self, other: Self) -> Self {
342        Self {
343            min: self.min.min(other.min),
344            max: self.max.max(other.max),
345        }
346    }
347
348    /// The intersection of two [`Rect`], i.e. the area covered by both.
349    #[inline]
350    #[must_use]
351    pub fn intersect(self, other: Self) -> Self {
352        Self {
353            min: self.min.max(other.min),
354            max: self.max.min(other.max),
355        }
356    }
357
358    #[inline(always)]
359    pub fn center(&self) -> Pos2 {
360        Pos2 {
361            x: fast_midpoint(self.min.x, self.max.x),
362            y: fast_midpoint(self.min.y, self.max.y),
363        }
364    }
365
366    /// `rect.size() == Vec2 { x: rect.width(), y: rect.height() }`
367    #[inline(always)]
368    pub fn size(&self) -> Vec2 {
369        self.max - self.min
370    }
371
372    /// Note: this can be negative.
373    #[inline(always)]
374    pub fn width(&self) -> f32 {
375        self.max.x - self.min.x
376    }
377
378    /// Note: this can be negative.
379    #[inline(always)]
380    pub fn height(&self) -> f32 {
381        self.max.y - self.min.y
382    }
383
384    /// Width / height
385    ///
386    /// * `aspect_ratio < 1`: portrait / high
387    /// * `aspect_ratio = 1`: square
388    /// * `aspect_ratio > 1`: landscape / wide
389    pub fn aspect_ratio(&self) -> f32 {
390        self.width() / self.height()
391    }
392
393    /// `[2, 1]` for wide screen, and `[1, 2]` for portrait, etc.
394    /// At least one dimension = 1, the other >= 1
395    /// Returns the proportions required to letter-box a square view area.
396    pub fn square_proportions(&self) -> Vec2 {
397        let w = self.width();
398        let h = self.height();
399        if w > h {
400            vec2(w / h, 1.0)
401        } else {
402            vec2(1.0, h / w)
403        }
404    }
405
406    /// This is never negative, and instead returns zero for negative rectangles.
407    #[inline(always)]
408    pub fn area(&self) -> f32 {
409        self.width().at_least(0.0) * self.height().at_least(0.0)
410    }
411
412    /// The distance from the rect to the position.
413    ///
414    /// The distance is zero when the position is in the interior of the rectangle.
415    ///
416    /// [Negative rectangles](Self::is_negative) always return [`f32::INFINITY`].
417    #[inline]
418    pub fn distance_to_pos(&self, pos: Pos2) -> f32 {
419        self.distance_sq_to_pos(pos).sqrt()
420    }
421
422    /// The distance from the rect to the position, squared.
423    ///
424    /// The distance is zero when the position is in the interior of the rectangle.
425    ///
426    /// [Negative rectangles](Self::is_negative) always return [`f32::INFINITY`].
427    #[inline]
428    pub fn distance_sq_to_pos(&self, pos: Pos2) -> f32 {
429        if self.is_negative() {
430            return f32::INFINITY;
431        }
432
433        let dx = if self.min.x > pos.x {
434            self.min.x - pos.x
435        } else if pos.x > self.max.x {
436            pos.x - self.max.x
437        } else {
438            0.0
439        };
440
441        let dy = if self.min.y > pos.y {
442            self.min.y - pos.y
443        } else if pos.y > self.max.y {
444            pos.y - self.max.y
445        } else {
446            0.0
447        };
448
449        dx * dx + dy * dy
450    }
451
452    /// Signed distance to the edge of the box.
453    ///
454    /// Negative inside the box.
455    ///
456    /// [Negative rectangles](Self::is_negative) always return [`f32::INFINITY`].
457    ///
458    /// ```
459    /// # use emath::{pos2, Rect};
460    /// let rect = Rect::from_min_max(pos2(0.0, 0.0), pos2(1.0, 1.0));
461    /// assert_eq!(rect.signed_distance_to_pos(pos2(0.50, 0.50)), -0.50);
462    /// assert_eq!(rect.signed_distance_to_pos(pos2(0.75, 0.50)), -0.25);
463    /// assert_eq!(rect.signed_distance_to_pos(pos2(1.50, 0.50)), 0.50);
464    /// ```
465    pub fn signed_distance_to_pos(&self, pos: Pos2) -> f32 {
466        if self.is_negative() {
467            return f32::INFINITY;
468        }
469
470        let edge_distances = (pos - self.center()).abs() - self.size() * 0.5;
471        let inside_dist = edge_distances.max_elem().min(0.0);
472        let outside_dist = edge_distances.max(Vec2::ZERO).length();
473        inside_dist + outside_dist
474    }
475
476    /// Linearly interpolate so that `[0, 0]` is [`Self::min`] and
477    /// `[1, 1]` is [`Self::max`].
478    #[inline]
479    pub fn lerp_inside(&self, t: impl Into<Vec2>) -> Pos2 {
480        let t = t.into();
481        Pos2 {
482            x: lerp(self.min.x..=self.max.x, t.x),
483            y: lerp(self.min.y..=self.max.y, t.y),
484        }
485    }
486
487    /// Linearly self towards other rect.
488    #[inline]
489    pub fn lerp_towards(&self, other: &Self, t: f32) -> Self {
490        Self {
491            min: self.min.lerp(other.min, t),
492            max: self.max.lerp(other.max, t),
493        }
494    }
495
496    #[inline(always)]
497    pub fn x_range(&self) -> Rangef {
498        Rangef::new(self.min.x, self.max.x)
499    }
500
501    #[inline(always)]
502    pub fn y_range(&self) -> Rangef {
503        Rangef::new(self.min.y, self.max.y)
504    }
505
506    /// The extent along the given axis: `0` for x, `1` for y.
507    ///
508    /// Equivalent to [`Self::x_range`] for `axis == 0` and [`Self::y_range`] for `axis == 1`.
509    ///
510    /// # Panics
511    /// If `axis` is not `0` or `1`.
512    #[inline]
513    pub fn range_along(&self, axis: usize) -> Rangef {
514        match axis {
515            0 => self.x_range(),
516            1 => self.y_range(),
517            _ => panic!("axis must be 0 or 1, got {axis}"),
518        }
519    }
520
521    /// The size along the given axis: `0` for x (width), `1` for y (height).
522    ///
523    /// Equivalent to `self.size()[axis]`.
524    ///
525    /// # Panics
526    /// If `axis` is not `0` or `1`.
527    #[inline]
528    pub fn size_along(&self, axis: usize) -> f32 {
529        self.size()[axis]
530    }
531
532    #[inline(always)]
533    pub fn bottom_up_range(&self) -> Rangef {
534        Rangef::new(self.max.y, self.min.y)
535    }
536
537    /// `width < 0 || height < 0`
538    #[inline(always)]
539    pub fn is_negative(&self) -> bool {
540        self.max.x < self.min.x || self.max.y < self.min.y
541    }
542
543    /// `width > 0 && height > 0`
544    #[inline(always)]
545    pub fn is_positive(&self) -> bool {
546        self.min.x < self.max.x && self.min.y < self.max.y
547    }
548
549    /// True if all members are also finite.
550    #[inline(always)]
551    pub fn is_finite(&self) -> bool {
552        self.min.is_finite() && self.max.is_finite()
553    }
554
555    /// True if any member is NaN.
556    #[inline(always)]
557    pub fn any_nan(self) -> bool {
558        self.min.any_nan() || self.max.any_nan()
559    }
560}
561
562/// ## Convenience functions (assumes origin is towards left top):
563impl Rect {
564    /// `min.x`
565    #[inline(always)]
566    pub fn left(&self) -> f32 {
567        self.min.x
568    }
569
570    /// `min.x`
571    #[inline(always)]
572    pub fn left_mut(&mut self) -> &mut f32 {
573        &mut self.min.x
574    }
575
576    /// `min.x`
577    #[inline(always)]
578    pub fn set_left(&mut self, x: f32) {
579        self.min.x = x;
580    }
581
582    /// `max.x`
583    #[inline(always)]
584    pub fn right(&self) -> f32 {
585        self.max.x
586    }
587
588    /// `max.x`
589    #[inline(always)]
590    pub fn right_mut(&mut self) -> &mut f32 {
591        &mut self.max.x
592    }
593
594    /// `max.x`
595    #[inline(always)]
596    pub fn set_right(&mut self, x: f32) {
597        self.max.x = x;
598    }
599
600    /// `min.y`
601    #[inline(always)]
602    pub fn top(&self) -> f32 {
603        self.min.y
604    }
605
606    /// `min.y`
607    #[inline(always)]
608    pub fn top_mut(&mut self) -> &mut f32 {
609        &mut self.min.y
610    }
611
612    /// `min.y`
613    #[inline(always)]
614    pub fn set_top(&mut self, y: f32) {
615        self.min.y = y;
616    }
617
618    /// `max.y`
619    #[inline(always)]
620    pub fn bottom(&self) -> f32 {
621        self.max.y
622    }
623
624    /// `max.y`
625    #[inline(always)]
626    pub fn bottom_mut(&mut self) -> &mut f32 {
627        &mut self.max.y
628    }
629
630    /// `max.y`
631    #[inline(always)]
632    pub fn set_bottom(&mut self, y: f32) {
633        self.max.y = y;
634    }
635
636    #[inline(always)]
637    #[doc(alias = "top_left")]
638    pub fn left_top(&self) -> Pos2 {
639        pos2(self.left(), self.top())
640    }
641
642    #[inline(always)]
643    pub fn center_top(&self) -> Pos2 {
644        pos2(self.center().x, self.top())
645    }
646
647    #[inline(always)]
648    #[doc(alias = "top_right")]
649    pub fn right_top(&self) -> Pos2 {
650        pos2(self.right(), self.top())
651    }
652
653    #[inline(always)]
654    pub fn left_center(&self) -> Pos2 {
655        pos2(self.left(), self.center().y)
656    }
657
658    #[inline(always)]
659    pub fn right_center(&self) -> Pos2 {
660        pos2(self.right(), self.center().y)
661    }
662
663    #[inline(always)]
664    #[doc(alias = "bottom_left")]
665    pub fn left_bottom(&self) -> Pos2 {
666        pos2(self.left(), self.bottom())
667    }
668
669    #[inline(always)]
670    pub fn center_bottom(&self) -> Pos2 {
671        pos2(self.center().x, self.bottom())
672    }
673
674    #[inline(always)]
675    #[doc(alias = "bottom_right")]
676    pub fn right_bottom(&self) -> Pos2 {
677        pos2(self.right(), self.bottom())
678    }
679
680    /// Split rectangle in left and right halves. `t` is expected to be in the (0,1) range.
681    pub fn split_left_right_at_fraction(&self, t: f32) -> (Self, Self) {
682        self.split_left_right_at_x(lerp(self.min.x..=self.max.x, t))
683    }
684
685    /// Split rectangle in left and right halves at the given `x` coordinate.
686    pub fn split_left_right_at_x(&self, split_x: f32) -> (Self, Self) {
687        let left = Self::from_min_max(self.min, Pos2::new(split_x, self.max.y));
688        let right = Self::from_min_max(Pos2::new(split_x, self.min.y), self.max);
689        (left, right)
690    }
691
692    /// Split rectangle in top and bottom halves. `t` is expected to be in the (0,1) range.
693    pub fn split_top_bottom_at_fraction(&self, t: f32) -> (Self, Self) {
694        self.split_top_bottom_at_y(lerp(self.min.y..=self.max.y, t))
695    }
696
697    /// Split rectangle in top and bottom halves at the given `y` coordinate.
698    pub fn split_top_bottom_at_y(&self, split_y: f32) -> (Self, Self) {
699        let top = Self::from_min_max(self.min, Pos2::new(self.max.x, split_y));
700        let bottom = Self::from_min_max(Pos2::new(self.min.x, split_y), self.max);
701        (top, bottom)
702    }
703}
704
705impl Rect {
706    /// Does this Rect intersect the given ray (where `d` is normalized)?
707    ///
708    /// A ray that starts inside the rect will return `true`.
709    pub fn intersects_ray(&self, o: Pos2, d: Vec2) -> bool {
710        debug_assert!(
711            d.is_normalized(),
712            "Debug assert: expected normalized direction, but `d` has length {}",
713            d.length()
714        );
715
716        let mut tmin = -f32::INFINITY;
717        let mut tmax = f32::INFINITY;
718
719        if d.x != 0.0 {
720            let tx1 = (self.min.x - o.x) / d.x;
721            let tx2 = (self.max.x - o.x) / d.x;
722
723            tmin = tmin.max(tx1.min(tx2));
724            tmax = tmax.min(tx1.max(tx2));
725        }
726
727        if d.y != 0.0 {
728            let ty1 = (self.min.y - o.y) / d.y;
729            let ty2 = (self.max.y - o.y) / d.y;
730
731            tmin = tmin.max(ty1.min(ty2));
732            tmax = tmax.min(ty1.max(ty2));
733        }
734
735        0.0 <= tmax && tmin <= tmax
736    }
737
738    /// Where does a ray from the center intersect the rectangle?
739    ///
740    /// `d` is the direction of the ray and assumed to be normalized.
741    pub fn intersects_ray_from_center(&self, d: Vec2) -> Pos2 {
742        debug_assert!(
743            d.is_normalized(),
744            "expected normalized direction, but `d` has length {}",
745            d.length()
746        );
747
748        let mut tmin = f32::NEG_INFINITY;
749        let mut tmax = f32::INFINITY;
750
751        for i in 0..2 {
752            let inv_d = 1.0 / -d[i];
753            let mut t0 = (self.min[i] - self.center()[i]) * inv_d;
754            let mut t1 = (self.max[i] - self.center()[i]) * inv_d;
755
756            if inv_d < 0.0 {
757                core::mem::swap(&mut t0, &mut t1);
758            }
759
760            tmin = tmin.max(t0);
761            tmax = tmax.min(t1);
762        }
763
764        let t = tmax.min(tmin);
765        self.center() + t * -d
766    }
767}
768
769impl fmt::Debug for Rect {
770    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
771        if let Some(precision) = f.precision() {
772            write!(f, "[{1:.0$?} - {2:.0$?}]", precision, self.min, self.max)
773        } else {
774            write!(f, "[{:?} - {:?}]", self.min, self.max)
775        }
776    }
777}
778
779impl fmt::Display for Rect {
780    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
781        f.write_str("[")?;
782        self.min.fmt(f)?;
783        f.write_str(" - ")?;
784        self.max.fmt(f)?;
785        f.write_str("]")?;
786        Ok(())
787    }
788}
789
790/// from (min, max) or (left top, right bottom)
791impl From<[Pos2; 2]> for Rect {
792    #[inline]
793    fn from([min, max]: [Pos2; 2]) -> Self {
794        Self { min, max }
795    }
796}
797
798impl Mul<f32> for Rect {
799    type Output = Self;
800
801    #[inline]
802    fn mul(self, factor: f32) -> Self {
803        Self {
804            min: self.min * factor,
805            max: self.max * factor,
806        }
807    }
808}
809
810impl Mul<Rect> for f32 {
811    type Output = Rect;
812
813    #[inline]
814    fn mul(self, vec: Rect) -> Rect {
815        Rect {
816            min: self * vec.min,
817            max: self * vec.max,
818        }
819    }
820}
821
822impl Div<f32> for Rect {
823    type Output = Self;
824
825    #[inline]
826    fn div(self, factor: f32) -> Self {
827        Self {
828            min: self.min / factor,
829            max: self.max / factor,
830        }
831    }
832}
833
834impl BitOr for Rect {
835    type Output = Self;
836
837    #[inline]
838    fn bitor(self, other: Self) -> Self {
839        self.union(other)
840    }
841}
842
843impl BitOrAssign for Rect {
844    #[inline]
845    fn bitor_assign(&mut self, other: Self) {
846        *self = self.union(other);
847    }
848}
849
850#[cfg(test)]
851mod tests {
852    use super::*;
853
854    #[test]
855    fn test_rect() {
856        let r = Rect::from_min_max(pos2(10.0, 10.0), pos2(20.0, 20.0));
857        assert_eq!(r.distance_sq_to_pos(pos2(15.0, 15.0)), 0.0);
858        assert_eq!(r.distance_sq_to_pos(pos2(10.0, 15.0)), 0.0);
859        assert_eq!(r.distance_sq_to_pos(pos2(10.0, 10.0)), 0.0);
860
861        assert_eq!(r.distance_sq_to_pos(pos2(5.0, 15.0)), 25.0); // left of
862        assert_eq!(r.distance_sq_to_pos(pos2(25.0, 15.0)), 25.0); // right of
863        assert_eq!(r.distance_sq_to_pos(pos2(15.0, 5.0)), 25.0); // above
864        assert_eq!(r.distance_sq_to_pos(pos2(15.0, 25.0)), 25.0); // below
865        assert_eq!(r.distance_sq_to_pos(pos2(25.0, 5.0)), 50.0); // right and above
866    }
867
868    #[test]
869    fn scale_rect() {
870        let c = pos2(100.0, 50.0);
871        let r = Rect::from_center_size(c, vec2(30.0, 60.0));
872
873        assert_eq!(
874            r.scale_from_center(2.0),
875            Rect::from_center_size(c, vec2(60.0, 120.0))
876        );
877        assert_eq!(
878            r.scale_from_center(0.5),
879            Rect::from_center_size(c, vec2(15.0, 30.0))
880        );
881        assert_eq!(
882            r.scale_from_center2(vec2(2.0, 3.0)),
883            Rect::from_center_size(c, vec2(60.0, 180.0))
884        );
885    }
886
887    #[expect(clippy::print_stdout)]
888    #[test]
889    fn test_ray_intersection() {
890        let rect = Rect::from_min_max(pos2(1.0, 1.0), pos2(3.0, 3.0));
891
892        println!("Righward ray from left:");
893        assert!(rect.intersects_ray(pos2(0.0, 2.0), Vec2::RIGHT));
894
895        println!("Righward ray from center:");
896        assert!(rect.intersects_ray(pos2(2.0, 2.0), Vec2::RIGHT));
897
898        println!("Righward ray from right:");
899        assert!(!rect.intersects_ray(pos2(4.0, 2.0), Vec2::RIGHT));
900
901        println!("Leftward ray from left:");
902        assert!(!rect.intersects_ray(pos2(0.0, 2.0), Vec2::LEFT));
903
904        println!("Leftward ray from center:");
905        assert!(rect.intersects_ray(pos2(2.0, 2.0), Vec2::LEFT));
906
907        println!("Leftward ray from right:");
908        assert!(rect.intersects_ray(pos2(4.0, 2.0), Vec2::LEFT));
909    }
910
911    #[test]
912    fn test_ray_from_center_intersection() {
913        let rect = Rect::from_min_max(pos2(1.0, 1.0), pos2(3.0, 3.0));
914
915        assert_eq!(
916            rect.intersects_ray_from_center(Vec2::RIGHT),
917            pos2(3.0, 2.0),
918            "rightward ray"
919        );
920
921        assert_eq!(
922            rect.intersects_ray_from_center(Vec2::UP),
923            pos2(2.0, 1.0),
924            "upward ray"
925        );
926
927        assert_eq!(
928            rect.intersects_ray_from_center(Vec2::LEFT),
929            pos2(1.0, 2.0),
930            "leftward ray"
931        );
932
933        assert_eq!(
934            rect.intersects_ray_from_center(Vec2::DOWN),
935            pos2(2.0, 3.0),
936            "downward ray"
937        );
938
939        assert_eq!(
940            rect.intersects_ray_from_center((Vec2::LEFT + Vec2::DOWN).normalized()),
941            pos2(1.0, 3.0),
942            "bottom-left corner ray"
943        );
944
945        assert_eq!(
946            rect.intersects_ray_from_center((Vec2::LEFT + Vec2::UP).normalized()),
947            pos2(1.0, 1.0),
948            "top-left corner ray"
949        );
950
951        assert_eq!(
952            rect.intersects_ray_from_center((Vec2::RIGHT + Vec2::DOWN).normalized()),
953            pos2(3.0, 3.0),
954            "bottom-right corner ray"
955        );
956
957        assert_eq!(
958            rect.intersects_ray_from_center((Vec2::RIGHT + Vec2::UP).normalized()),
959            pos2(3.0, 1.0),
960            "top-right corner ray"
961        );
962    }
963}