main
Colby Knox 0.2.123: slots and unplated holes from KiCad (#45, #49), outline Gerber check (#46), stack region refit (#47), eval siz… 4223811
//! The board outline as a fab reads it from an outline Gerber (GM1, GKO): the draws chained into closed loops, each with
//! its size, so a check can ask whether one of them IS the board shape. Counting draws passed a GM1 that held only two
//! mounting-hole circles and no outline (#46).
use serde_json::{json, Value};

type P = (f64, f64);

/// One draw: a line, or an arc flattened into points; `ends` are its start and end.
#[derive(Debug, Clone)]
pub struct Draw { pub pts: Vec<P>, pub start: P, pub end: P }

/// The draws (D01) of a Gerber file, in mm. Format, units, G01/G02/G03 (multi-quadrant, I/J from the start point),
/// modal coordinates. Flashes (D03) are not edges and are counted apart.
pub fn draws(text: &str) -> (Vec<Draw>, usize) {
    let mut dec_x = 4u32; let mut dec_y = 4u32;
    let mut scale = 1.0; // mm per unit
    let mut cur: P = (0.0, 0.0);
    let mut mode = 1; // 1 line, 2 clockwise, 3 counter-clockwise
    let mut out = Vec::new();
    let mut flashes = 0;
    for raw in text.split('*') {
        // a block keeps the % and line breaks around it ("%\n%MOIN"): both go
        let b = raw.trim_matches(|c: char| c == '%' || c.is_whitespace());
        if b.is_empty() { continue; }
        if let Some(fs) = b.strip_prefix("FS") {
            // FSLAX46Y46: the second digit of each pair is the decimals
            if let Some(i) = fs.find('X') { dec_x = fs[i + 2..i + 3].parse().unwrap_or(4); }
            if let Some(i) = fs.find('Y') { dec_y = fs[i + 2..i + 3].parse().unwrap_or(4); }
            continue;
        }
        if b.starts_with("MOMM") { scale = 1.0; continue; }
        if b.starts_with("MOIN") { scale = 25.4; continue; }
        if b.starts_with('%') || b.starts_with("AD") || b.starts_with("AM") || b.starts_with("LP") || b.starts_with("TF") || b.starts_with("TA") || b.starts_with("TO") || b.starts_with("TD") { continue; }
        let mut s = b;
        // G codes at the start of the block set the mode
        while let Some(rest) = s.strip_prefix('G') {
            let n: String = rest.chars().take_while(|c| c.is_ascii_digit()).collect();
            match n.as_str() { "01" | "1" => mode = 1, "02" | "2" => mode = 2, "03" | "3" => mode = 3, _ => {} }
            s = &rest[n.len()..];
        }
        if !(s.contains('X') || s.contains('Y') || s.contains('D')) { continue; }
        let field = |k: char| -> Option<f64> {
            let i = s.find(k)?;
            let v: String = s[i + 1..].chars().take_while(|c| c.is_ascii_digit() || *c == '-' || *c == '+').collect();
            v.parse::<f64>().ok()
        };
        let d: Option<u32> = s.find('D').and_then(|i| s[i + 1..].chars().take_while(|c| c.is_ascii_digit()).collect::<String>().parse().ok());
        let x = field('X').map(|v| v / 10f64.powi(dec_x as i32) * scale).unwrap_or(cur.0);
        let y = field('Y').map(|v| v / 10f64.powi(dec_y as i32) * scale).unwrap_or(cur.1);
        let to = (x, y);
        match d {
            Some(1) => {
                let pts = if mode == 1 { vec![cur, to] } else {
                    let i = field('I').map(|v| v / 10f64.powi(dec_x as i32) * scale).unwrap_or(0.0);
                    let j = field('J').map(|v| v / 10f64.powi(dec_y as i32) * scale).unwrap_or(0.0);
                    arc(cur, to, (cur.0 + i, cur.1 + j), mode == 3)
                };
                out.push(Draw { pts, start: cur, end: to });
                cur = to;
            }
            Some(2) => cur = to,
            Some(3) => { flashes += 1; cur = to; }
            _ => cur = to,
        }
    }
    (out, flashes)
}

/// An arc from `a` to `b` about `c`, counter-clockwise when `ccw`, as points within 1 um of the curve; a full circle
/// when a and b meet.
fn arc(a: P, b: P, c: P, ccw: bool) -> Vec<P> {
    let r = ((a.0 - c.0).powi(2) + (a.1 - c.1).powi(2)).sqrt();
    let a0 = (a.1 - c.1).atan2(a.0 - c.0);
    let a1 = (b.1 - c.1).atan2(b.0 - c.0);
    let tau = std::f64::consts::TAU;
    let mut sweep = if ccw { a1 - a0 } else { a0 - a1 };
    while sweep <= 1e-9 { sweep += tau; }
    let step = if r > 0.0 { 2.0 * (1.0 - 0.001 / r).clamp(-1.0, 1.0).acos() } else { tau };
    let n = ((sweep / step.max(0.01)).ceil() as usize).clamp(1, 720);
    (0..=n).map(|k| { let t = a0 + if ccw { 1.0 } else { -1.0 } * sweep * k as f64 / n as f64; (c.0 + r * t.cos(), c.1 + r * t.sin()) }).collect()
}

/// The closed loops the draws make (ends within `tol` mm chained; every corner of a loop shared by exactly two draws),
/// each as [width, height, draws] in mm, plus the draws that close nothing.
pub fn loops(ds: &[Draw], tol: f64) -> (Vec<(f64, f64, usize)>, usize) {
    let key = |p: P| ((p.0 / tol).round() as i64, (p.1 / tol).round() as i64);
    let near = |a: P, b: P| (a.0 - b.0).abs() <= tol && (a.1 - b.1).abs() <= tol;
    let n = ds.len();
    let mut parent: Vec<usize> = (0..n).collect();
    fn find(p: &mut Vec<usize>, x: usize) -> usize { let mut r = x; while p[r] != r { r = p[r]; } let mut y = x; while p[y] != r { let z = p[y]; p[y] = r; y = z; } r }
    for i in 0..n { for j in i + 1..n {
        let (a, b) = (&ds[i], &ds[j]);
        if near(a.start, b.start) || near(a.start, b.end) || near(a.end, b.start) || near(a.end, b.end) { let (x, y) = (find(&mut parent, i), find(&mut parent, j)); parent[x] = y; }
    } }
    let mut groups: std::collections::BTreeMap<usize, Vec<usize>> = Default::default();
    for i in 0..n { let r = find(&mut parent, i); groups.entry(r).or_default().push(i); }
    let mut out = Vec::new();
    let mut open = 0;
    for (_, g) in groups {
        let mut deg: std::collections::HashMap<(i64, i64), usize> = Default::default();
        for &i in &g { *deg.entry(key(ds[i].start)).or_default() += 1; *deg.entry(key(ds[i].end)).or_default() += 1; }
        let single_circle = g.len() == 1 && near(ds[g[0]].start, ds[g[0]].end) && ds[g[0]].pts.len() > 2;
        let closed = single_circle || (g.len() >= 2 && deg.values().all(|d| d % 2 == 0));
        if !closed { open += g.len(); continue; }
        let pts = g.iter().flat_map(|&i| ds[i].pts.iter().copied());
        let (mut x0, mut y0, mut x1, mut y1) = (f64::MAX, f64::MAX, f64::MIN, f64::MIN);
        for p in pts { x0 = x0.min(p.0); y0 = y0.min(p.1); x1 = x1.max(p.0); y1 = y1.max(p.1); }
        out.push((x1 - x0, y1 - y0, g.len()));
    }
    (out, open)
}

/// What one outline Gerber holds, and whether a loop in it is the board shape (`board`: width, height in mm, within
/// `tol` mm).
pub fn read(text: &str, board: Option<(f64, f64)>, tol: f64) -> Value {
    let (ds, flashes) = draws(text);
    let (ls, open) = loops(&ds, 0.01);
    let r3 = |v: f64| (v * 1000.0).round() / 1000.0;
    let matches = board.map(|(w, h)| ls.iter().any(|l| (l.0 - w).abs() <= tol && (l.1 - h).abs() <= tol));
    json!({"draws": ds.len(), "flashes": flashes, "closedLoops": ls.iter().map(|l| json!({"widthMm": r3(l.0), "heightMm": r3(l.1), "draws": l.2})).collect::<Vec<_>>(),
        "openDraws": open, "boardShape": matches})
}

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

    const HEAD: &str = "%FSLAX46Y46*%\n%MOMM*%\n%ADD10C,0.254*%\nD10*\n";

    #[test]
    fn a_rectangle_is_the_board_shape() {
        let t = format!("{HEAD}X0Y0D02*\nX50000000Y0D01*\nX50000000Y30000000D01*\nX0Y30000000D01*\nX0Y0D01*\nM02*\n");
        let r = read(&t, Some((50.0, 30.0)), 0.1);
        assert_eq!(r["draws"], 4);
        assert_eq!(r["closedLoops"][0]["widthMm"], json!(50.0));
        assert_eq!(r["boardShape"], json!(true));
        assert_eq!(read(&t, Some((60.0, 30.0)), 0.1)["boardShape"], json!(false), "another board's size");
    }

    #[test]
    fn two_hole_circles_are_not_an_outline() {
        // #46: Mechanical 1 held two mounting-hole circles and nothing else
        let t = format!("{HEAD}G75*\nX5000000Y3000000D02*\nG03X5000000Y3000000I-1600000J0D01*\nX45000000Y3000000D02*\nG03X45000000Y3000000I-1600000J0D01*\nM02*\n");
        let r = read(&t, Some((50.0, 30.0)), 0.1);
        assert_eq!(r["closedLoops"].as_array().unwrap().len(), 2, "{r}");
        assert!((r["closedLoops"][0]["widthMm"].as_f64().unwrap() - 3.2).abs() < 0.01, "{r}");
        assert_eq!(r["boardShape"], json!(false));
    }

    #[test]
    fn rounded_corners_and_inches() {
        // a 2 x 1 inch board with one rounded corner (arc), in inches with 5 decimals
        let t = "%FSLAX25Y25*%\n%MOIN*%\nG01*\nX0Y0D02*\nX190000Y0D01*\nG03X200000Y10000I0J10000D01*\nG01*\nX200000Y100000D01*\nX0Y100000D01*\nX0Y0D01*\nM02*\n";
        let r = read(t, Some((50.8, 25.4)), 0.1);
        assert_eq!(r["boardShape"], json!(true), "{r}");
        // an open line is no loop
        let o = format!("{HEAD}X0Y0D02*\nX50000000Y0D01*\nM02*\n");
        let ro = read(&o, Some((50.0, 30.0)), 0.1);
        assert_eq!((ro["openDraws"].as_u64(), ro["boardShape"].as_bool()), (Some(1), Some(false)));
    }
}