Your browser sucks, JavaScript disabled! Gunnar's console needs JavaScript and WebAssembly. Git over SSH on port 2222 does not.

nordisk/korp-map

crates/korp-map-quality/src/raster.rs

//! **A scanline polygon filler** (pixel centres, no anti-aliasing) and the connected
//! components the gap metric needs.
//!
//! A pixel `(x, y)` is inside when its centre `(x + 0.5, y + 0.5)` is inside the
//! polygon under the fill rule. Rings are given in continuous canvas pixels; rings
//! reaching off the canvas are fine (crossings left of the canvas still count).

/// The fill rule.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Rule {
    EvenOdd,
    NonZero,
    /// Inside where the winding number is positive: rings that run counter-clockwise as
    /// seen on the canvas (north up) — counter-clockwise in lon/lat, OSM's land-on-the-
    /// left — add; the other way subtract. A clockwise ring alone is never inside.
    Positive,
}

impl Rule {
    fn inside(self, wind: i32) -> bool {
        match self {
            Self::EvenOdd => wind & 1 == 1,
            Self::NonZero => wind != 0,
            Self::Positive => wind > 0,
        }
    }
    fn step(self, dir: i32) -> i32 {
        match self {
            Self::EvenOdd => 1,
            Self::NonZero | Self::Positive => dir,
        }
    }
}

struct Edge {
    /// First and one-past-last row whose centre the edge spans.
    r0: usize,
    r1: usize,
    /// x at the centre of row r0, and the step per row.
    x: f64,
    dx: f64,
    dir: i32,
}

/// Fill `rings` (each a run of canvas points; closed implicitly) on a `w`×`h` canvas,
/// calling `span(y, x0, x1)` for every inside run of pixels `x0..x1` on row `y`.
pub fn fill<'a, I, F>(w: u32, h: u32, rings: I, rule: Rule, mut span: F)
where
    I: IntoIterator<Item = &'a [(f64, f64)]>,
    F: FnMut(usize, usize, usize),
{
    let (wi, hi) = (w as i64, h as i64);
    let mut edges: Vec<Edge> = Vec::new();
    for ring in rings {
        let n = ring.len();
        if n < 3 {
            continue;
        }
        for i in 0..n {
            let (a, b) = (ring[i], ring[(i + 1) % n]);
            if a == b
                || a.1 == b.1
                || !(a.0.is_finite() && a.1.is_finite() && b.0.is_finite() && b.1.is_finite())
            {
                continue;
            }
            let (dir, lo, hi_p) = if a.1 < b.1 { (1, a, b) } else { (-1, b, a) };
            // Rows whose centre c = r + 0.5 satisfies lo.y <= c < hi.y.
            let r0 = ((lo.1 - 0.5).ceil() as i64).max(0);
            let r1 = ((hi_p.1 - 0.5).ceil() as i64).min(hi);
            if r0 >= r1 {
                continue;
            }
            let dx = (hi_p.0 - lo.0) / (hi_p.1 - lo.1);
            let x = lo.0 + (r0 as f64 + 0.5 - lo.1) * dx;
            edges.push(Edge {
                r0: r0 as usize,
                r1: r1 as usize,
                x,
                dx,
                dir,
            });
        }
    }
    if edges.is_empty() {
        return;
    }
    edges.sort_unstable_by_key(|e| e.r0);
    let mut next = 0;
    let mut active: Vec<Edge> = Vec::new();
    let mut xs: Vec<(f64, i32)> = Vec::new();
    let first = edges[0].r0;
    for y in first..h as usize {
        while next < edges.len() && edges[next].r0 == y {
            let e = std::mem::replace(
                &mut edges[next],
                Edge {
                    r0: 0,
                    r1: 0,
                    x: 0.0,
                    dx: 0.0,
                    dir: 0,
                },
            );
            active.push(e);
            next += 1;
        }
        active.retain(|e| e.r1 > y);
        if active.is_empty() {
            if next >= edges.len() {
                break;
            }
            continue;
        }
        xs.clear();
        for e in &mut active {
            let row_off = (y - e.r0) as f64;
            xs.push((e.x + row_off * e.dx, e.dir));
        }
        xs.sort_unstable_by(|a, b| a.0.total_cmp(&b.0));
        let mut wind = 0i32;
        for k in 0..xs.len() {
            let inside_before = rule.inside(wind);
            wind += rule.step(xs[k].1);
            if !inside_before && rule.inside(wind) {
                // Opening crossing: the span runs to the next crossing that closes it.
                let xa = xs[k].0;
                let mut wk = wind;
                let mut m = k + 1;
                while m < xs.len() {
                    wk += rule.step(xs[m].1);
                    if !rule.inside(wk) {
                        break;
                    }
                    m += 1;
                }
                let xb = if m < xs.len() { xs[m].0 } else { f64::INFINITY };
                let x0 = ((xa - 0.5).ceil() as i64).clamp(0, wi);
                let x1 = ((xb - 0.5).ceil().min(wi as f64) as i64).clamp(0, wi);
                if x0 < x1 {
                    span(y, x0 as usize, x1 as usize);
                }
            }
        }
    }
}

/// Draw a polyline 1 px thin (every pixel its centre line passes through), calling `px`.
pub fn polyline(w: u32, h: u32, pts: &[(f64, f64)], mut px: impl FnMut(usize)) {
    let (wf, hf) = (f64::from(w), f64::from(h));
    for s in pts.windows(2) {
        let (a, b) = (s[0], s[1]);
        if (a.0 < 0.0 && b.0 < 0.0)
            || (a.1 < 0.0 && b.1 < 0.0)
            || (a.0 >= wf && b.0 >= wf)
            || (a.1 >= hf && b.1 >= hf)
        {
            continue;
        }
        let n = ((b.0 - a.0).abs().max((b.1 - a.1).abs()) * 2.0)
            .ceil()
            .clamp(1.0, 1e6) as usize;
        for k in 0..=n {
            let t = k as f64 / n as f64;
            let (x, y) = (a.0 + (b.0 - a.0) * t, a.1 + (b.1 - a.1) * t);
            if x >= 0.0 && y >= 0.0 && x < wf && y < hf {
                px(y as usize * w as usize + x as usize);
            }
        }
    }
}

/// One 4-connected component of the cells `want` selects.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Component {
    pub pixels: usize,
    pub bbox: [usize; 4],
    /// The component touches the canvas edge.
    pub touches_edge: bool,
    /// Every pixel 4-adjacent to the component (and not in it) satisfies `enclosing`.
    pub enclosed: bool,
    /// Some pixel of the component satisfies `mark` (e.g. a road runs through it).
    pub marked: bool,
}

/// Label the 4-connected components of cells where `want(i)`; for each, whether every
/// neighbour outside it satisfies `enclosing(i)` and whether any of its cells is `mark`ed.
pub fn components(
    w: usize,
    h: usize,
    want: impl Fn(usize) -> bool,
    enclosing: impl Fn(usize) -> bool,
    mark: impl Fn(usize) -> bool,
) -> Vec<Component> {
    let mut seen = vec![false; w * h];
    let mut out = Vec::new();
    let mut stack = Vec::new();
    for start in 0..w * h {
        if seen[start] || !want(start) {
            continue;
        }
        seen[start] = true;
        stack.push(start);
        let mut c = Component {
            pixels: 0,
            bbox: [usize::MAX, usize::MAX, 0, 0],
            touches_edge: false,
            enclosed: true,
            marked: false,
        };
        while let Some(i) = stack.pop() {
            let (x, y) = (i % w, i / w);
            c.pixels += 1;
            c.marked |= mark(i);
            c.bbox = [
                c.bbox[0].min(x),
                c.bbox[1].min(y),
                c.bbox[2].max(x),
                c.bbox[3].max(y),
            ];
            if x == 0 || y == 0 || x + 1 == w || y + 1 == h {
                c.touches_edge = true;
            }
            let mut visit = |j: usize| {
                if want(j) {
                    if !seen[j] {
                        seen[j] = true;
                        stack.push(j);
                    }
                } else if !enclosing(j) {
                    c.enclosed = false;
                }
            };
            if x > 0 {
                visit(i - 1);
            }
            if x + 1 < w {
                visit(i + 1);
            }
            if y > 0 {
                visit(i - w);
            }
            if y + 1 < h {
                visit(i + w);
            }
        }
        out.push(c);
    }
    out
}

#[cfg(test)]
mod tests {
    use super::*;

    fn count(w: u32, h: u32, rings: &[Vec<(f64, f64)>], rule: Rule) -> usize {
        let mut n = 0;
        fill(w, h, rings.iter().map(Vec::as_slice), rule, |_, a, b| {
            n += b - a
        });
        n
    }

    #[test]
    fn a_square_fills_its_pixels() {
        let sq = vec![(10.0, 10.0), (20.0, 10.0), (20.0, 20.0), (10.0, 20.0)];
        assert_eq!(
            count(100, 100, std::slice::from_ref(&sq), Rule::EvenOdd),
            100
        );
        assert_eq!(count(100, 100, &[sq], Rule::NonZero), 100);
    }

    #[test]
    fn a_hole_is_cut_and_off_canvas_parts_clip() {
        let outer = vec![(-50.0, -50.0), (50.0, -50.0), (50.0, 50.0), (-50.0, 50.0)];
        let hole = vec![(10.0, 10.0), (10.0, 20.0), (20.0, 20.0), (20.0, 10.0)];
        // Canvas 0..40: outer covers 40×40 = 1600, minus the 10×10 hole.
        assert_eq!(
            count(40, 40, &[outer.clone(), hole.clone()], Rule::EvenOdd),
            1500
        );
        // Non-zero: the hole runs the other way, so it is cut too.
        assert_eq!(count(40, 40, &[outer, hole], Rule::NonZero), 1500);
    }

    #[test]
    fn overlapping_same_direction_rings_union_under_nonzero() {
        let a = vec![(0.0, 0.0), (10.0, 0.0), (10.0, 10.0), (0.0, 10.0)];
        let b = vec![(5.0, 0.0), (15.0, 0.0), (15.0, 10.0), (5.0, 10.0)];
        assert_eq!(count(20, 20, &[a.clone(), b.clone()], Rule::NonZero), 150);
        assert_eq!(count(20, 20, &[a, b], Rule::EvenOdd), 100);
    }

    #[test]
    fn positive_keeps_counter_clockwise_rings_only() {
        // As seen (y down): right along the top, down, left, up = clockwise.
        let cw = vec![(0.0, 0.0), (10.0, 0.0), (10.0, 10.0), (0.0, 10.0)];
        let ccw: Vec<_> = cw.iter().rev().copied().collect();
        assert_eq!(count(20, 20, &[ccw], Rule::Positive), 100);
        assert_eq!(count(20, 20, &[cw], Rule::Positive), 0);
    }

    #[test]
    fn a_triangle_is_half_its_box() {
        let t = vec![(0.0, 0.0), (100.0, 0.0), (0.0, 100.0)];
        let n = count(100, 100, &[t], Rule::NonZero) as i64;
        assert!((n - 5000).abs() <= 100, "{n}");
    }

    #[test]
    fn enclosed_components_are_found() {
        // 5×5 grid, all "fill" except a 1-px hole in the middle and a notch at the edge.
        let w = 5;
        let hole = |i: usize| i == 12 || i == 2;
        let c = components(w, 5, hole, |_| true, |_| false);
        assert_eq!(c.len(), 2);
        let mid = c.iter().find(|c| c.bbox[0] == 2 && c.bbox[1] == 2).unwrap();
        assert!(mid.enclosed && !mid.touches_edge);
        assert!(c.iter().any(|c| c.touches_edge));
    }
}