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.
← Commit history
0.2.79 (unreleased): thermal_vias, via_fence, height_check and placement_check answer through the standard's engine (standard 0.7.0, adom-eda-checks 0.4.0, #18 #19); altium_close no longer mistakes a drawing save prompt for a modal orphan
16 files changed
+908−657
CHANGELOG.md+10bridge-rs/Cargo.lock+1−1bridge-rs/src/boardedit.rs+1−1bridge-rs/src/bodies.rs+25−146bridge-rs/src/checks.rs+2−5bridge-rs/src/features.rs+43−350bridge-rs/src/lifecycle.rs+13−3bridge-rs/src/placement.rs+9−143bridge-rs/vendor/README.md+1−1bridge-rs/vendor/adom-eda-checks/Cargo.toml+1−1bridge-rs/vendor/adom-eda-checks/README.md+13−3bridge-rs/vendor/adom-eda-checks/src/bodies.rs+187bridge-rs/vendor/adom-eda-checks/src/features.rs+411bridge-rs/vendor/adom-eda-checks/src/lib.rs+29−2bridge-rs/vendor/adom-eda-checks/src/placement.rs+151bridge-rs/vendor/adom-eda-checks/tests/fixtures.rs+11−1CHANGELOG.md+10@@ -10,6 +10,16 @@ pour_state), and `poursAsDrawn` names layers drawn from a pour's outline instead. On the lane board, the engine's GenCAD and DXF match the bridge's own, line for line. +- **`thermal_vias`, `via_fence`, `height_check` and `placement_check` answer through the standard's engine** (#18, #19,+ standard 0.7.0, adom-eda-checks 0.4.0, vendored as published). The engine plans the vias from the board model and the+ board's rules, and the bridge places them as one undo step, as before. The engine reads `altium_bodies` (the standard's+ bodies companion) for heights, clashes and part boxes; placement_check now says `bodiesUsed`. `planned.via.from` now says where the via size came from on thermal_vias too.+ Every check reply's `engine` is the engine's own version string, no longer written by hand.++- `altium_close` no longer calls a save prompt a modal orphan. Altium disables its main window a moment before its+ Unsaved Changes prompt draws, and a close that polled in that gap answered `altium_modal_orphan`; with+ `discardChanges:true` it would have quit over the prompt. The orphan state must now hold for 4 s with no dialog.+ - `generate_body` marks the part: `marking` puts text on the body's top (a can's top for ecap) in a segment font (capitals, digits, - + / .), lines stacked, sized to fit the top. `markingStyle` raised stands 30 um proud, engraved is a 5 um layer flush on the top (the body is not cut). A light colour on the dark body; OCCT renders it legibly on a
bridge-rs/Cargo.lock+1−1@@ -10,7 +10,7 @@ checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa" [[package]] name = "adom-eda-checks"-version = "0.2.1"+version = "0.4.0" dependencies = [ "roxmltree", "serde_json",
bridge-rs/src/boardedit.rs+1−1@@ -1,7 +1,7 @@ //! Board edits from the EDA Bridge Standard's batch 3 (proposed by kicad-lane): remove, edit and align parts, set the //! copper layer count, copy a channel's routing, measure part clearances and remove board graphics. Millimetres, the //! board frame, KiCad layer names; every edit takes expectedRevision and dryRun and answers the board's new revision.-use crate::placement::part_boxes;+use adom_eda_checks::placement::part_boxes; use crate::routing::{self, apply, guarded, layer_id, layer_name, raw, PER_MM, BOTTOM, TOP}; use crate::sch::{agent_data, clean, st as sv}; use crate::agent;
bridge-rs/src/bodies.rs+25−146@@ -1,72 +1,21 @@-//! The board in 3D from its parts' bodies: how tall each part stands on its side, which ones break an enclosure's-//! height limit (board-wide, or under a lid feature in a region), and which bodies collide or come closer than a gap.-//! Bodies are compared as boxes (each body's footprint rectangle and its standoff-to-top range); a part made of-//! several bodies is several boxes, so L-shapes stay honest. Altium's Component Clearance DRC checks the real shapes.+//! The board in 3D from its parts' bodies. `bodies` answers the EDA Bridge Standard's bodies companion from Altium's+//! 3D bodies (one box per body); `height_check` (heights against an enclosure, lid regions, collisions and near misses)+//! is the standard's shared engine on that companion (vendor/adom-eda-checks `bodies`, standard 0.7.0). use crate::routing::PER_MM; use serde_json::{json, Value};-use std::collections::BTreeMap; fn r3(v: f64) -> f64 { (v * 1000.0).round() / 1000.0 } -/// One body as a box in mm: its part, side (top/bottom), x and y extent, and z from the board surface it sits on.-#[derive(Debug, Clone)]-pub struct BodyBox { pub part: String, pub top: bool, pub x0: f64, pub y0: f64, pub x1: f64, pub y1: f64, pub z0: f64, pub z1: f64 }--/// The `bodies` agent rows ([part, layer, overall, standoff, l, b, r, t], internal units) as boxes in mm.-pub fn boxes(rows: &[Value]) -> Vec<BodyBox> {- let n = |r: &Value, i: usize| r[i].as_f64().unwrap_or(0.0) / PER_MM;- rows.iter().filter(|r| r[0].as_str().map(|s| s != "-").unwrap_or(false)).map(|r| BodyBox {- part: r[0].as_str().unwrap_or("").to_string(), top: r[1].as_i64() != Some(32),- x0: n(r, 4), y0: n(r, 5), x1: n(r, 6), y1: n(r, 7), z0: n(r, 3), z1: n(r, 2),- }).collect()-}--/// Each part's height above its side and its footprint in mm, tallest first.-pub fn heights(bs: &[BodyBox]) -> Vec<Value> {- let mut m: BTreeMap<&str, (bool, f64, f64, f64, f64, f64)> = BTreeMap::new();- for b in bs {- let e = m.entry(&b.part).or_insert((b.top, 0.0, f64::MAX, f64::MAX, f64::MIN, f64::MIN));- e.1 = e.1.max(b.z1);- e.2 = e.2.min(b.x0); e.3 = e.3.min(b.y0); e.4 = e.4.max(b.x1); e.5 = e.5.max(b.y1);- }- let mut v: Vec<Value> = m.into_iter().map(|(p, (top, h, x0, y0, x1, y1))| json!({"ref": p, "side": if top { "top" } else { "bottom" }, "heightMm": r3(h), "rect": [r3(x0), r3(y0), r3(x1), r3(y1)]})).collect();- v.sort_by(|a, b| b["heightMm"].as_f64().partial_cmp(&a["heightMm"].as_f64()).unwrap());- v-}--/// Body pairs of different parts on the same side that overlap in 3D (`collisions`), or whose boxes come within-/// `gap` mm of each other in x and y where their heights overlap (`tooClose`). Pure.-pub fn clashes(bs: &[BodyBox], gap: f64) -> (Vec<Value>, Vec<Value>) {- let mut idx: Vec<usize> = (0..bs.len()).collect();- idx.sort_by(|a, b| bs[*a].x0.partial_cmp(&bs[*b].x0).unwrap());- let mut seen: BTreeMap<(String, String), (bool, f64, Value)> = BTreeMap::new();- for (k, &i) in idx.iter().enumerate() {- let a = &bs[i];- for &j in &idx[k + 1..] {- let b = &bs[j];- if b.x0 > a.x1 + gap { break; }- if a.part == b.part || a.top != b.top { continue; }- let dz = a.z1.min(b.z1) - a.z0.max(b.z0);- if dz <= 0.0 { continue; } // one sits above the other (a part under a connector's overhang)- let dx = (b.x0 - a.x1).max(a.x0 - b.x1);- let dy = (b.y0 - a.y1).max(a.y0 - b.y1);- let (hit, d) = if dx < 0.0 && dy < 0.0 { (true, -(dx.max(dy))) } else { (false, (dx.max(0.0).powi(2) + dy.max(0.0).powi(2)).sqrt()) };- if !hit && d >= gap { continue; }- let key = if a.part < b.part { (a.part.clone(), b.part.clone()) } else { (b.part.clone(), a.part.clone()) };- let at = json!([r3((a.x0.max(b.x0) + a.x1.min(b.x1)) / 2.0), r3((a.y0.max(b.y0) + a.y1.min(b.y1)) / 2.0)]);- // per pair keep the worst: a collision over a near miss, then the deepest or the closest- let worse = match seen.get(&key) { None => true, Some((h, v, _)) => (hit && !h) || (hit == *h && if hit { d > *v } else { d < *v }) };- if worse { seen.insert(key, (hit, d, at)); }- }- }- let (mut col, mut near) = (Vec::new(), Vec::new());- for ((p, q), (hit, d, at)) in seen {- if hit { col.push(json!({"parts": [p, q], "overlapMm": r3(d), "at": at})); } else { near.push(json!({"parts": [p, q], "gapMm": r3(d), "at": at})); }- }- (col, near)+/// The `bodies` agent rows ([part, layer, overall, standoff, l, b, r, t], internal units) as the companion's rows+/// ({ref, side, x0, y0, x1, y1, z0, z1}, mm). Rows with no part ("-") are left out. Pure.+pub fn rows(raw: &[Value]) -> Vec<Value> {+ let n = |r: &Value, i: usize| r3(r[i].as_f64().unwrap_or(0.0) / PER_MM);+ raw.iter().filter(|r| r[0].as_str().map(|s| s != "-").unwrap_or(false)).map(|r| json!({+ "ref": r[0], "side": if r[1].as_i64() == Some(32) { "bottom" } else { "top" },+ "x0": n(r, 4), "y0": n(r, 5), "x1": n(r, 6), "y1": n(r, 7), "z0": n(r, 3), "z1": n(r, 2),+ })).collect() } -/// altium_height_check {filePath?, maxTopMm?, maxBottomMm?, regions?: [{rect, maxMm, side?, name?}], minGapMm?} /// The bodies companion model of the EDA Bridge Standard: one box per body, in mm, z from the surface the part sits /// on; `refs` keeps only those parts. Parts with no body are listed, not dropped. pub fn bodies(args: &Value) -> Value {@@ -76,104 +25,34 @@ pub fn bodies(args: &Value) -> Value { let d = match r.get("data") { Some(d) if d.get("ok").and_then(|v| v.as_bool()) == Some(true) => d.clone(), _ => return r }; let want: Option<Vec<String>> = args.get("refs").and_then(|v| v.as_array()).map(|a| a.iter().filter_map(|x| x.as_str()).map(|x| x.to_ascii_uppercase()).collect()); let keep = |p: &str| want.as_ref().map(|w| w.contains(&p.to_ascii_uppercase())).unwrap_or(true);- let bs: Vec<BodyBox> = boxes(&d["bodies"].as_array().cloned().unwrap_or_default()).into_iter().filter(|b| keep(&b.part)).collect();- let rows: Vec<Value> = bs.iter().map(|b| json!({"ref": b.part, "side": if b.top { "top" } else { "bottom" },- "x0": r3(b.x0), "y0": r3(b.y0), "x1": r3(b.x1), "y1": r3(b.y1), "z0": r3(b.z0), "z1": r3(b.z1)})).collect();+ let rs: Vec<Value> = rows(&d["bodies"].as_array().cloned().unwrap_or_default()).into_iter().filter(|b| keep(b["ref"].as_str().unwrap_or(""))).collect(); let st = crate::routing::routing_state(&json!({}));- let with: std::collections::BTreeSet<&str> = bs.iter().map(|b| b.part.as_str()).collect();+ let with: std::collections::BTreeSet<&str> = rs.iter().filter_map(|b| b["ref"].as_str()).collect(); let no_body: Vec<Value> = st["components"].as_array().cloned().unwrap_or_default().iter().filter_map(|c| c["ref"].as_str().map(|s| s.to_string())) .filter(|r| keep(r) && !with.contains(r.as_str())).map(Value::from).collect();- json!({"success": true, "units": "mm", "bodies": rows, "count": bs.len(), "noBody": no_body, "model": "eda-bridge-standard/bodies",+ json!({"success": true, "units": "mm", "count": rs.len(), "bodies": rs, "noBody": no_body, "model": "eda-bridge-standard/bodies", "_hint": "One box per 3D body: x0..x1, y0..y1 in the board frame (mm, as altium_routing_state), z0..z1 above the surface the part sits on (a bottom part measures down from the bottom). A part made of several bodies has several boxes. noBody lists parts with no 3D body: give them one with altium_add_body. altium_height_check answers fit and clash questions from these boxes."}) } +/// altium_height_check {filePath?, maxTopMm?, maxBottomMm?, regions?: [{rect, maxMm, side?, name?}], minGapMm?, limit?} pub fn height_check(args: &Value) -> Value {- 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 r = crate::agent::call("bodies", &[], None, std::time::Duration::from_secs(120));- let d = match r.get("data") { Some(d) if d.get("ok").and_then(|v| v.as_bool()) == Some(true) => d.clone(), _ => return r };- let bs = boxes(&d["bodies"].as_array().cloned().unwrap_or_default());- let hs = heights(&bs);- let num = |k: &str| args.get(k).and_then(|v| v.as_f64());- let mut over = Vec::new();- for (side, lim) in [("top", num("maxTopMm")), ("bottom", num("maxBottomMm"))] {- let Some(lim) = lim else { continue };- for h in hs.iter().filter(|h| h["side"] == side) {- let mm = h["heightMm"].as_f64().unwrap_or(0.0);- if mm > lim { over.push(json!({"ref": h["ref"], "side": side, "heightMm": mm, "limitMm": lim, "overByMm": r3(mm - lim)})); }- }- }- // a region is a lid feature over part of the board (a boss, a rib, a display): parts under it must stay lower- let mut region_hits = Vec::new();- for (i, rg) in args.get("regions").and_then(|v| v.as_array()).cloned().unwrap_or_default().iter().enumerate() {- let rc: Vec<f64> = rg["rect"].as_array().map(|a| a.iter().filter_map(|v| v.as_f64()).collect()).unwrap_or_default();- let Some(max) = rg["maxMm"].as_f64() else { return json!({"success": false, "errorCode": "bad_args", "error": "each region is {rect:[x1,y1,x2,y2], maxMm, side?, name?}"}) };- if rc.len() != 4 { return json!({"success": false, "errorCode": "bad_args", "error": "region.rect is [x1, y1, x2, y2] in mm"}); }- let (rx0, ry0, rx1, ry1) = (rc[0].min(rc[2]), rc[1].min(rc[3]), rc[0].max(rc[2]), rc[1].max(rc[3]));- let top = rg["side"].as_str() != Some("bottom");- let name = rg["name"].as_str().map(|s| s.to_string()).unwrap_or(format!("region {}", i + 1));- let mut worst: BTreeMap<&str, f64> = BTreeMap::new();- for b in bs.iter().filter(|b| b.top == top && b.x1 > rx0 && b.x0 < rx1 && b.y1 > ry0 && b.y0 < ry1 && b.z1 > max) {- let e = worst.entry(&b.part).or_insert(0.0);- *e = e.max(b.z1);- }- for (p, h) in worst { region_hits.push(json!({"region": name, "ref": p, "heightMm": r3(h), "maxMm": max, "overByMm": r3(h - max)})); }- }- let gap = num("minGapMm").unwrap_or(0.0);- let (collisions, too_close) = clashes(&bs, gap);- // parts with no body have no height: say so, a height check that skips them is not a pass- let st = crate::routing::routing_state(&json!({}));- let with: std::collections::BTreeSet<&str> = bs.iter().map(|b| b.part.as_str()).collect();- let no_body: Vec<Value> = st["components"].as_array().cloned().unwrap_or_default().iter().filter_map(|c| c["ref"].as_str().map(|s| s.to_string())).filter(|r| !with.contains(r.as_str())).map(Value::from).collect();- let tallest = |side: &str| hs.iter().find(|h| h["side"] == side).cloned().unwrap_or(Value::Null);- let ok = over.is_empty() && region_hits.is_empty() && collisions.is_empty() && too_close.is_empty();- json!({"success": true, "ok": ok, "complete": no_body.is_empty(), "bodies": bs.len(), "parts": hs.len(), "tallest": {"top": tallest("top"), "bottom": tallest("bottom")},- "overLimit": over, "regionHits": region_hits, "collisions": collisions, "tooClose": too_close, "minGapMm": gap,- "noBody": no_body, "heights": hs.iter().take(args.get("limit").and_then(|v| v.as_u64()).unwrap_or(25) as usize).collect::<Vec<_>>(),- "_hint": "Heights are each part's tallest body above the surface it sits on (bottom-side parts below the bottom). collisions and tooClose compare body boxes; Altium's Component Clearance DRC (altium_run_drc) checks the real shapes. ok covers the parts that have bodies; complete is false while noBody lists parts with no 3D body and so no height: give them one (altium_add_body) before trusting the check."})+ let b = bodies(args);+ if b.get("success").and_then(|v| v.as_bool()) != Some(true) { return b; }+ crate::checks::engine("height_check", &json!({"bodies": b, "args": args})) } #[cfg(test)] mod tests { use super::*; - fn bx(p: &str, top: bool, x0: f64, y0: f64, x1: f64, y1: f64, z0: f64, z1: f64) -> BodyBox {- BodyBox { part: p.into(), top, x0, y0, x1, y1, z0, z1 }- }- #[test]- fn rows_become_boxes_in_mm() {+ fn rows_become_the_companion_in_mm() { let k = PER_MM;- let b = boxes(&[json!(["J1", 32, 4.1 * k, 4.0 * k, 0.0, 0.0, 10.0 * k, 5.0 * k]), json!(["-", 0, 1, 0, 0, 0, 1, 1])]);- assert_eq!(b.len(), 1);- assert!(!b[0].top && (b[0].z1 - 4.1).abs() < 1e-9 && (b[0].x1 - 10.0).abs() < 1e-9);- }-- #[test]- fn heights_take_each_parts_tallest_body() {- let bs = vec![bx("J1", true, 0.0, 0.0, 10.0, 5.0, 0.0, 3.2), bx("J1", true, 0.0, 0.0, 10.0, 5.0, 4.0, 4.1), bx("R1", true, 20.0, 0.0, 21.0, 0.5, 0.0, 0.4)];- let h = heights(&bs);- assert_eq!(h[0]["ref"], "J1");- assert_eq!(h[0]["heightMm"], 4.1);- assert_eq!(h[1]["rect"], json!([20.0, 0.0, 21.0, 0.5]));- }-- #[test]- fn clashes_find_overlaps_near_misses_and_ignore_stacked_and_opposite_sides() {- let bs = vec![- bx("U1", true, 0.0, 0.0, 5.0, 5.0, 0.0, 1.0),- bx("C1", true, 4.0, 1.0, 6.0, 2.0, 0.0, 0.5), // overlaps U1 by 1 mm in x- bx("C2", true, 5.2, 3.0, 6.0, 4.0, 0.0, 0.5), // 0.2 mm from U1- bx("C3", false, 1.0, 1.0, 2.0, 2.0, 0.0, 0.5), // under U1, other side- bx("D1", true, 1.0, 1.0, 2.0, 2.0, 1.5, 2.0), // above U1's top- ];- let (col, near) = clashes(&bs, 0.3);- assert_eq!(col.len(), 1);- assert_eq!(col[0]["parts"], json!(["C1", "U1"]));- assert_eq!(col[0]["overlapMm"], 1.0);- assert_eq!(near.len(), 1);- assert_eq!(near[0]["parts"], json!(["C2", "U1"]));- assert_eq!(near[0]["gapMm"], 0.2);- assert!(clashes(&bs, 0.0).1.is_empty());+ let b = rows(&[json!(["J1", 32, 4.1 * k, 4.0 * k, 0.0, 0.0, 10.0 * k, 5.0 * k]), json!(["-", 0, 1, 0, 0, 0, 1, 1])]);+ assert_eq!(b, vec![json!({"ref": "J1", "side": "bottom", "x0": 0.0, "y0": 0.0, "x1": 10.0, "y1": 5.0, "z0": 4.0, "z1": 4.1})]);+ // and the engine reads it back as J1's 4.1 mm on the bottom+ let h = adom_eda_checks::run("height_check", &json!({"bodies": {"bodies": b, "noBody": []}, "args": {"maxBottomMm": 3.0}}));+ assert_eq!(h["overLimit"][0]["ref"], "J1");+ assert_eq!(h["tallest"]["bottom"]["heightMm"], json!(4.1)); } }
bridge-rs/src/checks.rs+2−5@@ -5,9 +5,6 @@ use serde_json::{json, Value}; use std::time::Duration; -/// The vendored engine, as vendor/README.md records it.-const ENGINE: &str = "adom-eda-checks 0.2.1 (EDA Bridge Standard 0.5.1)";- /// adom/pcb-design-rules' vendor records, bundled at build time (vendor/README.md). const RECORDS: &[(&str, &str)] = &[ ("adom-3rdpartyfab", include_str!("../vendor/pcb-design-rules/records/adom-3rdpartyfab.json")),@@ -82,10 +79,10 @@ fn prefix_text(s: &str) -> String { out } -fn engine(check: &str, input: &Value) -> Value {+/// The engine's answer, its verbs prefixed. The reply names the engine version itself (`engine`, from 0.3.0).+pub fn engine(check: &str, input: &Value) -> Value { let mut r = adom_eda_checks::run(check, input); prefix_verbs(&mut r);- r["engine"] = json!(ENGINE); r }
bridge-rs/src/features.rs+43−350@@ -1,300 +1,51 @@-//! Board furniture an AI adds to every real board: mounting holes, fiducials and stitching vias. The stitching plan is-//! computed here from altium_routing_state (outline, and every piece of copper on another net), so it needs no dialog.+//! Board furniture an AI adds to every real board: mounting holes, fiducials, keepouts and stitching vias, plus the+//! standard's via plans (thermal_vias, via_fence). The plans come from the EDA Bridge Standard's shared engine+//! (vendor/adom-eda-checks `features`, standard 0.7.0) on altium_routing_state, so they need no dialog; this bridge+//! places what the engine plans, as one undo step.+use adom_eda_checks::features::{corners, plan_stitching_with, region_of, summary}; use serde_json::{json, Value}; -fn f(v: &Value) -> f64 { v.as_f64().unwrap_or(0.0) }-fn pt(v: &Value) -> (f64, f64) { (f(&v[0]), f(&v[1])) }--fn inside(poly: &[(f64, f64)], x: f64, y: f64) -> bool {- let mut c = false;- let n = poly.len();- for i in 0..n {- let (a, b) = (poly[i], poly[(i + n - 1) % n]);- if (a.1 > y) != (b.1 > y) && x < (b.0 - a.0) * (y - a.1) / (b.1 - a.1) + a.0 { c = !c; }- }- c-}--fn seg_dist(px: f64, py: f64, a: (f64, f64), b: (f64, f64)) -> f64 {- let (dx, dy) = (b.0 - a.0, b.1 - a.1);- let l2 = dx * dx + dy * dy;- let t = if l2 == 0.0 { 0.0 } else { (((px - a.0) * dx + (py - a.1) * dy) / l2).clamp(0.0, 1.0) };- ((px - a.0 - t * dx).powi(2) + (py - a.1 - t * dy).powi(2)).sqrt()-}--/// Copper that a stitching via on `net` must keep clear of: (kind, geometry, half-width) as segments and discs.-enum Ob { Seg((f64, f64), (f64, f64), f64), Disc(f64, f64, f64) }--fn obstacles(state: &Value, net: &str) -> (Vec<Ob>, Vec<(f64, f64)>) {- // copper on another net. Lines on mechanical and overlay layers are not copper, and net-less copper tracks are a- // hatched pour's pieces (Altium lists them with no net) that re-pour round a new via- let other = |v: &Value| {- let n = v["net"].as_str().unwrap_or("");- let copper = v.get("layer").map(|l| l.as_str().map(|s| s.ends_with(".Cu")).unwrap_or(false)).unwrap_or(true);- let piece = n.is_empty() && v.get("start").or(v.get("center")).is_some();- copper && !piece && !n.eq_ignore_ascii_case(net)- };- let mut ob = Vec::new();- let mut same_vias = Vec::new();- for t in state["tracks"].as_array().cloned().unwrap_or_default() {- if other(&t) { ob.push(Ob::Seg((f(&t["start"]["x"]), f(&t["start"]["y"])), (f(&t["end"]["x"]), f(&t["end"]["y"])), f(&t["width"]) / 2.0)); }- }- for a in state["arcs"].as_array().cloned().unwrap_or_default() {- if !other(&a) { continue; }- // an arc as short chords- let (cx, cy, r) = (f(&a["center"]["x"]), f(&a["center"]["y"]), f(&a["radius"]));- let (mut a1, a2) = (f(&a["startAngle"]), f(&a["endAngle"]));- let mut span = a2 - a1;- if span <= 0.0 { span += 360.0; }- let n = ((span / 10.0).ceil() as usize).max(1);- let p = |deg: f64| (cx + r * deg.to_radians().cos(), cy + r * deg.to_radians().sin());- for _ in 0..n { let b = a1 + span / n as f64; ob.push(Ob::Seg(p(a1), p(b), f(&a["width"]) / 2.0)); a1 = b; }- }- for v in state["vias"].as_array().cloned().unwrap_or_default() {- let (x, y) = (f(&v["position"]["x"]), f(&v["position"]["y"]));- if other(&v) { ob.push(Ob::Disc(x, y, f(&v["size"]) / 2.0)); } else { same_vias.push((x, y)); }- }- for p in state["pads"].as_array().cloned().unwrap_or_default() {- // a pad on the net still gets clearance: a via in a pad is not stitching. Its circumscribed circle keeps it- // conservative at any rotation.- let r = (f(&p["sizeX"]).powi(2) + f(&p["sizeY"]).powi(2)).sqrt() / 2.0;- ob.push(Ob::Disc(f(&p["x"]), f(&p["y"]), r.max(f(&p["drill"]) / 2.0)));- }- (ob, same_vias)-}--/// Where stitching vias for `net` go: a grid at `pitch` inside the outline (or `region`), `edge` mm clear of the-/// board edge, `clearance` mm clear of copper on other nets and of every pad, half a pitch from vias the net already-/// has, at most `max`. Pure, for the tests.-#[allow(clippy::too_many_arguments)]-pub fn plan_stitching(state: &Value, net: &str, pitch: f64, size: f64, clearance: f64, edge: f64, region: Option<&[(f64, f64)]>, max: usize) -> Vec<(f64, f64)> {- plan_stitching_with(state, net, pitch, size, clearance, edge, region, max, &[], true, &[])-}--/// plan_stitching, also clear of `extra` discs (x, y, radius: holes and fiducials placed in the same call) and, with-/// `avoid_parts`, out from under every part (the box around its pads, grown by the clearance).-#[allow(clippy::too_many_arguments)]-pub fn plan_stitching_with(state: &Value, net: &str, pitch: f64, size: f64, clearance: f64, edge: f64, region: Option<&[(f64, f64)]>, max: usize,- extra: &[(f64, f64, f64)], avoid_parts: bool, keepouts: &[(f64, f64, f64, f64)]) -> Vec<(f64, f64)> {- let outline: Vec<(f64, f64)> = state["outline"].as_array().cloned().unwrap_or_default().iter().map(pt).collect();- if outline.len() < 3 || pitch <= 0.0 { return vec![]; }- let area: Vec<(f64, f64)> = region.map(|r| r.to_vec()).unwrap_or_else(|| outline.clone());- let (mut ob, same) = obstacles(state, net);- for (x, y, r) in extra { ob.push(Ob::Disc(*x, *y, *r)); }- // each part's pad box: a via between a chip's pad rows sits under its body- let mut boxes: std::collections::BTreeMap<String, (f64, f64, f64, f64)> = Default::default();- if avoid_parts {- for p in state["pads"].as_array().cloned().unwrap_or_default() {- let Some(r) = p["ref"].as_str().filter(|r| !r.is_empty()) else { continue };- let h = (f(&p["sizeX"]).powi(2) + f(&p["sizeY"]).powi(2)).sqrt() / 2.0;- let (x, y) = (f(&p["x"]), f(&p["y"]));- let b = boxes.entry(r.to_string()).or_insert((f64::MAX, f64::MAX, f64::MIN, f64::MIN));- *b = (b.0.min(x - h), b.1.min(y - h), b.2.max(x + h), b.3.max(y + h));- }- }- let (x0, x1) = area.iter().fold((f64::MAX, f64::MIN), |a, p| (a.0.min(p.0), a.1.max(p.0)));- let (y0, y1) = area.iter().fold((f64::MAX, f64::MIN), |a, p| (a.0.min(p.1), a.1.max(p.1)));- let mut cands = Vec::new();- let mut y = y0 + pitch / 2.0;- while y < y1 {- let mut x = x0 + pitch / 2.0;- while x < x1 { if inside(&area, x, y) { cands.push((x, y)); } x += pitch; }- y += pitch;- }- keep_clear(state, &outline, &cands, pitch / 2.0, size, clearance, edge, max, &ob, &same, &boxes, keepouts)+/// The engine's plan for `check` on the current board (guarded) with the board's rules, or the refusal to answer with.+fn plan(check: &str, args: &Value) -> Result<(Value, Value), Value> {+ if let Some(g) = crate::support::need_licensed() { return Err(g); }+ if let Some(p) = crate::support::s(args, "filePath") { if let Some(e) = crate::support::must_open(&p, 60) { return Err(e); } }+ let st = crate::routing::guarded(args)?;+ // the board's Routing Via rule sizes the vias, so they pass its DRC (0.6/0.3 broke the Bluetooth Sentinel's 0.5/0.3+ // rule on every via)+ let rules = crate::agent::call("read_rules", &[], None, std::time::Duration::from_secs(60));+ let r = crate::checks::engine(check, &json!({"board": st, "rules": rules.get("data").cloned().unwrap_or(json!([])), "args": args}));+ Ok((r, st)) } -/// The candidate via points that fit: inside the outline, `edge` from it, `clearance` from other copper (`ob`), out of-/// part boxes and keepouts, and `sep` from the net's vias and from each other. Pure.-#[allow(clippy::too_many_arguments)]-fn keep_clear(_state: &Value, outline: &[(f64, f64)], cands: &[(f64, f64)], sep: f64, size: f64, clearance: f64, edge: f64, max: usize, ob: &[Ob],- same: &[(f64, f64)], boxes: &std::collections::BTreeMap<String, (f64, f64, f64, f64)>, keepouts: &[(f64, f64, f64, f64)]) -> Vec<(f64, f64)> {- let r = size / 2.0;- let mut out: Vec<(f64, f64)> = Vec::new();- for &(x, y) in cands {- if out.len() >= max { break; }- let ok = inside(outline, x, y)- && (0..outline.len()).all(|k| seg_dist(x, y, outline[k], outline[(k + 1) % outline.len()]) >= edge + r)- && ob.iter().all(|o| match o {- Ob::Seg(a, b, hw) => seg_dist(x, y, *a, *b) - hw - r >= clearance,- Ob::Disc(cx, cy, cr) => ((x - cx).powi(2) + (y - cy).powi(2)).sqrt() - cr - r >= clearance,- })- && same.iter().chain(out.iter()).all(|(sx, sy)| ((x - sx).powi(2) + (y - sy).powi(2)).sqrt() >= sep)- && boxes.values().all(|b| x + r + clearance <= b.0 || x - r - clearance >= b.2 || y + r + clearance <= b.1 || y - r - clearance >= b.3)- && keepouts.iter().all(|k| x + r <= k.0 || x - r >= k.2 || y + r <= k.1 || y - r >= k.3);- if ok { out.push(((x * 1000.0).round() / 1000.0, (y * 1000.0).round() / 1000.0)); }- }- out+/// place_vias ops for an engine plan's `apply` ({verb: "place_vias", args: {vias: [{net, x, y, size, drill}]}}). Pure.+pub fn via_ops(apply: &Value) -> Vec<String> {+ use crate::routing::{raw, BOTTOM, TOP};+ apply["args"]["vias"].as_array().cloned().unwrap_or_default().iter()+ .map(|v| format!("V|{}|{}|{}|{}|{}|{}|{}", raw(f(&v["x"])), raw(f(&v["y"])), raw(f(&v["size"])), raw(f(&v["drill"])), TOP, BOTTOM, v["net"].as_str().unwrap_or(""))).collect() } -/// Via fence candidates: both sides of every copper track of `nets`, `offset` from its centreline, every `pitch` along-/// it; and with `edge_inset`, along the outline that far inside it. Pure.-pub fn fence_points(state: &Value, nets: &[String], pitch: f64, offset: f64, edge_inset: Option<f64>) -> Vec<(f64, f64)> {- let mut v = Vec::new();- for t in state["tracks"].as_array().cloned().unwrap_or_default() {- let n = t["net"].as_str().unwrap_or("");- if !nets.iter().any(|x| x.eq_ignore_ascii_case(n)) || !t["layer"].as_str().map(|l| l.ends_with(".Cu")).unwrap_or(false) { continue; }- let (a, b) = ((f(&t["start"]["x"]), f(&t["start"]["y"])), (f(&t["end"]["x"]), f(&t["end"]["y"])));- let len = ((b.0 - a.0).powi(2) + (b.1 - a.1).powi(2)).sqrt();- if len <= 0.0 { continue; }- let (ux, uy) = ((b.0 - a.0) / len, (b.1 - a.1) / len);- let k = (len / pitch).floor() as usize;- for i in 0..=k {- let s = if k == 0 { len / 2.0 } else { i as f64 * len / k as f64 };- for side in [1.0, -1.0] { v.push((a.0 + ux * s - uy * offset * side, a.1 + uy * s + ux * offset * side)); }- }- }- if let Some(inset) = edge_inset {- let ring = crate::coppermap::outline_ring(state);- let n = ring.len();- // inward is left of each edge on a counterclockwise ring- let area: f64 = (0..n).map(|k| ring[k].0 * ring[(k + 1) % n].1 - ring[(k + 1) % n].0 * ring[k].1).sum();- let sgn = if area > 0.0 { 1.0 } else { -1.0 };- let mut carry: f64 = 0.0;- for k in 0..n {- let (a, b) = (ring[k], ring[(k + 1) % n]);- let len = ((b.0 - a.0).powi(2) + (b.1 - a.1).powi(2)).sqrt();- if len <= 0.0 { continue; }- let (ux, uy) = ((b.0 - a.0) / len, (b.1 - a.1) / len);- // clear of the corners by the inset, where an inward step from one edge lands on the next- let mut s = carry.max(inset);- while s <= len - inset { v.push((a.0 + ux * s - uy * inset * sgn, a.1 + uy * s + ux * inset * sgn)); s += pitch; }- carry = (s - len).max(0.0);- }+/// Place the engine's plan (or return it for dryRun or a refusal), keeping the plan, the engine and its hint in the reply.+fn place(check: &str, args: &Value, hint: &str) -> Value {+ let (r, st) = match plan(check, args) { Ok(x) => x, Err(e) => return e };+ if r["success"] != json!(true) || r.get("apply").is_none() { return r; }+ if args.get("dryRun").and_then(|b| b.as_bool()) == Some(true) {+ return json!({"success": true, "dryRun": true, "planned": r["planned"], "engine": r["engine"], "_hint": "Nothing placed. Call again without dryRun to place exactly this."}); }- v-}--/// The board's preferred via (diameter, drill) in mm from its Routing Via rule's descriptor, e.g. "Routing Via-/// (MinHoleWidth=0.3mm) ... (PreferredHoleWidth=0.3mm) ... (PreferedWidth=0.5mm) (All)" (Altium's own spelling). Pure.-pub fn via_style(rules: &[Value]) -> Option<(f64, f64)> {- let num = |d: &str, key: &str| -> Option<f64> {- let i = d.find(&format!("({key}="))? + key.len() + 2;- let s = &d[i..d[i..].find(')')? + i];- let (v, unit) = s.trim_end_matches(char::is_alphabetic).parse::<f64>().ok().map(|v| (v, &s[s.trim_end_matches(char::is_alphabetic).len()..]))?;- Some(if unit.eq_ignore_ascii_case("mil") { v * 0.0254 } else { v })- };- let mut rs: Vec<&Value> = rules.iter().filter(|r| r["enabled"] != json!(false) && r["descriptor"].as_str().map(|d| d.starts_with("Routing Via")).unwrap_or(false)).collect();- // the board-wide rule (scope All), highest priority first- rs.sort_by_key(|r| (r["scope1"].as_str() != Some("All"), r["priority"].as_i64().unwrap_or(99)));- let d = rs.first()?["descriptor"].as_str()?;- Some((num(d, "PreferedWidth").or(num(d, "PreferredWidth"))?, num(d, "PreferredHoleWidth")?))-}--/// Thermal via grid points inside a pad (x, y, sx, sy, rotation mm): `pitch` apart, `inset` from the pad's edge plus-/// the via's radius, centred. Pure.-pub fn thermal_grid(x: f64, y: f64, sx: f64, sy: f64, rot: f64, pitch: f64, size: f64, inset: f64) -> Vec<(f64, f64)> {- let (ux, uy) = (sx / 2.0 - inset - size / 2.0, sy / 2.0 - inset - size / 2.0);- if ux < 0.0 || uy < 0.0 { return vec![]; }- let (nx, ny) = ((2.0 * ux / pitch).floor() as i64 + 1, (2.0 * uy / pitch).floor() as i64 + 1);- let (c, s) = (rot.to_radians().cos(), rot.to_radians().sin());- let mut out = Vec::new();- for i in 0..nx { for j in 0..ny {- let (lx, ly) = ((i as f64 - (nx - 1) as f64 / 2.0) * pitch, (j as f64 - (ny - 1) as f64 / 2.0) * pitch);- out.push((((x + lx * c - ly * s) * 1000.0).round() / 1000.0, ((y + lx * s + ly * c) * 1000.0).round() / 1000.0));- } }- out+ let a = crate::routing::apply(&via_ops(&r["apply"]), &st, check);+ json!({"success": a["success"], "applied": a["applied"], "failed": a["failed"], "planned": r["planned"], "revision": a["revision"], "engine": r["engine"], "_hint": hint}) } /// altium_thermal_vias {filePath?, ref, pad?, pitchMm?, size?, drill?, insetMm?, dryRun?} pub fn thermal_vias(args: &Value) -> Value {- use crate::routing::{apply, guarded, raw, BOTTOM, TOP};- 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(rf) = crate::support::s(args, "ref") else { return json!({"success": false, "errorCode": "bad_args", "error": "ref names the part (e.g. U3)"}) };- let pads: Vec<Value> = st["pads"].as_array().cloned().unwrap_or_default().into_iter().filter(|p| p["ref"].as_str().map(|r| r.eq_ignore_ascii_case(&rf)).unwrap_or(false)).collect();- if pads.is_empty() { return json!({"success": false, "errorCode": "no_such_part", "error": format!("{rf} has no pads on this board")}); }- // the exposed pad: the one named, else the part's largest pad- let pad = match crate::support::s(args, "pad") {- Some(n) => pads.iter().find(|p| p["name"].as_str().map(|x| x.eq_ignore_ascii_case(&n)).unwrap_or(false)).cloned(),- None => pads.iter().max_by(|a, b| (f(&a["sizeX"]) * f(&a["sizeY"])).partial_cmp(&(f(&b["sizeX"]) * f(&b["sizeY"]))).unwrap()).cloned(),- };- let Some(pad) = pad else { return json!({"success": false, "errorCode": "no_such_pad", "error": "that pad is not on the part", "pads": pads.iter().map(|p| p["name"].clone()).collect::<Vec<_>>()}) };- let net = pad["net"].as_str().unwrap_or("").to_string();- if net.is_empty() { return json!({"success": false, "errorCode": "pad_has_no_net", "error": format!("{rf}.{} is on no net: thermal vias would float", pad["name"].as_str().unwrap_or(""))}); }- let rules = crate::agent::call("read_rules", &[], None, std::time::Duration::from_secs(60));- let style = via_style(&rules.get("data").and_then(|d| d["rules"].as_array().cloned()).unwrap_or_default());- let size = num(args, "size", style.map(|s| s.0).unwrap_or(0.6));- let drill = num(args, "drill", style.map(|s| s.1).unwrap_or(0.3));- let pitch = num(args, "pitchMm", (size + 0.5).max(1.0));- let inset = num(args, "insetMm", 0.1);- let grid = thermal_grid(f(&pad["x"]), f(&pad["y"]), f(&pad["sizeX"]), f(&pad["sizeY"]), f(&pad["rotation"]), pitch, size, inset);- // keep clear of vias already there: the Bluetooth Sentinel's U4 pad had 8, and a grid laid over them broke Altium's- // hole-to-hole rule 8 times (2026-10-26)- let vias: Vec<(f64, f64, f64)> = st["vias"].as_array().cloned().unwrap_or_default().iter().map(|v| (f(&v["position"]["x"]), f(&v["position"]["y"]), f(&v["size"]))).collect();- let inside = |x: f64, y: f64| (x - f(&pad["x"])).abs() <= f(&pad["sizeX"]).max(f(&pad["sizeY"])) / 2.0 && (y - f(&pad["y"])).abs() <= f(&pad["sizeX"]).max(f(&pad["sizeY"])) / 2.0;- let existing = vias.iter().filter(|(x, y, _)| inside(*x, *y)).count();- let pts: Vec<(f64, f64)> = grid.iter().cloned().filter(|(x, y)| vias.iter().all(|(vx, vy, vs)| ((x - vx).powi(2) + (y - vy).powi(2)).sqrt() >= size / 2.0 + vs / 2.0 + 0.2)).collect();- let planned = json!({"part": rf, "pad": pad["name"], "net": net, "padMm": [pad["sizeX"], pad["sizeY"]], "vias": pts.len(), "existingVias": existing, "skippedNearExisting": grid.len() - pts.len(), "pitchMm": pitch, "via": {"sizeMm": size, "drillMm": drill},- "points": pts.iter().map(|(x, y)| json!([x, y])).collect::<Vec<_>>()});- if pts.is_empty() {- return json!({"success": existing > 0, "errorCode": if existing > 0 { "already_has_vias" } else { "pad_too_small" }, "error": if existing > 0 { "the pad's existing vias leave no room for more at this pitch" } else { "no via fits inside the pad at this size and inset" }, "planned": planned});- }- if args.get("dryRun").and_then(|b| b.as_bool()) == Some(true) { return json!({"success": true, "dryRun": true, "planned": planned}); }- let ops: Vec<String> = pts.iter().map(|(x, y)| format!("V|{}|{}|{}|{}|{}|{}|{}", raw(*x), raw(*y), raw(size), raw(drill), TOP, BOTTOM, net)).collect();- let r = apply(&ops, &st, "thermal_vias");- json!({"success": r["success"], "applied": r["applied"], "failed": r["failed"], "planned": planned, "revision": r["revision"],- "_hint": "Vias inside the pad carry its heat to the other layers' copper: pour the net on the far side (altium_apply_pours) so they have somewhere to go. Open vias in a pad wick solder: ask the fab to tent or plug them (JLCPCB: via covering), or use 0.3 mm or smaller drills. altium_routing_drc afterwards."})+ place("thermal_vias", args, "Vias inside the pad carry its heat to the other layers' copper: pour the net on the far side (altium_apply_pours) so they have somewhere to go. Open vias in a pad wick solder: ask the fab to tent or plug them (JLCPCB: via covering), or use 0.3 mm or smaller drills. altium_routing_drc afterwards.") } -/// altium_via_fence {filePath?, nets?, edge?, viaNet, pitchMm?, freqGHz?, offsetMm?, size?, drill?, clearance?, dryRun?}+/// altium_via_fence {filePath?, nets?, edge?, viaNet, pitchMm?, freqGHz?, offsetMm?, edgeInsetMm?, size?, drill?, clearance?, dryRun?} pub fn via_fence(args: &Value) -> Value {- use crate::routing::{apply, guarded, raw, BOTTOM, TOP};- 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(via_net) = crate::support::s(args, "viaNet") else { return json!({"success": false, "errorCode": "bad_args", "error": "viaNet is the net the fence ties to, usually GND"}) };- if !st["nets"].as_array().map(|a| a.iter().any(|n| n.as_str().map(|s| s.eq_ignore_ascii_case(&via_net)).unwrap_or(false))).unwrap_or(false) {- return json!({"success": false, "errorCode": "no_such_net", "error": format!("{via_net} is not a net on this board"), "nets": st["nets"]});- }- let nets: Vec<String> = args.get("nets").and_then(|v| v.as_array()).map(|a| a.iter().filter_map(|v| v.as_str().map(String::from)).collect()).unwrap_or_default();- let edge_on = args.get("edge").and_then(|b| b.as_bool()).unwrap_or(false);- if nets.is_empty() && !edge_on { return json!({"success": false, "errorCode": "bad_args", "error": "name nets to fence (e.g. [\"ANT_RF\"]) and/or edge:true for a fence round the board edge"}); }- // the via the board's own Routing Via rule prefers, so the fence passes its DRC (0.6/0.3 broke the Bluetooth- // Sentinel example's 0.5/0.3 rule on every via)- let rules = crate::agent::call("read_rules", &[], None, std::time::Duration::from_secs(60));- let style = via_style(&rules.get("data").and_then(|d| d["rules"].as_array().cloned()).unwrap_or_default());- let size = num(args, "size", style.map(|s| s.0).unwrap_or(0.6));- let drill = num(args, "drill", style.map(|s| s.1).unwrap_or(0.3));- let clearance = num(args, "clearance", 0.2);- // lambda/20 in FR-4 (effective er about 3.4) at the highest frequency, else 2 mm- let pitch = match args.get("freqGHz").and_then(|v| v.as_f64()) { Some(g) if g > 0.0 => (299.79 / g / 3.4f64.sqrt() / 20.0).min(num(args, "pitchMm", f64::MAX)), _ => num(args, "pitchMm", 2.0) };- let widest = st["tracks"].as_array().cloned().unwrap_or_default().iter().filter(|t| nets.iter().any(|n| t["net"].as_str().map(|s| s.eq_ignore_ascii_case(n)).unwrap_or(false))).map(|t| f(&t["width"])).fold(0.0, f64::max);- let offset = num(args, "offsetMm", widest / 2.0 + clearance + size / 2.0 + 0.1);- let inset = if edge_on { Some(num(args, "edgeInsetMm", size / 2.0 + 0.5)) } else { None };- let cands = fence_points(&st, &nets, pitch, offset, inset);- let outline: Vec<(f64, f64)> = crate::coppermap::outline_ring(&st);- let (ob, same) = obstacles(&st, &via_net);- let pts = keep_clear(&st, &outline, &cands, pitch * 0.6, size, clearance, 0.3, 5000, &ob, &same, &Default::default(), &[]);- let planned = json!({"vias": pts.len(), "candidates": cands.len(), "via": {"sizeMm": size, "drillMm": drill, "from": if args.get("size").is_some() { "size/drill" } else if style.is_some() { "the board's Routing Via rule" } else { "default 0.6/0.3" }}, "pitchMm": (pitch * 1000.0).round() / 1000.0, "offsetMm": (offset * 1000.0).round() / 1000.0, "points": pts.iter().take(200).map(|(x, y)| json!([x, y])).collect::<Vec<_>>()});- if args.get("dryRun").and_then(|b| b.as_bool()) == Some(true) || pts.is_empty() {- return json!({"success": !pts.is_empty(), "dryRun": true, "planned": planned, "_hint": if pts.is_empty() { "No candidate fits: lower clearance or size, change offsetMm, or check the nets have tracks." } else { "Pass without dryRun to place them." }});- }- let ops: Vec<String> = pts.iter().map(|(x, y)| format!("V|{}|{}|{}|{}|{}|{}|{}", raw(*x), raw(*y), raw(size), raw(drill), TOP, BOTTOM, via_net)).collect();- let r = apply(&ops, &st, "via_fence");- json!({"success": r["success"], "applied": r["applied"], "failed": r["failed"], "planned": planned, "revision": r["revision"],- "_hint": "Fence vias placed as one undo step, each clear of other copper by clearance and of the board edge, sized by the board's Routing Via rule. Repour (altium_repour) so pours join them, then altium_routing_drc {full:true} (the quick read can show stale test-point messages after a repour). skipped = candidates - vias: spots where other copper, a pad or the edge was too close."})-}--/// The four corner positions of the outline's bounding box, `inset` mm in.-pub fn corners(state: &Value, inset: f64) -> Vec<(f64, f64)> {- let o: Vec<(f64, f64)> = state["outline"].as_array().cloned().unwrap_or_default().iter().map(pt).collect();- if o.is_empty() { return vec![]; }- let (x0, x1) = o.iter().fold((f64::MAX, f64::MIN), |a, p| (a.0.min(p.0), a.1.max(p.0)));- let (y0, y1) = o.iter().fold((f64::MAX, f64::MIN), |a, p| (a.0.min(p.1), a.1.max(p.1)));- vec![(x0 + inset, y0 + inset), (x1 - inset, y0 + inset), (x1 - inset, y1 - inset), (x0 + inset, y1 - inset)]-}--pub fn region_of(v: Option<&Value>) -> Option<Vec<(f64, f64)>> {- let a = v?.as_array()?;- let r: Vec<(f64, f64)> = a.iter().map(pt).collect();- if r.len() >= 3 { Some(r) } else { None }+ place("via_fence", args, "Fence vias placed as one undo step, each clear of other copper by clearance and of the board edge, sized by the board's Routing Via rule. Repour (altium_repour) so pours join them, then altium_routing_drc {full:true} (the quick read can show stale test-point messages after a repour). candidates - vias are the spots where other copper, a pad or the edge was too close.") } -pub fn summary(points: &[(f64, f64)]) -> Value {- json!(points.iter().map(|(x, y)| json!([x, y])).collect::<Vec<_>>())-}+fn f(v: &Value) -> f64 { v.as_f64().unwrap_or(0.0) } fn num(v: &Value, k: &str, d: f64) -> f64 { v.get(k).and_then(|x| x.as_f64().or_else(|| x.as_str().and_then(|s| s.parse().ok()))).unwrap_or(d) } @@ -407,75 +158,17 @@ pub fn board_features(args: &Value) -> Value { mod tests { use super::*; - fn board() -> Value {- json!({"outline": [[0, 0], [20, 0], [20, 10], [0, 10]],- "tracks": [{"start": {"x": 0.0, "y": 5.0}, "end": {"x": 20.0, "y": 5.0}, "width": 0.25, "net": "SIG"}],- "arcs": [], "vias": [{"position": {"x": 2.5, "y": 2.5}, "size": 0.6, "net": "GND"}],- "pads": [{"x": 17.5, "y": 7.5, "sizeX": 1.0, "sizeY": 1.0, "drill": 0.0, "net": "GND"}]})- }-- #[test]- fn stitching_keeps_clear_of_other_nets_pads_edges_and_existing_vias() {- let p = plan_stitching(&board(), "GND", 5.0, 0.6, 0.3, 0.5, None, 100);- // the 5 mm grid is 2.5/7.5/12.5/17.5 by 2.5/7.5; (2.5,2.5) has a GND via already, (17.5,7.5) is a pad- assert_eq!(p, vec![(7.5, 2.5), (12.5, 2.5), (17.5, 2.5), (2.5, 7.5), (7.5, 7.5), (12.5, 7.5)]);- // a track of another net through the grid row blocks it- let mut b = board();- b["tracks"][0]["start"]["y"] = json!(2.5);- b["tracks"][0]["end"]["y"] = json!(2.5);- assert!(plan_stitching(&b, "GND", 5.0, 0.6, 0.3, 0.5, None, 100).iter().all(|p| p.1 != 2.5));- // a region limits it, max caps it- let reg = [(0.0, 0.0), (10.0, 0.0), (10.0, 10.0), (0.0, 10.0)];- assert_eq!(plan_stitching(&board(), "GND", 5.0, 0.6, 0.3, 0.5, Some(®), 100), vec![(7.5, 2.5), (2.5, 7.5), (7.5, 7.5)]);- assert_eq!(plan_stitching(&board(), "GND", 5.0, 0.6, 0.3, 0.5, None, 2).len(), 2);- }-- #[test]- fn stitching_stays_off_holes_and_out_from_under_parts() {- let mut b = board();- // a part U1 whose two pads span x 6..9 at y 7.5: (7.5, 7.5) lies between them, under its body- b["pads"] = json!([{"ref": "U1", "x": 6.0, "y": 7.5, "sizeX": 0.6, "sizeY": 0.6, "drill": 0.0, "net": "SIG"},- {"ref": "U1", "x": 9.0, "y": 7.5, "sizeX": 0.6, "sizeY": 0.6, "drill": 0.0, "net": "SIG"}]);- let p = plan_stitching_with(&b, "GND", 5.0, 0.6, 0.3, 0.5, None, 100, &[(12.5, 2.5, 1.6)], true, &[(15.0, 0.0, 20.0, 10.0)]);- assert!(!p.contains(&(7.5, 7.5)) && !p.contains(&(12.5, 2.5)));- assert!(p.iter().all(|q| q.0 < 15.0), "the keepout at x 15..20 takes no via");- let p = plan_stitching_with(&b, "GND", 5.0, 0.6, 0.3, 0.5, None, 100, &[], false, &[]);- assert!(p.contains(&(7.5, 7.5)));- }-- #[test]- fn corner_holes_sit_inset_from_the_outline() {- assert_eq!(corners(&board(), 3.0), vec![(3.0, 3.0), (17.0, 3.0), (17.0, 7.0), (3.0, 7.0)]);- }- #[test]- fn fence_points_line_both_sides_of_a_track_and_the_edge() {- let st = json!({"tracks": [{"net": "RF", "layer": "F.Cu", "width": 0.4, "start": {"x": 0.0, "y": 5.0}, "end": {"x": 10.0, "y": 5.0}}],- "outline": [[-5, 0], [15, 0], [15, 10], [-5, 10]],- "outlineEdges": [{"kind": "line", "start": [-5.0, 0.0]}, {"kind": "line", "start": [15.0, 0.0]}, {"kind": "line", "start": [15.0, 10.0]}, {"kind": "line", "start": [-5.0, 10.0]}]});- let p = fence_points(&st, &["RF".to_string()], 2.0, 1.0, None);- assert_eq!(p.len(), 12);- assert!(p.contains(&(0.0, 6.0)) && p.contains(&(10.0, 4.0)));- let e = fence_points(&st, &[], 5.0, 1.0, Some(0.5));- assert!(e.iter().all(|(x, y)| *x >= -4.5 - 1e-9 && *x <= 14.5 + 1e-9 && *y >= 0.5 - 1e-9 && *y <= 9.5 + 1e-9), "{e:?}");- assert!(e.len() >= 10, "{e:?}");- }- #[test]- fn via_style_reads_altiums_descriptor() {- let rules = vec![json!({"enabled": true, "scope1": "All", "priority": 1, "descriptor": "Routing Via (MinHoleWidth=0.3mm) (MaxHoleWidth=0.3mm) (PreferredHoleWidth=0.3mm) (MinWidth=0.5mm) (MaxWidth=0.5mm) (PreferedWidth=0.5mm) (All)"})];- assert_eq!(via_style(&rules), Some((0.5, 0.3)));- let mil = vec![json!({"enabled": true, "scope1": "All", "priority": 1, "descriptor": "Routing Via (PreferredHoleWidth=12mil) (PreferedWidth=24mil) (All)"})];- let (s, d) = via_style(&mil).unwrap();- assert!((s - 0.6096).abs() < 1e-9 && (d - 0.3048).abs() < 1e-9);- } #[test]- fn thermal_grid_fills_an_exposed_pad() {- // a 3.3 mm QFN pad, 0.6 mm vias, 1.1 mm pitch: a 3 x 3 grid centred on the pad- let g = thermal_grid(10.0, 10.0, 3.3, 3.3, 0.0, 1.1, 0.6, 0.1);- assert_eq!(g.len(), 9);- assert!(g.contains(&(10.0, 10.0)) && g.contains(&(8.9, 11.1)));- assert!(thermal_grid(0.0, 0.0, 0.5, 0.5, 0.0, 1.0, 0.6, 0.1).is_empty());- // turned 90 degrees, a long pad's grid turns with it- let r = thermal_grid(0.0, 0.0, 4.0, 1.5, 90.0, 1.1, 0.6, 0.1);- assert!(r.iter().all(|(x, _)| x.abs() < 0.5));+ fn engine_plans_become_one_via_op_each() {+ // the standard's thermal_vias plan for a 3.3 mm pad, as the engine answers it, placed through place_vias' op+ let board = json!({"outline": [[0, 0], [20, 0], [20, 20], [0, 20]], "tracks": [], "arcs": [], "vias": [], "nets": ["GND"],+ "pads": [{"ref": "U1", "name": "EP", "x": 10.0, "y": 10.0, "sizeX": 3.3, "sizeY": 3.3, "rotation": 0.0, "net": "GND"}]});+ let rules = json!([{"enabled": true, "scope1": "All", "priority": 1, "descriptor": "Routing Via (PreferredHoleWidth=0.3mm) (PreferedWidth=0.5mm) (All)"}]);+ let r = adom_eda_checks::run("thermal_vias", &json!({"board": board, "rules": rules, "args": {"ref": "U1"}}));+ assert_eq!(r["planned"]["via"]["sizeMm"], json!(0.5));+ let ops = via_ops(&r["apply"]);+ assert_eq!(ops.len(), r["planned"]["vias"].as_u64().unwrap() as usize);+ assert!(ops.iter().all(|o| o.starts_with("V|") && o.ends_with("|GND")), "{ops:?}");+ assert!(ops.contains(&format!("V|{}|{}|{}|{}|{}|{}|GND", crate::routing::raw(10.0), crate::routing::raw(10.0), crate::routing::raw(0.5), crate::routing::raw(0.3), crate::routing::TOP, crate::routing::BOTTOM))); } }
bridge-rs/src/lifecycle.rs+13−3@@ -616,6 +616,9 @@ pub fn stop_all_live() -> Value { "stillAlive": stragglers, "_hint": "agent_recover"}) } +/// How long Altium must stay disabled with no dialog before it counts as a modal orphan.+const ORPHAN_SETTLE: Duration = Duration::from_secs(4);+ /// Is Altium stuck inside a modal loop whose DIALOG IS GONE? Windows disables a process's other /// top-level windows for the duration of a modal dialog, so "main window disabled + nothing on /// screen to answer" means the app is waiting on a box that no longer exists. In that state@@ -627,9 +630,16 @@ pub fn modal_orphan() -> Option<Value> { let rows = crate::win32::visible_windows()?; let pids = crate::win32::pids_of("X2.EXE").unwrap_or_default(); let pid = pids.into_iter().find(|p| crate::win32::pid_main_window_disabled(*p, &rows))?;- // A dialog we can SEE is not an orphan: it is a question, and answering it is the right fix.- if !crate::dialogs::scan().is_empty() {- return None;+ // A dialog we can SEE is not an orphan: it is a question, and answering it is the right fix. And it must STAY+ // dialog-less: a close disables the main window before the WPF "Unsaved Changes" prompt has drawn, and+ // altium_close called that gap an orphan (2026-10-28) - with discardChanges it would have quit over the prompt.+ let t = Instant::now();+ loop {+ if !crate::dialogs::scan().is_empty() { return None; }+ if t.elapsed() >= ORPHAN_SETTLE { break; }+ std::thread::sleep(Duration::from_millis(500));+ let now = crate::win32::visible_windows()?;+ if !crate::win32::pid_main_window_disabled(pid, &now) { return None; } } let tid = crate::win32::pid_ui_thread(pid, &rows)?; let hwnd = rows.iter().find(|w| w.pid == pid && w.class == "TDocumentForm").map(|w| w.hwnd);
bridge-rs/src/placement.rs+9−143@@ -1,151 +1,17 @@-//! A placement review before routing: parts whose courtyards (pads and body, grown by a margin) overlap on the same-//! side, parts off the board or over its edge, pads too close to the edge for assembly and depanelling, and parts on a-//! mounting hole.+//! A placement review before routing: courtyard overlaps, parts off or over the board edge, pads near the edge, parts+//! on a mounting hole. The standard's shared engine answers it (vendor/adom-eda-checks `placement`, standard 0.7.0)+//! from the board model and the bodies companion. use serde_json::{json, Value};-use std::collections::BTreeMap;--fn f(v: &Value) -> f64 { v.as_f64().unwrap_or(0.0) }-fn r3(v: f64) -> f64 { (v * 1000.0).round() / 1000.0 }-type Rect = (f64, f64, f64, f64);--fn hit(a: Rect, b: Rect) -> bool { a.0 < b.2 && b.0 < a.2 && a.1 < b.3 && b.1 < a.3 }-fn grow(r: Rect, d: f64) -> Rect { (r.0 - d, r.1 - d, r.2 + d, r.3 + d) }--/// Each part's box (its pads, and its 3D body's box when it has one) and side. Pure.-pub fn part_boxes(st: &Value, bodies: &BTreeMap<String, Rect>) -> BTreeMap<String, (bool, Rect)> {- let mut m: BTreeMap<String, (bool, Rect)> = BTreeMap::new();- let side: BTreeMap<String, bool> = st["components"].as_array().cloned().unwrap_or_default().iter()- .filter_map(|c| Some((c["ref"].as_str()?.to_string(), c["side"] == "bottom"))).collect();- for p in st["pads"].as_array().cloned().unwrap_or_default() {- let Some(r) = p["ref"].as_str().filter(|r| !r.is_empty()) else { continue };- let (c, s) = (f(&p["rotation"]).to_radians().cos().abs(), f(&p["rotation"]).to_radians().sin().abs());- let (hx, hy) = ((f(&p["sizeX"]) * c + f(&p["sizeY"]) * s) / 2.0, (f(&p["sizeX"]) * s + f(&p["sizeY"]) * c) / 2.0);- let b = (f(&p["x"]) - hx, f(&p["y"]) - hy, f(&p["x"]) + hx, f(&p["y"]) + hy);- let e = m.entry(r.to_string()).or_insert((side.get(r).copied().unwrap_or(false), b));- e.1 = (e.1 .0.min(b.0), e.1 .1.min(b.1), e.1 .2.max(b.2), e.1 .3.max(b.3));- }- for (r, b) in bodies {- if let Some(e) = m.get_mut(r) { e.1 = (e.1 .0.min(b.0), e.1 .1.min(b.1), e.1 .2.max(b.2), e.1 .3.max(b.3)); }- }- m-}--/// The review. `ring` is the outline (mm); holes are (x, y, radius) of the board's own drilled, part-less pads. Pure.-pub fn review(boxes: &BTreeMap<String, (bool, Rect)>, pads: &[Value], ring: &[(f64, f64)], holes: &[(f64, f64, f64)], margin: f64, edge: f64) -> Value {- let (bx0, bx1) = ring.iter().fold((f64::MAX, f64::MIN), |a, p| (a.0.min(p.0), a.1.max(p.0)));- let (by0, by1) = ring.iter().fold((f64::MAX, f64::MIN), |a, p| (a.0.min(p.1), a.1.max(p.1)));- 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- };- let dist = |x: f64, y: f64| (0..ring.len()).map(|k| {- let (a, b) = (ring[k], ring[(k + 1) % ring.len()]);- let (dx, dy) = (b.0 - a.0, b.1 - a.1);- let l2 = dx * dx + dy * dy;- let t = if l2 > 0.0 { (((x - a.0) * dx + (y - a.1) * dy) / l2).clamp(0.0, 1.0) } else { 0.0 };- ((a.0 + t * dx - x).powi(2) + (a.1 + t * dy - y).powi(2)).sqrt()- }).fold(f64::MAX, f64::min);- let (mut overlaps, mut off, mut near, mut on_holes) = (Vec::new(), Vec::new(), Vec::new(), Vec::new());- let list: Vec<(&String, &(bool, Rect))> = boxes.iter().collect();- for i in 0..list.len() {- for j in i + 1..list.len() {- let ((ra, (sa, a)), (rb, (sb, b))) = (list[i], list[j]);- if sa == sb && hit(grow(*a, margin), grow(*b, margin)) {- let ov = (a.2.min(b.2) - a.0.max(b.0)).min(a.3.min(b.3) - a.1.max(b.1));- overlaps.push(json!({"parts": [ra, rb], "side": if *sa { "bottom" } else { "top" }, "overlapMm": r3(ov + 2.0 * margin)}));- }- }- }- // on or off the board by its pads' centres: a box's corners fall outside a round board's edge while the part sits- // well inside it (the Bluetooth Sentinel's J1 read as off the board)- let mut pad_in: BTreeMap<&str, (usize, usize)> = BTreeMap::new();- for p in pads {- let Some(r) = p["ref"].as_str().filter(|r| !r.is_empty()) else { continue };- let e = pad_in.entry(r).or_insert((0, 0));- e.0 += 1;- if inside(f(&p["x"]), f(&p["y"])) { e.1 += 1; }- }- let _ = (bx0, bx1, by0, by1);- for (r, (_, b)) in boxes {- let (n, n_in) = pad_in.get(r.as_str()).copied().unwrap_or((0, 0));- if n > 0 && n_in == 0 { off.push(json!({"ref": r, "where": "off the board"})); continue; }- if n_in < n { off.push(json!({"ref": r, "where": "over the board edge"})); continue; }- for (x, y, hr) in holes { if hit(*b, (x - hr, y - hr, x + hr, y + hr)) { on_holes.push(json!({"ref": r, "hole": [r3(*x), r3(*y)]})); } }- }- // pads near the edge: the closest pad of each part- let mut closest: BTreeMap<String, f64> = BTreeMap::new();- for p in pads {- let Some(r) = p["ref"].as_str().filter(|r| !r.is_empty()) else { continue };- // the pad's four corners, turned with it: inside the outline their distance counts, outside it is negative- let (c, s) = (f(&p["rotation"]).to_radians().cos(), f(&p["rotation"]).to_radians().sin());- let (hx, hy) = (f(&p["sizeX"]) / 2.0, f(&p["sizeY"]) / 2.0);- let d = [(-hx, -hy), (hx, -hy), (hx, hy), (-hx, hy)].iter().map(|(u, v)| {- let (x, y) = (f(&p["x"]) + u * c - v * s, f(&p["y"]) + u * s + v * c);- if inside(x, y) { dist(x, y) } else { -dist(x, y) }- }).fold(f64::MAX, f64::min);- let e = closest.entry(r.to_string()).or_insert(f64::MAX);- if d < *e { *e = d; }- }- for (r, d) in &closest {- if *d < edge && !off.iter().any(|o| o["ref"] == json!(r)) { near.push(json!({"ref": r, "padToEdgeMm": r3(*d)})); }- }- let ok = overlaps.is_empty() && off.is_empty() && on_holes.is_empty();- json!({"parts": boxes.len(), "ok": ok, "courtyardOverlaps": overlaps, "offOrOverEdge": off, "onMountingHoles": on_holes, "nearEdge": near, "marginMm": margin, "edgeMm": edge})-} /// altium_placement_check {filePath?, marginMm?, edgeMm?} pub fn placement_check(args: &Value) -> Value { 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 = crate::routing::routing_state(&json!({}));- if st.get("success").and_then(|b| b.as_bool()) != Some(true) { return st; }- let ring = crate::coppermap::outline_ring(&st);- if ring.len() < 3 { return json!({"success": false, "errorCode": "no_outline", "error": "the board has no outline"}); }- // the parts' 3D bodies (silk_state's 'body' box takes in the designator text and made every neighbour overlap)- let rows = crate::agent::call("bodies", &[], None, std::time::Duration::from_secs(120));- let mut bodies: BTreeMap<String, Rect> = BTreeMap::new();- for b in crate::bodies::boxes(&rows.get("data").and_then(|d| d["bodies"].as_array().cloned()).unwrap_or_default()) {- let e = bodies.entry(b.part.clone()).or_insert((b.x0, b.y0, b.x1, b.y1));- *e = (e.0.min(b.x0), e.1.min(b.y0), e.2.max(b.x1), e.3.max(b.y1));- }- let boxes = part_boxes(&st, &bodies);- let pads = st["pads"].as_array().cloned().unwrap_or_default();- let holes: Vec<(f64, f64, f64)> = pads.iter().filter(|p| f(&p["drill"]) > 0.0 && p["ref"].as_str().map(|r| r.is_empty()).unwrap_or(true))- .map(|p| (f(&p["x"]), f(&p["y"]), f(&p["sizeX"]).max(f(&p["drill"])) / 2.0)).collect();- let num = |k: &str, d: f64| args.get(k).and_then(|v| v.as_f64()).unwrap_or(d);- let mut out = review(&boxes, &pads, &ring, &holes, num("marginMm", 0.1), num("edgeMm", 0.5));- out["success"] = json!(true);- out["_hint"] = json!("courtyardOverlaps: parts closer than twice marginMm (their pads and bodies): move them apart (altium_move_parts, altium_find_space). offOrOverEdge parts must come onto the board; nearEdge pads risk the router or the V-cut (JLCPCB: 0.4 mm from a V-cut, 0.2 from a routed edge). onMountingHoles: a screw head lands on the part.");- out-}--#[cfg(test)]-mod tests {- use super::*;-- #[test]- fn placement_review_finds_each_problem() {- let ring = vec![(0.0, 0.0), (40.0, 0.0), (40.0, 20.0), (0.0, 20.0)];- let mut boxes = BTreeMap::new();- boxes.insert("U1".to_string(), (false, (5.0, 5.0, 10.0, 10.0)));- boxes.insert("C1".to_string(), (false, (10.2, 5.0, 11.0, 6.0))); // 0.2 mm from U1: inside 2 x 0.25- boxes.insert("C2".to_string(), (true, (10.2, 5.0, 11.0, 6.0))); // the same spot on the bottom: fine- boxes.insert("J1".to_string(), (false, (38.0, 8.0, 42.0, 12.0))); // over the edge- boxes.insert("R9".to_string(), (false, (50.0, 5.0, 51.0, 6.0))); // off the board- boxes.insert("R2".to_string(), (false, (1.5, 15.5, 2.5, 16.5))); // on the hole at (2, 16)- let pad = |r: &str, x: f64, y: f64| json!({"ref": r, "x": x, "y": y, "sizeX": 0.6, "sizeY": 0.6});- let pads = vec![pad("C1", 10.6, 5.5), pad("U1", 5.2, 0.6), pad("J1", 39.0, 10.0), pad("J1", 41.0, 10.0), pad("R9", 50.5, 5.5)];- let r = review(&boxes, &pads, &ring, &[(2.0, 16.0, 1.6)], 0.25, 0.5);- assert_eq!(r["courtyardOverlaps"].as_array().unwrap().len(), 1);- assert_eq!(r["courtyardOverlaps"][0]["parts"], json!(["C1", "U1"]));- let off: Vec<String> = r["offOrOverEdge"].as_array().unwrap().iter().map(|o| format!("{} {}", o["ref"].as_str().unwrap(), o["where"].as_str().unwrap())).collect();- assert!(off.contains(&"J1 over the board edge".to_string()) && off.contains(&"R9 off the board".to_string()));- assert_eq!(r["onMountingHoles"][0]["ref"], "R2");- assert_eq!(r["nearEdge"][0]["ref"], "U1");- assert_eq!(r["ok"], json!(false));- }+ if st.get("success").and_then(|v| v.as_bool()) != Some(true) { return st; }+ // the parts' 3D bodies (silk_state's 'body' box takes in the designator text and made every neighbour overlap);+ // without them the engine reviews the pads alone and says so (bodiesUsed: false)+ let b = crate::bodies::bodies(&json!({}));+ let b = if b.get("success").and_then(|v| v.as_bool()) == Some(true) { b } else { Value::Null };+ crate::checks::engine("placement_check", &json!({"board": st, "bodies": b, "args": args})) }
bridge-rs/vendor/README.md+1−1@@ -2,7 +2,7 @@ | Folder | From | Version | |---|---|---|-| `adom-eda-checks/` | adom/eda-bridge-standard `engine/` (the shared checks engine) | standard 0.5.1, engine 0.2.1 |+| `adom-eda-checks/` | adom/eda-bridge-standard `engine/` (the shared checks engine) | standard 0.7.0, engine 0.4.0 | | `pcb-design-rules/records/` | adom/pcb-design-rules `rules/records/` (each fab's published limits, with sources and dates) | head of 2026-10-27 | The wiki has no git protocol, so these are copied at a version: refresh both from their pages, then run the tests.
bridge-rs/vendor/adom-eda-checks/Cargo.toml+1−1@@ -1,6 +1,6 @@ [package] name = "adom-eda-checks"-version = "0.2.1"+version = "0.4.0" edition = "2021" description = "The EDA Bridge Standard's checks and board-file writers, computed from the board model JSON: no bridge calls, no tool." license = "MIT"
bridge-rs/vendor/adom-eda-checks/README.md+13−3@@ -16,9 +16,17 @@ boards the engine gives the same answers the Altium bridge 0.2.76 gives. | `fab_check` | board, stack?, rules?, silk?, fab? | the board's smallest features, compared with a fab's limits from adom/pcb-design-rules; each finding names the fab's page and the date it was read | | `impedance` | stack | the track width (and pair gap) for a target impedance on each copper layer; `apply` answers `add_rule` arguments | | `current_capacity` | board, stack? | per net and layer, the narrowest copper against the width the current needs (IPC-2221), and the vias a layer change needs |+| `height_check` | bodies, board? | each part's height on its side, parts over `maxTopMm`/`maxBottomMm` or under a lid region (`regions`), body collisions and near misses (`minGapMm`); `noBody` and `complete: false` when a part has no 3D body |+| `placement_check` | board, bodies? | courtyard overlaps (pads and bodies, grown by `marginMm`), parts off or over the edge, pads within `edgeMm` of the edge, parts on mounting holes; `bodiesUsed: false` when no bodies were given |+| `thermal_vias` | board, rules? | a grid of vias in a part's exposed pad (`ref`, `pad?`), clear of vias already there; `apply` is `place_vias` arguments |+| `via_fence` | board, rules? | vias of `viaNet` both sides of the named nets' tracks and/or round the board edge (`edge`), at `pitchMm` or lambda/20 at `freqGHz`, clear of other copper; `apply` is `place_vias` arguments | -The other checks-tier verbs (assembly, 3D heights, placement, schematic review, pair routing, length tuning,-designators, via fences, panels, the board report) come over from the Altium bridge a module at a time.+The via plans size their vias from `args.size`/`drill`, else the board's via rule (`rules`: `{kind: "via", sizeMm, drillMm}`,+or Altium's Routing Via descriptor), else 0.6/0.3, and say which in `planned.via.from`.++The other checks-tier verbs (assembly, pair routing, length tuning,+designators, panels, the board report, schematic review, and the planners estimate_cost, check_clearance, place_decoupling, plan_fanout+and plan_route) come over a module at a time. ## Writers @@ -45,6 +53,7 @@ Every check takes one JSON object: | `board` | the board model, `<prefix>_routing_state` (`schema/board.schema.json`) | | `stack` | the stack-up companion, `<prefix>_layer_stack` | | `pours` | poured copper, `<prefix>_pour_state` (its `zones`) |+| `bodies` | the 3D bodies companion, `<prefix>_bodies`: `bodies[{ref, side, x0, y0, x1, y1, z0, z1}]` (one box per body or per part) and `noBody` | | `rules` | the board's rules, `<prefix>_read_rules`: a clearance rule as `{kind: "clearance", clearanceMm}` (a `value` with its unit, `"0.1mm"`, works too). Only copper-to-copper clearance counts: a rule whose kind or name names the board edge, mask, silk, paste, holes, a keepout or restrict area, the courtyard or the same net is skipped | | `silk` | `<prefix>_silk_state` | | `fab` | one record from adom/pcb-design-rules `rules/records/<vendor>.json`, with `vendor` |@@ -78,7 +87,8 @@ adom-eda-checks import_svg --svg logo.svg --args '{"at": [10, 10], "widthMm": 20 ``` Replies keep the standard envelope (`success`, `errorCode`, `error`, `_hint`) and name verbs without a prefix-(`apply_pours`, `add_rule`): a bridge adds its own.+(`apply_pours`, `add_rule`, `place_vias`): a bridge adds its own. Every reply also carries `engine`+(`"adom-eda-checks 0.4.0"`), so a bridge reports the engine it runs without writing the version by hand. ## Tests
bridge-rs/vendor/adom-eda-checks/src/bodies.rsadded+187@@ -0,0 +1,187 @@+//! The board in 3D from its parts' bodies (the bodies companion): how tall each part stands on its side, which ones break+//! an enclosure's height limit (board-wide, or under a lid feature in a region), and which bodies collide or come closer+//! than a gap. Bodies are compared as boxes (each body's footprint rectangle and its standoff-to-top range); a part made+//! of several bodies is several boxes, so L-shapes stay honest; a bridge that gives one box per part (Fusion) is the+//! union. The tool's own component clearance DRC checks the real shapes. From the Altium bridge's bodies.rs.+use serde_json::{json, Value};+use std::collections::BTreeMap;++fn r3(v: f64) -> f64 { (v * 1000.0).round() / 1000.0 }+fn f(v: &Value) -> f64 { v.as_f64().unwrap_or(0.0) }++/// One body as a box in mm: its part, side (top/bottom), x and y extent, and z from the board surface it sits on.+#[derive(Debug, Clone)]+pub struct BodyBox { pub part: String, pub top: bool, pub x0: f64, pub y0: f64, pub x1: f64, pub y1: f64, pub z0: f64, pub z1: f64 }++/// The bodies companion (`bodies[{ref, side, x0, y0, x1, y1, z0, z1}]`, mm) as boxes. Pure.+pub fn boxes(rows: &[Value]) -> Vec<BodyBox> {+ rows.iter().filter(|r| r["ref"].as_str().map(|s| !s.is_empty()).unwrap_or(false)).map(|r| BodyBox {+ part: r["ref"].as_str().unwrap_or("").to_string(), top: r["side"].as_str() != Some("bottom"),+ x0: f(&r["x0"]).min(f(&r["x1"])), y0: f(&r["y0"]).min(f(&r["y1"])), x1: f(&r["x0"]).max(f(&r["x1"])), y1: f(&r["y0"]).max(f(&r["y1"])),+ z0: f(&r["z0"]), z1: f(&r["z1"]),+ }).collect()+}++/// The input's bodies: the companion's `bodies`, or the companion given as a bare list.+pub fn input_boxes(input: &Value) -> Option<Vec<BodyBox>> {+ let b = crate::input::part(input, "bodies")?;+ let rows = b.get("bodies").or(Some(&b)).and_then(|x| x.as_array()).cloned()?;+ Some(boxes(&rows))+}++/// Parts on the board with no body: the companion's `noBody`, and every board part the boxes leave out.+fn no_body(input: &Value, bs: &[BodyBox]) -> Vec<Value> {+ let with: std::collections::BTreeSet<&str> = bs.iter().map(|b| b.part.as_str()).collect();+ let mut out: Vec<String> = crate::input::part(input, "bodies").and_then(|b| b["noBody"].as_array().cloned()).unwrap_or_default()+ .iter().filter_map(|v| v.as_str().map(String::from)).collect();+ if let Ok(st) = crate::input::board(input) {+ for r in st["components"].as_array().cloned().unwrap_or_default().iter().filter_map(|c| c["ref"].as_str().map(String::from)) {+ if !with.contains(r.as_str()) && !out.contains(&r) { out.push(r); }+ }+ }+ out.into_iter().map(Value::from).collect()+}++/// Each part's height above its side and its footprint in mm, tallest first.+pub fn heights(bs: &[BodyBox]) -> Vec<Value> {+ let mut m: BTreeMap<&str, (bool, f64, f64, f64, f64, f64)> = BTreeMap::new();+ for b in bs {+ let e = m.entry(&b.part).or_insert((b.top, 0.0, f64::MAX, f64::MAX, f64::MIN, f64::MIN));+ e.1 = e.1.max(b.z1);+ e.2 = e.2.min(b.x0); e.3 = e.3.min(b.y0); e.4 = e.4.max(b.x1); e.5 = e.5.max(b.y1);+ }+ let mut v: Vec<Value> = m.into_iter().map(|(p, (top, h, x0, y0, x1, y1))| json!({"ref": p, "side": if top { "top" } else { "bottom" }, "heightMm": r3(h), "rect": [r3(x0), r3(y0), r3(x1), r3(y1)]})).collect();+ v.sort_by(|a, b| b["heightMm"].as_f64().partial_cmp(&a["heightMm"].as_f64()).unwrap());+ v+}++/// Body pairs of different parts on the same side that overlap in 3D (`collisions`), or whose boxes come within+/// `gap` mm of each other in x and y where their heights overlap (`tooClose`). Pure.+pub fn clashes(bs: &[BodyBox], gap: f64) -> (Vec<Value>, Vec<Value>) {+ let mut idx: Vec<usize> = (0..bs.len()).collect();+ idx.sort_by(|a, b| bs[*a].x0.partial_cmp(&bs[*b].x0).unwrap());+ let mut seen: BTreeMap<(String, String), (bool, f64, Value)> = BTreeMap::new();+ for (k, &i) in idx.iter().enumerate() {+ let a = &bs[i];+ for &j in &idx[k + 1..] {+ let b = &bs[j];+ if b.x0 > a.x1 + gap { break; }+ if a.part == b.part || a.top != b.top { continue; }+ let dz = a.z1.min(b.z1) - a.z0.max(b.z0);+ if dz <= 0.0 { continue; } // one sits above the other (a part under a connector's overhang)+ let dx = (b.x0 - a.x1).max(a.x0 - b.x1);+ let dy = (b.y0 - a.y1).max(a.y0 - b.y1);+ let (hit, d) = if dx < 0.0 && dy < 0.0 { (true, -(dx.max(dy))) } else { (false, (dx.max(0.0).powi(2) + dy.max(0.0).powi(2)).sqrt()) };+ if !hit && d >= gap { continue; }+ let key = if a.part < b.part { (a.part.clone(), b.part.clone()) } else { (b.part.clone(), a.part.clone()) };+ let at = json!([r3((a.x0.max(b.x0) + a.x1.min(b.x1)) / 2.0), r3((a.y0.max(b.y0) + a.y1.min(b.y1)) / 2.0)]);+ // per pair keep the worst: a collision over a near miss, then the deepest or the closest+ let worse = match seen.get(&key) { None => true, Some((h, v, _)) => (hit && !h) || (hit == *h && if hit { d > *v } else { d < *v }) };+ if worse { seen.insert(key, (hit, d, at)); }+ }+ }+ let (mut col, mut near) = (Vec::new(), Vec::new());+ for ((p, q), (hit, d, at)) in seen {+ if hit { col.push(json!({"parts": [p, q], "overlapMm": r3(d), "at": at})); } else { near.push(json!({"parts": [p, q], "gapMm": r3(d), "at": at})); }+ }+ (col, near)+}++/// height_check: input {bodies, board?, args: {maxTopMm?, maxBottomMm?, regions?: [{rect, maxMm, side?, name?}], minGapMm?, limit?}}.+/// `board` names the parts with no body (they have no height, and the reply says the check is not complete).+pub fn height_check(input: &Value) -> Value {+ let args = &input["args"];+ let Some(bs) = input_boxes(input) else { return crate::input::refuse("no_bodies", "the input has no bodies: pass the bodies companion (<prefix>_bodies) as bodies") };+ let hs = heights(&bs);+ let num = |k: &str| args.get(k).and_then(|v| v.as_f64());+ let mut over = Vec::new();+ for (side, lim) in [("top", num("maxTopMm")), ("bottom", num("maxBottomMm"))] {+ let Some(lim) = lim else { continue };+ for h in hs.iter().filter(|h| h["side"] == side) {+ let mm = h["heightMm"].as_f64().unwrap_or(0.0);+ if mm > lim { over.push(json!({"ref": h["ref"], "side": side, "heightMm": mm, "limitMm": lim, "overByMm": r3(mm - lim)})); }+ }+ }+ // a region is a lid feature over part of the board (a boss, a rib, a display): parts under it must stay lower+ let mut region_hits = Vec::new();+ for (i, rg) in args.get("regions").and_then(|v| v.as_array()).cloned().unwrap_or_default().iter().enumerate() {+ let rc: Vec<f64> = rg["rect"].as_array().map(|a| a.iter().filter_map(|v| v.as_f64()).collect()).unwrap_or_default();+ let Some(max) = rg["maxMm"].as_f64() else { return json!({"success": false, "errorCode": "bad_args", "error": "each region is {rect:[x1,y1,x2,y2], maxMm, side?, name?}"}) };+ if rc.len() != 4 { return json!({"success": false, "errorCode": "bad_args", "error": "region.rect is [x1, y1, x2, y2] in mm"}); }+ let (rx0, ry0, rx1, ry1) = (rc[0].min(rc[2]), rc[1].min(rc[3]), rc[0].max(rc[2]), rc[1].max(rc[3]));+ let top = rg["side"].as_str() != Some("bottom");+ let name = rg["name"].as_str().map(|s| s.to_string()).unwrap_or(format!("region {}", i + 1));+ let mut worst: BTreeMap<&str, f64> = BTreeMap::new();+ for b in bs.iter().filter(|b| b.top == top && b.x1 > rx0 && b.x0 < rx1 && b.y1 > ry0 && b.y0 < ry1 && b.z1 > max) {+ let e = worst.entry(&b.part).or_insert(0.0);+ *e = e.max(b.z1);+ }+ for (p, h) in worst { region_hits.push(json!({"region": name, "ref": p, "heightMm": r3(h), "maxMm": max, "overByMm": r3(h - max)})); }+ }+ let gap = num("minGapMm").unwrap_or(0.0);+ let (collisions, too_close) = clashes(&bs, gap);+ // parts with no body have no height: say so, a height check that skips them is not a pass+ let no_body = no_body(input, &bs);+ let tallest = |side: &str| hs.iter().find(|h| h["side"] == side).cloned().unwrap_or(Value::Null);+ let ok = over.is_empty() && region_hits.is_empty() && collisions.is_empty() && too_close.is_empty();+ json!({"success": true, "ok": ok, "complete": no_body.is_empty(), "bodies": bs.len(), "parts": hs.len(), "tallest": {"top": tallest("top"), "bottom": tallest("bottom")},+ "overLimit": over, "regionHits": region_hits, "collisions": collisions, "tooClose": too_close, "minGapMm": gap,+ "noBody": no_body, "heights": hs.iter().take(args.get("limit").and_then(|v| v.as_u64()).unwrap_or(25) as usize).collect::<Vec<_>>(),+ "_hint": "Heights are each part's tallest body above the surface it sits on (bottom-side parts below the bottom). collisions and tooClose compare body boxes; the tool's component clearance DRC (run_drc) checks the real shapes. ok covers the parts that have bodies; complete is false while noBody lists parts with no 3D body and so no height: give them one (add_body) before trusting the check."})+}++#[cfg(test)]+mod tests {+ use super::*;++ fn bx(p: &str, top: bool, x0: f64, y0: f64, x1: f64, y1: f64, z0: f64, z1: f64) -> BodyBox {+ BodyBox { part: p.into(), top, x0, y0, x1, y1, z0, z1 }+ }++ #[test]+ fn the_companion_becomes_boxes() {+ let b = boxes(&[json!({"ref": "J1", "side": "bottom", "x0": 10.0, "y0": 5.0, "x1": 0.0, "y1": 0.0, "z0": 0.0, "z1": 4.1}), json!({"ref": "", "x0": 1})]);+ assert_eq!(b.len(), 1);+ assert!(!b[0].top && (b[0].z1 - 4.1).abs() < 1e-9 && (b[0].x1 - 10.0).abs() < 1e-9 && b[0].x0 == 0.0);+ }++ #[test]+ fn heights_take_each_parts_tallest_body() {+ let bs = vec![bx("J1", true, 0.0, 0.0, 10.0, 5.0, 0.0, 3.2), bx("J1", true, 0.0, 0.0, 10.0, 5.0, 4.0, 4.1), bx("R1", true, 20.0, 0.0, 21.0, 0.5, 0.0, 0.4)];+ let h = heights(&bs);+ assert_eq!(h[0]["ref"], "J1");+ assert_eq!(h[0]["heightMm"], 4.1);+ assert_eq!(h[1]["rect"], json!([20.0, 0.0, 21.0, 0.5]));+ }++ #[test]+ fn clashes_find_overlaps_near_misses_and_ignore_stacked_and_opposite_sides() {+ let bs = vec![+ bx("U1", true, 0.0, 0.0, 5.0, 5.0, 0.0, 1.0),+ bx("C1", true, 4.0, 1.0, 6.0, 2.0, 0.0, 0.5), // overlaps U1 by 1 mm in x+ bx("C2", true, 5.2, 3.0, 6.0, 4.0, 0.0, 0.5), // 0.2 mm from U1+ bx("C3", false, 1.0, 1.0, 2.0, 2.0, 0.0, 0.5), // under U1, other side+ bx("D1", true, 1.0, 1.0, 2.0, 2.0, 1.5, 2.0), // above U1's top+ ];+ let (col, near) = clashes(&bs, 0.3);+ assert_eq!(col.len(), 1);+ assert_eq!(col[0]["parts"], json!(["C1", "U1"]));+ assert_eq!(col[0]["overlapMm"], 1.0);+ assert_eq!(near.len(), 1);+ assert_eq!(near[0]["parts"], json!(["C2", "U1"]));+ assert_eq!(near[0]["gapMm"], 0.2);+ assert!(clashes(&bs, 0.0).1.is_empty());+ }++ #[test]+ fn height_check_reads_the_companion_and_names_parts_without_bodies() {+ let input = json!({"board": {"components": [{"ref": "U1"}, {"ref": "R7"}]},+ "bodies": {"bodies": [{"ref": "U1", "side": "top", "x0": 0.0, "y0": 0.0, "x1": 5.0, "y1": 5.0, "z0": 0.0, "z1": 2.0}], "noBody": []},+ "args": {"maxTopMm": 1.5}});+ let r = height_check(&input);+ assert_eq!(r["overLimit"][0]["ref"], "U1");+ assert_eq!(r["noBody"], json!(["R7"]));+ assert_eq!(r["complete"], json!(false));+ assert_eq!(height_check(&json!({"args": {}}))["errorCode"], "no_bodies");+ }+}
bridge-rs/vendor/adom-eda-checks/src/features.rsadded+411@@ -0,0 +1,411 @@+//! Via plans computed from the board model: thermal vias in a part's exposed pad and a via fence along RF tracks or the+//! board edge (and the stitching grid behind board_features). From the Altium bridge's features.rs. Plans only: each+//! answers the vias as place_vias arguments, and the bridge places them.+use serde_json::{json, Value};++fn f(v: &Value) -> f64 { v.as_f64().unwrap_or(0.0) }+fn pt(v: &Value) -> (f64, f64) { (f(&v[0]), f(&v[1])) }++fn inside(poly: &[(f64, f64)], x: f64, y: f64) -> bool {+ let mut c = false;+ let n = poly.len();+ for i in 0..n {+ let (a, b) = (poly[i], poly[(i + n - 1) % n]);+ if (a.1 > y) != (b.1 > y) && x < (b.0 - a.0) * (y - a.1) / (b.1 - a.1) + a.0 { c = !c; }+ }+ c+}++fn seg_dist(px: f64, py: f64, a: (f64, f64), b: (f64, f64)) -> f64 {+ let (dx, dy) = (b.0 - a.0, b.1 - a.1);+ let l2 = dx * dx + dy * dy;+ let t = if l2 == 0.0 { 0.0 } else { (((px - a.0) * dx + (py - a.1) * dy) / l2).clamp(0.0, 1.0) };+ ((px - a.0 - t * dx).powi(2) + (py - a.1 - t * dy).powi(2)).sqrt()+}++/// Copper that a stitching via on `net` must keep clear of: (kind, geometry, half-width) as segments and discs.+enum Ob { Seg((f64, f64), (f64, f64), f64), Disc(f64, f64, f64) }++fn obstacles(state: &Value, net: &str) -> (Vec<Ob>, Vec<(f64, f64)>) {+ // copper on another net. Lines on mechanical and overlay layers are not copper, and net-less copper tracks are a+ // hatched pour's pieces (Altium lists them with no net) that re-pour round a new via+ let other = |v: &Value| {+ let n = v["net"].as_str().unwrap_or("");+ let copper = v.get("layer").map(|l| l.as_str().map(|s| s.ends_with(".Cu")).unwrap_or(false)).unwrap_or(true);+ let piece = n.is_empty() && v.get("start").or(v.get("center")).is_some();+ copper && !piece && !n.eq_ignore_ascii_case(net)+ };+ let mut ob = Vec::new();+ let mut same_vias = Vec::new();+ for t in state["tracks"].as_array().cloned().unwrap_or_default() {+ if other(&t) { ob.push(Ob::Seg((f(&t["start"]["x"]), f(&t["start"]["y"])), (f(&t["end"]["x"]), f(&t["end"]["y"])), f(&t["width"]) / 2.0)); }+ }+ for a in state["arcs"].as_array().cloned().unwrap_or_default() {+ if !other(&a) { continue; }+ // an arc as short chords+ let (cx, cy, r) = (f(&a["center"]["x"]), f(&a["center"]["y"]), f(&a["radius"]));+ let (mut a1, a2) = (f(&a["startAngle"]), f(&a["endAngle"]));+ let mut span = a2 - a1;+ if span <= 0.0 { span += 360.0; }+ let n = ((span / 10.0).ceil() as usize).max(1);+ let p = |deg: f64| (cx + r * deg.to_radians().cos(), cy + r * deg.to_radians().sin());+ for _ in 0..n { let b = a1 + span / n as f64; ob.push(Ob::Seg(p(a1), p(b), f(&a["width"]) / 2.0)); a1 = b; }+ }+ for v in state["vias"].as_array().cloned().unwrap_or_default() {+ let (x, y) = (f(&v["position"]["x"]), f(&v["position"]["y"]));+ if other(&v) { ob.push(Ob::Disc(x, y, f(&v["size"]) / 2.0)); } else { same_vias.push((x, y)); }+ }+ for p in state["pads"].as_array().cloned().unwrap_or_default() {+ // a pad on the net still gets clearance: a via in a pad is not stitching. Its circumscribed circle keeps it+ // conservative at any rotation.+ let r = (f(&p["sizeX"]).powi(2) + f(&p["sizeY"]).powi(2)).sqrt() / 2.0;+ ob.push(Ob::Disc(f(&p["x"]), f(&p["y"]), r.max(f(&p["drill"]) / 2.0)));+ }+ (ob, same_vias)+}++/// Where stitching vias for `net` go: a grid at `pitch` inside the outline (or `region`), `edge` mm clear of the+/// board edge, `clearance` mm clear of copper on other nets and of every pad, half a pitch from vias the net already+/// has, at most `max`. Pure, for the tests.+#[allow(clippy::too_many_arguments)]+pub fn plan_stitching(state: &Value, net: &str, pitch: f64, size: f64, clearance: f64, edge: f64, region: Option<&[(f64, f64)]>, max: usize) -> Vec<(f64, f64)> {+ plan_stitching_with(state, net, pitch, size, clearance, edge, region, max, &[], true, &[])+}++/// plan_stitching, also clear of `extra` discs (x, y, radius: holes and fiducials placed in the same call) and, with+/// `avoid_parts`, out from under every part (the box around its pads, grown by the clearance).+#[allow(clippy::too_many_arguments)]+pub fn plan_stitching_with(state: &Value, net: &str, pitch: f64, size: f64, clearance: f64, edge: f64, region: Option<&[(f64, f64)]>, max: usize,+ extra: &[(f64, f64, f64)], avoid_parts: bool, keepouts: &[(f64, f64, f64, f64)]) -> Vec<(f64, f64)> {+ let outline: Vec<(f64, f64)> = state["outline"].as_array().cloned().unwrap_or_default().iter().map(pt).collect();+ if outline.len() < 3 || pitch <= 0.0 { return vec![]; }+ let area: Vec<(f64, f64)> = region.map(|r| r.to_vec()).unwrap_or_else(|| outline.clone());+ let (mut ob, same) = obstacles(state, net);+ for (x, y, r) in extra { ob.push(Ob::Disc(*x, *y, *r)); }+ // each part's pad box: a via between a chip's pad rows sits under its body+ let mut boxes: std::collections::BTreeMap<String, (f64, f64, f64, f64)> = Default::default();+ if avoid_parts {+ for p in state["pads"].as_array().cloned().unwrap_or_default() {+ let Some(r) = p["ref"].as_str().filter(|r| !r.is_empty()) else { continue };+ let h = (f(&p["sizeX"]).powi(2) + f(&p["sizeY"]).powi(2)).sqrt() / 2.0;+ let (x, y) = (f(&p["x"]), f(&p["y"]));+ let b = boxes.entry(r.to_string()).or_insert((f64::MAX, f64::MAX, f64::MIN, f64::MIN));+ *b = (b.0.min(x - h), b.1.min(y - h), b.2.max(x + h), b.3.max(y + h));+ }+ }+ let (x0, x1) = area.iter().fold((f64::MAX, f64::MIN), |a, p| (a.0.min(p.0), a.1.max(p.0)));+ let (y0, y1) = area.iter().fold((f64::MAX, f64::MIN), |a, p| (a.0.min(p.1), a.1.max(p.1)));+ let mut cands = Vec::new();+ let mut y = y0 + pitch / 2.0;+ while y < y1 {+ let mut x = x0 + pitch / 2.0;+ while x < x1 { if inside(&area, x, y) { cands.push((x, y)); } x += pitch; }+ y += pitch;+ }+ keep_clear(state, &outline, &cands, pitch / 2.0, size, clearance, edge, max, &ob, &same, &boxes, keepouts)+}++/// The candidate via points that fit: inside the outline, `edge` from it, `clearance` from other copper (`ob`), out of+/// part boxes and keepouts, and `sep` from the net's vias and from each other. Pure.+#[allow(clippy::too_many_arguments)]+fn keep_clear(_state: &Value, outline: &[(f64, f64)], cands: &[(f64, f64)], sep: f64, size: f64, clearance: f64, edge: f64, max: usize, ob: &[Ob],+ same: &[(f64, f64)], boxes: &std::collections::BTreeMap<String, (f64, f64, f64, f64)>, keepouts: &[(f64, f64, f64, f64)]) -> Vec<(f64, f64)> {+ let r = size / 2.0;+ let mut out: Vec<(f64, f64)> = Vec::new();+ for &(x, y) in cands {+ if out.len() >= max { break; }+ let ok = inside(outline, x, y)+ && (0..outline.len()).all(|k| seg_dist(x, y, outline[k], outline[(k + 1) % outline.len()]) >= edge + r)+ && ob.iter().all(|o| match o {+ Ob::Seg(a, b, hw) => seg_dist(x, y, *a, *b) - hw - r >= clearance,+ Ob::Disc(cx, cy, cr) => ((x - cx).powi(2) + (y - cy).powi(2)).sqrt() - cr - r >= clearance,+ })+ && same.iter().chain(out.iter()).all(|(sx, sy)| ((x - sx).powi(2) + (y - sy).powi(2)).sqrt() >= sep)+ && boxes.values().all(|b| x + r + clearance <= b.0 || x - r - clearance >= b.2 || y + r + clearance <= b.1 || y - r - clearance >= b.3)+ && keepouts.iter().all(|k| x + r <= k.0 || x - r >= k.2 || y + r <= k.1 || y - r >= k.3);+ if ok { out.push(((x * 1000.0).round() / 1000.0, (y * 1000.0).round() / 1000.0)); }+ }+ out+}++/// Via fence candidates: both sides of every copper track of `nets`, `offset` from its centreline, every `pitch` along+/// it; and with `edge_inset`, along the outline that far inside it. Pure.+pub fn fence_points(state: &Value, nets: &[String], pitch: f64, offset: f64, edge_inset: Option<f64>) -> Vec<(f64, f64)> {+ let mut v = Vec::new();+ for t in state["tracks"].as_array().cloned().unwrap_or_default() {+ let n = t["net"].as_str().unwrap_or("");+ if !nets.iter().any(|x| x.eq_ignore_ascii_case(n)) || !t["layer"].as_str().map(|l| l.ends_with(".Cu")).unwrap_or(false) { continue; }+ let (a, b) = ((f(&t["start"]["x"]), f(&t["start"]["y"])), (f(&t["end"]["x"]), f(&t["end"]["y"])));+ let len = ((b.0 - a.0).powi(2) + (b.1 - a.1).powi(2)).sqrt();+ if len <= 0.0 { continue; }+ let (ux, uy) = ((b.0 - a.0) / len, (b.1 - a.1) / len);+ let k = (len / pitch).floor() as usize;+ for i in 0..=k {+ let s = if k == 0 { len / 2.0 } else { i as f64 * len / k as f64 };+ for side in [1.0, -1.0] { v.push((a.0 + ux * s - uy * offset * side, a.1 + uy * s + ux * offset * side)); }+ }+ }+ if let Some(inset) = edge_inset {+ let ring = crate::coppermap::outline_ring(state);+ let n = ring.len();+ // inward is left of each edge on a counterclockwise ring+ let area: f64 = (0..n).map(|k| ring[k].0 * ring[(k + 1) % n].1 - ring[(k + 1) % n].0 * ring[k].1).sum();+ let sgn = if area > 0.0 { 1.0 } else { -1.0 };+ let mut carry: f64 = 0.0;+ for k in 0..n {+ let (a, b) = (ring[k], ring[(k + 1) % n]);+ let len = ((b.0 - a.0).powi(2) + (b.1 - a.1).powi(2)).sqrt();+ if len <= 0.0 { continue; }+ let (ux, uy) = ((b.0 - a.0) / len, (b.1 - a.1) / len);+ // clear of the corners by the inset, where an inward step from one edge lands on the next+ let mut s = carry.max(inset);+ while s <= len - inset { v.push((a.0 + ux * s - uy * inset * sgn, a.1 + uy * s + ux * inset * sgn)); s += pitch; }+ carry = (s - len).max(0.0);+ }+ }+ v+}++/// The board's preferred via (diameter, drill) in mm. A standard rule gives it as `{kind: "via", sizeMm, drillMm}`; Altium's+/// Routing Via descriptor is read too, e.g. "Routing Via (MinHoleWidth=0.3mm) ... (PreferredHoleWidth=0.3mm) ...+/// (PreferedWidth=0.5mm) (All)" (Altium's own spelling). Pure.+pub fn via_style(rules: &[Value]) -> Option<(f64, f64)> {+ if let Some(r) = rules.iter().filter(|r| r["enabled"] != json!(false))+ .find(|r| r["kind"].as_str().map(|k| k.eq_ignore_ascii_case("via")).unwrap_or(false) && r["sizeMm"].as_f64().is_some() && r["drillMm"].as_f64().is_some()) {+ return Some((f(&r["sizeMm"]), f(&r["drillMm"])));+ }+ let num = |d: &str, key: &str| -> Option<f64> {+ let i = d.find(&format!("({key}="))? + key.len() + 2;+ let s = &d[i..d[i..].find(')')? + i];+ let (v, unit) = s.trim_end_matches(char::is_alphabetic).parse::<f64>().ok().map(|v| (v, &s[s.trim_end_matches(char::is_alphabetic).len()..]))?;+ Some(if unit.eq_ignore_ascii_case("mil") { v * 0.0254 } else { v })+ };+ let mut rs: Vec<&Value> = rules.iter().filter(|r| r["enabled"] != json!(false) && r["descriptor"].as_str().map(|d| d.starts_with("Routing Via")).unwrap_or(false)).collect();+ // the board-wide rule (scope All), highest priority first+ rs.sort_by_key(|r| (r["scope1"].as_str() != Some("All"), r["priority"].as_i64().unwrap_or(99)));+ let d = rs.first()?["descriptor"].as_str()?;+ Some((num(d, "PreferedWidth").or(num(d, "PreferredWidth"))?, num(d, "PreferredHoleWidth")?))+}+++/// Thermal via grid points inside a pad (x, y, sx, sy, rotation mm): `pitch` apart, `inset` from the pad's edge plus+/// the via's radius, centred. Pure.+pub fn thermal_grid(x: f64, y: f64, sx: f64, sy: f64, rot: f64, pitch: f64, size: f64, inset: f64) -> Vec<(f64, f64)> {+ let (ux, uy) = (sx / 2.0 - inset - size / 2.0, sy / 2.0 - inset - size / 2.0);+ if ux < 0.0 || uy < 0.0 { return vec![]; }+ let (nx, ny) = ((2.0 * ux / pitch).floor() as i64 + 1, (2.0 * uy / pitch).floor() as i64 + 1);+ let (c, s) = (rot.to_radians().cos(), rot.to_radians().sin());+ let mut out = Vec::new();+ for i in 0..nx { for j in 0..ny {+ let (lx, ly) = ((i as f64 - (nx - 1) as f64 / 2.0) * pitch, (j as f64 - (ny - 1) as f64 / 2.0) * pitch);+ out.push((((x + lx * c - ly * s) * 1000.0).round() / 1000.0, ((y + lx * s + ly * c) * 1000.0).round() / 1000.0));+ } }+ out+}++/// The via each plan uses: `size`/`drill` from args, else the board's via rule (`rules`), else 0.6/0.3; with where it came from.+fn via_of(input: &Value) -> (f64, f64, &'static str) {+ let args = &input["args"];+ let style = via_style(&crate::input::rules(input));+ let from = if args.get("size").is_some() { "size/drill" } else if style.is_some() { "the board's via rule" } else { "default 0.6/0.3" };+ (num(args, "size", style.map(|s| s.0).unwrap_or(0.6)), num(args, "drill", style.map(|s| s.1).unwrap_or(0.3)), from)+}++/// The plan as place_vias arguments.+fn apply_of(pts: &[(f64, f64)], net: &str, size: f64, drill: f64) -> Value {+ json!({"verb": "place_vias", "args": {"vias": pts.iter().map(|(x, y)| json!({"net": net, "x": x, "y": y, "size": size, "drill": drill})).collect::<Vec<_>>()}})+}++/// thermal_vias: input {board, rules?, args: {ref, pad?, pitchMm?, size?, drill?, insetMm?}}. A grid of vias inside the part's+/// exposed pad (the one named, else its largest), clear of vias already there. Plans only: `apply` is place_vias' arguments.+pub fn thermal_vias(input: &Value) -> Value {+ let st = match crate::input::board(input) { Ok(b) => b, Err(e) => return e };+ let args = &input["args"];+ let Some(rf) = args["ref"].as_str() else { return crate::input::refuse("bad_args", "ref names the part (e.g. U3)") };+ let pads: Vec<Value> = st["pads"].as_array().cloned().unwrap_or_default().into_iter().filter(|p| p["ref"].as_str().map(|r| r.eq_ignore_ascii_case(rf)).unwrap_or(false)).collect();+ if pads.is_empty() { return crate::input::refuse("part_not_found", &format!("{rf} has no pads on this board")); }+ let pad = match args["pad"].as_str() {+ Some(n) => pads.iter().find(|p| p["name"].as_str().map(|x| x.eq_ignore_ascii_case(n)).unwrap_or(false)).cloned(),+ None => pads.iter().max_by(|a, b| (f(&a["sizeX"]) * f(&a["sizeY"])).partial_cmp(&(f(&b["sizeX"]) * f(&b["sizeY"]))).unwrap()).cloned(),+ };+ let Some(pad) = pad else { return json!({"success": false, "errorCode": "no_such_pad", "error": "that pad is not on the part", "pads": pads.iter().map(|p| p["name"].clone()).collect::<Vec<_>>()}) };+ let net = pad["net"].as_str().unwrap_or("").to_string();+ if net.is_empty() { return crate::input::refuse("pad_has_no_net", &format!("{rf}.{} is on no net: thermal vias would float", pad["name"].as_str().unwrap_or(""))); }+ let (size, drill, from) = via_of(input);+ let pitch = num(args, "pitchMm", (size + 0.5).max(1.0));+ let inset = num(args, "insetMm", 0.1);+ let grid = thermal_grid(f(&pad["x"]), f(&pad["y"]), f(&pad["sizeX"]), f(&pad["sizeY"]), f(&pad["rotation"]), pitch, size, inset);+ // keep clear of vias already there: the Bluetooth Sentinel's U4 pad had 8, and a grid laid over them broke Altium's+ // hole-to-hole rule 8 times (2026-10-26)+ let vias: Vec<(f64, f64, f64)> = st["vias"].as_array().cloned().unwrap_or_default().iter().map(|v| (f(&v["position"]["x"]), f(&v["position"]["y"]), f(&v["size"]))).collect();+ let half = f(&pad["sizeX"]).max(f(&pad["sizeY"])) / 2.0;+ let existing = vias.iter().filter(|(x, y, _)| (x - f(&pad["x"])).abs() <= half && (y - f(&pad["y"])).abs() <= half).count();+ let pts: Vec<(f64, f64)> = grid.iter().cloned().filter(|(x, y)| vias.iter().all(|(vx, vy, vs)| ((x - vx).powi(2) + (y - vy).powi(2)).sqrt() >= size / 2.0 + vs / 2.0 + 0.2)).collect();+ let planned = json!({"part": rf, "pad": pad["name"], "net": net, "padMm": [pad["sizeX"], pad["sizeY"]], "vias": pts.len(), "existingVias": existing, "skippedNearExisting": grid.len() - pts.len(), "pitchMm": pitch,+ "via": {"sizeMm": size, "drillMm": drill, "from": from}, "points": pts.iter().map(|(x, y)| json!([x, y])).collect::<Vec<_>>()});+ if pts.is_empty() {+ return json!({"success": existing > 0, "errorCode": if existing > 0 { "already_has_vias" } else { "pad_too_small" }, "error": if existing > 0 { "the pad's existing vias leave no room for more at this pitch" } else { "no via fits inside the pad at this size and inset" }, "planned": planned});+ }+ json!({"success": true, "planned": planned, "apply": apply_of(&pts, &net, size, drill),+ "_hint": "A plan only: run place_vias with apply.args. Vias inside the pad carry its heat to the other layers' copper: pour the net on the far side (apply_pours) so they have somewhere to go. Open vias in a pad wick solder: ask the fab to tent or plug them, or use 0.3 mm or smaller drills. run_drc afterwards."})+}++/// via_fence: input {board, rules?, args: {viaNet, nets?, edge?, pitchMm?, freqGHz?, offsetMm?, edgeInsetMm?, size?, drill?,+/// clearance?}}. Vias of viaNet both sides of the named nets' tracks and/or round the board edge, clear of other copper.+/// Plans only: `apply` is place_vias' arguments.+pub fn via_fence(input: &Value) -> Value {+ let st = match crate::input::board(input) { Ok(b) => b, Err(e) => return e };+ let args = &input["args"];+ let Some(via_net) = args["viaNet"].as_str() else { return crate::input::refuse("bad_args", "viaNet is the net the fence ties to, usually GND") };+ if !st["nets"].as_array().map(|a| a.iter().any(|n| n.as_str().map(|s| s.eq_ignore_ascii_case(via_net)).unwrap_or(false))).unwrap_or(false) {+ return json!({"success": false, "errorCode": "no_such_net", "error": format!("{via_net} is not a net on this board"), "nets": st["nets"]});+ }+ let nets: Vec<String> = args.get("nets").and_then(|v| v.as_array()).map(|a| a.iter().filter_map(|v| v.as_str().map(String::from)).collect()).unwrap_or_default();+ let edge_on = args.get("edge").and_then(|b| b.as_bool()).unwrap_or(false);+ if nets.is_empty() && !edge_on { return crate::input::refuse("bad_args", "name nets to fence (e.g. [\"ANT_RF\"]) and/or edge:true for a fence round the board edge"); }+ // the via the board's own via rule prefers, so the fence passes its DRC (0.6/0.3 broke the Bluetooth Sentinel+ // example's 0.5/0.3 rule on every via)+ let (size, drill, from) = via_of(input);+ let clearance = num(args, "clearance", 0.2);+ // lambda/20 in FR-4 (effective er about 3.4) at the highest frequency, else 2 mm+ let pitch = match args.get("freqGHz").and_then(|v| v.as_f64()) { Some(g) if g > 0.0 => (299.79 / g / 3.4f64.sqrt() / 20.0).min(num(args, "pitchMm", f64::MAX)), _ => num(args, "pitchMm", 2.0) };+ let widest = st["tracks"].as_array().cloned().unwrap_or_default().iter().filter(|t| nets.iter().any(|n| t["net"].as_str().map(|s| s.eq_ignore_ascii_case(n)).unwrap_or(false))).map(|t| f(&t["width"])).fold(0.0, f64::max);+ let offset = num(args, "offsetMm", widest / 2.0 + clearance + size / 2.0 + 0.1);+ let inset = if edge_on { Some(num(args, "edgeInsetMm", size / 2.0 + 0.5)) } else { None };+ let cands = fence_points(&st, &nets, pitch, offset, inset);+ let outline: Vec<(f64, f64)> = crate::coppermap::outline_ring(&st);+ let (ob, same) = obstacles(&st, via_net);+ let pts = keep_clear(&st, &outline, &cands, pitch * 0.6, size, clearance, 0.3, 5000, &ob, &same, &Default::default(), &[]);+ let planned = json!({"vias": pts.len(), "candidates": cands.len(), "via": {"sizeMm": size, "drillMm": drill, "from": from}, "pitchMm": (pitch * 1000.0).round() / 1000.0,+ "offsetMm": (offset * 1000.0).round() / 1000.0, "points": pts.iter().map(|(x, y)| json!([x, y])).collect::<Vec<_>>()});+ if pts.is_empty() {+ return json!({"success": false, "errorCode": "no_room", "error": "no fence via fits", "planned": planned, "_hint": "Lower clearance or size, change offsetMm, or check the nets have tracks."});+ }+ json!({"success": true, "planned": planned, "apply": apply_of(&pts, via_net, size, drill),+ "_hint": "A plan only: run place_vias with apply.args, then repour so pours join the vias, then run_drc. candidates - vias are the spots where other copper, a pad or the edge was too close."})+}++/// The four corner positions of the outline's bounding box, `inset` mm in.+pub fn corners(state: &Value, inset: f64) -> Vec<(f64, f64)> {+ let o: Vec<(f64, f64)> = state["outline"].as_array().cloned().unwrap_or_default().iter().map(pt).collect();+ if o.is_empty() { return vec![]; }+ let (x0, x1) = o.iter().fold((f64::MAX, f64::MIN), |a, p| (a.0.min(p.0), a.1.max(p.0)));+ let (y0, y1) = o.iter().fold((f64::MAX, f64::MIN), |a, p| (a.0.min(p.1), a.1.max(p.1)));+ vec![(x0 + inset, y0 + inset), (x1 - inset, y0 + inset), (x1 - inset, y1 - inset), (x0 + inset, y1 - inset)]+}++pub fn region_of(v: Option<&Value>) -> Option<Vec<(f64, f64)>> {+ let a = v?.as_array()?;+ let r: Vec<(f64, f64)> = a.iter().map(pt).collect();+ if r.len() >= 3 { Some(r) } else { None }+}++pub fn summary(points: &[(f64, f64)]) -> Value {+ json!(points.iter().map(|(x, y)| json!([x, y])).collect::<Vec<_>>())+}++fn num(v: &Value, k: &str, d: f64) -> f64 { v.get(k).and_then(|x| x.as_f64().or_else(|| x.as_str().and_then(|s| s.parse().ok()))).unwrap_or(d) }++#[cfg(test)]+mod tests {+ use super::*;++ fn board() -> Value {+ json!({"outline": [[0, 0], [20, 0], [20, 10], [0, 10]],+ "tracks": [{"start": {"x": 0.0, "y": 5.0}, "end": {"x": 20.0, "y": 5.0}, "width": 0.25, "net": "SIG"}],+ "arcs": [], "vias": [{"position": {"x": 2.5, "y": 2.5}, "size": 0.6, "net": "GND"}],+ "pads": [{"x": 17.5, "y": 7.5, "sizeX": 1.0, "sizeY": 1.0, "drill": 0.0, "net": "GND"}]})+ }++ #[test]+ fn stitching_keeps_clear_of_other_nets_pads_edges_and_existing_vias() {+ let p = plan_stitching(&board(), "GND", 5.0, 0.6, 0.3, 0.5, None, 100);+ // the 5 mm grid is 2.5/7.5/12.5/17.5 by 2.5/7.5; (2.5,2.5) has a GND via already, (17.5,7.5) is a pad+ assert_eq!(p, vec![(7.5, 2.5), (12.5, 2.5), (17.5, 2.5), (2.5, 7.5), (7.5, 7.5), (12.5, 7.5)]);+ // a track of another net through the grid row blocks it+ let mut b = board();+ b["tracks"][0]["start"]["y"] = json!(2.5);+ b["tracks"][0]["end"]["y"] = json!(2.5);+ assert!(plan_stitching(&b, "GND", 5.0, 0.6, 0.3, 0.5, None, 100).iter().all(|p| p.1 != 2.5));+ // a region limits it, max caps it+ let reg = [(0.0, 0.0), (10.0, 0.0), (10.0, 10.0), (0.0, 10.0)];+ assert_eq!(plan_stitching(&board(), "GND", 5.0, 0.6, 0.3, 0.5, Some(®), 100), vec![(7.5, 2.5), (2.5, 7.5), (7.5, 7.5)]);+ assert_eq!(plan_stitching(&board(), "GND", 5.0, 0.6, 0.3, 0.5, None, 2).len(), 2);+ }++ #[test]+ fn stitching_stays_off_holes_and_out_from_under_parts() {+ let mut b = board();+ // a part U1 whose two pads span x 6..9 at y 7.5: (7.5, 7.5) lies between them, under its body+ b["pads"] = json!([{"ref": "U1", "x": 6.0, "y": 7.5, "sizeX": 0.6, "sizeY": 0.6, "drill": 0.0, "net": "SIG"},+ {"ref": "U1", "x": 9.0, "y": 7.5, "sizeX": 0.6, "sizeY": 0.6, "drill": 0.0, "net": "SIG"}]);+ let p = plan_stitching_with(&b, "GND", 5.0, 0.6, 0.3, 0.5, None, 100, &[(12.5, 2.5, 1.6)], true, &[(15.0, 0.0, 20.0, 10.0)]);+ assert!(!p.contains(&(7.5, 7.5)) && !p.contains(&(12.5, 2.5)));+ assert!(p.iter().all(|q| q.0 < 15.0), "the keepout at x 15..20 takes no via");+ let p = plan_stitching_with(&b, "GND", 5.0, 0.6, 0.3, 0.5, None, 100, &[], false, &[]);+ assert!(p.contains(&(7.5, 7.5)));+ }++ #[test]+ fn corner_holes_sit_inset_from_the_outline() {+ assert_eq!(corners(&board(), 3.0), vec![(3.0, 3.0), (17.0, 3.0), (17.0, 7.0), (3.0, 7.0)]);+ }+ #[test]+ fn fence_points_line_both_sides_of_a_track_and_the_edge() {+ let st = json!({"tracks": [{"net": "RF", "layer": "F.Cu", "width": 0.4, "start": {"x": 0.0, "y": 5.0}, "end": {"x": 10.0, "y": 5.0}}],+ "outline": [[-5, 0], [15, 0], [15, 10], [-5, 10]],+ "outlineEdges": [{"kind": "line", "start": [-5.0, 0.0]}, {"kind": "line", "start": [15.0, 0.0]}, {"kind": "line", "start": [15.0, 10.0]}, {"kind": "line", "start": [-5.0, 10.0]}]});+ let p = fence_points(&st, &["RF".to_string()], 2.0, 1.0, None);+ assert_eq!(p.len(), 12);+ assert!(p.contains(&(0.0, 6.0)) && p.contains(&(10.0, 4.0)));+ let e = fence_points(&st, &[], 5.0, 1.0, Some(0.5));+ assert!(e.iter().all(|(x, y)| *x >= -4.5 - 1e-9 && *x <= 14.5 + 1e-9 && *y >= 0.5 - 1e-9 && *y <= 9.5 + 1e-9), "{e:?}");+ assert!(e.len() >= 10, "{e:?}");+ }+ #[test]+ fn via_style_reads_altiums_descriptor() {+ let rules = vec![json!({"enabled": true, "scope1": "All", "priority": 1, "descriptor": "Routing Via (MinHoleWidth=0.3mm) (MaxHoleWidth=0.3mm) (PreferredHoleWidth=0.3mm) (MinWidth=0.5mm) (MaxWidth=0.5mm) (PreferedWidth=0.5mm) (All)"})];+ assert_eq!(via_style(&rules), Some((0.5, 0.3)));+ let mil = vec![json!({"enabled": true, "scope1": "All", "priority": 1, "descriptor": "Routing Via (PreferredHoleWidth=12mil) (PreferedWidth=24mil) (All)"})];+ let (s, d) = via_style(&mil).unwrap();+ assert!((s - 0.6096).abs() < 1e-9 && (d - 0.3048).abs() < 1e-9);+ }+ #[test]+ fn thermal_grid_fills_an_exposed_pad() {+ // a 3.3 mm QFN pad, 0.6 mm vias, 1.1 mm pitch: a 3 x 3 grid centred on the pad+ let g = thermal_grid(10.0, 10.0, 3.3, 3.3, 0.0, 1.1, 0.6, 0.1);+ assert_eq!(g.len(), 9);+ assert!(g.contains(&(10.0, 10.0)) && g.contains(&(8.9, 11.1)));+ assert!(thermal_grid(0.0, 0.0, 0.5, 0.5, 0.0, 1.0, 0.6, 0.1).is_empty());+ // turned 90 degrees, a long pad's grid turns with it+ let r = thermal_grid(0.0, 0.0, 4.0, 1.5, 90.0, 1.1, 0.6, 0.1);+ assert!(r.iter().all(|(x, _)| x.abs() < 0.5));+ }++ #[test]+ fn via_style_takes_the_standard_rule_first() {+ let rules = vec![json!({"kind": "via", "sizeMm": 0.45, "drillMm": 0.2}),+ json!({"enabled": true, "scope1": "All", "priority": 1, "descriptor": "Routing Via (PreferredHoleWidth=0.3mm) (PreferedWidth=0.5mm) (All)"})];+ assert_eq!(via_style(&rules), Some((0.45, 0.2)));+ }++ #[test]+ fn the_verbs_answer_place_vias_plans() {+ let st = json!({"nets": ["GND", "RF"], "outline": [[0, 0], [30, 0], [30, 20], [0, 20]],+ "outlineEdges": [{"kind": "line", "start": [0.0, 0.0]}, {"kind": "line", "start": [30.0, 0.0]}, {"kind": "line", "start": [30.0, 20.0]}, {"kind": "line", "start": [0.0, 20.0]}],+ "tracks": [{"net": "RF", "layer": "F.Cu", "width": 0.4, "start": {"x": 5.0, "y": 10.0}, "end": {"x": 25.0, "y": 10.0}}], "arcs": [], "vias": [],+ "pads": [{"ref": "U1", "name": "EP", "x": 15.0, "y": 4.0, "sizeX": 3.3, "sizeY": 3.3, "rotation": 0.0, "drill": 0.0, "net": "GND", "layer": "F.Cu"}]});+ let t = thermal_vias(&json!({"board": st, "rules": [{"kind": "via", "sizeMm": 0.6, "drillMm": 0.3}], "args": {"ref": "U1"}}));+ assert_eq!(t["success"], json!(true), "{t}");+ assert_eq!(t["planned"]["vias"], 9);+ assert_eq!(t["apply"]["verb"], "place_vias");+ assert_eq!(t["apply"]["args"]["vias"][0]["net"], "GND");+ assert_eq!(t["planned"]["via"]["from"], "the board's via rule");+ let v = via_fence(&json!({"board": st, "args": {"viaNet": "GND", "nets": ["RF"], "pitchMm": 2.0}}));+ assert_eq!(v["success"], json!(true), "{v}");+ assert!(v["planned"]["vias"].as_u64().unwrap() >= 10);+ assert_eq!(v["apply"]["args"]["vias"].as_array().unwrap().len() as u64, v["planned"]["vias"].as_u64().unwrap());+ assert_eq!(via_fence(&json!({"board": st, "args": {"viaNet": "NOPE", "nets": ["RF"]}}))["errorCode"], "no_such_net");+ assert_eq!(thermal_vias(&json!({"board": st, "args": {"ref": "U9"}}))["errorCode"], "part_not_found");+ }+}
bridge-rs/vendor/adom-eda-checks/src/lib.rs+29−2@@ -7,26 +7,53 @@ //! Every check takes one input bundle, `{board, stack?, pours?, rules?, silk?, fab?, bodies?, sheetParts?, netlist?, args?}` (see `input`). use serde_json::Value; +pub mod bodies; pub mod coppermap; pub mod current; pub mod fab;+pub mod features; pub mod geom; pub mod impedance; pub mod input;+pub mod placement; pub mod writers; +/// This engine's version. Every reply carries it as `engine` ("adom-eda-checks 0.3.0"), so a bridge never writes it by hand+/// (kicad-lane's replies said 0.1.2 for three releases after re-vendoring).+pub const VERSION: &str = env!("CARGO_PKG_VERSION");+ /// The checks this build answers, by standard verb name.-pub const CHECKS: &[&str] = &["copper_balance", "current_capacity", "fab_check", "impedance", "return_path"];+pub const CHECKS: &[&str] = &["copper_balance", "current_capacity", "fab_check", "height_check", "impedance", "placement_check", "return_path", "thermal_vias", "via_fence"]; -/// Run one check or writer by its standard name.+/// Run one check or writer by its standard name. The reply carries `engine`. pub fn run(check: &str, input: &Value) -> Value {+ let mut out = answer(check, input);+ if let Some(o) = out.as_object_mut() { o.entry("engine").or_insert(Value::String(format!("adom-eda-checks {VERSION}"))); }+ out+}++fn answer(check: &str, input: &Value) -> Value { if let Some(out) = writers::run(check, input) { return out; } match check { "copper_balance" => coppermap::copper_balance(input), "current_capacity" => current::current_capacity(input), "fab_check" => fab::fab_check(input),+ "height_check" => bodies::height_check(input), "impedance" => impedance::impedance(input),+ "placement_check" => placement::placement_check(input), "return_path" => coppermap::return_path(input),+ "thermal_vias" => features::thermal_vias(input),+ "via_fence" => features::via_fence(input), _ => input::refuse("not_supported", &format!("{check} is not a verb this engine answers (checks: {}; writers: {})", CHECKS.join(", "), writers::WRITERS.join(", "))), } }++#[cfg(test)]+mod tests {+ #[test]+ fn every_reply_names_the_engine_version() {+ let r = super::run("copper_balance", &serde_json::json!({}));+ assert_eq!(r["engine"], format!("adom-eda-checks {}", super::VERSION));+ assert_eq!(super::run("no_such_check", &serde_json::json!({}))["engine"], r["engine"]);+ }+}
bridge-rs/vendor/adom-eda-checks/src/placement.rsadded+151@@ -0,0 +1,151 @@+//! A placement review before routing: parts whose courtyards (pads and body, grown by a margin) overlap on the same+//! side, parts off the board or over its edge, pads too close to the edge for assembly and depanelling, and parts on a+//! mounting hole. From the Altium bridge's placement.rs.+use serde_json::{json, Value};+use std::collections::BTreeMap;++fn f(v: &Value) -> f64 { v.as_f64().unwrap_or(0.0) }+fn r3(v: f64) -> f64 { (v * 1000.0).round() / 1000.0 }+type Rect = (f64, f64, f64, f64);++fn hit(a: Rect, b: Rect) -> bool { a.0 < b.2 && b.0 < a.2 && a.1 < b.3 && b.1 < a.3 }+fn grow(r: Rect, d: f64) -> Rect { (r.0 - d, r.1 - d, r.2 + d, r.3 + d) }++/// Each part's box (its pads, and its 3D body's box when it has one) and side. Pure.+pub fn part_boxes(st: &Value, bodies: &BTreeMap<String, Rect>) -> BTreeMap<String, (bool, Rect)> {+ let mut m: BTreeMap<String, (bool, Rect)> = BTreeMap::new();+ let side: BTreeMap<String, bool> = st["components"].as_array().cloned().unwrap_or_default().iter()+ .filter_map(|c| Some((c["ref"].as_str()?.to_string(), c["side"] == "bottom"))).collect();+ for p in st["pads"].as_array().cloned().unwrap_or_default() {+ let Some(r) = p["ref"].as_str().filter(|r| !r.is_empty()) else { continue };+ let (c, s) = (f(&p["rotation"]).to_radians().cos().abs(), f(&p["rotation"]).to_radians().sin().abs());+ let (hx, hy) = ((f(&p["sizeX"]) * c + f(&p["sizeY"]) * s) / 2.0, (f(&p["sizeX"]) * s + f(&p["sizeY"]) * c) / 2.0);+ let b = (f(&p["x"]) - hx, f(&p["y"]) - hy, f(&p["x"]) + hx, f(&p["y"]) + hy);+ let e = m.entry(r.to_string()).or_insert((side.get(r).copied().unwrap_or(false), b));+ e.1 = (e.1 .0.min(b.0), e.1 .1.min(b.1), e.1 .2.max(b.2), e.1 .3.max(b.3));+ }+ for (r, b) in bodies {+ if let Some(e) = m.get_mut(r) { e.1 = (e.1 .0.min(b.0), e.1 .1.min(b.1), e.1 .2.max(b.2), e.1 .3.max(b.3)); }+ }+ m+}++/// The review. `ring` is the outline (mm); holes are (x, y, radius) of the board's own drilled, part-less pads. Pure.+pub fn review(boxes: &BTreeMap<String, (bool, Rect)>, pads: &[Value], ring: &[(f64, f64)], holes: &[(f64, f64, f64)], margin: f64, edge: f64) -> Value {+ let (bx0, bx1) = ring.iter().fold((f64::MAX, f64::MIN), |a, p| (a.0.min(p.0), a.1.max(p.0)));+ let (by0, by1) = ring.iter().fold((f64::MAX, f64::MIN), |a, p| (a.0.min(p.1), a.1.max(p.1)));+ 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+ };+ let dist = |x: f64, y: f64| (0..ring.len()).map(|k| {+ let (a, b) = (ring[k], ring[(k + 1) % ring.len()]);+ let (dx, dy) = (b.0 - a.0, b.1 - a.1);+ let l2 = dx * dx + dy * dy;+ let t = if l2 > 0.0 { (((x - a.0) * dx + (y - a.1) * dy) / l2).clamp(0.0, 1.0) } else { 0.0 };+ ((a.0 + t * dx - x).powi(2) + (a.1 + t * dy - y).powi(2)).sqrt()+ }).fold(f64::MAX, f64::min);+ let (mut overlaps, mut off, mut near, mut on_holes) = (Vec::new(), Vec::new(), Vec::new(), Vec::new());+ let list: Vec<(&String, &(bool, Rect))> = boxes.iter().collect();+ for i in 0..list.len() {+ for j in i + 1..list.len() {+ let ((ra, (sa, a)), (rb, (sb, b))) = (list[i], list[j]);+ if sa == sb && hit(grow(*a, margin), grow(*b, margin)) {+ let ov = (a.2.min(b.2) - a.0.max(b.0)).min(a.3.min(b.3) - a.1.max(b.1));+ overlaps.push(json!({"parts": [ra, rb], "side": if *sa { "bottom" } else { "top" }, "overlapMm": r3(ov + 2.0 * margin)}));+ }+ }+ }+ // on or off the board by its pads' centres: a box's corners fall outside a round board's edge while the part sits+ // well inside it (the Bluetooth Sentinel's J1 read as off the board)+ let mut pad_in: BTreeMap<&str, (usize, usize)> = BTreeMap::new();+ for p in pads {+ let Some(r) = p["ref"].as_str().filter(|r| !r.is_empty()) else { continue };+ let e = pad_in.entry(r).or_insert((0, 0));+ e.0 += 1;+ if inside(f(&p["x"]), f(&p["y"])) { e.1 += 1; }+ }+ let _ = (bx0, bx1, by0, by1);+ for (r, (_, b)) in boxes {+ let (n, n_in) = pad_in.get(r.as_str()).copied().unwrap_or((0, 0));+ if n > 0 && n_in == 0 { off.push(json!({"ref": r, "where": "off the board"})); continue; }+ if n_in < n { off.push(json!({"ref": r, "where": "over the board edge"})); continue; }+ for (x, y, hr) in holes { if hit(*b, (x - hr, y - hr, x + hr, y + hr)) { on_holes.push(json!({"ref": r, "hole": [r3(*x), r3(*y)]})); } }+ }+ // pads near the edge: the closest pad of each part+ let mut closest: BTreeMap<String, f64> = BTreeMap::new();+ for p in pads {+ let Some(r) = p["ref"].as_str().filter(|r| !r.is_empty()) else { continue };+ // the pad's four corners, turned with it: inside the outline their distance counts, outside it is negative+ let (c, s) = (f(&p["rotation"]).to_radians().cos(), f(&p["rotation"]).to_radians().sin());+ let (hx, hy) = (f(&p["sizeX"]) / 2.0, f(&p["sizeY"]) / 2.0);+ let d = [(-hx, -hy), (hx, -hy), (hx, hy), (-hx, hy)].iter().map(|(u, v)| {+ let (x, y) = (f(&p["x"]) + u * c - v * s, f(&p["y"]) + u * s + v * c);+ if inside(x, y) { dist(x, y) } else { -dist(x, y) }+ }).fold(f64::MAX, f64::min);+ let e = closest.entry(r.to_string()).or_insert(f64::MAX);+ if d < *e { *e = d; }+ }+ for (r, d) in &closest {+ if *d < edge && !off.iter().any(|o| o["ref"] == json!(r)) { near.push(json!({"ref": r, "padToEdgeMm": r3(*d)})); }+ }+ let ok = overlaps.is_empty() && off.is_empty() && on_holes.is_empty();+ json!({"parts": boxes.len(), "ok": ok, "courtyardOverlaps": overlaps, "offOrOverEdge": off, "onMountingHoles": on_holes, "nearEdge": near, "marginMm": margin, "edgeMm": edge})+}++/// placement_check: input {board, bodies?, args: {marginMm?, edgeMm?}}. Without bodies the parts' boxes are their pads+/// only, and the reply says so (`bodiesUsed: false`).+pub fn placement_check(input: &Value) -> Value {+ let st = match crate::input::board(input) { Ok(b) => b, Err(e) => return e };+ let args = &input["args"];+ let ring = crate::coppermap::outline_ring(&st);+ if ring.len() < 3 { return crate::input::refuse("no_outline", "the board has no outline"); }+ // the parts' 3D bodies (silk_state's 'body' box takes in the designator text and made every neighbour overlap)+ let mut bodies: BTreeMap<String, Rect> = BTreeMap::new();+ let given = crate::bodies::input_boxes(input);+ for b in given.clone().unwrap_or_default() {+ let e = bodies.entry(b.part.clone()).or_insert((b.x0, b.y0, b.x1, b.y1));+ *e = (e.0.min(b.x0), e.1.min(b.y0), e.2.max(b.x1), e.3.max(b.y1));+ }+ let boxes = part_boxes(&st, &bodies);+ let pads = st["pads"].as_array().cloned().unwrap_or_default();+ let holes: Vec<(f64, f64, f64)> = pads.iter().filter(|p| f(&p["drill"]) > 0.0 && p["ref"].as_str().map(|r| r.is_empty()).unwrap_or(true))+ .map(|p| (f(&p["x"]), f(&p["y"]), f(&p["sizeX"]).max(f(&p["drill"])) / 2.0)).collect();+ let num = |k: &str, d: f64| args.get(k).and_then(|v| v.as_f64()).unwrap_or(d);+ let mut out = review(&boxes, &pads, &ring, &holes, num("marginMm", 0.1), num("edgeMm", 0.5));+ out["success"] = json!(true);+ out["bodiesUsed"] = json!(given.is_some());+ out["_hint"] = json!("courtyardOverlaps: parts closer than twice marginMm (their pads and bodies): move them apart (move_parts, find_space). offOrOverEdge parts must come onto the board; nearEdge pads risk the router or the V-cut (JLCPCB: 0.4 mm from a V-cut, 0.2 from a routed edge). onMountingHoles: a screw head lands on the part. Without bodies (bodiesUsed false) a part's box is its pads only: pass the bodies companion to count overhanging bodies.");+ out+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn placement_review_finds_each_problem() {+ let ring = vec![(0.0, 0.0), (40.0, 0.0), (40.0, 20.0), (0.0, 20.0)];+ let mut boxes = BTreeMap::new();+ boxes.insert("U1".to_string(), (false, (5.0, 5.0, 10.0, 10.0)));+ boxes.insert("C1".to_string(), (false, (10.2, 5.0, 11.0, 6.0))); // 0.2 mm from U1: inside 2 x 0.25+ boxes.insert("C2".to_string(), (true, (10.2, 5.0, 11.0, 6.0))); // the same spot on the bottom: fine+ boxes.insert("J1".to_string(), (false, (38.0, 8.0, 42.0, 12.0))); // over the edge+ boxes.insert("R9".to_string(), (false, (50.0, 5.0, 51.0, 6.0))); // off the board+ boxes.insert("R2".to_string(), (false, (1.5, 15.5, 2.5, 16.5))); // on the hole at (2, 16)+ let pad = |r: &str, x: f64, y: f64| json!({"ref": r, "x": x, "y": y, "sizeX": 0.6, "sizeY": 0.6});+ let pads = vec![pad("C1", 10.6, 5.5), pad("U1", 5.2, 0.6), pad("J1", 39.0, 10.0), pad("J1", 41.0, 10.0), pad("R9", 50.5, 5.5)];+ let r = review(&boxes, &pads, &ring, &[(2.0, 16.0, 1.6)], 0.25, 0.5);+ assert_eq!(r["courtyardOverlaps"].as_array().unwrap().len(), 1);+ assert_eq!(r["courtyardOverlaps"][0]["parts"], json!(["C1", "U1"]));+ let off: Vec<String> = r["offOrOverEdge"].as_array().unwrap().iter().map(|o| format!("{} {}", o["ref"].as_str().unwrap(), o["where"].as_str().unwrap())).collect();+ assert!(off.contains(&"J1 over the board edge".to_string()) && off.contains(&"R9 off the board".to_string()));+ assert_eq!(r["onMountingHoles"][0]["ref"], "R2");+ assert_eq!(r["nearEdge"][0]["ref"], "U1");+ assert_eq!(r["ok"], json!(false));+ }+}
bridge-rs/vendor/adom-eda-checks/tests/fixtures.rs+11−1@@ -16,7 +16,7 @@ fn load(p: PathBuf) -> Option<Value> { Some(serde_json::from_str(&std::fs::read_ fn bundle(d: &PathBuf, board: &str) -> Option<Value> { Some(json!({"board": load(d.join(format!("{board}.routing_state.json")))?, "stack": load(d.join(format!("{board}.layer_stack.json")))?, "pours": load(d.join(format!("{board}.pour_state.json")))?, "rules": load(d.join(format!("{board}.read_rules.json"))),- "silk": load(d.join(format!("{board}.silk_state.json"))), "args": {}}))+ "silk": load(d.join(format!("{board}.silk_state.json"))), "bodies": load(d.join(format!("{board}.bodies.json"))), "args": {}})) } fn same(check: &str, keys: &[&str]) {@@ -54,3 +54,13 @@ fn fab_check_measures_what_altium_measures() { "measured.holeToHoleVia", "measured.largestDrill", "measured.padHole", "measured.smdPad", "measured.track", "measured.viaAnnularRing", "measured.viaDiameter", "measured.viaDrill", "outsideLimits", "limitsChecked"]); }++#[test]+fn height_check_matches_altium() {+ same("height_check", &["ok", "complete", "bodies", "parts", "tallest", "overLimit", "regionHits", "collisions", "tooClose", "minGapMm", "noBody", "heights"]);+}++#[test]+fn placement_check_matches_altium() {+ same("placement_check", &["ok", "parts", "courtyardOverlaps", "offOrOverEdge", "onMountingHoles", "nearEdge", "marginMm", "edgeMm"]);+}