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.121 source: altium_add_dimensions (anchored footprint dimensions), altium_check_silkscreen, fabOutline edges (#43)
def89d5
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305
//! altium_check_silkscreen (#43): edge-to-edge clearance between a footprint's silkscreen (overlay lines, arcs, texts,
//! fills) and each pad's exposed copper (the pad grown by its solder mask expansion), measured on the footprint as
//! Altium holds it. Every shape is a core (a point, a polyline or a filled polygon) with a radius around it: a round
//! pad is a point with half its diameter, an oval a segment with half its width, a rounded rectangle its inner
//! rectangle with the corner radius, a silk line its centre line with half its width. The mask expansion and the stroke
//! width only add to the radius, so one distance function covers every pair.
use serde_json::{json, Value};
pub type P = (f64, f64);
#[derive(Clone, Debug)]
pub enum Core {
/// a point or an open polyline (an arc is flattened into one)
Line(Vec<P>),
/// a filled convex polygon
Poly(Vec<P>),
}
#[derive(Clone, Debug)]
pub struct Shape { pub core: Core, pub r: f64 }
fn rot(p: P, deg: f64) -> P { let (s, c) = deg.to_radians().sin_cos(); (p.0 * c - p.1 * s, p.0 * s + p.1 * c) }
fn add(a: P, b: P) -> P { (a.0 + b.0, a.1 + b.1) }
fn sub(a: P, b: P) -> P { (a.0 - b.0, a.1 - b.1) }
fn dot(a: P, b: P) -> f64 { a.0 * b.0 + a.1 * b.1 }
fn cross(a: P, b: P) -> f64 { a.0 * b.1 - a.1 * b.0 }
fn len(a: P) -> f64 { dot(a, a).sqrt() }
fn point_seg(p: P, a: P, b: P) -> f64 {
let ab = sub(b, a);
let l2 = dot(ab, ab);
if l2 == 0.0 { return len(sub(p, a)); }
let t = (dot(sub(p, a), ab) / l2).clamp(0.0, 1.0);
len(sub(p, add(a, (ab.0 * t, ab.1 * t))))
}
fn segs_cross(a: P, b: P, c: P, d: P) -> bool {
let (d1, d2) = (cross(sub(b, a), sub(c, a)), cross(sub(b, a), sub(d, a)));
let (d3, d4) = (cross(sub(d, c), sub(a, c)), cross(sub(d, c), sub(b, c)));
((d1 > 0.0 && d2 < 0.0) || (d1 < 0.0 && d2 > 0.0)) && ((d3 > 0.0 && d4 < 0.0) || (d3 < 0.0 && d4 > 0.0))
}
fn seg_seg(a: P, b: P, c: P, d: P) -> f64 {
if segs_cross(a, b, c, d) { return 0.0; }
point_seg(a, c, d).min(point_seg(b, c, d)).min(point_seg(c, a, b)).min(point_seg(d, a, b))
}
/// Inside a convex polygon (either winding), edges included.
fn inside(p: P, poly: &[P]) -> bool {
let n = poly.len();
if n < 3 { return false; }
let mut sign = 0.0;
for i in 0..n {
let c = cross(sub(poly[(i + 1) % n], poly[i]), sub(p, poly[i]));
if c.abs() < 1e-12 { continue; }
if sign == 0.0 { sign = c.signum(); } else if c.signum() != sign { return false; }
}
true
}
fn edges(c: &Core) -> Vec<(P, P)> {
match c {
Core::Line(v) if v.len() == 1 => vec![(v[0], v[0])],
Core::Line(v) => v.windows(2).map(|w| (w[0], w[1])).collect(),
Core::Poly(v) => (0..v.len()).map(|i| (v[i], v[(i + 1) % v.len()])).collect(),
}
}
fn points(c: &Core) -> &Vec<P> { match c { Core::Line(v) | Core::Poly(v) => v } }
/// The distance between two cores: 0 when they touch or one holds the other.
pub fn core_dist(a: &Core, b: &Core) -> f64 {
if let Core::Poly(pa) = a { if points(b).iter().any(|p| inside(*p, pa)) { return 0.0; } }
if let Core::Poly(pb) = b { if points(a).iter().any(|p| inside(*p, pb)) { return 0.0; } }
let (ea, eb) = (edges(a), edges(b));
let mut m = f64::MAX;
for (p, q) in &ea { for (r, s) in &eb { m = m.min(seg_seg(*p, *q, *r, *s)); } }
m
}
/// Edge-to-edge clearance: 0 or less when the shapes touch or overlap.
pub fn clearance(a: &Shape, b: &Shape) -> f64 { core_dist(&a.core, &b.core) - a.r - b.r }
fn rect(c: P, w: f64, h: f64, deg: f64) -> Vec<P> {
[(-w / 2.0, -h / 2.0), (w / 2.0, -h / 2.0), (w / 2.0, h / 2.0), (-w / 2.0, h / 2.0)].iter().map(|p| add(c, rot(*p, deg))).collect()
}
/// A pad's exposed copper on one side: Altium's shape code (1 round, 2 rectangle, 3 octagon, 9 rounded rectangle),
/// size, corner radius (% of half the short side), rotation and the mask expansion `e`. An octagon is taken as its
/// rectangle (the clearance read is then never larger than the real one).
pub fn pad_shape(c: P, shape: i64, sx: f64, sy: f64, cr_pct: f64, deg: f64, e: f64) -> Shape {
match shape {
1 if (sx - sy).abs() < 1e-9 => Shape { core: Core::Line(vec![c]), r: sx / 2.0 + e },
1 => {
let (l, w) = (sx.max(sy), sx.min(sy));
let half = (l - w) / 2.0;
let (a, b) = if sx >= sy { ((-half, 0.0), (half, 0.0)) } else { ((0.0, -half), (0.0, half)) };
Shape { core: Core::Line(vec![add(c, rot(a, deg)), add(c, rot(b, deg))]), r: w / 2.0 + e }
}
9 => {
let cr = (cr_pct / 100.0) * sx.min(sy) / 2.0;
let (iw, ih) = ((sx - 2.0 * cr).max(0.0), (sy - 2.0 * cr).max(0.0));
let core = if iw == 0.0 && ih == 0.0 { Core::Line(vec![c]) } else if iw == 0.0 || ih == 0.0 {
Core::Line(vec![add(c, rot((-iw / 2.0, -ih / 2.0), deg)), add(c, rot((iw / 2.0, ih / 2.0), deg))])
} else { Core::Poly(rect(c, iw, ih, deg)) };
Shape { core, r: cr + e }
}
_ => Shape { core: Core::Poly(rect(c, sx, sy, deg)), r: e },
}
}
/// An arc (degrees, counter-clockwise from start to end) as a polyline whose chords stay within 1 um of the curve.
pub fn arc_points(c: P, r: f64, a0: f64, a1: f64) -> Vec<P> {
let mut sweep = a1 - a0;
while sweep <= 0.0 { sweep += 360.0; }
let step = if r > 0.0 { (2.0 * (1.0 - 0.001 / r).clamp(-1.0, 1.0).acos()).to_degrees().max(0.5) } else { 360.0 };
let n = ((sweep / step).ceil() as usize).clamp(1, 720);
(0..=n).map(|i| { let a = (a0 + sweep * i as f64 / n as f64).to_radians(); (c.0 + r * a.cos(), c.1 + r * a.sin()) }).collect()
}
/// One silkscreen item: its layer, shape and what to call it in a reply.
pub struct Silk { pub layer: i64, pub shape: Shape, pub what: Value }
/// One pad's exposed copper on one side.
pub struct Copper { pub side: i64, pub shape: Shape, pub pad: String }
/// The footprint geometry the agent read (fp_geometry), as silk items and exposed copper. `mask`: the mask expansion
/// to use (mm), else each pad's own manual one, else `default_mask`.
pub fn parse(d: &Value, mask: Option<f64>, default_mask: f64) -> (Vec<Silk>, Vec<Copper>, Vec<String>) {
let k = d["k"].as_f64().unwrap_or(10_000_000.0) / 25.4; // internal units per mm
let mm = |v: &Value| v.as_f64().unwrap_or(0.0) / k;
let arr = |key: &str| d[key].as_array().cloned().unwrap_or_default();
let mut silk = Vec::new();
let mut notes = Vec::new();
let r4 = |v: f64| (v * 10000.0).round() / 10000.0;
for t in arr("tracks") {
let l = t[0].as_i64().unwrap_or(0);
if l != 33 && l != 34 { continue; }
let (a, b) = ((mm(&t[1]), mm(&t[2])), (mm(&t[3]), mm(&t[4])));
silk.push(Silk { layer: l, shape: Shape { core: Core::Line(vec![a, b]), r: mm(&t[5]) / 2.0 }, what: json!({"kind": "line", "from": [r4(a.0), r4(a.1)], "to": [r4(b.0), r4(b.1)], "widthMm": r4(mm(&t[5]))}) });
}
for t in arr("arcs") {
let l = t[0].as_i64().unwrap_or(0);
if l != 33 && l != 34 { continue; }
let (c, r) = ((mm(&t[1]), mm(&t[2])), mm(&t[3]));
let (a0, a1) = (t[4].as_f64().unwrap_or(0.0) / 1000.0, t[5].as_f64().unwrap_or(0.0) / 1000.0);
silk.push(Silk { layer: l, shape: Shape { core: Core::Line(arc_points(c, r, a0, a1)), r: mm(&t[6]) / 2.0 },
what: json!({"kind": "arc", "center": [r4(c.0), r4(c.1)], "radiusMm": r4(r), "startAngle": a0, "endAngle": a1, "widthMm": r4(mm(&t[6]))}) });
}
for t in arr("texts") {
let l = t[0].as_i64().unwrap_or(0);
if l != 33 && l != 34 { continue; }
let (x0, y0, x1, y1) = (mm(&t[1]), mm(&t[2]), mm(&t[3]), mm(&t[4]));
silk.push(Silk { layer: l, shape: Shape { core: Core::Poly(vec![(x0, y0), (x1, y0), (x1, y1), (x0, y1)]), r: 0.0 },
what: json!({"kind": "text", "text": t[5], "box": [r4(x0), r4(y0), r4(x1), r4(y1)]}) });
}
for t in arr("fills") {
let l = t[0].as_i64().unwrap_or(0);
if l != 33 && l != 34 { continue; }
let (x0, y0, x1, y1) = (mm(&t[1]), mm(&t[2]), mm(&t[3]), mm(&t[4]));
let deg = t[5].as_f64().unwrap_or(0.0) / 1000.0;
let c = ((x0 + x1) / 2.0, (y0 + y1) / 2.0);
silk.push(Silk { layer: l, shape: Shape { core: Core::Poly(rect(c, (x1 - x0).abs(), (y1 - y0).abs(), deg)), r: 0.0 }, what: json!({"kind": "fill", "box": [r4(x0), r4(y0), r4(x1), r4(y1)]}) });
}
if !arr("texts").iter().all(|t| t[0].as_i64() != Some(33) && t[0].as_i64() != Some(34)) {
notes.push("A text is measured by its bounding box: a rotated string reads closer than its strokes are.".into());
}
let mut copper = Vec::new();
let mut octagon = false;
for p in arr("pads") {
let name = p[0].as_str().unwrap_or("").to_string();
let c = (mm(&p[1]), mm(&p[2]));
let deg = p[3].as_f64().unwrap_or(0.0) / 1000.0;
let layer = p[4].as_i64().unwrap_or(1);
let e = mask.unwrap_or(if p[15].as_i64() == Some(1) { mm(&p[14]) } else { default_mask });
let sides: &[(i64, usize)] = match layer { 1 => &[(33, 5)], 32 => &[(34, 8)], _ => &[(33, 5), (34, 8)] };
for (side, at) in sides {
let shape = p[*at].as_i64().unwrap_or(2);
if shape == 3 { octagon = true; }
let cr = p[if *at == 5 { 11 } else { 12 }].as_f64().unwrap_or(0.0);
copper.push(Copper { side: *side, shape: pad_shape(c, shape, mm(&p[at + 1]), mm(&p[at + 2]), cr, deg, e), pad: name.clone() });
}
}
if octagon { notes.push("An octagonal pad is measured as its rectangle.".into()); }
(silk, copper, notes)
}
/// Every silk-to-copper pair on the same side: (clearance mm, silk index, copper index), closest first.
pub fn pairs(silk: &[Silk], copper: &[Copper]) -> Vec<(f64, usize, usize)> {
let mut v = Vec::new();
for (i, s) in silk.iter().enumerate() {
for (j, c) in copper.iter().enumerate() {
if s.layer == c.side { v.push((clearance(&s.shape, &c.shape), i, j)); }
}
}
v.sort_by(|a, b| a.0.partial_cmp(&b.0).unwrap_or(std::cmp::Ordering::Equal));
v
}
/// Altium's default solder mask expansion rule: 4 mil.
pub const DEFAULT_MASK_MM: f64 = 0.1016;
/// altium_check_silkscreen {libraryPath, footprint | footprints, minMm?, maskExpansionMm?}
pub fn check_silkscreen(args: &Value) -> Value {
let bad = |m: &str| json!({"success": false, "errorCode": "bad_args", "error": m});
let Some(lib) = crate::support::s(args, "libraryPath").filter(|l| l.to_lowercase().ends_with(".pcblib")) else { return bad("libraryPath (.PcbLib) is required") };
let mut names: Vec<String> = args.get("footprints").and_then(|v| v.as_array()).map(|a| a.iter().filter_map(|x| x.as_str().map(str::to_string)).collect()).unwrap_or_default();
if let Some(f) = crate::support::s(args, "footprint").or_else(|| crate::support::s(args, "name")) { names.insert(0, f); }
if names.is_empty() { return bad("footprint (or footprints: [...]) is required"); }
let min = args.get("minMm").and_then(|v| v.as_f64()).unwrap_or(0.15);
let mask = args.get("maskExpansionMm").and_then(|v| v.as_f64());
if let Some(g) = crate::support::need_licensed() { return g; }
if let Some(e) = crate::support::must_open(&lib, 60) { return e; }
let mut results = Vec::new();
let mut all_pass = true;
let mut notes: Vec<String> = Vec::new();
for name in &names {
let r = crate::agent::call("fp_geometry", &[("path", lib.replace('/', "\\")), ("name", name.clone())], None, std::time::Duration::from_secs(90));
let d = match crate::sch::agent_data(&r) { Ok(d) => d, Err(e) => { results.push(json!({"footprint": name, "error": e["error"], "errorCode": e["errorCode"]})); all_pass = false; continue; } };
let (silk, copper, n) = parse(&d, mask, DEFAULT_MASK_MM);
for x in n { if !notes.contains(&x) { notes.push(x); } }
let pr = pairs(&silk, &copper);
let r3 = |v: f64| (v * 1000.0).round() / 1000.0;
let item = |(c, i, j): &(f64, usize, usize)| {
let side = if silk[*i].layer == 34 { "bottom" } else { "top" };
json!({"clearanceMm": r3(*c), "silk": silk[*i].what, "side": side, "pad": copper[*j].pad, "overlaps": *c <= 1e-9})
};
let under: Vec<Value> = pr.iter().filter(|p| p.0 < min - 1e-9).map(item).collect();
// one line per silk item and pad: its closest approach
let mut seen = std::collections::HashSet::new();
let under: Vec<Value> = under.into_iter().filter(|v| seen.insert((v["silk"].to_string(), v["pad"].to_string()))).collect();
let pass = under.is_empty();
if !pass { all_pass = false; }
results.push(json!({"footprint": name, "result": if pass { "PASS" } else { "FAIL" }, "closest": pr.first().map(item), "under": under,
"silkItems": silk.len(), "pads": copper.iter().map(|c| c.pad.clone()).collect::<std::collections::BTreeSet<_>>().len()}));
}
let unsaved = crate::project::has_changes(&lib) == Some(true);
json!({"success": true, "result": if all_pass { "PASS" } else { "FAIL" }, "minMm": min,
"maskExpansion": match mask { Some(m) => json!({"mm": m, "from": "the call"}), None => json!({"mm": DEFAULT_MASK_MM, "from": "each pad's own manual expansion, else Altium's default rule (4 mil)"}) },
"footprints": results, "notes": notes, "unsavedChanges": unsaved,
"_hint": if all_pass { "Every silkscreen item clears every pad's exposed copper by at least minMm." } else {
"under lists each silkscreen item closer than minMm to a pad (its closest approach), overlaps when it touches the copper. Move or trim it (altium_edit_footprint graphics), then check again." }})
}
#[cfg(test)]
mod tests {
use super::*;
fn close(a: f64, b: f64) -> bool { (a - b).abs() < 1e-3 }
#[test]
fn a_line_beside_a_rectangular_pad() {
// pad 1 x 1 at the origin; a 0.2 mm line 1 mm above its centre: 1 - 0.5 - 0.1 = 0.4
let pad = pad_shape((0.0, 0.0), 2, 1.0, 1.0, 0.0, 0.0, 0.0);
let line = Shape { core: Core::Line(vec![(-2.0, 1.0), (2.0, 1.0)]), r: 0.1 };
assert!(close(clearance(&line, &pad), 0.4), "{}", clearance(&line, &pad));
// the mask grows the copper by 0.05
let masked = pad_shape((0.0, 0.0), 2, 1.0, 1.0, 0.0, 0.0, 0.05);
assert!(close(clearance(&line, &masked), 0.35));
// a line across the pad overlaps it
let across = Shape { core: Core::Line(vec![(-2.0, 0.0), (2.0, 0.0)]), r: 0.1 };
assert!(clearance(&across, &pad) < 0.0);
}
#[test]
fn round_oval_and_rounded_pads() {
// a 1 mm round pad, a point 1.5 mm away: 1.5 - 0.5 = 1.0
let dot = Shape { core: Core::Line(vec![(1.5, 0.0)]), r: 0.0 };
assert!(close(clearance(&dot, &pad_shape((0.0, 0.0), 1, 1.0, 1.0, 0.0, 0.0, 0.0)), 1.0));
// a 2 x 1 oval: its end is 1 mm out along x
assert!(close(clearance(&dot, &pad_shape((0.0, 0.0), 1, 2.0, 1.0, 0.0, 0.0, 0.0)), 0.5));
// turned 90 degrees, the same point is 1.5 - 0.5 = 1.0 from the side
assert!(close(clearance(&dot, &pad_shape((0.0, 0.0), 1, 2.0, 1.0, 0.0, 90.0, 0.0)), 1.0));
// a 1 x 1 rounded rectangle at 50 %: corner radius 0.25; diagonally the corner is rounded, not square
let diag = Shape { core: Core::Line(vec![(1.0, 1.0)]), r: 0.0 };
let rr = clearance(&diag, &pad_shape((0.0, 0.0), 9, 1.0, 1.0, 50.0, 0.0, 0.0));
let sq = clearance(&diag, &pad_shape((0.0, 0.0), 2, 1.0, 1.0, 0.0, 0.0, 0.0));
assert!(close(sq, (0.5f64 * 0.5 * 2.0).sqrt()), "{sq}");
assert!(close(rr, (0.75f64 * 0.75 * 2.0).sqrt() - 0.25), "{rr}");
}
#[test]
fn arcs_and_texts() {
// a 0.1 mm wide arc of radius 2 round a 1 mm round pad: 2 - 0.05 - 0.5 = 1.45
let arc = Shape { core: Core::Line(arc_points((0.0, 0.0), 2.0, 0.0, 90.0)), r: 0.05 };
assert!(close(clearance(&arc, &pad_shape((0.0, 0.0), 1, 1.0, 1.0, 0.0, 0.0, 0.0)), 1.45));
// a text box holding the pad reads as overlapping
let boxed = Shape { core: Core::Poly(vec![(-1.0, -1.0), (1.0, -1.0), (1.0, 1.0), (-1.0, 1.0)]), r: 0.0 };
assert!(clearance(&boxed, &pad_shape((0.0, 0.0), 2, 0.5, 0.5, 0.0, 0.0, 0.0)) <= 0.0, "touching or inside reads as no clearance");
}
#[test]
fn geometry_from_the_agent() {
// k = internal units per 1000 mil: 10_000_000 per inch
let k = 10_000_000.0;
let u = |mm: f64| (mm / 25.4 * k).round();
let d = json!({"k": k, "pads": [["1", u(0.0), u(0.0), 0, 1, 2, u(1.0), u(1.0), 2, u(1.0), u(1.0), 0, 0, 0, 0, 0]],
"tracks": [[33, u(-2.0), u(1.0), u(2.0), u(1.0), u(0.2)], [57, u(-2.0), u(0.6), u(2.0), u(0.6), u(0.2)]], "arcs": [], "texts": [], "fills": []});
let (s, c, _) = parse(&d, Some(0.0), 0.1016);
assert_eq!((s.len(), c.len()), (1, 1), "the mechanical line is not silkscreen");
let p = pairs(&s, &c);
assert!(close(p[0].0, 0.4), "{:?}", p[0].0);
let (_, c2, _) = parse(&d, None, 0.1016);
assert!(close(pairs(&s, &c2)[0].0, 0.4 - 0.1016), "the default mask expansion applies");
}
}