Skip to main content

bevy_sprite/texture_slice/
border_rect.rs

1use bevy_math::Vec2;
2use bevy_reflect::{std_traits::ReflectDefault, Reflect};
3
4/// Defines border insets that shrink a rectangle from its minimum and maximum corners.
5///
6/// This struct is used to represent thickness or offsets from the four edges
7/// of a rectangle, with values increasing inwards.
8#[derive(Default, Copy, Clone, PartialEq, Debug, Reflect)]
9#[reflect(Clone, PartialEq, Default)]
10pub struct BorderRect {
11    /// Inset applied to the rectangle’s minimum corner
12    pub min_inset: Vec2,
13    /// Inset applied to the rectangle’s maximum corner
14    pub max_inset: Vec2,
15}
16
17impl BorderRect {
18    /// An empty border with zero thickness along each edge
19    pub const ZERO: Self = Self::all(0.);
20
21    /// Creates a border with the same `inset` along each edge
22    #[must_use]
23    #[inline]
24    pub const fn all(inset: f32) -> Self {
25        Self {
26            min_inset: Vec2::splat(inset),
27            max_inset: Vec2::splat(inset),
28        }
29    }
30
31    /// Creates a new border with the `min.x` and `max.x` insets equal to `horizontal`, and the `min.y` and `max.y` insets equal to `vertical`.
32    #[must_use]
33    #[inline]
34    pub const fn axes(horizontal: f32, vertical: f32) -> Self {
35        let insets = Vec2::new(horizontal, vertical);
36        Self {
37            min_inset: insets,
38            max_inset: insets,
39        }
40    }
41}
42
43impl From<f32> for BorderRect {
44    fn from(inset: f32) -> Self {
45        Self::all(inset)
46    }
47}
48
49impl From<[f32; 4]> for BorderRect {
50    fn from([min_x, max_x, min_y, max_y]: [f32; 4]) -> Self {
51        Self {
52            min_inset: Vec2::new(min_x, min_y),
53            max_inset: Vec2::new(max_x, max_y),
54        }
55    }
56}
57
58impl core::ops::Add for BorderRect {
59    type Output = Self;
60
61    fn add(mut self, rhs: Self) -> Self::Output {
62        self.min_inset += rhs.min_inset;
63        self.max_inset += rhs.max_inset;
64        self
65    }
66}
67
68impl core::ops::Sub for BorderRect {
69    type Output = Self;
70
71    fn sub(mut self, rhs: Self) -> Self::Output {
72        self.min_inset -= rhs.min_inset;
73        self.max_inset -= rhs.max_inset;
74        self
75    }
76}
77
78impl core::ops::Mul<f32> for BorderRect {
79    type Output = Self;
80
81    fn mul(mut self, rhs: f32) -> Self::Output {
82        self.min_inset *= rhs;
83        self.max_inset *= rhs;
84        self
85    }
86}
87
88impl core::ops::Div<f32> for BorderRect {
89    type Output = Self;
90
91    fn div(mut self, rhs: f32) -> Self::Output {
92        self.min_inset /= rhs;
93        self.max_inset /= rhs;
94        self
95    }
96}