Skip to main content

epaint/shapes/
band_shape.rs

1use emath::{Pos2, Rangef, Rect, TSTransform};
2
3use crate::{Color32, Shape, Stroke, StrokeKind};
4
5/// A sample in a [`BandShape`].
6#[derive(Clone, Copy, Debug, PartialEq)]
7#[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))]
8pub struct BandPoint {
9    /// The horizontal position of this sample.
10    pub x: f32,
11
12    /// The vertical extent of the band at [`Self::x`].
13    pub y: Rangef,
14}
15
16impl BandPoint {
17    #[inline]
18    pub fn new(x: f32, y: impl Into<Rangef>) -> Self {
19        Self { x, y: y.into() }
20    }
21
22    #[inline]
23    pub fn from_pos_and_width(pos: Pos2, width: f32) -> Self {
24        let half_width = 0.5 * width;
25        Self::new(pos.x, (pos.y - half_width)..=(pos.y + half_width))
26    }
27
28    /// Whether all coordinates are finite.
29    #[inline]
30    pub fn is_finite(self) -> bool {
31        self.x.is_finite() && self.y.min.is_finite() && self.y.max.is_finite()
32    }
33
34    pub(crate) fn is_valid(self) -> bool {
35        self.is_finite() && self.y.min <= self.y.max
36    }
37}
38
39/// A varying-width band along a line segment.
40///
41/// If you want a meandering path of fixed width, use [`PathShape`](crate::PathShape) instead.
42///
43/// ```text
44///              min_y
45///             __________
46///            /          \________
47///     ______/                    |
48///    |                   ________|
49///    |        __________/
50///    |_______/
51///            max_y
52///
53///
54///     x-----x-x---------x-x-------x
55///
56/// ```
57#[derive(Clone, Debug, PartialEq)]
58#[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))]
59pub struct BandShape {
60    /// The samples that define the lower and upper boundaries, sorted by [`BandPoint::x`].
61    pub points: Vec<BandPoint>,
62
63    /// The fill color of the band.
64    pub fill: Color32,
65
66    /// An optional stroke around the band.
67    ///
68    /// The stroke follows the whole outline, end caps included.
69    pub stroke: Stroke,
70
71    /// Whether the stroke is inside, outside, or centered on the band edge.
72    ///
73    /// For anything but [`StrokeKind::Outside`], the stroke color replaces the fill color.
74    pub stroke_kind: StrokeKind,
75
76    /// Rotate the band by this many radians clockwise around the origin `(0, 0)`.
77    pub angle: f32,
78}
79
80impl BandShape {
81    #[inline]
82    pub fn new(
83        points: Vec<BandPoint>,
84        fill: impl Into<Color32>,
85        stroke: impl Into<Stroke>,
86    ) -> Self {
87        Self {
88            points,
89            fill: fill.into(),
90            stroke: stroke.into(),
91            stroke_kind: StrokeKind::Middle,
92            angle: 0.0,
93        }
94    }
95
96    #[inline]
97    pub fn filled(points: Vec<BandPoint>, fill: impl Into<Color32>) -> Self {
98        Self::new(points, fill, Stroke::NONE)
99    }
100
101    #[inline]
102    pub fn stroke(points: Vec<BandPoint>, stroke: impl Into<Stroke>) -> Self {
103        Self::new(points, Color32::TRANSPARENT, stroke)
104    }
105
106    /// Set if the stroke is on the inside, outside, or centered on the band edge.
107    #[inline]
108    pub fn with_stroke_kind(mut self, stroke_kind: StrokeKind) -> Self {
109        self.stroke_kind = stroke_kind;
110        self
111    }
112
113    /// Set the rotation of the band (in radians, clockwise) around a custom pivot point.
114    ///
115    /// The band keeps the position it already had at `pivot`, so calling this again
116    /// with a different angle rotates around the same point.
117    #[inline]
118    pub fn with_angle_and_pivot(mut self, angle: f32, pivot: Pos2) -> Self {
119        let pivot = pivot.to_vec2();
120        // The points are stored pre-rotation, so undo each rotation to get the local offset:
121        let translation =
122            emath::Rot2::from_angle(-angle) * pivot - emath::Rot2::from_angle(-self.angle) * pivot;
123        self.angle = angle;
124        for point in &mut self.points {
125            point.x += translation.x;
126            point.y.min += translation.y;
127            point.y.max += translation.y;
128        }
129        self
130    }
131
132    /// Transform the band in-place.
133    pub fn transform(&mut self, transform: TSTransform) {
134        let translation = emath::Rot2::from_angle(-self.angle) * transform.translation;
135        for point in &mut self.points {
136            point.x = transform.scaling * point.x + translation.x;
137            point.y.min = transform.scaling * point.y.min + translation.y;
138            point.y.max = transform.scaling * point.y.max + translation.y;
139        }
140        self.stroke.width *= transform.scaling;
141    }
142
143    /// The visual bounding rectangle, including the stroke width.
144    pub fn visual_bounding_rect(&self) -> Rect {
145        if !self.angle.is_finite() || (self.fill == Color32::TRANSPARENT && self.stroke.is_empty())
146        {
147            return Rect::NOTHING;
148        }
149
150        let rect = self.local_bounding_rect();
151        if rect == Rect::NOTHING {
152            return Rect::NOTHING;
153        }
154
155        let stroke_width = match self.stroke_kind {
156            // A band too thin for an inside stroke is widened to fit it,
157            // so the stroke can reach a full width past a pinch:
158            StrokeKind::Inside | StrokeKind::Outside => self.stroke.width,
159            StrokeKind::Middle => self.stroke.width / 2.0,
160        };
161        rect.expand(stroke_width)
162            .rotate_bb(emath::Rot2::from_angle(self.angle))
163    }
164
165    fn local_bounding_rect(&self) -> Rect {
166        let mut rect = Rect::NOTHING;
167        for &[left, right] in self.points.array_windows() {
168            if left.is_valid() && right.is_valid() && left.x < right.x {
169                rect.extend_with(Pos2::new(left.x, left.y.min));
170                rect.extend_with(Pos2::new(left.x, left.y.max));
171                rect.extend_with(Pos2::new(right.x, right.y.min));
172                rect.extend_with(Pos2::new(right.x, right.y.max));
173            }
174        }
175        rect
176    }
177}
178
179impl From<BandShape> for Shape {
180    #[inline(always)]
181    fn from(shape: BandShape) -> Self {
182        Self::Band(shape)
183    }
184}
185
186#[cfg(test)]
187mod tests {
188    use emath::{TSTransform, pos2, vec2};
189
190    use super::*;
191
192    #[test]
193    fn band_point_is_finite() {
194        assert!(BandPoint::new(0.0, 1.0..=2.0).is_finite());
195        assert!(!BandPoint::new(f32::NAN, 1.0..=2.0).is_finite());
196        assert!(!BandPoint::new(0.0, f32::NEG_INFINITY..=2.0).is_finite());
197        assert!(!BandPoint::new(0.0, 1.0..=f32::INFINITY).is_finite());
198    }
199
200    #[test]
201    fn band_point_from_pos_and_width() {
202        assert_eq!(
203            BandPoint::from_pos_and_width(pos2(2.0, 3.0), 4.0),
204            BandPoint::new(2.0, 1.0..=5.0),
205        );
206    }
207
208    #[test]
209    fn transform_preserves_rotation() {
210        let mut band = BandShape::filled(
211            vec![
212                BandPoint::new(0.0, 1.0..=3.0),
213                BandPoint::new(2.0, 2.0..=4.0),
214            ],
215            Color32::WHITE,
216        )
217        .with_angle_and_pivot(core::f32::consts::FRAC_PI_2, Pos2::ZERO);
218
219        band.transform(TSTransform::from_translation(vec2(2.0, 3.0)));
220
221        assert!((band.points[0].x - 3.0).abs() < 1e-6);
222        assert!((band.points[0].y.min + 1.0).abs() < 1e-6);
223        assert!((band.points[0].y.max - 1.0).abs() < 1e-6);
224    }
225
226    #[test]
227    fn with_angle_and_pivot_preserves_pivot() {
228        let band = BandShape::filled(
229            vec![
230                BandPoint::new(1.0, 0.0..=2.0),
231                BandPoint::new(3.0, 0.0..=2.0),
232            ],
233            Color32::WHITE,
234        )
235        .with_angle_and_pivot(core::f32::consts::FRAC_PI_2, pos2(2.0, 1.0));
236
237        assert!((band.points[0].x - 0.0).abs() < 1e-6);
238        assert!((band.points[0].y.min + 3.0).abs() < 1e-6);
239        assert!((band.points[0].y.max + 1.0).abs() < 1e-6);
240    }
241
242    #[test]
243    fn with_angle_and_pivot_is_relative_to_the_previous_angle() {
244        let points = vec![BandPoint::new(1.0, 0.0..=2.0)];
245        let pivot = pos2(2.0, 1.0);
246        let once = BandShape::filled(points.clone(), Color32::WHITE)
247            .with_angle_and_pivot(core::f32::consts::FRAC_PI_2, pivot);
248        let twice = BandShape::filled(points, Color32::WHITE)
249            .with_angle_and_pivot(core::f32::consts::FRAC_PI_4, pivot)
250            .with_angle_and_pivot(core::f32::consts::FRAC_PI_2, pivot);
251
252        assert!((once.points[0].x - twice.points[0].x).abs() < 1e-6);
253        assert!((once.points[0].y.min - twice.points[0].y.min).abs() < 1e-6);
254        assert!((once.points[0].y.max - twice.points[0].y.max).abs() < 1e-6);
255    }
256
257    #[test]
258    fn transform_before_with_angle_and_pivot_rotates_around_translated_origin() {
259        let mut band = BandShape::filled(vec![BandPoint::new(1.0, 0.0..=2.0)], Color32::WHITE);
260        let center = pos2(10.0, 20.0);
261        band.transform(TSTransform::from_translation(center.to_vec2()));
262        let band = band.with_angle_and_pivot(core::f32::consts::FRAC_PI_2, center);
263
264        let rotation = emath::Rot2::from_angle(band.angle);
265        let min = rotation * vec2(band.points[0].x, band.points[0].y.min);
266        let max = rotation * vec2(band.points[0].x, band.points[0].y.max);
267        assert!((min.x - 10.0).abs() < 1e-6);
268        assert!((min.y - 21.0).abs() < 1e-6);
269        assert!((max.x - 8.0).abs() < 1e-6);
270        assert!((max.y - 21.0).abs() < 1e-6);
271    }
272}