main
Colby Knox 0.2.121 source: altium_add_dimensions (anchored footprint dimensions), altium_check_silkscreen, fabOutline edges (#43) def89d5
//! Footprints from a datasheet's land pattern: the AI gives the numbers the datasheet prints (pitch, pad size, row
//! span, body), the standard's shared engine lays out the footprint (vendor/adom-eda-checks `landpattern`, ported from
//! this file: pads numbered the standard way, an exposed pad, the courtyard, silkscreen kept clear of the copper with a
//! pin-1 dot, a fab outline with a pin-1 chamfer), and this bridge writes it as the agent's build_footprint spec (mm,
//! Y up, origin at the centre).
use adom_eda_checks::landpattern::{layout, Fp};
use serde_json::{json, Value};

fn num(a: &Value, k: &str) -> Option<f64> { a.get(k).and_then(|v| v.as_f64().or_else(|| v.as_str().and_then(|s| s.parse().ok()))) }

/// The agent's spec text.
pub fn spec(name: &str, desc: &str, fp: &Fp) -> String {
    let clean = |s: &str| s.replace(['|', '\n', '\r'], " ");
    let mut s = format!("META|{}|{}\n", clean(name), clean(desc));
    for p in &fp.pads {
        let crp = if p.shape == "roundrect" { 25 } else { 0 };
        s.push_str(&format!("PAD|{}|{:.4}|{:.4}|{:.4}|{:.4}|{}|{:.3}|{}|{}\n", clean(&p.name), p.x, p.y, p.w, p.h, p.shape, p.hole, if p.hole > 0.0 { "multi" } else { "top" }, crp));
    }
    for (l, a, b, c, d, w) in &fp.lines { s.push_str(&format!("LINE|{l}|{a:.4}|{b:.4}|{c:.4}|{d:.4}|{w:.4}\n")); }
    for (l, x, y, r) in &fp.discs { s.push_str(&format!("DISC|{l}|{x:.4}|{y:.4}|{r:.4}\n")); }
    s
}

/// `fabOutline: "edges"` (#43): the assembly outline as exactly four lines, one per body edge, meeting at the body's
/// corners (TL, TR, BR, BL), and the pin-1 chamfer as a line of its own across the top-left corner. The layout draws
/// the outline as one polyline with that corner cut off, so the corner was no line's end and a dimension could not
/// attach to it. Returns the corners (mm), or None when the layout drew no fab outline.
pub fn fab_edges(fp: &mut Fp) -> Option<Value> {
    let fab: Vec<_> = fp.lines.iter().filter(|l| l.0 == "fab").cloned().collect();
    if fab.is_empty() { return None; }
    let xs = fab.iter().flat_map(|l| [l.1, l.3]);
    let ys = fab.iter().flat_map(|l| [l.2, l.4]);
    let (x0, x1) = xs.clone().fold((f64::MAX, f64::MIN), |(a, b), v| (a.min(v), b.max(v)));
    let (y0, y1) = ys.clone().fold((f64::MAX, f64::MIN), |(a, b), v| (a.min(v), b.max(v)));
    let w = fab[0].5;
    let ch = ((x1 - x0).min(y1 - y0) * 0.25).min(1.0);
    let r3 = |v: f64| (v * 1000.0).round() / 1000.0;
    fp.lines.retain(|l| l.0 != "fab");
    for (a, b, c, d) in [(x0, y1, x1, y1), (x1, y1, x1, y0), (x1, y0, x0, y0), (x0, y0, x0, y1)] { fp.lines.push(("fab", r3(a), r3(b), r3(c), r3(d), w)); }
    fp.lines.push(("fab", r3(x0), r3(y1 - ch), r3(x0 + ch), r3(y1), w));
    Some(json!({"mode": "edges", "corners": {"TL": [r3(x0), r3(y1)], "TR": [r3(x1), r3(y1)], "BR": [r3(x1), r3(y0)], "BL": [r3(x0), r3(y0)]},
        "edges": ["top TL-TR", "right TR-BR", "bottom BR-BL", "left BL-TL"], "pin1Chamfer": [[r3(x0), r3(y1 - ch)], [r3(x0 + ch), r3(y1)]]}))
}

/// A plain description: "SOIC-8, 1.27 mm pitch, 8 pads".
fn describe(a: &Value, fp: &Fp) -> String {
    let fam = a.get("family").and_then(|f| f.as_str()).unwrap_or("dual");
    let pitch = num(a, "pitch").map(|p| format!(", {p} mm pitch")).unwrap_or_default();
    format!("{} {}{}, {} pads (from the datasheet land pattern)", a.get("name").and_then(|n| n.as_str()).unwrap_or(""), fam, pitch, fp.pads.len())
}

/// altium_footprint_from_land_pattern {libraryPath, name, family, ..., dryRun?}
pub fn from_land_pattern(args: &Value) -> Value {
    let Some(name) = crate::support::s(args, "name").filter(|n| !n.is_empty()) else { return json!({"success": false, "errorCode": "bad_args", "error": "name is required"}) };
    let mut fp = match layout(args) { Ok(f) => f, Err(e) => return json!({"success": false, "errorCode": "bad_args", "error": e,
        "_hint": "Give the datasheet's RECOMMENDED LAND PATTERN numbers (mm): chip {span, padLength, padWidth}; dual/sot {pins | leftPins+rightPins, pitch, span (pad centre to pad centre across), padLength, padWidth}; quad {pins | pinsPerSideX+pinsPerSideY, pitch, span, spanY?, padLength, padWidth}; bga {rows, cols, pitch, ballPad, missing?}; plus exposedPad {w, h} and body {w, l, height?}."}) };
    let fab_outline = match crate::support::s(args, "fabOutline").as_deref() {
        None | Some("chamfer") => None,
        Some("edges") => fab_edges(&mut fp),
        Some(o) => return json!({"success": false, "errorCode": "bad_args", "error": format!("fabOutline {o}: chamfer (the default: one outline with the pin-1 corner cut) or edges (four edges meeting at the corners, for dimensions)")}),
    };
    let desc = crate::support::s(args, "description").unwrap_or_else(|| describe(args, &fp));
    let text = spec(&name, &desc, &fp);
    let summary = json!({"pads": fp.pads.len(), "courtyardMm": [fp.courtyard.0, fp.courtyard.1, fp.courtyard.2, fp.courtyard.3], "fabOutline": fab_outline,
        "silkLines": fp.lines.iter().filter(|l| l.0 == "overlay").count(),
        "padTable": fp.pads.iter().take(12).map(|p| json!([p.name, p.x, p.y, p.w, p.h])).collect::<Vec<_>>()});
    if args.get("dryRun").and_then(|b| b.as_bool()) == Some(true) {
        return json!({"success": true, "dryRun": true, "name": name, "description": desc, "summary": summary, "spec": text,
            "_hint": "Nothing built. Check padTable (name, x, y, w, h in mm, Y up, pin 1 top-left) against the datasheet, then call again without dryRun."});
    }
    let Some(lib) = crate::support::s(args, "libraryPath").filter(|p| p.to_lowercase().ends_with(".pcblib")) else {
        return json!({"success": false, "errorCode": "bad_args", "error": "libraryPath (.PcbLib) is required"});
    };
    let dir = crate::agent::cache_dir().join("footprints");
    let _ = std::fs::create_dir_all(&dir);
    let safe: String = name.chars().map(|c| if c.is_ascii_alphanumeric() || c == '-' || c == '_' { c } else { '_' }).collect();
    let path = dir.join(format!("{safe}.spec"));
    if let Err(e) = std::fs::write(&path, crate::agent::agent_text(&text)) { return json!({"success": false, "errorCode": "write_failed", "error": format!("{}: {e}", path.display())}); }
    // the call's layer map and template ride along (#41); the library's and the user's are read by build_footprint
    let mut fa = json!({"libraryPath": lib, "spec": path.to_string_lossy(), "timeout": 240});
    for k in ["layerMap", "template"] { if let Some(v) = args.get(k) { fa[k] = v.clone(); } }
    let mut r = crate::library::build_footprint(&fa);
    // a 3D body when the height is known: an extruded box the size of the body
    let body = args.get("body").cloned().unwrap_or(json!({}));
    if r.get("success").and_then(|b| b.as_bool()) != Some(false) {
        if let (Some(w), Some(l), Some(h)) = (num(&body, "w"), num(&body, "l"), num(&body, "height")) {
            let mil = |mm: f64| (mm / 0.0254).round() as i64;
            let mut ba = json!({"libraryPath": lib, "footprintName": name, "bwMil": mil(w), "bhMil": mil(l), "hMil": mil(h), "soMil": mil(num(&body, "standoff").unwrap_or(0.0))});
            // the call's layer map reaches the body too (body3d, #41)
            if let Some(v) = args.get("layerMap") { ba["layerMap"] = v.clone(); }
            let b = crate::library::add_body(&ba);
            r["body3d"] = json!({"success": b.get("success"), "error": b.get("error"), "layer": b.pointer("/layerMap/keys/body3d/layer")});
        }
        r["_hint"] = json!("Built in the PcbLib (unsaved): check shot.image, then altium_save {filePath: libraryPath}. Link it to a symbol with altium_set_models.");
    }
    r["summary"] = summary;
    r["spec"] = json!(path.to_string_lossy());
    r
}

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

    #[test]
    fn the_spec_carries_every_pad_and_line() {
        let fp = layout(&json!({"family": "dual", "pins": 8, "pitch": 1.27, "span": 5.4, "padLength": 1.55, "padWidth": 0.6, "body": {"w": 3.9, "l": 4.9}})).unwrap();
        let t = spec("SOIC-8", "a|b", &fp);
        assert!(t.starts_with("META|SOIC-8|a b\n"), "{t}");
        assert_eq!(t.lines().filter(|l| l.starts_with("PAD|")).count(), 8);
        assert!(t.lines().any(|l| l.starts_with("LINE|courtyard|")));
    }

    #[test]
    fn the_edges_outline_meets_at_the_body_corners() {
        let mut fp = layout(&json!({"family": "dual", "pins": 8, "pitch": 1.27, "span": 5.4, "padLength": 1.55, "padWidth": 0.6, "body": {"w": 3.9, "l": 4.9}})).unwrap();
        let before = fp.lines.iter().filter(|l| l.0 != "fab").count();
        let c = fab_edges(&mut fp).unwrap();
        let fab: Vec<_> = fp.lines.iter().filter(|l| l.0 == "fab").collect();
        assert_eq!(fab.len(), 5, "four edges and the chamfer");
        assert_eq!(fp.lines.iter().filter(|l| l.0 != "fab").count(), before, "other layers untouched");
        let tl = (c["corners"]["TL"][0].as_f64().unwrap(), c["corners"]["TL"][1].as_f64().unwrap());
        // the top edge starts at TL and the left edge ends there: a corner is an end of two lines
        assert_eq!((fab[0].1, fab[0].2), tl);
        assert_eq!((fab[3].3, fab[3].4), tl);
        let br = (c["corners"]["BR"][0].as_f64().unwrap(), c["corners"]["BR"][1].as_f64().unwrap());
        assert!((br.0 - tl.0 - 3.9).abs() < 1e-6 || (br.0 - tl.0 - 4.9).abs() < 1e-6, "{c}");
    }

    #[test]
    fn a_sot23_5s_short_column_spans_the_long_one() {
        // EDA Bridge Standard #25: pins 4 and 5 level with 3 and 1, the courtyard round the pads and body only
        let fp = layout(&json!({"family": "sot", "leftPins": 3, "rightPins": 2, "pitch": 0.95, "span": 2.6, "padLength": 1.1, "padWidth": 0.6})).unwrap();
        let y = |n: &str| fp.pads.iter().find(|p| p.name == n).unwrap().y;
        assert!((y("4") + 0.95).abs() < 1e-9 && (y("5") - 0.95).abs() < 1e-9, "{:?}", fp.pads);
        let bga = layout(&json!({"family": "bga", "rows": 8, "cols": 8, "pitch": 0.8, "ballPad": 0.4, "body": {"w": 7, "l": 7}})).unwrap();
        let c = bga.courtyard;
        assert!((c.0 + c.2).abs() < 1e-9 && (c.1 + c.3).abs() < 1e-9, "a symmetric part has a symmetric courtyard: {c:?}");
    }
}