1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
//! The ellipse primitive

use crate::{
    geometry::{Dimensions, Point, Size},
    primitives::{circle, ContainsPoint, OffsetOutline, PointsIter, Primitive, Rectangle},
    transform::Transform,
};

mod points;
mod styled;

pub use points::Points;
pub use styled::StyledPixelsIterator;

/// Ellipse primitive
///
/// # Examples
///
/// ## Create some ellipses with different styles
///
/// ```rust
/// use embedded_graphics::{
///     pixelcolor::Rgb565,
///     prelude::*,
///     primitives::{Ellipse, PrimitiveStyle, PrimitiveStyleBuilder},
/// };
/// # use embedded_graphics::mock_display::MockDisplay;
///
/// // Ellipse with 1 pixel wide white stroke with top-left point at (10, 20) with a size of (30, 40)
/// # let mut display = MockDisplay::default();
/// Ellipse::new(Point::new(10, 20), Size::new(30, 40))
///     .into_styled(PrimitiveStyle::with_stroke(Rgb565::WHITE, 1))
///     .draw(&mut display)?;
///
/// // Ellipse with styled stroke and fill with top-left point at (20, 30) with a size of (40, 30)
/// let style = PrimitiveStyleBuilder::new()
///     .stroke_color(Rgb565::RED)
///     .stroke_width(3)
///     .fill_color(Rgb565::GREEN)
///     .build();
///
/// # let mut display = MockDisplay::default();
/// Ellipse::new(Point::new(20, 30), Size::new(40, 30))
///     .into_styled(style)
///     .draw(&mut display)?;
///
/// // Ellipse with blue fill and no stroke with a translation applied
/// # let mut display = MockDisplay::default();
/// Ellipse::new(Point::new(10, 20), Size::new(20, 40))
///     .translate(Point::new(10, -15))
///     .into_styled(PrimitiveStyle::with_fill(Rgb565::BLUE))
///     .draw(&mut display)?;
/// # Ok::<(), core::convert::Infallible>(())
/// ```
#[derive(Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash, Debug, Default)]
pub struct Ellipse {
    /// Top-left point of ellipse's bounding box
    pub top_left: Point,

    /// Size of the ellipse
    pub size: Size,
}

impl Ellipse {
    /// Create a new ellipse delimited with a top-left point with a specific size
    pub const fn new(top_left: Point, size: Size) -> Self {
        Ellipse { top_left, size }
    }

    /// Create a new ellipse centered around a given point with a specific size
    pub fn with_center(center: Point, size: Size) -> Self {
        let top_left = Rectangle::with_center(center, size).top_left;

        Ellipse { top_left, size }
    }

    /// Return the center point of the ellipse
    pub fn center(&self) -> Point {
        self.bounding_box().center()
    }

    /// Return the center point of the ellipse scaled by a factor of 2
    ///
    /// This method is used to accurately calculate the outside edge of the ellipse.
    /// The result is not equivalent to `self.center() * 2` because of rounding.
    fn center_2x(&self) -> Point {
        center_2x(self.top_left, self.size)
    }
}

impl OffsetOutline for Ellipse {
    fn offset(&self, offset: i32) -> Self {
        let size = if offset >= 0 {
            self.size.saturating_add(Size::new_equal(2 * offset as u32))
        } else {
            self.size
                .saturating_sub(Size::new_equal(2 * (-offset) as u32))
        };

        Self::with_center(self.center(), size)
    }
}

/// Return the center point of the ellipse scaled by a factor of 2
///
/// This method is used to accurately calculate the outside edge of the ellipse.
/// The result is not equivalent to `Ellipse::center() * 2` because of rounding.
pub(in crate::primitives) fn center_2x(top_left: Point, size: Size) -> Point {
    let radius = size.saturating_sub(Size::new(1, 1));

    top_left * 2 + radius
}

impl Primitive for Ellipse {}

impl PointsIter for Ellipse {
    type Iter = Points;

    fn points(&self) -> Self::Iter {
        Points::new(self)
    }
}

impl ContainsPoint for Ellipse {
    fn contains(&self, point: Point) -> bool {
        let ellipse_contains = EllipseContains::new(self.size);
        ellipse_contains.contains(point * 2 - self.center_2x())
    }
}

impl Dimensions for Ellipse {
    fn bounding_box(&self) -> Rectangle {
        Rectangle::new(self.top_left, self.size)
    }
}

impl Transform for Ellipse {
    /// Translate the ellipse from its current position to a new position by (x, y) pixels,
    /// returning a new `Ellipse`. For a mutating transform, see `translate_mut`.
    ///
    /// ```
    /// # use embedded_graphics::primitives::Ellipse;
    /// # use embedded_graphics::prelude::*;
    /// let ellipse = Ellipse::new(Point::new(5, 10), Size::new(10, 15));
    /// let moved = ellipse.translate(Point::new(10, 10));
    ///
    /// assert_eq!(moved.top_left, Point::new(15, 20));
    /// ```
    fn translate(&self, by: Point) -> Self {
        Self {
            top_left: self.top_left + by,
            ..*self
        }
    }

    /// Translate the ellipse from its current position to a new position by (x, y) pixels.
    ///
    /// ```
    /// # use embedded_graphics::primitives::Ellipse;
    /// # use embedded_graphics::prelude::*;
    /// let mut ellipse = Ellipse::new(Point::new(5, 10), Size::new(10, 15));
    /// ellipse.translate_mut(Point::new(10, 10));
    ///
    /// assert_eq!(ellipse.top_left, Point::new(15, 20));
    /// ```
    fn translate_mut(&mut self, by: Point) -> &mut Self {
        self.top_left += by;

        self
    }
}

/// Determines if a point is inside an ellipse.
// TODO: Make this available to the user as part of #343
#[derive(Clone, Copy, Eq, PartialEq, PartialOrd, Ord, Hash, Debug)]
pub(in crate::primitives) struct EllipseContains {
    a: u32,
    b: u32,
    threshold: u32,
}

impl EllipseContains {
    /// Creates an object to determine if a point is inside an ellipse.
    ///
    /// The ellipse is always located in the origin.
    pub fn new(size: Size) -> Self {
        let Size { width, height } = size;

        let a = width.pow(2);
        let b = height.pow(2);

        // Special case for circles, where width and height are equal
        let threshold = if width == height {
            circle::diameter_to_threshold(width)
        } else {
            b * a
        };

        Self { a, b, threshold }
    }

    /// Returns `true` if the point is inside the ellipse.
    pub fn contains(&self, point: Point) -> bool {
        let x = point.x.pow(2) as u32;
        let y = point.y.pow(2) as u32;

        // Special case for circles, where width and height are equal
        if self.a == self.b {
            x + y < self.threshold
        } else {
            self.b * x + self.a * y < self.threshold
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::{
        geometry::{Point, Size},
        mock_display::MockDisplay,
        pixelcolor::BinaryColor,
        primitives::ContainsPoint,
    };

    #[test]
    fn contains() {
        let ellipse = Ellipse::new(Point::zero(), Size::new(40, 20));

        let display = MockDisplay::from_points(
            ellipse
                .bounding_box()
                .points()
                .filter(|p| ellipse.contains(*p)),
            BinaryColor::On,
        );

        let expected = MockDisplay::from_points(ellipse.points(), BinaryColor::On);

        display.assert_eq(&expected);
    }

    #[test]
    fn translate() {
        let moved = Ellipse::new(Point::new(4, 6), Size::new(5, 8)).translate(Point::new(3, 5));

        assert_eq!(moved, Ellipse::new(Point::new(7, 11), Size::new(5, 8)));
    }

    #[test]
    fn offset() {
        let center = Point::new(5, 6);
        let ellipse = Ellipse::with_center(center, Size::new(3, 4));

        assert_eq!(ellipse.offset(0), ellipse);

        assert_eq!(
            ellipse.offset(1),
            Ellipse::with_center(center, Size::new(5, 6))
        );
        assert_eq!(
            ellipse.offset(2),
            Ellipse::with_center(center, Size::new(7, 8))
        );

        assert_eq!(
            ellipse.offset(-1),
            Ellipse::with_center(center, Size::new(1, 2))
        );
        assert_eq!(
            ellipse.offset(-2),
            Ellipse::with_center(center, Size::new(0, 0))
        );
        assert_eq!(
            ellipse.offset(-3),
            Ellipse::with_center(center, Size::new(0, 0))
        );
    }
}