Skip to main content

rust_glass/
geometry.rs

1//! Points, sizes and rectangles.
2//!
3//! All UI code works in logical points. The painter converts to physical
4//! pixels with [`Context::pixels_per_point`](crate::Context::pixels_per_point).
5
6use std::ops::{Add, AddAssign, Div, Mul, Neg, Sub, SubAssign};
7
8/// A point or a size in points.
9#[derive(Clone, Copy, Debug, Default, PartialEq)]
10pub struct Vec2 {
11    /// Horizontal component, growing to the right.
12    pub x: f32,
13    /// Vertical component, growing downwards.
14    pub y: f32,
15}
16
17/// Creates a [`Vec2`].
18pub const fn vec2(x: f32, y: f32) -> Vec2 {
19    Vec2 { x, y }
20}
21
22impl Vec2 {
23    /// `(0, 0)`.
24    pub const ZERO: Vec2 = vec2(0.0, 0.0);
25
26    /// Creates a vector with both components set to `value`.
27    pub const fn splat(value: f32) -> Self {
28        vec2(value, value)
29    }
30    /// Returns the length.
31    pub fn length(self) -> f32 {
32        self.x.hypot(self.y)
33    }
34    /// Returns a vector of length 1 in the same direction, or zero for a
35    /// zero vector.
36    pub fn normalized(self) -> Self {
37        let l = self.length();
38        if l > 1e-6 { self / l } else { Vec2::ZERO }
39    }
40    /// Returns the dot product.
41    pub fn dot(self, other: Vec2) -> f32 {
42        self.x * other.x + self.y * other.y
43    }
44    /// Returns the smaller of each component.
45    pub fn min(self, other: Vec2) -> Self {
46        vec2(self.x.min(other.x), self.y.min(other.y))
47    }
48    /// Returns the larger of each component.
49    pub fn max(self, other: Vec2) -> Self {
50        vec2(self.x.max(other.x), self.y.max(other.y))
51    }
52    /// Returns the absolute value of each component.
53    pub fn abs(self) -> Self {
54        vec2(self.x.abs(), self.y.abs())
55    }
56    /// Mixes towards `other`: `t` = 0 gives `self`, 1 gives `other`.
57    pub fn lerp(self, other: Vec2, t: f32) -> Self {
58        self + (other - self) * t
59    }
60}
61
62impl Add for Vec2 {
63    type Output = Vec2;
64    fn add(self, other: Vec2) -> Vec2 {
65        vec2(self.x + other.x, self.y + other.y)
66    }
67}
68impl Sub for Vec2 {
69    type Output = Vec2;
70    fn sub(self, other: Vec2) -> Vec2 {
71        vec2(self.x - other.x, self.y - other.y)
72    }
73}
74impl Mul<f32> for Vec2 {
75    type Output = Vec2;
76    fn mul(self, factor: f32) -> Vec2 {
77        vec2(self.x * factor, self.y * factor)
78    }
79}
80impl Div<f32> for Vec2 {
81    type Output = Vec2;
82    fn div(self, divisor: f32) -> Vec2 {
83        vec2(self.x / divisor, self.y / divisor)
84    }
85}
86impl Neg for Vec2 {
87    type Output = Vec2;
88    fn neg(self) -> Vec2 {
89        vec2(-self.x, -self.y)
90    }
91}
92impl AddAssign for Vec2 {
93    fn add_assign(&mut self, other: Vec2) {
94        *self = *self + other;
95    }
96}
97impl SubAssign for Vec2 {
98    fn sub_assign(&mut self, other: Vec2) {
99        *self = *self - other;
100    }
101}
102
103/// Mixes two numbers: `t` = 0 gives `a`, 1 gives `b`.
104pub fn lerp(a: f32, b: f32, t: f32) -> f32 {
105    a + (b - a) * t
106}
107
108/// Returns 0 below `edge0`, 1 above `edge1`, and a smooth S curve between.
109pub fn smoothstep(edge0: f32, edge1: f32, x: f32) -> f32 {
110    let t = ((x - edge0) / (edge1 - edge0)).clamp(0.0, 1.0);
111    t * t * (3.0 - 2.0 * t)
112}
113
114/// An axis aligned rectangle in points, from its top left corner `min` to
115/// its bottom right corner `max`.
116#[derive(Clone, Copy, Debug, Default, PartialEq)]
117pub struct Rect {
118    /// Top left corner.
119    pub min: Vec2,
120    /// Bottom right corner.
121    pub max: Vec2,
122}
123
124/// Creates a [`Rect`] from its top left corner and its size.
125pub const fn rect(x: f32, y: f32, width: f32, height: f32) -> Rect {
126    Rect { min: vec2(x, y), max: vec2(x + width, y + height) }
127}
128
129impl Rect {
130    /// A rectangle larger than any window. Use it as a clip that clips
131    /// nothing.
132    pub const EVERYTHING: Rect = Rect { min: vec2(-1e6, -1e6), max: vec2(1e6, 1e6) };
133    /// An inverted rectangle, the starting point for [`Rect::union`].
134    pub const NOTHING: Rect = Rect { min: vec2(1e6, 1e6), max: vec2(-1e6, -1e6) };
135
136    /// Creates a rectangle from its top left corner and its size.
137    pub fn from_min_size(min: Vec2, size: Vec2) -> Self {
138        Rect { min, max: min + size }
139    }
140    /// Creates a rectangle from its center and its size.
141    pub fn from_center_size(center: Vec2, size: Vec2) -> Self {
142        Rect { min: center - size * 0.5, max: center + size * 0.5 }
143    }
144    /// Returns the width.
145    pub fn width(&self) -> f32 {
146        self.max.x - self.min.x
147    }
148    /// Returns the height.
149    pub fn height(&self) -> f32 {
150        self.max.y - self.min.y
151    }
152    /// Returns the width and height.
153    pub fn size(&self) -> Vec2 {
154        self.max - self.min
155    }
156    /// Returns the center point.
157    pub fn center(&self) -> Vec2 {
158        (self.min + self.max) * 0.5
159    }
160    /// Returns the x of the left edge.
161    pub fn left(&self) -> f32 {
162        self.min.x
163    }
164    /// Returns the x of the right edge.
165    pub fn right(&self) -> f32 {
166        self.max.x
167    }
168    /// Returns the y of the top edge.
169    pub fn top(&self) -> f32 {
170        self.min.y
171    }
172    /// Returns the y of the bottom edge.
173    pub fn bottom(&self) -> f32 {
174        self.max.y
175    }
176    /// Returns `true` if `point` is inside. The right and bottom edges are
177    /// outside.
178    pub fn contains(&self, point: Vec2) -> bool {
179        point.x >= self.min.x && point.x < self.max.x && point.y >= self.min.y && point.y < self.max.y
180    }
181    /// Returns `true` if the two rectangles overlap.
182    pub fn intersects(&self, other: &Rect) -> bool {
183        self.min.x < other.max.x
184            && other.min.x < self.max.x
185            && self.min.y < other.max.y
186            && other.min.y < self.max.y
187    }
188    /// Returns the overlap of the two rectangles. It is empty, see
189    /// [`Rect::is_positive`], when they do not overlap.
190    pub fn intersect(&self, other: Rect) -> Rect {
191        Rect { min: self.min.max(other.min), max: self.max.min(other.max) }
192    }
193    /// Returns the smallest rectangle that contains both.
194    pub fn union(&self, other: Rect) -> Rect {
195        Rect { min: self.min.min(other.min), max: self.max.max(other.max) }
196    }
197    /// Returns `true` if the width and height are larger than zero.
198    pub fn is_positive(&self) -> bool {
199        self.max.x > self.min.x && self.max.y > self.min.y
200    }
201    /// Grows every side by `amount`.
202    pub fn expand(&self, amount: f32) -> Rect {
203        self.expand2(Vec2::splat(amount))
204    }
205    /// Grows the left and right sides by `amount.x`, the top and bottom by
206    /// `amount.y`.
207    pub fn expand2(&self, amount: Vec2) -> Rect {
208        Rect { min: self.min - amount, max: self.max + amount }
209    }
210    /// Shrinks every side by `amount`.
211    pub fn shrink(&self, amount: f32) -> Rect {
212        self.expand(-amount)
213    }
214    /// Shrinks the left and right sides by `amount.x`, the top and bottom by
215    /// `amount.y`.
216    pub fn shrink2(&self, amount: Vec2) -> Rect {
217        self.expand2(-amount)
218    }
219    /// Moves the rectangle by `offset`.
220    pub fn translate(&self, offset: Vec2) -> Rect {
221        Rect { min: self.min + offset, max: self.max + offset }
222    }
223    /// Scales width and height around the center.
224    pub fn scale_from_center(&self, scale_x: f32, scale_y: f32) -> Rect {
225        Rect::from_center_size(self.center(), vec2(self.width() * scale_x, self.height() * scale_y))
226    }
227    /// Mixes towards `other`: `t` = 0 gives `self`, 1 gives `other`.
228    pub fn lerp(&self, other: &Rect, t: f32) -> Rect {
229        Rect { min: self.min.lerp(other.min, t), max: self.max.lerp(other.max, t) }
230    }
231    /// Rounds the edges to whole physical pixels.
232    pub fn snap(&self, pixels_per_point: f32) -> Rect {
233        let round = |v: f32| (v * pixels_per_point).round() / pixels_per_point;
234        Rect {
235            min: vec2(round(self.min.x), round(self.min.y)),
236            max: vec2(round(self.max.x), round(self.max.y)),
237        }
238    }
239    /// Moves the rectangle, without resizing it, so it lies inside `outer`.
240    /// When it is larger than `outer`, its top left corner stays inside.
241    pub fn clamp_inside(&self, outer: Rect) -> Rect {
242        let mut d = Vec2::ZERO;
243        if self.max.x > outer.max.x {
244            d.x = outer.max.x - self.max.x;
245        }
246        if self.min.x + d.x < outer.min.x {
247            d.x = outer.min.x - self.min.x;
248        }
249        if self.max.y > outer.max.y {
250            d.y = outer.max.y - self.max.y;
251        }
252        if self.min.y + d.y < outer.min.y {
253            d.y = outer.min.y - self.min.y;
254        }
255        self.translate(d)
256    }
257}
258
259#[cfg(test)]
260mod tests {
261    use super::*;
262
263    #[test]
264    fn union_with_nothing_is_identity() {
265        let r = rect(1.0, 2.0, 3.0, 4.0);
266        assert_eq!(Rect::NOTHING.union(r), r);
267    }
268
269    #[test]
270    fn clamp_inside_moves_without_resizing() {
271        let r = rect(90.0, -5.0, 20.0, 10.0).clamp_inside(rect(0.0, 0.0, 100.0, 100.0));
272        assert_eq!(r, rect(80.0, 0.0, 20.0, 10.0));
273    }
274}