main
Colby Knox 0.2.111: routing_drc and gloss explain pours shorted to holes with no copper (AD24+ hole clearance) 83da0da
//! altium_gloss: Altium's own Gloss (Route > Gloss Selected) on the nets asked for, with the routing it must not touch
//! left out, the pours poured again after, and what changed measured (length and corners per net, DRC before and after).
//! Measured on Altium Designer 26.11.1 (2026-11-25): Gloss acts only on tracks at 90/45-degree steps, straightens length
//! tuning (79 matched-length violations on Altium's SODIMM example when every track was taken), runs tracks into pours
//! until they are poured again, and cannot be undone from a script. So the board is left unsaved, and reopening it
//! without saving is the way back.
use serde_json::{json, Value};
use std::collections::{BTreeMap, BTreeSet};
use std::time::{Duration, Instant};

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

fn r3(v: f64) -> f64 {
    (v * 1000.0).round() / 1000.0
}

/// One net's routing: length (mm), track and arc pieces, and corners (where two straight pieces of the net meet end to
/// end at an angle).
#[derive(Debug, Default, Clone, PartialEq)]
pub struct NetRoute {
    pub length: f64,
    pub segments: usize,
    pub corners: usize,
}

/// Every routed net's length, pieces and corners, from a routing_state board model. Pure.
pub fn net_routes(st: &Value) -> BTreeMap<String, NetRoute> {
    let mut out: BTreeMap<String, NetRoute> = BTreeMap::new();
    // the directions of the straight pieces meeting at each end point, per net and layer
    let mut ends: BTreeMap<(String, String, i64, i64), Vec<(f64, f64)>> = BTreeMap::new();
    let key = |x: f64, y: f64| ((x * 1000.0).round() as i64, (y * 1000.0).round() as i64);
    for t in st["tracks"].as_array().cloned().unwrap_or_default() {
        let Some(net) = t["net"].as_str().filter(|n| !n.is_empty()) else { continue };
        let (x0, y0, x1, y1) = (f(&t["start"]["x"]), f(&t["start"]["y"]), f(&t["end"]["x"]), f(&t["end"]["y"]));
        let len = ((x1 - x0).powi(2) + (y1 - y0).powi(2)).sqrt();
        let e = out.entry(net.to_string()).or_default();
        e.length += len;
        e.segments += 1;
        if len < 1e-6 { continue; }
        let layer = t["layer"].as_str().unwrap_or("").to_string();
        let (ux, uy) = ((x1 - x0) / len, (y1 - y0) / len);
        let (a, b) = (key(x0, y0), key(x1, y1));
        ends.entry((net.to_string(), layer.clone(), a.0, a.1)).or_default().push((ux, uy));
        ends.entry((net.to_string(), layer, b.0, b.1)).or_default().push((-ux, -uy));
    }
    for a in st["arcs"].as_array().cloned().unwrap_or_default() {
        let Some(net) = a["net"].as_str().filter(|n| !n.is_empty()) else { continue };
        let mut sweep = f(&a["endAngle"]) - f(&a["startAngle"]);
        if sweep <= 0.0 { sweep += 360.0; }
        let e = out.entry(net.to_string()).or_default();
        e.length += f(&a["radius"]) * sweep.to_radians();
        e.segments += 1;
    }
    for ((net, _, _, _), dirs) in ends {
        // a corner: exactly two pieces meet and do not carry straight on
        if dirs.len() == 2 {
            let dot = dirs[0].0 * dirs[1].0 + dirs[0].1 * dirs[1].1;
            if dot > -0.9998 { out.entry(net).or_default().corners += 1; }
        }
    }
    for v in out.values_mut() { v.length = r3(v.length); }
    out
}

/// The tracks of these nets Gloss will not touch because they do not run at a multiple of 45 degrees, counted per net.
/// Pure.
pub fn off_angle(st: &Value, nets: &BTreeSet<String>) -> BTreeMap<String, usize> {
    let mut out = BTreeMap::new();
    for t in st["tracks"].as_array().cloned().unwrap_or_default() {
        let Some(net) = t["net"].as_str().filter(|n| nets.contains(&n.to_uppercase())) else { continue };
        let (dx, dy) = (f(&t["end"]["x"]) - f(&t["start"]["x"]), f(&t["end"]["y"]) - f(&t["start"]["y"]));
        if (dx * dx + dy * dy).sqrt() < 0.01 { continue; }
        let deg = dy.atan2(dx).to_degrees().rem_euclid(45.0);
        if deg.min(45.0 - deg) > 0.5 { *out.entry(net.to_string()).or_insert(0) += 1; }
    }
    out
}

fn drc_key(v: &Value) -> String {
    let mut objs: Vec<String> = v["objects"].as_array().cloned().unwrap_or_default().iter().filter_map(|o| o.as_str().map(str::to_string)).collect();
    objs.sort();
    format!("{}|{}", v["rule"].as_str().unwrap_or(""), objs.join("|"))
}

/// Violations after that were not there before, and those before that are gone. Pure.
pub fn drc_diff(before: &[Value], after: &[Value]) -> (Vec<Value>, Vec<Value>) {
    let b: BTreeSet<String> = before.iter().map(drc_key).collect();
    let a: BTreeSet<String> = after.iter().map(drc_key).collect();
    (after.iter().filter(|v| !b.contains(&drc_key(v))).cloned().collect(),
     before.iter().filter(|v| !a.contains(&drc_key(v))).cloned().collect())
}

fn names(args: &Value, k: &str) -> Vec<String> {
    match &args[k] {
        Value::Array(a) => a.iter().filter_map(|v| v.as_str().map(|s| s.trim().to_string())).filter(|s| !s.is_empty()).collect(),
        Value::String(s) => s.split([',', ';']).map(|x| x.trim().to_string()).filter(|x| !x.is_empty()).collect(),
        _ => Vec::new(),
    }
}

fn drc(full: bool) -> Value {
    crate::routing::routing_drc(&json!({"full": full}))
}

fn effort() -> Value {
    let r = crate::prefs::preferences(&json!({"key": "AdvPCB/SystemOptions/EffortForGlossRetrace"}));
    r["current"]["AdvPCB/SystemOptions/EffortForGlossRetrace"].clone()
}

/// altium_gloss {nets?, all?, exclude?, protect?, repour?, dryRun?, filePath?}
pub fn gloss(args: &Value) -> Value {
    if let Some(g) = crate::support::need_licensed() { return g; }
    if let Some(b) = crate::support::s(args, "filePath").filter(|p| p.to_lowercase().ends_with(".pcbdoc")) {
        if let Some(e) = crate::support::must_open(&b, 60) { return e; }
    }
    let all = args["all"].as_bool() == Some(true);
    let nets = names(args, "nets");
    let exclude = names(args, "exclude");
    if !all && nets.is_empty() {
        return json!({"success": false, "errorCode": "bad_args", "error": "name the nets to gloss (nets), or pass all:true for every routed net",
            "_hint": "Gloss straightens length tuning: on a board with tuned nets, name the nets you routed rather than all:true."});
    }
    let protect = args["protect"].as_bool() != Some(false);
    let dry = args["dryRun"].as_bool() == Some(true);
    let t0 = Instant::now();
    let st0 = crate::routing::routing_state(&json!({}));
    if st0["success"] != json!(true) { return st0; }
    let known: BTreeSet<String> = st0["nets"].as_array().cloned().unwrap_or_default().iter().filter_map(|n| n.as_str().map(|s| s.to_uppercase())).collect();
    let unknown: Vec<&String> = nets.iter().filter(|n| !known.contains(&n.to_uppercase())).collect();
    if !unknown.is_empty() {
        return json!({"success": false, "errorCode": "no_such_net", "error": format!("not nets on this board: {}", unknown.iter().map(|s| s.as_str()).collect::<Vec<_>>().join(", ")), "unknownNets": unknown});
    }
    let mut payload: Vec<String> = nets.clone();
    payload.extend(exclude.iter().map(|n| format!("X|{n}")));
    let mut params: Vec<(&str, String)> = Vec::new();
    if all { params.push(("all", "1".into())); }
    if protect { params.push(("protect", "1".into())); }
    if dry { params.push(("dry", "1".into())); }
    let sel = crate::agent::call("gloss_select", &params, Some(&payload.join("\n")), Duration::from_secs(300));
    let Some(sd) = sel.get("data").filter(|d| d["ok"] == json!(true)).cloned() else { return sel };
    let protected_nets: BTreeSet<String> = ["lengthNets", "pairNets"].iter()
        .flat_map(|k| sd[*k].as_array().cloned().unwrap_or_default()).filter_map(|v| v.as_str().map(|s| s.to_uppercase())).collect();
    let ex: BTreeSet<String> = exclude.iter().map(|s| s.to_uppercase()).collect();
    let taken: BTreeSet<String> = if all { known.iter().cloned().collect() } else { nets.iter().map(|s| s.to_uppercase()).collect() };
    let taken: BTreeSet<String> = taken.into_iter().filter(|n| !ex.contains(n) && !protected_nets.contains(n)).collect();
    let skipped = off_angle(&st0, &taken);
    let protected = json!({"lengthRuled": sd["lengthNets"], "differentialPairs": sd["pairNets"], "lockedTracks": sd["lockedTracks"], "lockedOn": sd["lockedNets"]});
    let selected = sd["selected"].as_i64().unwrap_or(0);
    if dry || selected == 0 {
        return json!({"success": true, "dryRun": dry, "glossed": false, "tracksSelected": selected, "protected": protected,
            "offAngle": skipped, "excluded": exclude, "glossEffort": effort(),
            "_hint": if selected == 0 { "No track of these nets can be glossed (all protected, excluded or not routed); nothing changed." }
                     else { "Nothing changed. These tracks would be glossed; offAngle lists tracks Gloss leaves alone because they are not at a multiple of 45 degrees." }});
    }
    let before_drc = drc(true);
    let run = crate::agent::call("run_process", &[("process", "PCB:Gloss".into()), ("params", "Track=True".into())], None, Duration::from_secs(600));
    if run.get("data").and_then(|d| d.get("ok")) != Some(&json!(true)) {
        return json!({"success": false, "errorCode": "gloss_failed", "error": "Altium's Gloss did not run", "run": run, "protected": protected});
    }
    let pours = st0["counts"]["polygons"].as_i64().unwrap_or(0) > 0;
    let repoured = if pours && args["repour"].as_bool() != Some(false) {
        let r = crate::routing::repour(&json!({}));
        json!(r["success"] == json!(true))
    } else { Value::Null };
    let st1 = crate::routing::routing_state(&json!({}));
    let mut after_drc = drc(true);
    // a read straight after a repour once answered 0 on a board with 91 violations: a clean answer then is read again
    if !repoured.is_null() && after_drc["errors"].as_i64() == Some(0) && before_drc["errors"].as_i64().unwrap_or(0) > 0 {
        std::thread::sleep(Duration::from_secs(2));
        after_drc = drc(true);
    }
    let (r0, r1) = (net_routes(&st0), net_routes(&st1));
    let mut changed = Vec::new();
    let (mut l0, mut l1) = (0.0, 0.0);
    for (n, a) in &r0 {
        if !taken.contains(&n.to_uppercase()) { continue; }
        let b = r1.get(n).cloned().unwrap_or_default();
        l0 += a.length; l1 += b.length;
        if (a.length - b.length).abs() > 0.001 || a.segments != b.segments || a.corners != b.corners {
            changed.push(json!({"net": n, "lengthMm": [a.length, b.length], "segments": [a.segments, b.segments], "corners": [a.corners, b.corners]}));
        }
    }
    changed.sort_by(|a, b| {
        let d = |v: &Value| f(&v["lengthMm"][1]) - f(&v["lengthMm"][0]);
        d(a).partial_cmp(&d(b)).unwrap_or(std::cmp::Ordering::Equal)
    });
    let arr = |v: &Value| v["violations"].as_array().cloned().unwrap_or_default();
    let (new, cleared) = drc_diff(&arr(&before_drc), &arr(&after_drc));
    let unconnected = (st0["unconnected"].clone(), st1["unconnected"].clone());
    let connections_lost = unconnected.1.as_i64().unwrap_or(0) > unconnected.0.as_i64().unwrap_or(0);
    json!({"success": true, "glossed": true, "tracksSelected": selected, "netsChanged": changed.len(), "nets": changed,
        "totalLengthMm": [r3(l0), r3(l1)], "protected": protected, "offAngle": skipped, "excluded": exclude,
        "repoured": repoured, "unconnected": [unconnected.0, unconnected.1],
        "drc": {"before": before_drc["errors"], "after": after_drc["errors"], "new": new, "cleared": cleared.len(), "clean": new.is_empty() && !connections_lost,
                "holeClearance": after_drc.get("holeClearance").cloned().unwrap_or(Value::Null)},
        "glossEffort": effort(), "revision": st1["revision"], "saved": false, "durationMs": t0.elapsed().as_millis() as u64,
        "undo": "Gloss cannot be undone from a script: the board is left unsaved, so reopen it without saving to go back (altium_close_document, then open it again). altium_save keeps the result.",
        "_hint": if new.is_empty() && !connections_lost { "Glossed: nets[] gives each changed net's length, pieces and corners before and after, and DRC found nothing new. offAngle lists tracks left alone because they are not at a multiple of 45 degrees. The board is unsaved: altium_save keeps it." }
                 else if after_drc.get("holeClearance").is_some() { "Glossed. DRC found new violations (drc.new): pours shorted to holes with no copper come from the repour on this board, not from the gloss (drc.holeClearance names the cause and the fix); check the rest. Reopening the board without saving undoes the gloss." }
                 else { "Glossed, but DRC found new violations (drc.new) or connections were lost (unconnected): check them; reopening the board without saving undoes the gloss." }})
}

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

    fn tr(net: &str, a: (f64, f64), b: (f64, f64)) -> Value {
        json!({"net": net, "layer": "F.Cu", "start": {"x": a.0, "y": a.1}, "end": {"x": b.0, "y": b.1}})
    }

    #[test]
    fn a_route_is_measured_by_length_pieces_and_corners() {
        // a U-shaped detour: up, across, down, with one straight joint in the middle of the top run
        let st = json!({"tracks": [tr("N1", (0.0, 0.0), (0.0, 5.0)), tr("N1", (0.0, 5.0), (5.0, 5.0)), tr("N1", (5.0, 5.0), (10.0, 5.0)),
                                   tr("N1", (10.0, 5.0), (10.0, 0.0)), tr("GND", (0.0, 0.0), (3.0, 3.0))], "arcs": []});
        let r = net_routes(&st);
        assert_eq!(r["N1"], NetRoute { length: 20.0, segments: 4, corners: 2 }, "the straight joint is not a corner");
        assert_eq!(r["GND"].corners, 0);
    }

    #[test]
    fn tracks_off_the_45_degree_steps_are_found() {
        let st = json!({"tracks": [tr("N1", (0.0, 0.0), (1.0, 3.0)), tr("N1", (0.0, 0.0), (3.0, 3.0)), tr("N1", (0.0, 0.0), (0.0, 4.0)), tr("N2", (0.0, 0.0), (2.0, 7.0))]});
        let nets: BTreeSet<String> = ["N1".to_string()].into_iter().collect();
        let off = off_angle(&st, &nets);
        assert_eq!(off.get("N1"), Some(&1), "only the 71-degree piece of N1");
        assert!(off.get("N2").is_none(), "a net not asked for is not reported");
    }

    #[test]
    fn drc_is_compared_by_rule_and_objects() {
        let v = |rule: &str, o: &[&str]| json!({"rule": rule, "objects": o});
        let before = vec![v("Clearance", &["Track A", "Pad B"]), v("ShortCircuit", &["P", "Q"])];
        let after = vec![v("Clearance", &["Pad B", "Track A"]), v("MatchedLengths_BL0", &["x", "y"])];
        let (new, cleared) = drc_diff(&before, &after);
        assert_eq!(new.len(), 1);
        assert_eq!(new[0]["rule"], json!("MatchedLengths_BL0"));
        assert_eq!(cleared.len(), 1, "the short is gone; the clearance pair is the same in either order");
    }
}