by adom
Let an AI (Claude, ChatGPT, Codex or any agent) run Altium Designer for you: create symbols and footprints, place parts (also from Altium 365), wire and annotate schematics, Update PCB, set the stack-up and rules, route, pour copper, add mounting holes and stitching vias, run ERC and DRC, and make Gerbers, BOMs and STEP. Free in Hydrogen; bring your own AI and Altium licence.
main
Colby Knox
0.2.75 source (not yet released, needs signing): schematic_review, pin_pad_check, route_pair, length_tune, thermal_vias…
289c671
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218
//! A differential pair routed as a pair: one centreline from the midpoint of the source pads through waypoints to the
//! midpoint of the destination pads, each net offset half a pitch (width + gap) to its own side with mitred corners,
//! a short fan-out from each pad, and both lengths and the skew reported.
use serde_json::{json, Value};
fn r3(v: f64) -> f64 { (v * 1000.0).round() / 1000.0 }
type P = (f64, f64);
fn sub(a: P, b: P) -> P { (a.0 - b.0, a.1 - b.1) }
fn norm(a: P) -> P { let l = (a.0 * a.0 + a.1 * a.1).sqrt(); if l > 0.0 { (a.0 / l, a.1 / l) } else { (0.0, 0.0) } }
fn left(d: P) -> P { (-d.1, d.0) }
/// The polyline offset `d` to the left (negative: right), corners mitred. Pure.
pub fn offset(path: &[P], d: f64) -> Vec<P> {
let n = path.len();
(0..n).map(|i| {
let din = if i > 0 { norm(sub(path[i], path[i - 1])) } else { norm(sub(path[1], path[0])) };
let dout = if i + 1 < n { norm(sub(path[i + 1], path[i])) } else { din };
let (n1, n2) = (left(din), left(dout));
let m = norm((n1.0 + n2.0, n1.1 + n2.1));
let k = (m.0 * n1.0 + m.1 * n1.1).max(0.2); // a hairpin would blow the mitre up: cap it at 5x
(path[i].0 + m.0 * d / k, path[i].1 + m.1 * d / k)
}).collect()
}
fn length(p: &[P]) -> f64 { p.windows(2).map(|w| ((w[1].0 - w[0].0).powi(2) + (w[1].1 - w[0].1).powi(2)).sqrt()).sum() }
/// Both nets' points from pad to pad: the centreline from the pad midpoints through `via`, each net on the side its
/// source pad is on, `fan` mm of fan-out at each end. Pure.
pub fn plan(pos: (P, P), neg: (P, P), via: &[P], width: f64, gap: f64, fan: f64) -> (Vec<P>, Vec<P>) {
let s = ((pos.0 .0 + neg.0 .0) / 2.0, (pos.0 .1 + neg.0 .1) / 2.0);
let e = ((pos.1 .0 + neg.1 .0) / 2.0, (pos.1 .1 + neg.1 .1) / 2.0);
let mut centre = vec![s];
centre.extend_from_slice(via);
centre.push(e);
// pull the ends in by the fan-out so each pad has room to reach its own side
let d0 = norm(sub(centre[1], centre[0]));
let k = centre.len();
let d1 = norm(sub(centre[k - 1], centre[k - 2]));
centre[0] = (s.0 + d0.0 * fan, s.1 + d0.1 * fan);
centre[k - 1] = (e.0 - d1.0 * fan, e.1 - d1.1 * fan);
let half = (width + gap) / 2.0;
// the positive net goes on the side its source pad is on
let side = { let v = sub(pos.0, s); let n = left(d0); if v.0 * n.0 + v.1 * n.1 >= 0.0 { 1.0 } else { -1.0 } };
let mut p = vec![pos.0]; p.extend(offset(¢re, half * side)); p.push(pos.1);
let mut n = vec![neg.0]; n.extend(offset(¢re, -half * side)); n.push(neg.1);
(p, n)
}
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()
}
fn crosses(a: P, b: P, c: P, d: P) -> bool {
let o = |p: P, q: P, r: P| (q.0 - p.0) * (r.1 - p.1) - (q.1 - p.1) * (r.0 - p.0);
let (d1, d2, d3, d4) = (o(c, d, a), o(c, d, b), o(a, b, c), o(a, b, d));
(d1 > 0.0) != (d2 > 0.0) && (d3 > 0.0) != (d4 > 0.0)
}
/// What is wrong with a planned pair before it touches the board: the two nets crossing each other (the pads swap
/// sides between the ends), or a segment passing over another net's pad on the layer. Pads are (ref.name, net, x, y,
/// radius). Pure.
/// A pad as a stadium: its long axis from a to b and half its short side (a round pad: a = b). Pure.
pub fn pad_shape(x: f64, y: f64, sx: f64, sy: f64, rot: f64) -> (P, P, f64) {
let (long, short) = (sx.max(sy), sx.min(sy));
let ang = rot.to_radians() + if sy > sx { std::f64::consts::FRAC_PI_2 } else { 0.0 };
let h = (long - short) / 2.0;
((x - h * ang.cos(), y - h * ang.sin()), (x + h * ang.cos(), y + h * ang.sin()), short / 2.0)
}
fn seg_seg(a: P, b: P, c: P, d: P) -> f64 {
if crosses(a, b, c, d) { return 0.0; }
seg_dist(a, c, d).min(seg_dist(b, c, d)).min(seg_dist(c, a, b)).min(seg_dist(d, a, b))
}
pub fn check(p: &[P], n: &[P], pads: &[(String, String, P, P, f64)], nets: (&str, &str), width: f64, clearance: f64) -> Vec<Value> {
let mut out = Vec::new();
for i in 0..p.len().saturating_sub(1) {
for j in 0..n.len().saturating_sub(1) {
if crosses(p[i], p[i + 1], n[j], n[j + 1]) {
out.push(json!({"problem": "pair_crosses", "at": [r3((p[i].0 + p[i + 1].0) / 2.0), r3((p[i].1 + p[i + 1].1) / 2.0)],
"fix": "the pads are on swapped sides at the two ends: route to a via pair and cross on another layer, or swap the pins"}));
return out;
}
}
}
for (path, net) in [(p, nets.0), (n, nets.1)] {
for w in path.windows(2) {
if let Some(hit) = pads.iter().find(|(_, pn, a, b, r)| !pn.eq_ignore_ascii_case(net) && seg_seg(*a, *b, w[0], w[1]) < r + width / 2.0 + clearance - 1e-9) {
out.push(json!({"problem": "over_a_pad", "net": net, "pad": hit.0, "padNet": hit.1, "fix": "add waypoints (via) that lead the pair out of the part before it turns"}));
break;
}
}
}
out
}
/// altium_route_pair {pos, neg, from:{pos, neg}, to:{pos, neg}, via?, layer?, width?, gap?, diffOhms?, fanMm?}
pub fn route_pair(args: &Value) -> Value {
if let Some(g) = crate::support::need_licensed() { return g; }
let s = |k: &str| args.get(k).and_then(|v| v.as_str()).map(String::from);
let (Some(pn), Some(nn)) = (s("pos"), s("neg")) else { return json!({"success": false, "errorCode": "bad_args", "error": "pos and neg are the pair's two nets"}) };
let pad = |o: &str, k: &str| args.get(o).and_then(|v| v.get(k)).and_then(|v| v.as_str()).map(String::from);
let (Some(pf), Some(nf), Some(pt), Some(nt)) = (pad("from", "pos"), pad("from", "neg"), pad("to", "pos"), pad("to", "neg")) else {
return json!({"success": false, "errorCode": "bad_args", "error": "from:{pos:\"U1.3\", neg:\"U1.4\"} and to:{pos, neg} name the pads at each end"});
};
let st = crate::routing::routing_state(&json!({}));
if st.get("success").and_then(|b| b.as_bool()) != Some(true) { return st; }
let at = |key: &str| -> Option<P> {
let (r, n) = key.split_once('.')?;
st["pads"].as_array()?.iter().find(|p| p["ref"].as_str() == Some(r) && p["name"].as_str() == Some(n)).map(|p| (p["x"].as_f64().unwrap_or(0.0), p["y"].as_f64().unwrap_or(0.0)))
};
let (Some(a), Some(b), Some(c), Some(d)) = (at(&pf), at(&nf), at(&pt), at(&nt)) else {
return json!({"success": false, "errorCode": "no_such_pad", "error": format!("one of {pf}, {nf}, {pt}, {nt} is not a pad on the board")});
};
let layer = args.get("layer").cloned().unwrap_or(json!("F.Cu"));
let lname = layer.as_str().unwrap_or("F.Cu").to_string();
// width and gap: given, or solved from the stack-up for diffOhms on this layer (gap = width)
let mut sized = Value::Null;
let (mut width, mut gap) = (args.get("width").and_then(|v| v.as_f64()), args.get("gap").and_then(|v| v.as_f64()));
if let Some(z) = args.get("diffOhms").and_then(|v| v.as_f64()) {
let stack = crate::agent::call("layer_stack", &[], None, std::time::Duration::from_secs(60));
let geo = crate::impedance::geometry(&stack.get("data").cloned().unwrap_or(Value::Null));
let names = crate::coppermap::stack_layers(&stack.get("data").cloned().unwrap_or(Value::Null));
if let Some(i) = names.iter().position(|n| n.0 == lname) {
let rows = crate::impedance::widths(&geo[i..=i], None, Some(z), gap);
if let (Some(w), Some(g)) = (rows[0]["diffWidth"].as_f64(), rows[0]["diffGap"].as_f64()) { width = width.or(Some(w)); gap = gap.or(Some(g)); sized = rows[0].clone(); }
}
}
let (Some(width), Some(gap)) = (width, gap) else { return json!({"success": false, "errorCode": "bad_args", "error": "give width and gap (mm), or diffOhms to solve them from the stack-up"}) };
let via: Vec<P> = args.get("via").and_then(|v| v.as_array()).map(|a| a.iter().filter_map(|p| Some((p[0].as_f64()?, p[1].as_f64()?))).collect()).unwrap_or_default();
let fan = args.get("fanMm").and_then(|v| v.as_f64()).unwrap_or(1.0);
let (pp, np) = plan((a, c), (b, d), &via, width, gap, fan);
// check it before anything lands: crossing nets, or a segment over another net's pad on this layer
let on_layer = |l: &str| l == "*.Cu" || l == lname;
let num = |q: &Value, k: &str| q[k].as_f64().unwrap_or(0.0);
let pads: Vec<(String, String, P, P, f64)> = st["pads"].as_array().cloned().unwrap_or_default().iter()
.filter(|q| on_layer(q["layer"].as_str().unwrap_or("")))
.map(|q| { let (a, b, r) = pad_shape(num(q, "x"), num(q, "y"), num(q, "sizeX"), num(q, "sizeY"), num(q, "rotation"));
(format!("{}.{}", q["ref"].as_str().unwrap_or(""), q["name"].as_str().unwrap_or("")), q["net"].as_str().unwrap_or("").to_string(), a, b, r) }).collect();
let clearance = args.get("clearance").and_then(|v| v.as_f64()).unwrap_or(0.15);
let problems = check(&pp, &np, &pads, (&pn, &nn), width, clearance);
if !problems.is_empty() && args.get("force").and_then(|b| b.as_bool()) != Some(true) {
return json!({"success": false, "errorCode": "pair_plan_blocked", "error": "the planned pair would short", "problems": problems,
"planned": {pn.clone(): pp.iter().map(|q| json!([r3(q.0), r3(q.1)])).collect::<Vec<_>>(), nn.clone(): np.iter().map(|q| json!([r3(q.0), r3(q.1)])).collect::<Vec<_>>()},
"widthMm": r3(width), "gapMm": r3(gap), "_hint": "Nothing was placed. Fix the plan (waypoints that lead out of the parts, or a layer change where the pair must cross) and call again."});
}
let pts = |v: &[P], first: &str, last: &str| -> Value {
let mut out = vec![json!({"pad": first})];
for p in &v[1..v.len() - 1] { out.push(json!([r3(p.0), r3(p.1)])); }
out.push(json!({"pad": last}));
json!([out])
};
let rp = crate::routing::route_net(&json!({"net": pn, "width": width, "layer": layer, "paths": pts(&pp, &pf, &pt)}));
if rp.get("success").and_then(|b| b.as_bool()) != Some(true) { return json!({"success": false, "errorCode": "route_failed", "error": format!("{pn} did not route"), "detail": rp}); }
let rn = crate::routing::route_net(&json!({"net": nn, "width": width, "layer": layer, "paths": pts(&np, &nf, &nt)}));
// the pair's own width rule (+/-10%): a board's default width rule caps tracks well under a 90 ohm pair's (the
// test board's DRC flagged every segment of a 0.573 mm pair, 2026-10-26)
let rule = if args.get("rule").and_then(|b| b.as_bool()) != Some(false) {
let r = crate::routing::add_rule(&json!({"kind": "width", "name": format!("Pair {pn} {nn}"), "scope1": format!("InNet('{pn}') Or InNet('{nn}')"),
"min": r3(width * 0.9), "preferred": r3(width), "max": r3(width * 1.1)}));
json!({"name": format!("Adom Pair {pn} {nn}"), "success": r.get("success").cloned().unwrap_or(json!(false)), "descriptor": r.get("descriptor").cloned().unwrap_or(Value::Null)})
} else { Value::Null };
let (lp, ln) = (length(&pp), length(&np));
json!({"success": rn.get("success").and_then(|b| b.as_bool()) == Some(true), "widthMm": r3(width), "gapMm": r3(gap), "sizedFor": sized, "layer": lname, "widthRule": rule,
"lengthsMm": {pn.clone(): r3(lp), nn.clone(): r3(ln)}, "skewMm": r3((lp - ln).abs()), "revision": rn["revision"], "detail": if rn.get("success").and_then(|b| b.as_bool()) == Some(true) { Value::Null } else { rn.clone() },
"_hint": "Both nets are routed as one pair along the centreline. skewMm is the length difference from the fan-outs and corners: altium_net_lengths measures it routed, and altium_add_rule kind diffpair / matched keeps it in check. Run altium_routing_drc for clearances."})
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn offset_keeps_the_pitch_round_a_corner() {
let path = vec![(0.0, 0.0), (10.0, 0.0), (10.0, 10.0)];
let l = offset(&path, 0.5);
assert!((l[0].1 - 0.5).abs() < 1e-9);
// the inside corner of a left turn: 0.5 from both legs
assert!((l[1].0 - 9.5).abs() < 1e-9 && (l[1].1 - 0.5).abs() < 1e-9);
assert!((l[2].0 - 9.5).abs() < 1e-9);
}
#[test]
fn plan_puts_each_net_on_its_pads_side() {
// pads 1 mm apart across a straight 20 mm run, positive on the left (+y)
let (p, n) = plan(((0.0, 0.5), (20.0, 0.5)), ((0.0, -0.5), (20.0, -0.5)), &[], 0.2, 0.15, 1.0);
assert_eq!(p.first(), Some(&(0.0, 0.5)));
assert!(p[1].1 > 0.0 && n[1].1 < 0.0);
assert!((p[1].1 - n[1].1 - 0.35).abs() < 1e-9);
assert!((length(&p) - length(&n)).abs() < 1e-9);
}
#[test]
fn check_catches_a_crossing_and_a_pad_in_the_way() {
// destination pads swapped: the nets cross
let (p, n) = plan(((0.0, 0.5), (20.0, -0.5)), ((0.0, -0.5), (20.0, 0.5)), &[], 0.2, 0.15, 1.0);
assert_eq!(check(&p, &n, &[], ("P", "N"), 0.2, 0.15)[0]["problem"], "pair_crosses");
// a pad of another net on the straight run
let (p, n) = plan(((0.0, 0.5), (20.0, 0.5)), ((0.0, -0.5), (20.0, -0.5)), &[], 0.2, 0.15, 1.0);
let pads = vec![("U1.8".to_string(), "X".to_string(), (10.0, 0.175), (10.0, 0.175), 0.3)];
assert_eq!(check(&p, &n, &pads, ("P", "N"), 0.2, 0.15)[0]["pad"], "U1.8");
assert!(check(&p, &n, &[], ("P", "N"), 0.2, 0.15).is_empty());
}
#[test]
fn a_trace_leaving_a_soic_pin_clears_the_next_pin() {
// SOIC pins 1.5 x 0.6 at 1.27 pitch: a 0.3 mm trace leaving pin 2 straight out passes pin 1 at 0.97 - 0.3 - 0.15
let pin1 = pad_shape(0.0, 0.0, 1.5, 0.6, 0.0);
let pads = vec![("U1.1".to_string(), "A".to_string(), pin1.0, pin1.1, pin1.2)];
let p = vec![(0.0, 1.27), (3.0, 1.27)];
assert!(check(&p, &[(0.0, 5.0), (3.0, 5.0)], &pads, ("B", "C"), 0.3, 0.15).is_empty());
// the same trace run straight across pin 1 is caught
let q = vec![(-2.0, 0.1), (3.0, 0.1)];
assert_eq!(check(&q, &[(0.0, 5.0), (3.0, 5.0)], &pads, ("B", "C"), 0.3, 0.15)[0]["pad"], "U1.1");
}
}