Skip to main content

blit/
geometry.rs

1use core::{
2    fmt::Debug,
3    ops::{Add, AddAssign, Mul, Neg, Sub},
4};
5
6use crate::math;
7
8/// coordinate arithmetic and snapping used by [`Context::Scalar`](crate::Context::Scalar)
9///
10/// - floats use continuous coordinates and preserve fractions
11/// - integers use discrete coordinates and snap to whole units
12pub trait Scalar:
13    Copy + Default + Debug + PartialOrd + Add<Output = Self> + AddAssign + Sub<Output = Self> + Neg<Output = Self> + 'static
14{
15    /// the additive identity
16    const ZERO: Self;
17    /// represents no upper size limit
18    /// must compare greater than every finite extent
19    const UNBOUNDED: Self;
20
21    /// converts a float using this coordinate system's snapping rule
22    /// discrete coordinates round to their grid and saturate at their limits
23    fn from_f32(value: f32) -> Self;
24    /// converts to a float which may lose precision
25    fn to_f32(self) -> f32;
26    /// signed distance to another coordinate without snapping either endpoint
27    fn delta(self, end: Self) -> f32 {
28        end.to_f32() - self.to_f32()
29    }
30    /// applies a continuous offset before snapping the result
31    fn offset(self, amount: f32) -> Self {
32        Self::from_f32(self.to_f32() + amount)
33    }
34    /// resolves shares using one cursor initialized to zero for the whole group
35    /// discrete coordinates advance the cursor and subtract consecutive snapped boundaries
36    /// e.g. three equal shares of ten cells snap to `3, 4, 3`
37    /// continuous coordinates return `share` directly to avoid cancellation
38    fn allocate(cursor: &mut f32, share: f32) -> Self;
39    /// multiplies by a count with saturation for bounded integer coordinates
40    fn repeat(self, count: usize) -> Self;
41    /// evaluates `self + (end - self) * amount` with coordinate snapping
42    /// `amount` is not clamped so values outside zero to one extrapolate
43    #[inline]
44    fn lerp(self, end: Self, amount: f32) -> Self {
45        self.offset(self.delta(end) * amount)
46    }
47    /// returns the lesser coordinate
48    #[inline]
49    fn min(self, other: Self) -> Self {
50        if self < other { self } else { other }
51    }
52    /// returns the greater coordinate
53    #[inline]
54    fn max(self, other: Self) -> Self {
55        if self > other { self } else { other }
56    }
57    /// clamps to an inclusive range and panics if `min <= max` is false
58    #[inline]
59    fn clamp(self, min: Self, max: Self) -> Self {
60        assert!(min <= max, "min > max");
61        self.max(min).min(max)
62    }
63    /// adds an extent with saturation for bounded integer coordinates
64    fn endpoint(self, extent: Self) -> Self;
65
66    /// whether this is finite and differs from the unbounded sentinel
67    fn is_finite(self) -> bool;
68}
69
70impl Scalar for f32 {
71    const ZERO: Self = 0.0;
72    const UNBOUNDED: Self = f32::INFINITY;
73
74    #[inline]
75    fn from_f32(value: f32) -> Self {
76        value
77    }
78    #[inline]
79    fn to_f32(self) -> f32 {
80        self
81    }
82    #[inline]
83    fn allocate(_: &mut f32, share: f32) -> Self {
84        share
85    }
86    #[inline]
87    fn repeat(self, count: usize) -> Self {
88        self * count as Self
89    }
90    #[inline]
91    fn endpoint(self, extent: Self) -> Self {
92        self + extent
93    }
94    #[inline]
95    fn is_finite(self) -> bool {
96        f32::is_finite(self)
97    }
98}
99
100impl Scalar for i32 {
101    const ZERO: Self = 0;
102    const UNBOUNDED: Self = i32::MAX;
103
104    #[inline]
105    fn from_f32(value: f32) -> Self {
106        math::round(value as f64)
107    }
108    #[inline]
109    fn to_f32(self) -> f32 {
110        self as f32
111    }
112    #[inline]
113    fn delta(self, end: Self) -> f32 {
114        (end as f64 - self as f64) as f32
115    }
116    #[inline]
117    fn offset(self, amount: f32) -> Self {
118        math::round(self as f64 + amount as f64)
119    }
120    #[inline]
121    fn allocate(cursor: &mut f32, share: f32) -> Self {
122        let start = Self::from_f32(*cursor);
123        *cursor += share;
124        Self::from_f32(*cursor) - start
125    }
126    #[inline]
127    fn repeat(self, count: usize) -> Self {
128        let count = count.min(u32::MAX as usize) as i64;
129        (self as i64 * count).clamp(Self::MIN as i64, Self::MAX as i64) as Self
130    }
131    #[inline]
132    fn endpoint(self, extent: Self) -> Self {
133        self.saturating_add(extent)
134    }
135    #[inline]
136    fn is_finite(self) -> bool {
137        self != Self::UNBOUNDED
138    }
139}
140
141pub type LogicalPoint = Point<f32>;
142pub type LogicalRect = Rect<f32>;
143pub type LogicalSize = Size<f32>;
144pub type PhysicalPoint = Point<i32>;
145pub type PhysicalRect = Rect<i32>;
146pub type PhysicalSize = Size<i32>;
147
148#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
149pub struct Point<T> {
150    pub x: T,
151    pub y: T,
152}
153
154impl<T> Point<T> {
155    pub const fn new(x: T, y: T) -> Self {
156        Self { x, y }
157    }
158}
159
160impl<T: Scalar> Point<T> {
161    pub const ZERO: Self = Self { x: T::ZERO, y: T::ZERO };
162}
163
164#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
165pub struct Size<T> {
166    pub width: T,
167    pub height: T,
168}
169
170impl<T> Size<T> {
171    pub const fn new(width: T, height: T) -> Self {
172        Self { width, height }
173    }
174}
175
176impl<T: Copy> Size<T> {
177    pub const fn uniform(size: T) -> Self {
178        Self::new(size, size)
179    }
180}
181
182impl<T: Scalar> Size<T> {
183    pub const ZERO: Self = Self {
184        width: T::ZERO,
185        height: T::ZERO,
186    };
187
188    pub fn max(self, other: Self) -> Self {
189        Self {
190            width: self.width.max(other.width),
191            height: self.height.max(other.height),
192        }
193    }
194}
195
196impl<T: Add<Output = T>> Add for Size<T> {
197    type Output = Self;
198
199    fn add(self, other: Self) -> Self {
200        Self::new(self.width + other.width, self.height + other.height)
201    }
202}
203
204impl<T: Sub<Output = T>> Sub for Size<T> {
205    type Output = Self;
206
207    fn sub(self, other: Self) -> Self {
208        Self::new(self.width - other.width, self.height - other.height)
209    }
210}
211
212impl<T: Mul<U, Output = T>, U: Copy> Mul<U> for Size<T> {
213    type Output = Self;
214
215    fn mul(self, scale: U) -> Self {
216        Self::new(self.width * scale, self.height * scale)
217    }
218}
219
220#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
221pub struct Rect<T> {
222    pub x: T,
223    pub y: T,
224    pub width: T,
225    pub height: T,
226}
227
228impl<T> Rect<T> {
229    pub const fn new(x: T, y: T, width: T, height: T) -> Self {
230        Self { x, y, width, height }
231    }
232}
233
234impl<T: Copy> Rect<T> {
235    pub const fn size(self) -> Size<T> {
236        Size::new(self.width, self.height)
237    }
238}
239
240impl<T: Scalar> Rect<T> {
241    pub fn contains(self, point: Point<T>) -> bool {
242        point.x >= self.x
243            && point.y >= self.y
244            && point.x < self.x.endpoint(self.width)
245            && point.y < self.y.endpoint(self.height)
246    }
247
248    pub fn outset(self, sides: Sides<T>) -> Self {
249        Self::new(
250            self.x - sides.left,
251            self.y - sides.top,
252            self.width + sides.left + sides.right,
253            self.height + sides.top + sides.bottom,
254        )
255    }
256
257    pub fn inset(self, padding: Sides<T>) -> Self {
258        Self::new(
259            self.x + padding.left,
260            self.y + padding.top,
261            (self.width - padding.left - padding.right).max(T::ZERO),
262            (self.height - padding.top - padding.bottom).max(T::ZERO),
263        )
264    }
265
266    pub fn intersection(self, other: Self) -> Option<Self> {
267        let x = self.x.max(other.x);
268        let y = self.y.max(other.y);
269        let right = self.x.endpoint(self.width).min(other.x.endpoint(other.width));
270        let bottom = self.y.endpoint(self.height).min(other.y.endpoint(other.height));
271        (right > x && bottom > y).then_some(Self::new(x, y, right - x, bottom - y))
272    }
273
274    pub fn touches(self, other: Self) -> bool {
275        self.x <= other.x.endpoint(other.width)
276            && other.x <= self.x.endpoint(self.width)
277            && self.y <= other.y.endpoint(other.height)
278            && other.y <= self.y.endpoint(self.height)
279    }
280
281    pub fn union(self, other: Self) -> Self {
282        let x = self.x.min(other.x);
283        let y = self.y.min(other.y);
284        Self::new(
285            x,
286            y,
287            self.x.endpoint(self.width).max(other.x.endpoint(other.width)) - x,
288            self.y.endpoint(self.height).max(other.y.endpoint(other.height)) - y,
289        )
290    }
291}
292
293impl Rect<f32> {
294    pub fn to_physical(self, scale: Scale2) -> PhysicalRect {
295        let x = math::floor(self.x * scale.x);
296        let y = math::floor(self.y * scale.y);
297        let right = math::ceil((self.x + self.width) * scale.x);
298        let bottom = math::ceil((self.y + self.height) * scale.y);
299        PhysicalRect {
300            x,
301            y,
302            width: right.saturating_sub(x),
303            height: bottom.saturating_sub(y),
304        }
305    }
306}
307
308impl Rect<i32> {
309    pub fn to_logical(self, scale: Scale2) -> Rect<f32> {
310        Rect {
311            x: self.x as f32 / scale.x,
312            y: self.y as f32 / scale.y,
313            width: self.width as f32 / scale.x,
314            height: self.height as f32 / scale.y,
315        }
316    }
317
318    pub fn area(self) -> i64 {
319        self.width as i64 * self.height as i64
320    }
321}
322
323#[derive(Clone, Copy, Debug, PartialEq)]
324pub struct Scale2 {
325    pub x: f32,
326    pub y: f32,
327}
328
329impl Scale2 {
330    pub const IDENTITY: Self = Self { x: 1.0, y: 1.0 };
331
332    pub const fn uniform(scale: f32) -> Self {
333        Self { x: scale, y: scale }
334    }
335}
336
337#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
338pub struct Sides<T> {
339    pub top: T,
340    pub right: T,
341    pub bottom: T,
342    pub left: T,
343}
344
345impl<T: Copy + Default> Sides<T> {
346    pub fn new() -> Self {
347        Self::default()
348    }
349
350    pub fn x(value: T) -> Self {
351        Self::xy(value, T::default())
352    }
353
354    pub fn y(value: T) -> Self {
355        Self::xy(T::default(), value)
356    }
357}
358
359impl<T: Copy> Sides<T> {
360    pub const fn all(value: T) -> Self {
361        Self::xy(value, value)
362    }
363
364    pub const fn xy(x: T, y: T) -> Self {
365        Self {
366            top: y,
367            right: x,
368            bottom: y,
369            left: x,
370        }
371    }
372
373    pub const fn top(mut self, value: T) -> Self {
374        self.top = value;
375        self
376    }
377
378    pub const fn right(mut self, value: T) -> Self {
379        self.right = value;
380        self
381    }
382
383    pub const fn bottom(mut self, value: T) -> Self {
384        self.bottom = value;
385        self
386    }
387
388    pub const fn left(mut self, value: T) -> Self {
389        self.left = value;
390        self
391    }
392
393    pub fn map<U>(self, mut map: impl FnMut(T) -> U) -> Sides<U> {
394        Sides {
395            top: map(self.top),
396            right: map(self.right),
397            bottom: map(self.bottom),
398            left: map(self.left),
399        }
400    }
401}
402
403impl<T: Scalar> From<T> for Sides<T> {
404    fn from(value: T) -> Self {
405        Self::all(value)
406    }
407}
408
409impl<T: Add<Output = T>> Add for Sides<T> {
410    type Output = Self;
411
412    #[inline]
413    fn add(self, other: Self) -> Self {
414        Self {
415            top: self.top + other.top,
416            right: self.right + other.right,
417            bottom: self.bottom + other.bottom,
418            left: self.left + other.left,
419        }
420    }
421}
422
423impl<T: Add<Output = T>> Sides<T> {
424    #[inline]
425    pub fn size(self) -> Size<T> {
426        Size::new(self.left + self.right, self.top + self.bottom)
427    }
428}
429
430crate::builder! {
431    /// radii of a rounded rectangle
432    #[derive(Clone, Copy, Debug, PartialEq)]
433    pub struct Corners<T: Scalar> {
434        new(),
435        top_left: T = T::ZERO,
436        top_right: T = T::ZERO,
437        bottom_right: T = T::ZERO,
438        bottom_left: T = T::ZERO,
439    }
440}
441
442impl<T: Scalar> Corners<T> {
443    pub const fn all(value: T) -> Self {
444        Self {
445            top_left: value,
446            top_right: value,
447            bottom_right: value,
448            bottom_left: value,
449        }
450    }
451}
452
453impl<T: Scalar> From<T> for Corners<T> {
454    fn from(value: T) -> Self {
455        Self::all(value)
456    }
457}
458
459#[derive(Clone, Copy, Debug, PartialEq)]
460pub struct Constraints<T> {
461    pub min: Size<T>,
462    pub max: Size<T>,
463}
464
465impl<T: Scalar> Constraints<T> {
466    pub const fn loose(max: Size<T>) -> Self {
467        Self { min: Size::ZERO, max }
468    }
469
470    pub const fn tight(size: Size<T>) -> Self {
471        Self { min: size, max: size }
472    }
473
474    #[inline]
475    pub fn constrain(self, size: Size<T>) -> Size<T> {
476        Size {
477            width: size.width.clamp(self.min.width, self.max.width),
478            height: size.height.clamp(self.min.height, self.max.height),
479        }
480    }
481
482    #[inline]
483    pub fn shrink(self, amount: Size<T>) -> Self {
484        Self {
485            min: (self.min - amount).max(Size::ZERO),
486            max: Size::new(
487                if self.max.width == T::UNBOUNDED {
488                    T::UNBOUNDED
489                } else {
490                    (self.max.width - amount.width).max(T::ZERO)
491                },
492                if self.max.height == T::UNBOUNDED {
493                    T::UNBOUNDED
494                } else {
495                    (self.max.height - amount.height).max(T::ZERO)
496                },
497            ),
498        }
499    }
500}