Skip to main content

agg_gui/
geometry.rs

1//! Basic 2D geometry types.
2//!
3//! All coordinates are in first-quadrant (Y-up) space unless otherwise noted.
4//! Origin is bottom-left. Positive Y goes upward.
5
6/// A 2D point in first-quadrant (Y-up) coordinates.
7#[derive(Clone, Copy, Debug, Default, PartialEq)]
8#[cfg_attr(feature = "reflect", derive(bevy_reflect::Reflect))]
9pub struct Point {
10    pub x: f64,
11    pub y: f64,
12}
13
14impl Point {
15    pub const ORIGIN: Self = Self { x: 0.0, y: 0.0 };
16
17    pub const fn new(x: f64, y: f64) -> Self {
18        Self { x, y }
19    }
20}
21
22/// A 2D size (width × height), always non-negative.
23#[derive(Clone, Copy, Debug, Default, PartialEq)]
24#[cfg_attr(feature = "reflect", derive(bevy_reflect::Reflect))]
25pub struct Size {
26    pub width: f64,
27    pub height: f64,
28}
29
30impl Size {
31    pub const ZERO: Self = Self {
32        width: 0.0,
33        height: 0.0,
34    };
35
36    /// A very large size used as the default `max_size` in [`WidgetBase`].
37    ///
38    /// Uses `f64::MAX / 2` rather than `f64::MAX` so that summing sizes with
39    /// margins or gaps never overflows to infinity.
40    pub const MAX: Self = Self {
41        width: f64::MAX / 2.0,
42        height: f64::MAX / 2.0,
43    };
44
45    pub const fn new(width: f64, height: f64) -> Self {
46        Self { width, height }
47    }
48}
49
50/// An axis-aligned rectangle in first-quadrant (Y-up) coordinates.
51///
52/// `(x, y)` is the bottom-left corner. Width and height are positive.
53#[derive(Clone, Copy, Debug, Default, PartialEq)]
54#[cfg_attr(feature = "reflect", derive(bevy_reflect::Reflect))]
55pub struct Rect {
56    pub x: f64,
57    pub y: f64,
58    pub width: f64,
59    pub height: f64,
60}
61
62impl Rect {
63    pub const fn new(x: f64, y: f64, width: f64, height: f64) -> Self {
64        Self {
65            x,
66            y,
67            width,
68            height,
69        }
70    }
71
72    pub fn left(&self) -> f64 {
73        self.x
74    }
75    pub fn bottom(&self) -> f64 {
76        self.y
77    }
78    pub fn right(&self) -> f64 {
79        self.x + self.width
80    }
81    pub fn top(&self) -> f64 {
82        self.y + self.height
83    }
84
85    pub fn center(&self) -> Point {
86        Point::new(self.x + self.width * 0.5, self.y + self.height * 0.5)
87    }
88
89    pub fn contains(&self, p: Point) -> bool {
90        p.x >= self.x && p.x <= self.right() && p.y >= self.y && p.y <= self.top()
91    }
92}