main
Colby Knox 0.2.108: keepouts in routing_state; engine 0.26.0 (plan_route keepouts, fab_check edge clearance) 7b0e3bc
//! Keepouts in the board model, as the standard reads them (engine 0.26.0's plan_route keeps out of them):
//! `[{layers, points, kind, name}]` in mm. Altium's keepouts are tracks, arcs, fills and regions marked keepout, and
//! anything on the Keep-Out layer (every copper layer). Each comes as the area its copper would have covered: a track
//! its band (square ends: a little more room than Altium keeps, never less), an arc its curved band, a fill its rotated
//! rectangle, a region its outline. No `rules` are sent, which the standard reads as tracks and vias both kept out:
//! Altium's default for a keepout. Which objects a restricted keepout allows is not read yet (the script API names it
//! differently on this build), so such a keepout is treated as keeping out both.
use serde_json::{json, Value};

/// Altium's Keep-Out layer id: a keepout there applies to every copper layer.
const KEEP_OUT_LAYER: i64 = 56;

fn n(v: &Value) -> f64 {
    v.as_f64().unwrap_or(0.0)
}

fn r4(v: f64) -> f64 {
    (v * 10000.0).round() / 10000.0
}

/// The band a straight piece of copper of half-width `h` covers, as a rectangle with square ends.
fn band(a: (f64, f64), b: (f64, f64), h: f64) -> Vec<(f64, f64)> {
    let (dx, dy) = (b.0 - a.0, b.1 - a.1);
    let len = (dx * dx + dy * dy).sqrt();
    let (ux, uy) = if len < 1e-9 { (1.0, 0.0) } else { (dx / len, dy / len) };
    let (nx, ny) = (-uy * h, ux * h);
    let (ex, ey) = (ux * h, uy * h);
    vec![(a.0 - ex + nx, a.1 - ey + ny), (b.0 + ex + nx, b.1 + ey + ny), (b.0 + ex - nx, b.1 + ey - ny), (a.0 - ex - nx, a.1 - ey - ny)]
}

/// The curved band an arc of half-width `h` covers: its outer edge forward, its inner edge back.
fn arc_band(c: (f64, f64), r: f64, a1: f64, a2: f64, h: f64) -> Vec<(f64, f64)> {
    let mut sweep = a2 - a1;
    if sweep <= 0.0 { sweep += 360.0; }
    let steps = ((sweep / 10.0).ceil() as usize).max(4);
    let at = |rad: f64, i: usize| {
        let t = (a1 + sweep * i as f64 / steps as f64).to_radians();
        (c.0 + rad * t.cos(), c.1 + rad * t.sin())
    };
    let mut pts: Vec<(f64, f64)> = (0..=steps).map(|i| at(r + h, i)).collect();
    pts.extend((0..=steps).rev().map(|i| at((r - h).max(0.0), i)));
    pts
}

/// A fill's rectangle turned by its rotation (degrees) about its centre.
fn fill_rect(x1: f64, y1: f64, x2: f64, y2: f64, rot: f64) -> Vec<(f64, f64)> {
    let (cx, cy) = ((x1 + x2) / 2.0, (y1 + y2) / 2.0);
    let (s, c) = rot.to_radians().sin_cos();
    [(x1, y1), (x2, y1), (x2, y2), (x1, y2)].iter()
        .map(|(x, y)| { let (dx, dy) = (x - cx, y - cy); (cx + dx * c - dy * s, cy + dx * s + dy * c) }).collect()
}

/// The agent's raw keepout rows (`["t", layer, x1, y1, x2, y2, width]`, `["a", layer, cx, cy, r, a1*1000, a2*1000,
/// width]`, `["f", layer, x1, y1, x2, y2, rot*1000]`, `["r", layer, [[x, y], ...]]`, raw units) as the board model's
/// keepouts. `to_mm` converts raw units; `layer` names a copper layer id. A keepout on a layer that is not copper is
/// left out. Pure.
pub fn shape(raw: &[Value], to_mm: impl Fn(f64) -> f64, layer: impl Fn(i64) -> String) -> Vec<Value> {
    let mut out = Vec::new();
    for (i, k) in raw.iter().enumerate() {
        let id = k[1].as_i64().unwrap_or(-1);
        let lname = if id == KEEP_OUT_LAYER { "*.Cu".to_string() } else { layer(id) };
        if !(lname == "*.Cu" || lname.ends_with(".Cu")) { continue; }
        let m = |j: usize| to_mm(n(&k[j]));
        let (kind, pts) = match k[0].as_str().unwrap_or("") {
            "t" => ("track", band((m(2), m(3)), (m(4), m(5)), m(6) / 2.0)),
            "a" => ("arc", arc_band((m(2), m(3)), m(4), n(&k[5]) / 1000.0, n(&k[6]) / 1000.0, m(7) / 2.0)),
            "f" => ("fill", fill_rect(m(2), m(3), m(4), m(5), n(&k[6]) / 1000.0)),
            "r" => ("region", k[2].as_array().cloned().unwrap_or_default().iter().map(|p| (to_mm(n(&p[0])), to_mm(n(&p[1])))).collect()),
            _ => continue,
        };
        if pts.len() < 3 { continue; }
        out.push(json!({"name": format!("keepout {kind} {}", i + 1), "kind": kind, "layers": [lname],
                        "points": pts.iter().map(|(x, y)| json!([r4(*x), r4(*y)])).collect::<Vec<_>>()}));
    }
    out
}

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

    fn layer(id: i64) -> String {
        match id { 1 => "F.Cu".into(), 32 => "B.Cu".into(), _ => format!("L{id}") }
    }

    #[test]
    fn each_keepout_is_the_area_it_covers_on_its_layers() {
        let raw = vec![
            json!(["t", 56, 0, 0, 10, 0, 2]),
            json!(["f", 1, 0, 0, 4, 2, 90000]),
            json!(["r", 32, [[0, 0], [3, 0], [0, 3]]]),
            json!(["a", 1, 0, 0, 5, 0, 90000, 2]),
            json!(["t", 33, 0, 0, 1, 1, 1]),
        ];
        let k = shape(&raw, |v| v, layer);
        assert_eq!(k.len(), 4, "the keepout on a layer that is not copper is left out: {k:?}");
        assert_eq!(k[0]["layers"], json!(["*.Cu"]), "the Keep-Out layer is every copper layer");
        assert_eq!(k[0]["points"], json!([[-1.0, 1.0], [11.0, 1.0], [11.0, -1.0], [-1.0, -1.0]]), "a track's band with square ends");
        assert_eq!(k[1]["points"], json!([[3.0, -1.0], [3.0, 3.0], [1.0, 3.0], [1.0, -1.0]]), "a fill turned 90 degrees about its centre");
        assert_eq!(k[2]["kind"], json!("region"));
        assert_eq!(k[2]["layers"], json!(["B.Cu"]));
        let arc: Vec<(f64, f64)> = k[3]["points"].as_array().unwrap().iter().map(|p| (n(&p[0]), n(&p[1]))).collect();
        assert!(arc.iter().all(|(x, y)| { let r = (x * x + y * y).sqrt(); r > 3.99 && r < 6.01 }), "an arc's band lies between r-h and r+h");
        assert!(k.iter().all(|x| x.get("rules").is_none()), "no rules: tracks and vias both kept out");
    }
}