xref: /StarryEngine/starry_toolkit/src/base/rect.rs (revision 282ef85ca13266353a8fb594bdc60918a2715518)
1 use super::vector2::Vector2;
2 
3 /// 表示一个矩形区域
4 #[derive(Clone, Copy, Debug, Default)]
5 pub struct Rect {
6     /// 左上角x坐标(世界坐标)
7     pub x: i32,
8     /// 左上角y坐标(世界坐标)
9     pub y: i32,
10     /// 矩形宽度
11     pub width: u32,
12     /// 矩形高度
13     pub height: u32,
14 }
15 
16 impl Rect {
17     pub fn new(x: i32, y: i32, width: u32, height: u32) -> Rect {
18         Rect {
19             x: x,
20             y: y,
21             width: width,
22             height: height,
23         }
24     }
25 
26     /// 返回矩形左上角的位置点
27     pub fn top_left_pos(&self) -> Vector2 {
28         Vector2::new(self.x, self.y)
29     }
30 
31     pub fn top_pos(&self) -> Vector2 {
32         Vector2::new(self.x + self.width as i32 / 2, self.y)
33     }
34 
35     pub fn top_right_pos(&self) -> Vector2 {
36         Vector2::new(self.x + self.width as i32, self.y)
37     }
38 
39     pub fn left_pos(&self) -> Vector2 {
40         Vector2::new(self.x, self.y + self.height as i32 / 2)
41     }
42 
43     pub fn center_pos(&self) -> Vector2 {
44         Vector2::new(
45             self.x + self.width as i32 / 2,
46             self.y + self.height as i32 / 2,
47         )
48     }
49 
50     pub fn right_pos(&self) -> Vector2 {
51         Vector2::new(self.x + self.width as i32, self.y + self.height as i32 / 2)
52     }
53 
54     pub fn bottom_left_pos(&self) -> Vector2 {
55         Vector2::new(self.x, self.y + self.height as i32)
56     }
57 
58     pub fn bottom_pos(&self) -> Vector2 {
59         Vector2::new(self.x + self.width as i32 / 2, self.y + self.height as i32)
60     }
61 
62     pub fn bottom_right_pos(&self) -> Vector2 {
63         Vector2::new(self.x + self.width as i32, self.y + self.height as i32)
64     }
65 
66     /// 判断该矩形是否包含某点
67     pub fn contains(&self, p: Vector2) -> bool {
68         p.x >= self.x
69             && p.x < self.x + self.width as i32
70             && p.y >= self.y
71             && p.y < self.y + self.height as i32
72     }
73 
74     /// 判断该矩形是否完全包含另一个矩形
75     pub fn contains_rect(&self, r: &Rect) -> bool {
76         let p1 = r.top_left_pos();
77         let p2 = p1 + Vector2::new(r.width as i32, r.height as i32);
78         self.contains(p1) && self.contains(p2)
79     }
80 
81     // 判断该矩形是否和另一矩形有重叠部分
82     pub fn intersects(&self, r: &Rect) -> bool {
83         !(r.x >= (self.x + self.width as i32)
84             || self.x >= (r.x + r.width as i32)
85             || r.y >= (self.y + self.height as i32)
86             || self.y >= (r.y + r.height as i32))
87     }
88 }
89