main
Colby Knox 0.2.75 source (not yet released, needs signing): schematic_review, pin_pad_check, route_pair, length_tune, thermal_vias… 289c671
//! Length tuning: a serpentine in the net's longest straight track that has room beside it, its bumps sized to add
//! exactly the length a target (or another net's length) asks for, every bump clear of other copper and inside the
//! board, or a refusal that says why.
use serde_json::{json, Value};

fn f(v: &Value) -> f64 { v.as_f64().unwrap_or(0.0) }
fn r3(v: f64) -> f64 { (v * 1000.0).round() / 1000.0 }
type P = (f64, f64);

/// The serpentine's points replacing a track a->b: `n` rectangular bumps of height `amp` to the side `side` (+1 left,
/// -1 right), each `pitch` long along the track, centred on it. Pure.
pub fn meander(a: P, b: P, n: usize, amp: f64, pitch: f64, side: f64) -> Vec<P> {
    let len = ((b.0 - a.0).powi(2) + (b.1 - a.1).powi(2)).sqrt();
    let (ux, uy) = ((b.0 - a.0) / len, (b.1 - a.1) / len);
    let (nx, ny) = (-uy * side, ux * side);
    let at = |s: f64, h: f64| (a.0 + ux * s + nx * h, a.1 + uy * s + ny * h);
    let start = (len - n as f64 * pitch) / 2.0;
    let mut pts = vec![a];
    for k in 0..n {
        let s = start + k as f64 * pitch;
        pts.push(at(s, 0.0));
        pts.push(at(s, amp));
        pts.push(at(s + pitch / 2.0, amp));
        pts.push(at(s + pitch / 2.0, 0.0));
    }
    pts.push(b);
    pts.dedup_by(|p, q| (p.0 - q.0).abs() < 1e-9 && (p.1 - q.1).abs() < 1e-9);
    pts
}

fn seg_dist(p: P, a: P, b: P) -> f64 {
    let (dx, dy) = (b.0 - a.0, b.1 - a.1);
    let l2 = dx * dx + dy * dy;
    let t = if l2 > 0.0 { (((p.0 - a.0) * dx + (p.1 - a.1) * dy) / l2).clamp(0.0, 1.0) } else { 0.0 };
    ((a.0 + t * dx - p.0).powi(2) + (a.1 + t * dy - p.1).powi(2)).sqrt()
}

/// How many bumps and how tall, to add `extra` mm along a track `len` long: as few bumps as fit at `max_amp`, each
/// `pitch` long, leaving `margin` at both ends. None when it cannot fit. Pure.
pub fn sizing(extra: f64, len: f64, pitch: f64, max_amp: f64, margin: f64) -> Option<(usize, f64)> {
    if extra <= 0.0 { return None; }
    let room = ((len - 2.0 * margin) / pitch).floor() as usize;
    if room == 0 { return None; }
    let n = ((extra / (2.0 * max_amp)).ceil() as usize).max(1);
    if n > room { return None; }
    Some((n, extra / (2.0 * n as f64)))
}

/// altium_length_tune {filePath?, net, targetMm? | matchTo?, maxAmplitudeMm?, pitchMm?, clearance?, dryRun?, expectedRevision?}
pub fn length_tune(args: &Value) -> Value {
    use crate::routing::{apply, guarded, layer_id, raw};
    if let Some(g) = crate::support::need_licensed() { return g; }
    if let Some(p) = crate::support::s(args, "filePath") { if let Some(e) = crate::support::must_open(&p, 60) { return e; } }
    let st = match guarded(args) { Ok(s) => s, Err(e) => return e };
    let Some(net) = crate::support::s(args, "net") else { return json!({"success": false, "errorCode": "bad_args", "error": "net is the net to lengthen"}) };
    let lens = crate::lengths::lengths(&st);
    let len_of = |n: &str| lens.iter().find(|(k, _)| k.eq_ignore_ascii_case(n)).map(|(_, v)| f(&v["lengthMm"]));
    let Some(now) = len_of(&net) else { return json!({"success": false, "errorCode": "not_routed", "error": format!("{net} has no routed track")}) };
    let target = match (args.get("targetMm").and_then(|v| v.as_f64()), crate::support::s(args, "matchTo")) {
        (Some(t), _) => t,
        (None, Some(m)) => match len_of(&m) { Some(l) => l, None => return json!({"success": false, "errorCode": "not_routed", "error": format!("{m} has no routed track to match")}) },
        _ => return json!({"success": false, "errorCode": "bad_args", "error": "targetMm (mm) or matchTo (a net) says how long it should be"}),
    };
    let extra = target - now;
    if extra <= 0.01 { return json!({"success": true, "changed": false, "net": net, "lengthMm": r3(now), "targetMm": r3(target), "_hint": "Already at or past the target: tuning only lengthens. Shorten the other net, or route this one more directly."}); }
    let num = |k: &str, d: f64| args.get(k).and_then(|v| v.as_f64()).unwrap_or(d);
    let clearance = num("clearance", 0.2);
    // other copper on the board, per layer, as segments with half-widths (pads as their circumscribed circles)
    let mut other: Vec<(String, P, P, f64)> = Vec::new();
    for t in st["tracks"].as_array().cloned().unwrap_or_default() {
        if t["net"].as_str().map(|n| n.eq_ignore_ascii_case(&net)).unwrap_or(false) || !t["layer"].as_str().map(|l| l.ends_with(".Cu")).unwrap_or(false) { continue; }
        other.push((t["layer"].as_str().unwrap_or("").into(), (f(&t["start"]["x"]), f(&t["start"]["y"])), (f(&t["end"]["x"]), f(&t["end"]["y"])), f(&t["width"]) / 2.0));
    }
    for v in st["vias"].as_array().cloned().unwrap_or_default() {
        let p = (f(&v["position"]["x"]), f(&v["position"]["y"]));
        other.push(("*".into(), p, p, f(&v["size"]) / 2.0));
    }
    for p in st["pads"].as_array().cloned().unwrap_or_default() {
        if p["net"].as_str().map(|n| n.eq_ignore_ascii_case(&net)).unwrap_or(false) { continue; }
        let c = (f(&p["x"]), f(&p["y"]));
        other.push((p["layer"].as_str().unwrap_or("*.Cu").replace("*.Cu", "*"), c, c, (f(&p["sizeX"]).powi(2) + f(&p["sizeY"]).powi(2)).sqrt() / 2.0));
    }
    let ring = crate::coppermap::outline_ring(&st);
    let inside = |x: f64, y: f64| {
        let mut c = false;
        for k in 0..ring.len() { let (a, b) = (ring[k], ring[(k + 1) % ring.len()]); if (a.1 > y) != (b.1 > y) && x < (b.0 - a.0) * (y - a.1) / (b.1 - a.1) + a.0 { c = !c; } }
        c
    };
    // the net's tracks, longest first; for each, a side where the serpentine fits
    let mut tracks: Vec<Value> = st["tracks"].as_array().cloned().unwrap_or_default().into_iter().filter(|t| t["net"].as_str().map(|n| n.eq_ignore_ascii_case(&net)).unwrap_or(false)).collect();
    let tlen = |t: &Value| ((f(&t["end"]["x"]) - f(&t["start"]["x"])).powi(2) + (f(&t["end"]["y"]) - f(&t["start"]["y"])).powi(2)).sqrt();
    tracks.sort_by(|a, b| tlen(b).partial_cmp(&tlen(a)).unwrap());
    let mut why = Vec::new();
    for t in &tracks {
        let (a, b) = ((f(&t["start"]["x"]), f(&t["start"]["y"])), (f(&t["end"]["x"]), f(&t["end"]["y"])));
        let w = f(&t["width"]);
        let layer = t["layer"].as_str().unwrap_or("F.Cu").to_string();
        let pitch = num("pitchMm", (4.0 * w).max(4.0 * clearance + 2.0 * w));
        let max_amp = num("maxAmplitudeMm", 3.0);
        let Some((n, amp)) = sizing(extra, tlen(t), pitch, max_amp, 2.0 * w) else { why.push(json!({"track": [a, b], "why": "too short for the bumps this needs at this amplitude"})); continue };
        for side in [1.0, -1.0] {
            let pts = meander(a, b, n, amp, pitch, side);
            let clear = pts.windows(2).all(|s| other.iter().filter(|o| o.0 == layer || o.0 == "*").all(|o| {
                // segment to segment distance: endpoints against the other segment, and its endpoints against ours
                let d = seg_dist(s[0], o.1, o.2).min(seg_dist(s[1], o.1, o.2)).min(seg_dist(o.1, s[0], s[1])).min(seg_dist(o.2, s[0], s[1]));
                d >= o.3 + w / 2.0 + clearance
            })) && pts.iter().all(|p| inside(p.0, p.1));
            if !clear { continue; }
            let added: f64 = pts.windows(2).map(|s| ((s[1].0 - s[0].0).powi(2) + (s[1].1 - s[0].1).powi(2)).sqrt()).sum::<f64>() - tlen(t);
            let plan = json!({"net": net, "layer": layer, "replaces": [[r3(a.0), r3(a.1)], [r3(b.0), r3(b.1)]], "bumps": n, "amplitudeMm": r3(amp), "pitchMm": r3(pitch),
                              "side": if side > 0.0 { "left" } else { "right" }, "addsMm": r3(added), "points": pts.iter().map(|p| json!([r3(p.0), r3(p.1)])).collect::<Vec<_>>()});
            if args.get("dryRun").and_then(|b| b.as_bool()) == Some(true) {
                return json!({"success": true, "dryRun": true, "lengthMm": r3(now), "targetMm": r3(target), "plan": plan});
            }
            let lid = layer_id(&json!(layer)).unwrap_or(1);
            let mut ops = vec![format!("D|T|{}|{}|{}|{}|{lid}", raw(a.0), raw(a.1), raw(b.0), raw(b.1))];
            for s in pts.windows(2) { ops.push(format!("T|{}|{}|{}|{}|{}|{lid}|{net}", raw(s[0].0), raw(s[0].1), raw(s[1].0), raw(s[1].1), raw(w))); }
            let r = apply(&ops, &st, "length_tune");
            let after = crate::lengths::lengths(&crate::routing::routing_state(&json!({})));
            let got = after.iter().find(|(k, _)| k.eq_ignore_ascii_case(&net)).map(|(_, v)| f(&v["lengthMm"])).unwrap_or(0.0);
            return json!({"success": r["success"], "changed": true, "lengthBeforeMm": r3(now), "lengthMm": r3(got), "targetMm": r3(target), "errorMm": r3(got - target), "plan": plan, "revision": r["revision"],
                "_hint": "One serpentine, one undo step. altium_net_lengths shows the routed lengths; altium_routing_drc checks clearances (the plan kept clearance from every other net's copper)."});
        }
        why.push(json!({"track": [[r3(a.0), r3(a.1)], [r3(b.0), r3(b.1)]], "why": "no clear room on either side for the bumps"}));
    }
    json!({"success": false, "errorCode": "no_room", "error": format!("no track of {net} has room for {:.2} mm more", extra), "lengthMm": r3(now), "targetMm": r3(target), "tried": why,
           "_hint": "Lower maxAmplitudeMm for more, shorter bumps, raise it for fewer, or reroute the net with a longer straight run in open space."})
}

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

    #[test]
    fn a_meander_adds_exactly_twice_its_height_per_bump() {
        let (n, amp) = sizing(6.0, 30.0, 1.2, 1.0, 0.4).unwrap();
        assert_eq!(n, 3);
        assert!((amp - 1.0).abs() < 1e-9);
        let pts = meander((0.0, 0.0), (30.0, 0.0), n, amp, 1.2, 1.0);
        let len: f64 = pts.windows(2).map(|s| ((s[1].0 - s[0].0).powi(2) + (s[1].1 - s[0].1).powi(2)).sqrt()).sum();
        assert!((len - 36.0).abs() < 1e-9, "{len}");
        assert!(pts.iter().all(|p| p.1 >= -1e-9 && p.1 <= 1.0 + 1e-9));
        // too much for the room: refused
        assert!(sizing(100.0, 5.0, 1.2, 1.0, 0.4).is_none());
        assert!(sizing(-1.0, 30.0, 1.2, 1.0, 0.4).is_none());
    }
}