aboutsummaryrefslogtreecommitdiff
path: root/src/math/rect.rs
blob: 560364235893e836b75a12942906a2b3a7d281ac (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
use super::{LineSegment, Polygon, Surface, Vec2};
//use alga::general::{Additive, Identity};
use nalgebra::{ClosedAdd, ClosedSub, RealField, Scalar};
use num_traits::identities::Zero;
use num_traits::{NumCast, ToPrimitive};
use serde::{Deserialize, Serialize};
use std::ops::{Add, AddAssign};

/// Represents a Rectangle with the value type T.
#[derive(Copy, Clone, Debug, Default, Serialize, Deserialize)]
pub struct Rect<T: Scalar + Copy> {
    /// The x coordinate, or leftmost coordinate of the Rect.
    pub x: T,
    /// The y coordinate, or rightmost coordinate of the Rect.
    pub y: T,
    /// The width of the Rect.
    pub w: T,
    /// The height of the Rect.
    pub h: T,
}

impl<T: Scalar + Copy> Rect<T> {
    pub fn new(x: T, y: T, w: T, h: T) -> Self {
        Self { x, y, w, h }
    }

    /// Create a Rectangle from a slice. Indices are [x, y, w, h].
    pub fn from_slice(slice: [T; 4]) -> Rect<T>
    where
        T: Copy,
    {
        Rect {
            x: slice[0],
            y: slice[1],
            w: slice[2],
            h: slice[3],
        }
    }

    /// Move by the Vec provided.
    pub fn translate(&mut self, by: Vec2<T>)
    where
        T: AddAssign,
    {
        self.x += by.x;
        self.y += by.y;
    }

    /// Set the posiotien of the rectangle to the given one without changing its
    /// size
    pub fn set_pos(&mut self, pos: Vec2<T>) {
        self.x = pos.x;
        self.y = pos.y;
    }

    /// Test if two rectangles intersect.
    pub fn intersect<'a>(this: &'a Rect<T>, other: &'a Rect<T>) -> bool
    where
        T: Add<Output = T> + PartialOrd + Copy,
    {
        !(this.x > other.x + other.w
            || this.x + this.w < other.x
            || this.y > other.y + other.h
            || this.y + this.h < other.y)
    }

    /// Function to calculate the bounding rectangle that is between two vectors. The order of the
    /// vectors is irrelevent for this. As long as they are diagonally opposite of each other, this
    /// function will work.
    pub fn bounding_rect(pos1: Vec2<T>, pos2: Vec2<T>) -> Self
    where
        T: RealField,
    {
        let min_x = pos1.x.min(pos2.x);
        let min_y = pos1.y.min(pos2.y);
        let max_x = pos1.x.max(pos2.x);
        let max_y = pos1.y.max(pos2.y);

        Self {
            x: min_x,
            y: min_y,
            w: max_x - min_x,
            h: max_y - min_y,
        }
    }

    /// Get the shortest way that must be applied to this Rect to clear out of
    /// another Rect of the same type so that they would not intersect any more.
    pub fn shortest_way_out(&self, of: &Rect<T>) -> Vec2<T>
    where
        T: RealField,
    {
        // Check upwards
        let mut move_y = of.y - self.y - self.h;
        // Check downwards
        let move_down = of.y + of.h - self.y;
        if move_down < -move_y {
            move_y = move_down;
        }

        // Check left
        let mut move_x = of.x - self.x - self.w;
        // Check right
        let move_right = of.x + of.w - self.x;
        if move_right < -move_x {
            move_x = move_right;
        }

        if move_x.abs() < move_y.abs() {
            Vec2::new(move_x, T::zero())
        } else {
            Vec2::new(T::zero(), move_y)
        }
    }
}

impl<T: Scalar + Copy + PartialOrd + ClosedAdd + ClosedSub + Zero> Surface<T> for Rect<T> {
    fn contains_point(&self, point: &Vec2<T>) -> bool {
        point.x >= self.x
            && point.x <= self.x + self.w
            && point.y >= self.y
            && point.y <= self.y + self.h
    }

    fn contains_line_segment(&self, line_segment: &LineSegment<T>) -> bool {
        self.contains_point(&line_segment.start) && self.contains_point(&line_segment.end)
    }

    fn contains_rect(&self, rect: &Rect<T>) -> bool {
        /* True, if the rightmost x-coordinate of the called rectangle is further right or the same
         * as the rightmost coordinate of the given rect.
         */
        let x_exceeds = self.x + self.w - rect.x - rect.w >= T::zero();
        // The same for the y-coordinates
        let y_exceeds = self.y + self.h - rect.y - rect.h >= T::zero();

        x_exceeds && y_exceeds && self.x <= rect.x && self.y <= rect.y
    }

    fn contains_polygon(&self, polygon: &Polygon<T>) -> bool {
        // Check if all vertices of the polygon lie inside the rectangle. If so, the polygon must
        // be contained in its entirety.
        polygon
            .corners()
            .iter()
            .all(|&corner| self.contains_point(&corner))
    }
}

// This is sad, but also sadly necessary :/
impl<T: From<f32> + Scalar + Copy> From<raylib::ffi::Rectangle> for Rect<T> {
    fn from(r: raylib::ffi::Rectangle) -> Self {
        Self {
            x: T::from(r.x),
            y: T::from(r.y),
            w: T::from(r.width),
            h: T::from(r.height),
        }
    }
}
impl<T: From<f32> + Scalar + Copy> From<raylib::math::Rectangle> for Rect<T> {
    fn from(r: raylib::math::Rectangle) -> Self {
        Self {
            x: T::from(r.x),
            y: T::from(r.y),
            w: T::from(r.width),
            h: T::from(r.height),
        }
    }
}

impl<T: Scalar + Copy + ToPrimitive> Into<raylib::math::Rectangle> for Rect<T> {
    fn into(self) -> raylib::math::Rectangle {
        raylib::math::Rectangle {
            x: NumCast::from(self.x).expect("Unable to cast Rect into raylib Rect"),
            y: NumCast::from(self.y).expect("Unable to cast Rect into raylib Rect"),
            width: NumCast::from(self.w).expect("Unable to cast Rect into raylib Rect"),
            height: NumCast::from(self.h).expect("Unable to cast Rect into raylib Rect"),
        }
    }
}
impl<T: Scalar + Copy + ToPrimitive> Into<raylib::ffi::Rectangle> for Rect<T> {
    fn into(self) -> raylib::ffi::Rectangle {
        raylib::ffi::Rectangle {
            x: NumCast::from(self.x).expect("Unable to cast Rect into raylib Rect"),
            y: NumCast::from(self.y).expect("Unable to cast Rect into raylib Rect"),
            width: NumCast::from(self.w).expect("Unable to cast Rect into raylib Rect"),
            height: NumCast::from(self.h).expect("Unable to cast Rect into raylib Rect"),
        }
    }
}

#[cfg(test)]
mod test {
    use super::*;

    #[test]
    fn test_intersect() {
        let a = Rect::from_slice([0, 0, 4, 4]);
        let b = Rect::from_slice([-1, -1, 1, 1]);

        assert!(Rect::intersect(&a, &b));
    }
}