1use yog_data::Schema;
4
5use crate::math::Vec2;
6
7#[derive(Schema, Debug, Clone, Copy, PartialEq, Default)]
10pub struct Rect {
11 pub x: f32,
12 pub y: f32,
13 pub w: f32,
14 pub h: f32,
15}
16
17impl Rect {
18 pub const fn new(x: f32, y: f32, w: f32, h: f32) -> Rect {
19 Rect { x, y, w, h }
20 }
21
22 pub const fn from_edges(x0: f32, y0: f32, x1: f32, y1: f32) -> Rect {
24 Rect { x: x0, y: y0, w: x1 - x0, h: y1 - y0 }
25 }
26
27 pub fn from_corners(a: Vec2, b: Vec2) -> Rect {
29 Rect { x: a.x.min(b.x), y: a.y.min(b.y), w: (a.x - b.x).abs(), h: (a.y - b.y).abs() }
30 }
31
32 pub fn right(&self) -> f32 {
33 self.x + self.w
34 }
35
36 pub fn bottom(&self) -> f32 {
37 self.y + self.h
38 }
39
40 pub fn center(&self) -> Vec2 {
41 Vec2::new(self.x + self.w / 2.0, self.y + self.h / 2.0)
42 }
43
44 pub fn contains(&self, p: Vec2) -> bool {
45 p.x >= self.x && p.y >= self.y && p.x < self.right() && p.y < self.bottom()
46 }
47
48 pub fn inset(&self, pad: [f32; 4]) -> Rect {
51 Rect { x: self.x + pad[3], y: self.y + pad[0], w: (self.w - pad[1] - pad[3]).max(0.0), h: (self.h - pad[0] - pad[2]).max(0.0) }
52 }
53
54 pub fn outset(&self, r: f32) -> Rect {
56 Rect { x: self.x - r, y: self.y - r, w: self.w + 2.0 * r, h: self.h + 2.0 * r }
57 }
58
59 pub fn translate(&self, d: Vec2) -> Rect {
60 Rect { x: self.x + d.x, y: self.y + d.y, ..*self }
61 }
62
63 pub fn scale(&self, s: f32) -> Rect {
65 Rect::from_corners(Vec2::new(self.x * s, self.y * s), Vec2::new(self.right() * s, self.bottom() * s))
66 }
67
68 pub fn intersect(&self, o: &Rect) -> Option<Rect> {
70 let (x0, y0) = (self.x.max(o.x), self.y.max(o.y));
71 let (x1, y1) = (self.right().min(o.right()), self.bottom().min(o.bottom()));
72 (x1 > x0 && y1 > y0).then_some(Rect { x: x0, y: y0, w: x1 - x0, h: y1 - y0 })
73 }
74
75 pub fn union(&self, o: &Rect) -> Rect {
76 let (x, y) = (self.x.min(o.x), self.y.min(o.y));
77 Rect { x, y, w: self.right().max(o.right()) - x, h: self.bottom().max(o.bottom()) - y }
78 }
79
80 pub fn around(points: impl IntoIterator<Item = Vec2>) -> Option<Rect> {
82 let mut it = points.into_iter();
83 let first = it.next()?;
84 let (lo, hi) = it.fold((first, first), |(lo, hi), p| (Vec2::new(lo.x.min(p.x), lo.y.min(p.y)), Vec2::new(hi.x.max(p.x), hi.y.max(p.y))));
85 Some(Rect::from_corners(lo, hi))
86 }
87}