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
//! Scanline iterator.

use core::ops::Range;

use crate::{
    pixelcolor::PixelColor,
    primitives::{
        common::Scanline,
        polyline::{
            scanline_intersections::ScanlineIntersections, styled::untranslated_bounding_box,
        },
        Polyline, PrimitiveStyle,
    },
};

/// Iterate over every scanline in the polyline's bounding box.
///
/// Each scanline produces multiple actual `Line`s for each intersection of the thick polyline.
#[derive(Clone, Debug)]
#[cfg_attr(feature = "defmt", derive(::defmt::Format))]
pub struct ScanlineIterator<'a> {
    rows: Range<i32>,
    scanline_y: i32,
    intersections: ScanlineIntersections<'a>,
}

impl<'a> ScanlineIterator<'a> {
    /// New.
    pub fn new<C: PixelColor>(primitive: &Polyline<'a>, style: &PrimitiveStyle<C>) -> Self {
        debug_assert!(
            style.stroke_width > 1,
            "Polyline ScanlineIterator should only be used for stroke widths greater than 1"
        );

        let mut rows = untranslated_bounding_box(primitive, style).rows();

        if let Some(scanline_y) = rows.next() {
            let intersections =
                ScanlineIntersections::new(primitive.vertices, style.stroke_width, scanline_y);

            Self {
                rows,
                scanline_y,
                intersections,
            }
        } else {
            Self::empty()
        }
    }

    const fn empty() -> Self {
        Self {
            rows: 0i32..0,
            scanline_y: 0,
            intersections: ScanlineIntersections::empty(),
        }
    }
}

impl<'a> Iterator for ScanlineIterator<'a> {
    type Item = Scanline;

    fn next(&mut self) -> Option<Self::Item> {
        loop {
            if let Some(next) = self.intersections.next() {
                if !next.is_empty() {
                    break Some(next);
                }
            } else {
                self.scanline_y = self.rows.next()?;

                self.intersections.reset_with_new_scanline(self.scanline_y);
            }
        }
    }
}