Skip to main content

zenthra_core/
rect.rs

1// crates/zenthra-core/src/rect.rs
2
3use glam::Vec2;
4
5#[derive(Debug, Clone, Copy, PartialEq, Default)]
6pub struct Point {
7    pub x: f32,
8    pub y: f32,
9}
10
11impl Point {
12    pub const ZERO: Self = Self { x: 0.0, y: 0.0 };
13    pub fn new(x: f32, y: f32) -> Self {
14        Self { x, y }
15    }
16    pub fn to_vec2(self) -> Vec2 {
17        Vec2::new(self.x, self.y)
18    }
19}
20
21#[derive(Debug, Clone, Copy, PartialEq, Default)]
22pub struct Size {
23    pub width: f32,
24    pub height: f32,
25}
26
27impl Size {
28    pub const ZERO: Self = Self {
29        width: 0.0,
30        height: 0.0,
31    };
32    pub const INFINITY: Self = Self {
33        width: f32::INFINITY,
34        height: f32::INFINITY,
35    };
36
37    pub fn new(width: f32, height: f32) -> Self {
38        Self { width, height }
39    }
40
41    pub fn clamp(self, min: Size, max: Size) -> Self {
42        Self {
43            width: self.width.clamp(min.width, max.width),
44            height: self.height.clamp(min.height, max.height),
45        }
46    }
47}
48
49#[derive(Debug, Clone, Copy, PartialEq, Default)]
50pub struct Rect {
51    pub origin: Point,
52    pub size: Size,
53}
54
55impl Rect {
56    pub const ZERO: Self = Self {
57        origin: Point::ZERO,
58        size: Size::ZERO,
59    };
60
61    pub fn new(x: f32, y: f32, width: f32, height: f32) -> Self {
62        Self {
63            origin: Point::new(x, y),
64            size: Size::new(width, height),
65        }
66    }
67
68    pub fn from_min_max(min: Vec2, max: Vec2) -> Self {
69        Self::new(min.x, min.y, max.x - min.x, max.y - min.y)
70    }
71
72    pub fn contains(&self, p: Point) -> bool {
73        p.x >= self.origin.x
74            && p.y >= self.origin.y
75            && p.x <= self.origin.x + self.size.width
76            && p.y <= self.origin.y + self.size.height
77    }
78
79    pub fn min(&self) -> Vec2 {
80        Vec2::new(self.origin.x, self.origin.y)
81    }
82    pub fn max(&self) -> Vec2 {
83        Vec2::new(
84            self.origin.x + self.size.width,
85            self.origin.y + self.size.height,
86        )
87    }
88}