← Commit history
CHANGELOG.md+31−2
@@ -2,13 +2,42 @@  ## 0.2.80 (unreleased) +- **Altium covers the whole EDA Bridge Standard: 236 of 236 verbs.** The last four come from the standard's shared engine+  (adom-eda-checks 0.10.3, standard 0.13.3, vendored as published): `plan_route`, `place_decoupling`, `plan_fanout` and+  `estimate_cost`. 255 verbs. Engine 0.10.0 checks a route's through vias on every copper layer, takes the strictest+  board-wide copper clearance (scoped rules left out), and names the pours a route crosses (`crossesPours`;+  `avoidPours` keeps out of all of them or of the nets listed, `pourCost` makes them dearer instead).+- **`altium_plan_fanout`: a BGA's or a QFN/QFP's escape** (#22): the outer ring on the surface and a dogbone via (or via+  in pad) for each inner ball, an outward stub per perimeter pad, a via grid in an exposed pad, as route_net calls, every+  via and stub measured against other nets' pads (`conflicts`). `apply:true` routes the calls one after another, each+  guarded by the revision the one before left, and refuses while a conflict is listed.+- **`altium_estimate_cost`: the numbers a fab quote needs** (#22): size, copper layers, thickness, smallest track, gap+  and drill, holes, parts and joints. Prices only from a record the caller passes (`prices`, read from the fab's own page+  with its date): no rates are built in, so none can go stale.+- **Pours come back whole, and a repour that does nothing is caught.** routing_state's `polygons` and pour_state's+  outlines carried only each segment's start point, so the Bluetooth Sentinel's round GND pours read as 3 to 5 corners+  (and the planners' `crossesPours`/`avoidPours` could not see them): arc segments are now split into chords. A hatched+  pour (poured as tracks, not regions) read as unfilled; pour_state now counts its pieces (`hatchedPieces`). And+  Altium's Repour All left those hatched pours untouched after new copper went in (17 DRC errors against two new+  stubs): when it changes no pour, `altium_repour` rebuilds each polygon from the agent (`rebuiltInScript`), which+  cleared all 17.+- **The checks that read 3D bodies read the board once.** `place_decoupling`, `placement_check` and `check_clearance`+  read the board model and then the bodies, which read it again for the parts with no body: 74 s each time on the+  Bluetooth Sentinel, so the check ran past the relay's limit. The bodies now take the board already read.++- **`altium_place_decoupling`: an IC's decoupling caps beside the power pins they serve, from the standard's shared+  planner** (#22, standard 0.10.0, adom-eda-checks 0.7.0, vendored as published). Each cap goes just outside the IC+  (gapMm, 0.3 by default), its power pad facing the pin and lined up with it, sliding along the side when the spot is+  taken. The default set leaves out a crystal's load caps and caps nearer another IC on the same supply (`leftOut`+  says why); naming caps places them anyway. The plan comes checked by placement_check on the moved board, and+  `apply:true` moves the caps with move_parts, guarded by the revision it was planned on. `check_clearance` answers from the engine too: pads by their real outline (it measured bounding rectangles, so a rounded or turned pad read closer than it is), parts as pads plus 3D bodies.+ - **`altium_plan_route`: a path for one net between two pads, from the standard's shared planner** (#21, standard 0.9.1,   adom-eda-checks 0.6.1, vendored as published). An A* search on a grid, over the copper layers you allow (any number,   inner layers too), with vias between them; every step keeps the board's clearance rule from other nets' copper, pads   measured by their real outline. It answers `routeNet`, altium_route_net's own arguments, and `apply:true` routes it   here, guarded by the revision it was planned on. The track and via take the board's own Width and Routing Via rules-  unless widthMm / viaSizeMm are given (`planner.widthFrom`, `viaFrom`): 0.25 mm broke a 10 mil Width rule (#21, PR #4). Pours are not obstacles: repour after. 252 verbs; Altium now covers-  233 of the standard's 236.+  unless widthMm / viaSizeMm are given (`planner.widthFrom`, `viaFrom`): 0.25 mm broke a 10 mil Width rule (#21, PR #4). Pours are not obstacles: repour after.   - **`generate_body` is the standard's engine writer now** (#20, standard 0.8.1, adom-eda-checks 0.5.1, vendored as   published): this bridge's body3d moved into the engine, so Altium, KiCad and Fusion make the same body. The bridge
README.md+7−4
@@ -15,7 +15,7 @@ normal session. Ask in plain words and it: - makes the outputs: Gerbers, NC drill, pick and place, BOMs grouped by MPN (JLCPCB, Mouser, DigiKey files),   schematic PDF and STEP, checking that the outline and every copper layer reached the Gerbers -252 commands, tested on Altium Designer 26.11 and Altium Designer Develop. It runs in **Hydrogen**, Adom's free+255 commands, tested on Altium Designer 26.11 and Altium Designer Develop. It runs in **Hydrogen**, Adom's free desktop app, through Adom Bridge. You bring your own AI subscription and your own Altium licence.  ::youtube{id="dFecpcIzdSE" title="An AI designs a 12 V to 5 V buck converter in Altium Designer"}@@ -29,7 +29,7 @@ and the verb prefix `altium_`.  ## What it can do -Tested on Altium Designer 26.11.1 and Altium Designer Develop. 252 verbs; each row names the ones+Tested on Altium Designer 26.11.1 and Altium Designer Develop. 255 verbs; each row names the ones behind it (prefix `altium_`).  | Area | What the AI can do | Verbs |@@ -70,7 +70,7 @@ This bridge is the reference for the [EDA Bridge Standard](https://wiki.adom.inc  Altium Designer is the user's own **host app**. The bridge finds an installed Altium (`%ProgramFiles%\Altium\AD*\X2.EXE`, Designer or Develop), starts it in the background, runs a small-**DelphiScript agent** inside it, and gives the AI 252 `altium_*` verbs.+**DelphiScript agent** inside it, and gives the AI 255 `altium_*` verbs.  - **Page and docs:** https://wiki.adom.inc/adom/altium-bridge - **Bridge SDK:** https://wiki.adom.inc/adom/adom-bridge-sdk@@ -170,7 +170,7 @@ way to read it). A stopped engine is restarted with `altium_agent_recover`.  <!-- verbs:start (tools/readme_verbs.py writes this list) --> -All 252 verbs, by area (prefix `altium_`). `altium_describe` returns the live catalog with every input, output, hint and example.+All 255 verbs, by area (prefix `altium_`). `altium_describe` returns the live catalog with every input, output, hint and example.  ### Running Altium: launch, close, health, dialogs @@ -246,6 +246,9 @@ All 252 verbs, by area (prefix `altium_`). `altium_describe` returns the live ca - `altium_route_net`: Route one net as tracks, segment by segment; a waypoint on another layer drops a via there. - `altium_plan_route`: Find a path for one net between two pads, clear of other nets' copper by the board's clearance rule, on the copper layers you allow, with vias between them (the standard's shared planner). - `altium_move_parts`: Move, rotate and flip placed components (side top or bottom; flip:true turns a part over); each part is read back to 0.001 mm, the exact rotation and its side.+- `altium_place_decoupling`: Put an IC's decoupling caps beside the power pins they serve: each cap just outside the IC, power pad facing its pin, lined up with it, sliding along the side when the spot is taken (the standard's shared planner).+- `altium_plan_fanout`: Plan a BGA's or a QFN/QFP's escape (the standard's shared planner): the outer ring on the surface and a dogbone via (or via in pad) for each inner ball, an outward stub per perimeter pad (with a via for ground or viaPerimeter), a via grid in an exposed pad.+- `altium_estimate_cost`: The numbers a fab quote needs (size, copper layers, thickness, smallest track, gap and drill, holes, parts and joints) from the board, and a rough price table at the quantities asked when you pass a price record read from the fab's own page (the standard's shared estimator; it has no rates of its own). - `altium_export_library_part`: Export one library part into its own small library files: a symbol library with only its symbol, a footprint library with only its footprint, and its 3D model file. - `altium_create_part_project`: Generate a small real project (schematic and board) around one library part, so the part can be shown and tested in every view: schematic, 2D board and 3D board. - `altium_library_views`: Pictures of library parts for review, each as an image file: the schematic symbol, the footprint (pads and layers), the 3D body seated on the footprint, and the device view that maps symbol pins to pads.
SKILL.md+1−1
@@ -34,7 +34,7 @@ Say **altium** to reach this bridge. Every verb returns `success`, a stable `err | Net classes, their widths and clearances; diff pairs | `altium_net_classes`, `altium_diff_pairs`, `altium_set_track_width` (existing copper) (**altium-boards**) | | Check the design | `altium_compile` (ERC), `altium_run_drc`, `altium_routing_drc`, `altium_review_board`, `altium_cross_check`, `altium_read_rules` (rule values) | | Find a part on the sheet or board | `altium_sch_zoom`, `altium_zoom_to` |-| Place, route, pour, silkscreen a board | `altium_move_parts`, `altium_route_net`, `altium_plan_route` (a path pad to pad), `altium_autoroute` (Situs), `altium_place_vias`, `altium_apply_pours`, `altium_apply_silkscreen`, `altium_set_design_rules`, `altium_layer_stack`, `altium_find_space` (free spots near a part; overlap check) (**altium-boards**) |+| Place, route, pour, silkscreen a board | `altium_move_parts`, `altium_route_net`, `altium_plan_route` (a path pad to pad), `altium_place_decoupling`, `altium_plan_fanout`, `altium_estimate_cost`, `altium_autoroute` (Situs), `altium_place_vias`, `altium_apply_pours`, `altium_apply_silkscreen`, `altium_set_design_rules`, `altium_layer_stack`, `altium_find_space` (free spots near a part; overlap check) (**altium-boards**) | | Silkscreen off the pads before fab or a render (Tools > Silkscreen Preparation) | `altium_silkscreen_prep {filePath}` (runs inside `altium_export_manufacturing` by default) (**altium-outputs**) | | Routed net lengths, pair skew, matched-length groups; length, matched, diff-pair and via rules | `altium_net_lengths`, `altium_add_rule {kind: length\|matched\|diffpair\|via}` (**altium-boards**) | | Component classes and rooms; teardrops | `altium_component_classes {name, members, room}`, `altium_teardrops` (**altium-boards**) |
bridge-rs/Cargo.lock+1−1
@@ -10,7 +10,7 @@ checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa"  [[package]] name = "adom-eda-checks"-version = "0.6.1"+version = "0.10.3" dependencies = [  "roxmltree",  "serde_json",
bridge-rs/src/boardedit.rs+8−62
@@ -345,63 +345,18 @@ pub fn copy_routing(args: &Value) -> Value {  // -- check_clearance -------------------------------------------------------------------------------------------------------- -fn rect_gap(a: Rect, b: Rect) -> f64 {-    let dx = (b.0 - a.2).max(a.0 - b.2);-    let dy = (b.1 - a.3).max(a.1 - b.3);-    if dx < 0.0 && dy < 0.0 { dx.max(dy) } else { (dx.max(0.0).powi(2) + dy.max(0.0).powi(2)).sqrt() }-}--/// Pairs of boxes closer than the threshold, closest first: (a, b, distance; negative is an overlap). Pure.-pub fn close_pairs(items: &[(String, i32, Rect)], threshold: f64, keep: &dyn Fn(&str, &str) -> bool) -> Vec<(String, String, f64)> {-    let mut out = Vec::new();-    for i in 0..items.len() {-        for j in (i + 1)..items.len() {-            let (a, b) = (&items[i], &items[j]);-            if a.0 == b.0 || a.1 & b.1 == 0 || !keep(&a.0, &b.0) { continue; }-            let d = rect_gap(a.2, b.2);-            if d < threshold { out.push((a.0.clone(), b.0.clone(), r3(d))); }-        }-    }-    out.sort_by(|x, y| x.2.partial_cmp(&y.2).unwrap());-    out-}--/// altium_check_clearance {refs?, mode: courtyard|pads, thresholdMm?, includeSameNet?, maxPairs?}+/// altium_check_clearance {refs?, mode: courtyard|pads, thresholdMm?, includeSameNet?, maxPairs?}: the standard's shared+/// check (vendor/adom-eda-checks `placetools`, #22) on the board model and the parts' 3D bodies. Pads are measured by+/// their real outline (rounded pads as circles or stadiums), parts as their pads plus bodies; Altium courtyards are not read. pub fn check_clearance(args: &Value) -> Value {     if let Some(e) = open_board(args) { return e; }     let st = routing::routing_state(&json!({}));     if st.get("success").and_then(|b| b.as_bool()) != Some(true) { return st; }-    let refs: Vec<String> = refs_of(args.get("refs")).iter().map(|r| r.to_uppercase()).collect();-    let pads_mode = args.get("mode").and_then(|v| v.as_str()) == Some("pads");-    let th = args.get("thresholdMm").and_then(|v| v.as_f64()).unwrap_or(if pads_mode { 0.2 } else { 0.25 });-    let max = args.get("maxPairs").and_then(|v| v.as_u64()).unwrap_or(200) as usize;-    let keep_ref = |a: &str, b: &str| refs.is_empty() || refs.iter().any(|r| a.to_uppercase().starts_with(&format!("{r}.")) || a.eq_ignore_ascii_case(r) || b.to_uppercase().starts_with(&format!("{r}.")) || b.eq_ignore_ascii_case(r));-    let (items, measured): (Vec<(String, i32, Rect)>, &str) = if pads_mode {-        let v = st["pads"].as_array().cloned().unwrap_or_default().iter().filter(|p| !st_str(&p["ref"]).is_empty()).map(|p| {-            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 side = match p["layer"].as_str() { Some("F.Cu") => 1, Some("B.Cu") => 2, _ => 3 };-            (format!("{}.{}|{}", st_str(&p["ref"]), st_str(&p["name"]), st_net(p)), side, (f(&p["x"]) - hx, f(&p["y"]) - hy, f(&p["x"]) + hx, f(&p["y"]) + hy))-        }).collect();-        (v, "pads (each pad's bounding rectangle)")-    } else {-        (part_boxes(&st, &BTreeMap::new()).into_iter().map(|(r, (bottom, b))| (r, if bottom { 2 } else { 1 }, b)).collect(), "part box (pads; Altium courtyards are not read)")-    };-    let same_net = args.get("includeSameNet").and_then(|v| v.as_bool()) == Some(true);-    let keep = |a: &str, b: &str| -> bool {-        let (ar, an) = a.split_once('|').unwrap_or((a, ""));-        let (br, bn) = b.split_once('|').unwrap_or((b, ""));-        if pads_mode {-            if ar.split('.').next() == br.split('.').next() { return false; } // pads of the same part-            if !same_net && !an.is_empty() && an == bn { return false; }-        }-        keep_ref(ar, br)-    };-    let pairs = close_pairs(&items, th, &keep);-    let total = pairs.len();-    let out: Vec<Value> = pairs.into_iter().take(max).map(|(a, b, d)| json!({"a": a.split('|').next(), "b": b.split('|').next(), "distanceMm": d.max(0.0), "overlapping": d < 0.0, "overlapMm": if d < 0.0 { json!(-d) } else { Value::Null }, "touching": d.abs() < 1e-6})).collect();-    json!({"success": true, "pairs": out, "count": total, "clean": total == 0, "thresholdMm": th, "measuredOn": measured,-        "_hint": "Computed from the board model, by bounding rectangles: rounded pads read a little close. Altium's own DRC (altium_run_drc, Component Clearance) is the authority."})+    let b = crate::bodies::bodies_on(&json!({}), Some(&st));+    let b = if b.get("success").and_then(|v| v.as_bool()) == Some(true) { b } else { Value::Null };+    let mut a = args.clone();+    if let Some(o) = a.as_object_mut() { o.remove("filePath"); }+    crate::checks::engine("check_clearance", &json!({"board": st, "bodies": b, "args": a})) }  // -- remove_graphics ---------------------------------------------------------------------------------------------------------@@ -480,15 +435,6 @@ mod tests {         assert_eq!(glob("CH1_*", "CH1_R5").as_deref(), Some("R5"));     } -    #[test]-    fn clearance_pairs_are_closest_first_and_same_side_only() {-        let items = vec![("A".to_string(), 1, (0.0, 0.0, 1.0, 1.0)), ("B".to_string(), 1, (1.1, 0.0, 2.0, 1.0)), ("C".to_string(), 1, (0.5, 0.5, 1.5, 1.5)), ("D".to_string(), 2, (0.0, 0.0, 1.0, 1.0))];-        let pairs = close_pairs(&items, 0.25, &|_, _| true);-        assert_eq!(pairs[0].0, "A");-        assert!(pairs[0].2 < 0.0, "A and C overlap");-        assert!(!pairs.iter().any(|p| p.0 == "D" || p.1 == "D"), "D is on the other side");-    }-     #[test]     fn a_graphic_key_reads_as_mm_on_its_layer() {         let k = format!("line:57:{},{},{},{},{}", raw(1.0), raw(2.0), raw(11.0), raw(2.0), raw(0.15));
bridge-rs/src/bodies.rs+7−2
@@ -18,7 +18,11 @@ pub fn rows(raw: &[Value]) -> Vec<Value> {  /// 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 {+pub fn bodies(args: &Value) -> Value { bodies_on(args, None) }++/// The bodies companion, with `noBody` from a board model the caller has already read (`st`): reading it again cost+/// 74 s on the Bluetooth Sentinel, and a check that read it twice ran past the relay's limit (2026-10-28).+pub fn bodies_on(args: &Value, st: Option<&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));@@ -26,7 +30,8 @@ pub fn bodies(args: &Value) -> Value {     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 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 read;+    let st = match st { Some(s) => s, None => { read = crate::routing::routing_state(&json!({})); &read } };     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();
bridge-rs/src/checks.rs+66−2
@@ -116,7 +116,7 @@ pub fn plan_route(args: &Value) -> Value {     if let Some(e) = open(args) { return e; }     let st = match board() { Ok(s) => s, Err(e) => return e };     let rules = crate::agent::call("read_rules", &[], None, Duration::from_secs(60)).get("data").cloned().unwrap_or(Value::Null);-    let mut r = engine("plan_route", &json!({"board": st, "rules": rules, "args": without(args, &["filePath", "apply"])}));+    let mut r = engine("plan_route", &json!({"board": st, "stack": stack(), "rules": rules, "args": without(args, &["filePath", "apply"])}));     if args.get("apply").and_then(|b| b.as_bool()) != Some(true) || r["found"] != json!(true) { return r; }     let mut rn = r["routeNet"].clone();     rn["expectedRevision"] = r["revision"].clone();@@ -124,10 +124,74 @@ pub fn plan_route(args: &Value) -> Value {     r["applied"] = json!({"success": a["success"], "applied": a["applied"], "failed": a["failed"], "results": a["results"], "unconnected": a["unconnected"], "errorCode": a["errorCode"], "error": a["error"]});     r["revision"] = a["revision"].clone();     if a["success"] != json!(true) { r["success"] = json!(false); r["errorCode"] = a["errorCode"].clone(); }-    r["_hint"] = json!("Routed as one undo step (altium_undo takes it back). Pours were not obstacles: repour (altium_repour), then altium_routing_drc.");+    r["_hint"] = json!("Routed as one undo step (Ctrl+Z in Altium takes it back; altium_ripup_nets clears the net). Pours were not obstacles: repour (altium_repour), then altium_routing_drc.");     r } +/// altium_place_decoupling {ic, caps?, gapMm?, apply?, filePath?}: the engine places each of an IC's decoupling caps beside the+/// power pin it serves, power pad facing the pin, and checks the moved board with placement_check (#22); apply:true moves+/// them here with move_parts, guarded by the revision it was planned on.+pub fn place_decoupling(args: &Value) -> Value {+    if let Some(e) = open(args) { return e; }+    let st = match board() { Ok(s) => s, Err(e) => return e };+    // the parts' 3D bodies make the boxes honest (a tall cap overhangs its pads); without them the engine uses pads+    let b = crate::bodies::bodies_on(&json!({}), Some(&st));+    let b = if b.get("success").and_then(|v| v.as_bool()) == Some(true) { b } else { Value::Null };+    let mut r = engine("place_decoupling", &json!({"board": st, "bodies": b, "args": without(args, &["filePath", "apply"])}));+    if args.get("apply").and_then(|b| b.as_bool()) != Some(true) || r["success"] != json!(true) { return r; }+    if r["moveArgs"]["parts"].as_array().map(|a| a.is_empty()).unwrap_or(true) { return r; }+    let a = crate::routing::move_parts(&r["moveArgs"]);+    r["applied"] = json!({"success": a["success"], "applied": a["applied"], "failed": a["failed"], "mismatches": a["mismatches"], "errorCode": a["errorCode"], "error": a["error"]});+    r["revision"] = a["revision"].clone();+    if a["success"] != json!(true) { r["success"] = json!(false); r["errorCode"] = a["errorCode"].clone(); }+    r["_hint"] = json!("Moved as one undo step (Ctrl+Z in Altium takes it back; altium_move_parts with each placement's `from` puts the caps back). The tracks to the caps' old spots stayed: rip them up and route again (altium_ripup_nets, altium_plan_route), then altium_repour and altium_routing_drc.");+    r+}++/// altium_plan_fanout {ref, style?, escapeLayer?, viaMm?, viaDrillMm?, widthMm?, clearanceMm?, pitchMm?, stubMm?,+/// surfaceOuterRing?, viaPerimeter?, apply?, filePath?}: the engine plans a BGA's or a QFN/QFP's escape (#22): stubs, dogbone+/// vias, an exposed pad's via grid, as route_net calls, each via and stub measured against other nets' pads. apply:true+/// routes the calls here, one after another, each guarded by the revision the one before left; never over a conflict.+pub fn plan_fanout(args: &Value) -> Value {+    if let Some(e) = open(args) { return e; }+    let st = match board() { Ok(s) => s, Err(e) => return e };+    let rules = crate::agent::call("read_rules", &[], None, Duration::from_secs(60)).get("data").cloned().unwrap_or(Value::Null);+    let mut r = engine("plan_fanout", &json!({"board": st, "stack": stack(), "rules": rules, "args": without(args, &["filePath", "apply"])}));+    if args.get("apply").and_then(|b| b.as_bool()) != Some(true) || r["success"] != json!(true) { return r; }+    if r["conflicts"].as_array().map(|c| !c.is_empty()).unwrap_or(false) {+        r["success"] = json!(false);+        r["errorCode"] = json!("fanout_conflicts");+        r["error"] = json!("the plan has vias or stubs too close to another net's pad: nothing was routed");+        r["_hint"] = json!("Read conflicts: change viaMm, pitchMm, stubMm or style and plan again, or route the clean calls yourself with altium_route_net.");+        return r;+    }+    // every call's tracks and vias from the board read once, applied as one undo step, guarded by the planned revision+    let cur = match crate::routing::guarded(&json!({"expectedRevision": r["revision"]})) { Ok(s) => s, Err(e) => return e };+    let mut ops = Vec::new();+    for call in r["calls"].as_array().cloned().unwrap_or_default() {+        match crate::routing::route_ops(&cur, &call) {+            Ok(o) => ops.extend(o),+            Err(e) => { r["success"] = json!(false); r["errorCode"] = json!("fanout_call_refused"); r["error"] = json!(format!("{}: {}", call["net"].as_str().unwrap_or(""), e["error"].as_str().unwrap_or(""))); return r; }+        }+    }+    let a = crate::routing::apply(&ops, &cur, "plan_fanout");+    r["applied"] = json!({"success": a["success"], "applied": a["applied"], "failed": a["failed"], "calls": r["callCount"], "errorCode": a["errorCode"], "error": a["error"]});+    r["revision"] = a["revision"].clone();+    if a["success"] != json!(true) { r["success"] = json!(false); r["errorCode"] = a["errorCode"].clone(); }+    r["_hint"] = json!("Routed as one undo step (Ctrl+Z in Altium takes it back; altium_ripup_nets clears the nets). Tracks and pours were not checked: altium_repour, then altium_routing_drc.");+    r+}++/// altium_estimate_cost {quantities?, assembly?, basicParts?, prices?, filePath?}: the numbers a fab quote needs, from the+/// board (#22), priced only from a price record the caller passes (`prices`, read from the fab's page with its date):+/// the engine has no rates, and none is made up here.+pub fn estimate_cost(args: &Value) -> Value {+    if let Some(e) = open(args) { return e; }+    let st = match board() { Ok(s) => s, Err(e) => return e };+    let rules = crate::agent::call("read_rules", &[], None, Duration::from_secs(60)).get("data").cloned().unwrap_or(Value::Null);+    engine("estimate_cost", &json!({"board": st, "stack": stack(), "rules": rules, "prices": args.get("prices").cloned().unwrap_or(Value::Null), "args": without(args, &["filePath", "prices"])}))+}+ /// altium_copper_balance {filePath?, resolutionMm?} pub fn copper_balance(args: &Value) -> Value {     if let Some(e) = open(args) { return e; }
bridge-rs/src/placement.rs+1−1
@@ -11,7 +11,7 @@ pub fn placement_check(args: &Value) -> Value {     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 = crate::bodies::bodies_on(&json!({}), Some(&st));     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/src/routing.rs+93−11
@@ -250,7 +250,7 @@ pub fn shape(d: &Value) -> Value {         "has3d": c.get(6).and_then(|b| b.as_i64()).map(|b| b > 0)})).collect();     let polys: Vec<Value> = arr(d, "polys").iter().map(|g| json!({         "net": g[0], "layer": layer_name(i(&g[1])), "layerId": g[1],-        "points": g[2].as_array().map(|ps| ps.iter().map(|p| json!([mm(&p[0]), mm(&p[1])])).collect::<Vec<_>>()).unwrap_or_default()})).collect();+        "points": poly_ring(g[2].as_array().map(|v| v.as_slice()).unwrap_or(&[]))})).collect();     let outline: Vec<Value> = arr(d, "outline").iter().map(|p| json!([mm(&p[0]), mm(&p[1])])).collect();     // the outline as edges: a vertex of kind 1 bends the edge from it to the next into an arc     let raw_out = arr(d, "outline");@@ -427,9 +427,16 @@ fn tht_pad_at(state: &Value, x: f64, y: f64, net: &str) -> bool { /// One track per segment; a waypoint that names a different layer drops a via at that point. pub fn route_net(args: &Value) -> Value {     let st = match guarded(args) { Ok(s) => s, Err(e) => return e };+    match route_ops(&st, args) { Ok(ops) => apply(&ops, &st, "route_net"), Err(e) => e }+}++/// The edit ops of one route_net call on the board model `st` (tracks, and a via at each layer change), or the refusal.+/// Several calls built on one read apply as one undo step (plan_fanout's 30 calls re-read the Sentinel 30 times).+pub fn route_ops(st: &Value, args: &Value) -> Result<Vec<String>, Value> {+    let st = st.clone();     let net = args.get("net").and_then(|v| v.as_str()).unwrap_or("");     if net.is_empty() || !st["nets"].as_array().map(|n| n.iter().any(|x| x.as_str() == Some(net))).unwrap_or(false) {-        return err("unknown_net", format!("net {net:?} is not on the board"), "Use a net name from altium_routing_state nets[].");+        return Err(err("unknown_net", format!("net {net:?} is not on the board"), "Use a net name from altium_routing_state nets[]."));     }     let width = args.get("width").and_then(|v| v.as_f64()).unwrap_or(0.25);     let mut layer = args.get("layer").and_then(layer_id).unwrap_or(TOP);@@ -441,10 +448,10 @@ pub fn route_net(args: &Value) -> Value {     };     let mut ops = Vec::new();     for path in &paths {-        let pts = match path.as_array() { Some(p) => p, None => return err("bad_args", "each path is an array of waypoints".into(), "") };+        let pts = match path.as_array() { Some(p) => p, None => return Err(err("bad_args", "each path is an array of waypoints".into(), "")) };         let mut prev: Option<(f64, f64)> = None;         for w in pts {-            let (x, y, lay) = match waypoint(&st, w) { Ok(v) => v, Err(e) => return err("bad_args", e, "Waypoints are [x,y], {x,y,layer} or {pad:\"U1.3\"}.") };+            let (x, y, lay) = match waypoint(&st, w) { Ok(v) => v, Err(e) => return Err(err("bad_args", e, "Waypoints are [x,y], {x,y,layer} or {pad:\"U1.3\"}.")) };             // Fusion's convention, which AI Flow plans for: the segment ARRIVING at a waypoint is on             // the current layer; a waypoint naming another layer drops a via there and the path             // LEAVES on that layer.@@ -470,7 +477,7 @@ pub fn route_net(args: &Value) -> Value {             prev = Some((x, y));         }     }-    apply(&ops, &st, "route_net")+    Ok(ops) }  /// altium_move_parts {parts:[{ref,x,y,rotation}], expectedRevision?}@@ -595,6 +602,44 @@ fn shoelace_mm2(pts: &[Value]) -> f64 {     (a / 2.0).abs() / (PER_MM * PER_MM) } +/// A polygon's outline from the agent's vertices ([x,y,0] for a line, [x,y,1,cx,cy,r,a1,a2] for an arc to the next+/// vertex, internal units) as a ring of points in mm, each arc split into chords of at most 5 degrees. A bare [x,y]+/// (an older agent) is a line. Pure.+pub fn poly_ring(raw: &[Value]) -> Vec<Value> {+    let mm = |v: &Value| mm(v).as_f64().unwrap_or(0.0);+    let deg = |v: &Value| deg(v).as_f64().unwrap_or(0.0);+    let mut out = Vec::new();+    let n = raw.len();+    for k in 0..n {+        let (p, q) = (&raw[k], &raw[(k + 1) % n]);+        let (x, y) = (mm(&p[0]), mm(&p[1]));+        out.push(json!([x, y]));+        if i(&p.get(2).cloned().unwrap_or(json!(0))) != 1 || n < 2 { continue; }+        let (cx, cy, r) = (mm(&p[3]), mm(&p[4]), mm(&p[5]));+        let (a1, a2) = (deg(&p[6]), deg(&p[7]));+        if r <= 0.0 { continue; }+        // Altium's arc runs counter-clockwise from Angle1 to Angle2; the outline may walk it either way+        let sweep = (a2 - a1).rem_euclid(360.0);+        let sweep = if sweep < 1e-9 { 360.0 } else { sweep };+        let at = |x: f64, y: f64| (y - cy).atan2(x - cx).to_degrees();+        let start = at(x, y);+        let near = |a: f64, b: f64| ((a - b + 540.0).rem_euclid(360.0) - 180.0).abs() < 1.0;+        let (from, dir) = if near(start, a1) { (a1, 1.0) } else if near(start, a2) { (a2, -1.0) } else {+            // neither end on this vertex: go the short way round to the next vertex+            let end = at(mm(&q[0]), mm(&q[1]));+            let d = (end - start + 540.0).rem_euclid(360.0) - 180.0;+            (start, d.signum())+        };+        let total = if near(start, a1) || near(start, a2) { sweep } else { ((at(mm(&q[0]), mm(&q[1])) - start + 540.0).rem_euclid(360.0) - 180.0).abs() };+        let steps = (total / 5.0).ceil().max(1.0) as usize;+        for j in 1..steps {+            let a = (from + dir * total * j as f64 / steps as f64).to_radians();+            out.push(json!([((cx + r * a.cos()) * 10000.0).round() / 10000.0, ((cy + r * a.sin()) * 10000.0).round() / 10000.0]));+        }+    }+    out+}+ /// The agent's pour dump as zones with their real poured copper area. pub fn shape_pours(d: &Value) -> Value {     let mut by_layer = serde_json::Map::new();@@ -616,10 +661,13 @@ pub fn shape_pours(d: &Value) -> Value {         }         let area = (area * 1000.0).round() / 1000.0;         *by_layer.entry(layer.clone()).or_insert(json!(0.0)) = json!(by_layer.get(&layer).and_then(|v| v.as_f64()).unwrap_or(0.0) + area);-        let outline: Vec<Value> = g[3].as_array().cloned().unwrap_or_default().iter().map(|p| json!([mm(&p[0]), mm(&p[1])])).collect();+        let outline = poly_ring(g[3].as_array().map(|v| v.as_slice()).unwrap_or(&[]));+        // a hatched pour is poured as tracks and arcs, not regions: its pieces say it is poured+        let pieces = g.get(6).and_then(|v| v.as_i64()).unwrap_or(0);+        let poured = area > 0.0 || pieces > 0;         let z = json!({"net": g[0], "name": g[5], "layer": layer, "layerId": g[1], "pourIndex": g[2], "outline": outline,-                       "filledMm2": area, "islands": islands, "filled": area > 0.0, "fills": fills});-        if area <= 0.0 {+                       "filledMm2": area, "islands": islands, "filled": poured, "hatchedPieces": pieces, "fills": fills});+        if !poured {             unfilled.push(z.clone());         }         zones.push(z);@@ -802,17 +850,36 @@ fn repour_outside_script() -> Value { /// altium_repour {inScript?}: repour every polygon on the board (Altium's Repour All). By default /// outside the script engine so scoped rules apply; inScript:true keeps the old in-agent repour. pub fn repour(args: &Value) -> Value {+    // what each pour holds, to tell whether a repour changed anything+    let mark = |p: &Value| -> Vec<(String, String, String)> {+        let mut v: Vec<(String, String, String)> = ["zones", "unfilled"].iter().flat_map(|k| p[*k].as_array().cloned().unwrap_or_default())+            .map(|z| (z["pourIndex"].to_string(), z["filledMm2"].to_string(), z["hatchedPieces"].to_string())).collect();+        v.sort();+        v+    };+    let before = mark(&pour_state(&json!({})));     let r = if args.get("inScript").and_then(|v| v.as_bool()) == Some(true) {         agent::call("run_process", &[("process", "PCB:ChangeObject".into()), ("params", "ContextObject=Polygon|Action=RepourAllPolygons".into())], None, Duration::from_secs(600))     } else {         json!({"data": repour_outside_script()})     };-    let pours = pour_state(&json!({}));-    let mut out = json!({"success": pours.get("success").cloned().unwrap_or(json!(false)), "run": r.get("data").cloned().unwrap_or(r.clone())});+    let mut pours = pour_state(&json!({}));+    // Altium's Repour All left the Bluetooth Sentinel's hatched pours untouched (new stubs stayed shorted to them) where+    // rebuilding each polygon cleared them: when no pour changed, rebuild them here and say so+    let mut rebuilt = Value::Null;+    if !before.is_empty() && mark(&pours) == before {+        rebuilt = agent::call("rebuild_pours", &[], None, Duration::from_secs(600)).get("data").cloned().unwrap_or(Value::Null);+        pours = pour_state(&json!({}));+    }+    let mut out = json!({"success": pours.get("success").cloned().unwrap_or(json!(false)), "run": r.get("data").cloned().unwrap_or(r.clone()), "rebuiltInScript": rebuilt});     for k in ["zones", "filledAreaByLayerMm2", "unfilled"] {         out[k] = pours[k].clone();     }-    out["_hint"] = json!("Repoured every polygon outside the script engine (the agent stops for it and starts again), so scoped rules (each pour's connect style, net-class clearances) apply. zones[] is the copper after the repour.");+    out["_hint"] = json!(if out["rebuiltInScript"].is_null() {+        "Repoured every polygon outside the script engine (the agent stops for it and starts again), so scoped rules (each pour's connect style, net-class clearances) apply. zones[] is the copper after the repour."+    } else {+        "Altium's Repour All changed no pour, so each polygon was rebuilt from inside the script engine (rebuiltInScript). Scoped pour rules (IsNamedPolygon) do not apply there: if the board has them, check with altium_routing_drc. zones[] is the copper after."+    });     out } @@ -1480,4 +1547,19 @@ mod project_listing_tests {         assert_eq!(docs[0], std::path::Path::new("/w").join("Buck.SchDoc"));         assert_eq!(docs[3], std::path::PathBuf::from("C:\\other\\Shared.PcbLib"));     }+    #[test]+    fn a_pour_outline_with_arcs_becomes_a_ring_of_points() {+        let k = PER_MM;+        // a half disc of radius 10 at the origin: a line along the x axis, then an arc back over the top+        let raw = vec![json!([10.0 * k, 0.0, 0]), json!([-10.0 * k, 0.0, 1, 0.0, 0.0, 10.0 * k, 0, 180000])];+        let ring = poly_ring(&raw);+        assert!(ring.len() > 30, "{}", ring.len());+        assert!(ring.iter().all(|p| p[1].as_f64().unwrap() >= -1e-6), "the arc goes over the top, not under");+        assert!(ring.iter().any(|p| (p[1].as_f64().unwrap() - 10.0).abs() < 0.05), "it reaches the top of the disc");+        // the same arc walked from its other end goes back the same way+        let raw2 = vec![json!([-10.0 * k, 0.0, 0]), json!([10.0 * k, 0.0, 1, 0.0, 0.0, 10.0 * k, 0, 180000])];+        assert!(poly_ring(&raw2).iter().all(|p| p[1].as_f64().unwrap() >= -1e-6));+        // an older agent's bare vertices still read+        assert_eq!(poly_ring(&[json!([0, 0]), json!([k, 0.0]), json!([k, k])]).len(), 3);+    } }
bridge-rs/src/verbs.rs+23−5
@@ -22,7 +22,7 @@ pub const KNOWN: &[&str] = &[     "list_nets", "net_connections", "layers", "copper_layers", "read_rules",     "set_layer_visibility", "footprint_primitives", "schematic_data", "layer_stack", "net_classes", "diff_pairs", "board_outline", "set_track_width", "find_space", "selection", "check_orientation", "replicate_layout", "outjob_info", "find_symbol", "part_parameters",     // the live-board lane AI Flow drives-    "routing_state", "route_net", "plan_route", "move_parts", "export_library_part", "create_part_project", "library_views", "render_board_3d", "render_board_layers", "document_info", "close_all_documents", "project_info", "project_create", "project_rename", "project_snapshot", "cross_probe", "read_footprint", "export_odb", "export_ipc2581", "export_ipc356", "export_dxf", "export_gencad", "import_svg", "edit_footprint", "generate_body", "remove_parts", "edit_parts", "align_parts", "set_layer_count", "copy_routing", "check_clearance", "remove_graphics", "place_vias", "board_features", "sch_sheet_symbol", "netlist", "silkscreen_prep", "net_lengths", "teardrops", "component_classes", "read_sheet_file", "fab_check", "panelize", "impedance", "current_capacity", "height_check", "bodies", "copper_balance", "return_path", "silk_designators", "via_fence", "assembly_check", "jlcpcb_order", "schematic_review", "pin_pad_check", "route_pair", "thermal_vias", "board_report", "placement_check", "auto_classes", "length_tune", "remove_items", "ripup_nets", "apply_pours", "pour_state", "remove_pours", "repour", "routing_drc", "build_board", "set_outline", "set_design_rules", "zoom_to", "add_rule", "build_schematic", "export_manufacturing", "select_net", "silk_state", "apply_silkscreen",+    "routing_state", "route_net", "plan_route", "move_parts", "place_decoupling", "plan_fanout", "estimate_cost", "export_library_part", "create_part_project", "library_views", "render_board_3d", "render_board_layers", "document_info", "close_all_documents", "project_info", "project_create", "project_rename", "project_snapshot", "cross_probe", "read_footprint", "export_odb", "export_ipc2581", "export_ipc356", "export_dxf", "export_gencad", "import_svg", "edit_footprint", "generate_body", "remove_parts", "edit_parts", "align_parts", "set_layer_count", "copy_routing", "check_clearance", "remove_graphics", "place_vias", "board_features", "sch_sheet_symbol", "netlist", "silkscreen_prep", "net_lengths", "teardrops", "component_classes", "read_sheet_file", "fab_check", "panelize", "impedance", "current_capacity", "height_check", "bodies", "copper_balance", "return_path", "silk_designators", "via_fence", "assembly_check", "jlcpcb_order", "schematic_review", "pin_pad_check", "route_pair", "thermal_vias", "board_report", "placement_check", "auto_classes", "length_tune", "remove_items", "ripup_nets", "apply_pours", "pour_state", "remove_pours", "repour", "routing_drc", "build_board", "set_outline", "set_design_rules", "zoom_to", "add_rule", "build_schematic", "export_manufacturing", "select_net", "silk_state", "apply_silkscreen",     // surfaces     "show_project", "show_schematic", "show_2d_board", "show_3d_board", "show_library",     "show_symbol", "show_footprint", "show_3d_chip", "list_library", "demo",@@ -413,10 +413,25 @@ fn describe() -> Value {             "Coordinates are mm in Altium's frame, the same as altium_routing_state. There is no clearance check here yet: run your own DRC (AI Flow's gate) or altium_run_drc after.",             &["routing_state", "place_vias", "remove_items", "ripup_nets"], &["Needs the board current.", "A net name must already exist on the board (nets come from the schematic / pads)."], json!({"net": "VOUT", "width": 0.5, "paths": [[{"pad": "L1.2"}, [120.0, 90.0], {"pad": "C6.1"}]]})),         verb_doc("plan_route", "Find a path for one net between two pads, clear of other nets' copper by the board's clearance rule, on the copper layers you allow, with vias between them (the standard's shared planner). A plan: apply:true routes it.",-            json!({"net": "string (required)", "from": "Ref.Pad (required), e.g. U1.3", "to": "Ref.Pad (required)", "widthMm": "track width, default the board's Width rule (Preferred), else 0.25", "layers": "[F.Cu, B.Cu, In<n>.Cu] - default F.Cu and B.Cu", "allowVias": "bool, default true", "viaSizeMm": "mm, default the board's Routing Via rule, else 0.6", "viaDrillMm": "mm, default the Routing Via rule, else 0.3", "gridMm": "search grid, default 0.5; 0.1 for fine-pitch pads", "clearanceMm": "only raises the board's rule", "edgeClearanceMm": "mm from the outline", "maxNodes": "search bound, default 50000", "apply": "bool, default false - route it with altium_route_net, guarded by the revision it was planned on", "filePath": "the .PcbDoc (opened first; else the current board)"}),-            json!({"found": "bool", "routeNet": "altium_route_net's own arguments {net, layer, width, viaSize, viaDrill, paths}", "lengthMm": "float", "vias": "int", "viaAt": "[[x, y]]", "revision": "string - pass as expectedRevision", "reason": "string - why no path, when found is false", "applied": "{success, applied, failed, unconnected} - with apply", "engine": "string"}), 300,+            json!({"net": "string (required)", "from": "Ref.Pad (required), e.g. U1.3", "to": "Ref.Pad (required)", "widthMm": "track width, default the board's Width rule (Preferred), else 0.25", "layers": "[F.Cu, B.Cu, In<n>.Cu] - default F.Cu and B.Cu", "allowVias": "bool, default true", "viaSizeMm": "mm, default the board's Routing Via rule, else 0.6", "viaDrillMm": "mm, default the Routing Via rule, else 0.3", "gridMm": "search grid, default 0.5; 0.1 for fine-pitch pads", "clearanceMm": "only raises the board's rule", "edgeClearanceMm": "mm from the outline", "maxNodes": "search bound, default 50000", "avoidPours": "true keeps out of every other net's pour, [net] out of those nets' pours only; default false (a route may cross them, crossesPours names each)", "pourCost": "number, default 0 - each mm inside another net's pour costs 1 + pourCost mm: a preference, not a wall", "apply": "bool, default false - route it with altium_route_net, guarded by the revision it was planned on", "filePath": "the .PcbDoc (opened first; else the current board)"}),+            json!({"found": "bool", "routeNet": "altium_route_net's own arguments {net, layer, width, viaSize, viaDrill, paths}", "lengthMm": "float", "vias": "int", "viaAt": "[[x, y]]", "revision": "string - pass as expectedRevision", "reason": "string - why no path, when found is false", "crossesPours": "[the other nets' pours the route runs through: check after the repour that none split]", "applied": "{success, applied, failed, unconnected} - with apply", "engine": "string"}), 300,             "A plan changes nothing: read it, then call again with apply:true, or pass routeNet to altium_route_net yourself. Pours are not obstacles: repour after. The path is orthogonal on the grid: a 0.5 mm pitch part needs gridMm 0.1 to escape its pads. found:false says why (no room at this grid and clearance, or the search bound).",             &["route_net", "routing_state", "repour", "routing_drc", "route_pair"], &["Pours are ignored: a route through a pour's area cuts it until the repour.", "A coarse grid misses paths between fine-pitch pads: try gridMm 0.1 before giving up."], json!({"net": "N1", "from": "U1.8", "to": "U2.1", "gridMm": 0.25})),+        verb_doc("place_decoupling", "Put an IC's decoupling caps beside the power pins they serve: each cap just outside the IC, power pad facing its pin, lined up with it, sliding along the side when the spot is taken (the standard's shared planner). A plan checked with placement_check; apply:true moves them.",+            json!({"ic": "the IC's designator (required), e.g. U1", "caps": "[designator] - optional; default every cap between one of the IC's power nets and ground, leaving out signal caps (a crystal's load caps) and caps nearer another IC on the same supply", "gapMm": "mm outside the IC's box, default 0.3", "apply": "bool, default false - move them with altium_move_parts, guarded by the revision planned on", "filePath": "the .PcbDoc (opened first; else the current board)"}),+            json!({"placements": "[{cap, net, pin, side, x, y, rotation, powerPad, padToPinMm, slidMm, from}]", "leftOut": "[{cap, reason: signal_net | nearer_another_ic}]", "skipped": "[{cap, reason: other_side | no_shared_power_net | no_free_spot}]", "moveArgs": "altium_move_parts' own arguments {parts, expectedRevision}", "validation": "placement_check on the moved board, what concerns the caps", "applied": "{success, applied, failed, mismatches} - with apply", "engine": "string"}), 300,+            "A plan changes nothing: read placements, leftOut and validation, then call again with apply:true (or pass moveArgs to altium_move_parts). The tracks to the caps' old spots stay: rip up and route again (altium_plan_route), then repour. Name caps to place one the default set left out.",+            &["move_parts", "placement_check", "plan_route", "ripup_nets", "repour", "check_clearance"], &["Boxes are pads plus 3D bodies: Altium courtyards are not read.", "A cap on the other side from the IC is skipped (other_side): flip it first if it should move."], json!({"ic": "U1"})),+        verb_doc("plan_fanout", "Plan a BGA's or a QFN/QFP's escape (the standard's shared planner): the outer ring on the surface and a dogbone via (or via in pad) for each inner ball, an outward stub per perimeter pad (with a via for ground or viaPerimeter), a via grid in an exposed pad. route_net calls, one per net, each via and stub measured against other nets' pads. apply:true routes them.",+            json!({"ref": "the package's designator (required)", "style": "dogbone | via_in_pad (BGA)", "escapeLayer": "copper layer the vias reach (default the first inner layer, else the other side)", "viaMm": "via diameter", "viaDrillMm": "via drill", "widthMm": "stub width", "clearanceMm": "to other nets' pads", "pitchMm": "override the measured pitch", "stubMm": "stub length", "surfaceOuterRing": "bool (BGA): the outer ring escapes on the surface", "viaPerimeter": "bool: a via at the end of every perimeter stub", "includeRouted": "bool, default false - plan pins their net already reaches too", "apply": "bool, default false - route every call as one undo step, guarded by the revision planned on; refused while conflicts are listed", "filePath": "the .PcbDoc (opened first; else the current board)"}),+            json!({"package": "bga | perimeter", "pitchMm": "float", "escapeLayer": "string", "calls": "[altium_route_net arguments], one per net", "callCount": "int", "viaCount": "int", "minViaToPadMm": "float", "conflicts": "[vias or stubs closer than clearanceMm to another net's pad, track, arc or via]", "pads": "[{pad, net, action, why?}] - action skip with why \"already routed\" for pins their net already reaches (includeRouted plans them)", "crossesPours": "[pours the stubs run into]", "warnings": "[string]", "revision": "string", "applied": "{success, applied, failed, calls} - with apply: every call as one undo step", "engine": "string"}), 300,+            "A plan changes nothing: read conflicts first. apply:true routes every call (each one undo step) and refuses while conflicts are listed. Tracks and pours are not checked: repour and run altium_routing_drc after. Via-in-pad needs filled and capped vias: tell the user first.",+            &["route_net", "plan_route", "routing_state", "repour", "routing_drc", "layer_stack"], &["Repour before DRC: a hatched pour's net-less pieces re-pour round the new copper only on the repour.", "Via in pad (style via_in_pad) costs filled, capped vias at the fab."], json!({"ref": "U3"})),+        verb_doc("estimate_cost", "The numbers a fab quote needs (size, copper layers, thickness, smallest track, gap and drill, holes, parts and joints) from the board, and a rough price table at the quantities asked when you pass a price record read from the fab's own page (the standard's shared estimator; it has no rates of its own).",+            json!({"quantities": "[int], default [5, 10, 30, 100]", "assembly": "bool, default false", "basicParts": "int: parts the assembler stocks as basic", "prices": "a price record {vendor, url, read, currency, pcb: [{layers, setup, perM2, promo?}], thickness?, assembly?, excludes?} read from the fab's page with its date; without one the reply is the numbers only", "filePath": "the .PcbDoc (opened first; else the current board)"}),+            json!({"board": "{widthMm, heightMm, areaMm2, layers, thicknessMm, minTrackMm, minGapMm, minDrillMm, holes, vias, smdParts, thtParts, smdJoints, thtJoints, uniqueParts, assemblySides}", "prices": "[{quantity, ...}] - only with a price record", "source": "{name, url, read} of the record", "notes": "[string]", "rough": "bool", "engine": "string"}), 120,+            "No rates are built in, so none can go stale: read the fab's current prices from its page, pass them as prices with the date read, and the reply prices the quantities from them. altium_fab_check compares the same numbers with a fab's limits. altium_jlcpcb_order makes the order files.",+            &["fab_check", "jlcpcb_order", "layer_stack", "board_report"], &["A rough estimate only: get a real quote before ordering."], json!({"quantities": [5, 30]})),         verb_doc("move_parts", "Move, rotate and flip placed components (side top or bottom; flip:true turns a part over); each part is read back to 0.001 mm, the exact rotation and its side. One undo step.",             json!({"parts": "[{ref, x, y, rotation, side?: top|bottom, flip?: bool}] - mm and degrees, Altium's frame; or {ref, dx, dy} to move by an offset; rotation and side kept when left out", "expectedRevision": "string (optional) - the revision you last read; refused with stale_board if the board changed", "boardId": "string (optional) - refused with board_mismatch unless this is the current board", "expectPath": "string (optional)"}),             json!({"revision": "string", "results": "[ok|err:...]", "mismatches": "[{ref, asked, got}] when a part did not land where asked (errorCode readback_mismatch)"}), 300,@@ -755,8 +770,8 @@ fn describe() -> Value {             "A track is copied when both ends are in the box, a via when its centre is. Without a remap the copy keeps its nets. Dry-run first and check netMap.", &["routing_state", "move_parts"], &["Only through vias are copied: blind and buried vias are skipped.", "The copy connects only where the target pads sit at the same offset: place the target channel identically first (replicate_layout).", "One source net mapping to two target nets is refused (net_map_conflict) unless netMap settles it.", "Arcs are listed under skipped, not copied, on Altium yet.", "validate runs Altium's batch DRC before and after: a copy that adds errors is taken back out (rolledBack:true)."], json!({"filePath": "C:/proj/Board.PcbDoc", "box": [10, 10, 30, 25], "offset": [25, 0], "refPattern": {"from": "CH1_*", "to": "CH2_*"}, "expectedRevision": "<rev>"})),         verb_doc("check_clearance", "Measure the gaps between parts, courtyard to courtyard or pad copper to pad copper, for the listed parts or the whole board, and report every pair under a threshold, closest first.",             json!({"filePath": "path to the board file (default: the board open in the tool)", "refs": "[\"U1\", \"C3\"]: keep pairs that involve one of these (default every part)", "mode": "courtyard|pads, default courtyard", "thresholdMm": "number, default 0.25 (courtyard) or 0.2 (pads)", "includeSameNet": "bool, default false (pads)", "maxPairs": "int, default 200"}),-            json!({"pairs": "[{a, b, distanceMm, overlapping: bool, touching: bool}]", "clean": "bool", "thresholdMm": "number", "measuredOn": "courtyard outline|courtyard box|pads"}), 300,-            "Computed from the board model: courtyards compare only parts on the same side, pads only copper that shares a side.", &["routing_state", "move_parts"], &["Rounded pads may be measured as their full rectangle, so a gap can read a little small: the tool's DRC (run_drc) is the authority.", "Measured on bounding rectangles from the board model: a rotated or rounded pad reads closer than it is."], json!({"filePath": "C:/proj/Board.PcbDoc", "refs": ["U1"], "mode": "pads", "thresholdMm": 0.2})),+            json!({"pairs": "[{a, b, distanceMm, overlapping: bool, touching: bool}] closest first", "clean": "bool", "thresholdMm": "number", "measuredOn": "what was compared", "pairsChecked": "int", "violationCount": "int", "truncated": "bool", "engine": "string"}), 300,+            "The standard's shared check on the board model and the parts' 3D bodies: courtyard mode compares part boxes (pads plus bodies) on the same side, pads mode compares pad copper of different parts on a shared layer by its real outline (round pads as circles or stadiums, turned pads turned).", &["routing_state", "move_parts", "place_decoupling", "placement_check"], &["Altium courtyards are not read: a part is its pads plus its 3D body. The tool's DRC (run_drc, Component Clearance) is the authority."], json!({"filePath": "C:/proj/Board.PcbDoc", "refs": ["U1"], "mode": "pads", "thresholdMm": 0.2})),         verb_doc("remove_graphics", "Remove board graphics (lines, rectangles, circles, arcs, polygons, texts, dimensions) by id, or every one on a layer and of a kind. One undo step.",             json!({"filePath": "path to the board file (default: the board open in the tool)", "expectedRevision": "string: the revision you last read (routing_state); refused with stale_board if the board changed", "ids": "[id]", "layer": "\"F.SilkS\": every graphic on this layer", "kinds": "[line|rect|circle|arc|polygon|text|dimension]", "dryRun": "bool, default false: answer the plan and change nothing"}),             json!({"removed": "[{id, kind, layer, points}]", "revision": "string: the board's new revision"}), 300,@@ -2077,6 +2092,9 @@ pub fn dispatch(command: &str, args: &Value, _forwarded: &[(String, String)]) ->         "impedance" => crate::checks::impedance(args),         "current_capacity" => crate::checks::current_capacity(args),         "plan_route" => crate::checks::plan_route(args),+        "place_decoupling" => crate::checks::place_decoupling(args),+        "plan_fanout" => crate::checks::plan_fanout(args),+        "estimate_cost" => crate::checks::estimate_cost(args),         "height_check" => crate::bodies::height_check(args),         "bodies" => crate::bodies::bodies(args),         "copper_balance" => crate::checks::copper_balance(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.9.1, engine 0.6.1 |+| `adom-eda-checks/` | adom/eda-bridge-standard `engine/` (the shared checks engine) | standard 0.13.3, engine 0.10.3 | | `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.6.1"+version = "0.10.3" 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+7−2
@@ -11,14 +11,18 @@ boards the engine gives the same answers the Altium bridge 0.2.76 gives.  | Check | Reads | What it answers | |---|---|---|+| `check_clearance` | board, bodies? | pairs of parts closer than `thresholdMm`, closest first: `mode: courtyard` (default 0.25) measures part boxes (pads, and 3D bodies when given) on the same side; `mode: pads` (default 0.2) measures pad copper of different parts that shares a layer, by its real outline, skipping same-net pairs unless `includeSameNet`; `refs` keeps pairs involving those parts. A part under a raised one (pads apart, bodies apart in 3D) is listed in `stacked`, not `pairs`, as placement_check lists it. From the KiCad bridge's place_tools | | `copper_balance` | board, stack, pours | copper per layer and how evenly mirrored layers match (bow and twist) | | `return_path` | board, stack, pours | signal tracks running over a gap in the neighbouring layer's reference copper, with a pour plan that closes each gap (`apply_pours`) |+| `estimate_cost` | board, stack?, rules?, prices? | the numbers a fab quote needs (size, copper layers, thickness from the stack, smallest track, gap from the clearance rule, smallest drill, holes, SMD and through-hole parts and joints, unique parts, assembled sides) and, with a `prices` record, a rough table at `quantities` (default 5, 10, 30, 100), with assembly when asked, every assumption stated and the record named in `source`. The engine carries no rates: without `prices` the reply is the numbers only. From the KiCad bridge's fab.rs | | `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 |+| `place_decoupling` | board, bodies? | positions for an IC's decoupling caps (`ic`, `caps?`, `gapMm` 0.3): each just outside the IC's box on the side of the power pin it serves, turned so its power pad faces the pin and level with it, sliding along when the spot is taken (by a part on the same side, or a through-hole pad from the other). Without `caps` it takes caps across ground and a supply of the IC, leaving out (`leftOut`) a signal net with one cap (a crystal's load) and a cap nearer another IC's pin on that supply. Each cap's pads keep clear of the stubs and vias plan_fanout would give the IC's other pins (`leaveFanout`, default true), so the fanout still fits after. A cap it cannot place stays where it is and keeps its spot. `icPowerNets` lists the IC's supplies. `moveArgs` is move_parts' arguments; `validation` is placement_check on the moved board. From the KiCad bridge's place_tools | | `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; `stacked` lists plan-view overlaps where one part sits wholly above the other (a part under a raised molecule: pads apart, no bodies meeting in 3D); `bodiesUsed: false` when no bodies were given |-| `plan_route` | board, rules? | a path between two pads of a net (`from`, `to` as Ref.Pad) on any listed copper `layers`, with through vias between them: a bounded orthogonal A* on `gridMm`, width and via from the args, else the board's width and via rules (`planner.widthFrom`, `viaFrom`), keeping `widthMm/2` + the board's clearance from other nets' copper (pads by their real outline), inside the outline, no via in a pad. `routeNet` is route_net's arguments, unchanged; pours are not obstacles (repour after) |+| `plan_fanout` | board, stack?, rules? | the fanout of a BGA or QFN/QFP (`ref`): pitch and package from its pads; a BGA's outer ring escapes on the surface and each inner ball takes a dogbone via, or a via in the pad when the dogbone does not fit (`style` auto); a perimeter pad takes an outward stub, with a via at its end for ground or `viaPerimeter`, and an exposed pad a via grid. `calls` are route_net arguments, one per net; `conflicts` lists each via and stub closer than the clearance to another net's pad, track, arc or via anywhere on the board. A pin its net's copper already reaches is skipped (`includeRouted` plans it anyway), the exposed-pad grid keeps clear of holes already there, and `crossesPours` names other nets' pours the plan runs into (repour before DRC). From the KiCad bridge's place_tools |+| `plan_route` | board, rules? | a path between two pads of a net (`from`, `to` as Ref.Pad) on any listed copper `layers`, with through vias between them: a bounded orthogonal A* on `gridMm`, width and via from the args, else the board's width and via rules (`planner.widthFrom`, `viaFrom`), keeping `widthMm/2` + the board's strictest board-wide copper clearance rule from other nets' copper (pads by their real outline), inside the outline, no via in a pad; a through via is checked on every copper layer of the board (`planner.viasCheckedOn`), not only the planned ones. `routeNet` is route_net's arguments, unchanged. Pours are not obstacles (repour after), but `crossesPours` names each other net's pour the route runs through, since that can split it; `avoidPours: true` keeps the route out of them (or a list of nets: out of theirs only), and `pourCost` makes a mm inside one cost 1 + pourCost mm, a preference where a hard block finds no path | | `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 | @@ -59,6 +63,7 @@ Every check takes one JSON object: | `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` |+| `prices` | a price record read from the fab's own page: `{vendor, url, read, currency, pcb: [{layers, setup, perM2, promo?: {maxMm: [w, h], prices: [[qty, price]]}}], thickness?: {standardMm, factor}, assembly?: {setupPerSide, stencilPerSide, perSmdJoint, perThtJoint, perExtendedPart}, excludes?}`. The pcb row used is the one for the fewest copper layers that covers the board | | `args` | the check's own arguments, as the standard verb documents them |  Each part may be the bare model or the bridge's whole reply: the model's keys at the top level, or under `data`.@@ -90,7 +95,7 @@ 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`, `place_vias`): a bridge adds its own. Every reply also carries `engine`-(`"adom-eda-checks 0.6.1"`), so a bridge reports the engine it runs without writing the version by hand.+(`"adom-eda-checks 0.10.3"`), so a bridge reports the engine it runs without writing the version by hand.  ## Tests 
bridge-rs/vendor/adom-eda-checks/src/cost.rsadded+182
@@ -0,0 +1,182 @@+//! The numbers a fab quote needs, from the board model (size, copper layers, thickness, smallest track, gap and drill,+//! holes, parts and joints), and a rough price table at the quantities asked. From the KiCad bridge's fab.rs, with one+//! change: the engine has no rates of its own. Prices come in as a record read from the fab's own page with its date+//! (`prices`), and without one the reply is the numbers only. Pure.+use serde_json::{json, Value};+use std::collections::BTreeSet;++fn f(v: &Value) -> f64 { v.as_f64().unwrap_or(0.0) }+fn r2(v: f64) -> f64 { (v * 100.0).round() / 100.0 }+fn r3(v: f64) -> f64 { (v * 1000.0).round() / 1000.0 }++/// The board's numbers. `layers` from the stack when given, else the copper layers the board uses; the thickness from+/// the stack only.+pub fn board_numbers(st: &Value, stack: Option<&Value>, rules: &[Value]) -> Value {+    let (w, h) = crate::geom::outline_bbox(st).map(|(x0, y0, x1, y1)| (x1 - x0, y1 - y0)).unwrap_or((0.0, 0.0));+    let mut used: BTreeSet<String> = BTreeSet::new();+    for k in ["tracks", "arcs", "pads", "polygons"] {+        for x in st[k].as_array().into_iter().flatten() {+            if let Some(l) = x["layer"].as_str().filter(|l| l.ends_with(".Cu") && *l != "*.Cu") { used.insert(l.to_string()); }+        }+    }+    let layers = stack.and_then(|s| s["copperLayers"].as_u64()).unwrap_or((used.len() as u64).max(2));+    let thickness = stack.and_then(|s| s["totalUm"].as_f64()).filter(|t| *t > 0.0).map(|t| r3(t / 1000.0));+    let m = crate::fab::measure(st);+    let mm = |k: &str| m.get(k).and_then(|v| v["mm"].as_f64());+    let min_drill = [mm("viaDrill"), mm("padHole")].into_iter().flatten().fold(None, |a: Option<f64>, b| Some(a.map(|x| x.min(b)).unwrap_or(b)));+    let pads = st["pads"].as_array().cloned().unwrap_or_default();+    let vias = st["vias"].as_array().map(|a| a.len()).unwrap_or(0);+    let drilled = pads.iter().filter(|p| f(&p["drill"]) > 0.0).count();+    // a part is a component with pads (a logo or a drawing has none); through-hole when any pad is drilled+    let (mut smd, mut tht, mut smd_j, mut tht_j, mut sides, mut unique) = (0, 0, 0, 0, BTreeSet::new(), BTreeSet::new());+    for c in st["components"].as_array().into_iter().flatten() {+        let r = c["ref"].as_str().unwrap_or("");+        let own: Vec<&Value> = pads.iter().filter(|p| p["ref"].as_str() == Some(r)).collect();+        if own.is_empty() { continue; }+        let holes = own.iter().filter(|p| f(&p["drill"]) > 0.0).count();+        if holes > 0 { tht += 1; } else { smd += 1; }+        smd_j += own.len() - holes;+        tht_j += holes;+        sides.insert(c["side"].as_str().unwrap_or("top").to_string());+        unique.insert(c["pattern"].as_str().unwrap_or(r).to_string());+    }+    json!({"widthMm": r3(w), "heightMm": r3(h), "areaMm2": r2(w * h), "layers": layers, "thicknessMm": thickness,+        "minTrackMm": mm("track"), "minGapMm": crate::fab::min_clearance(rules), "minDrillMm": min_drill,+        "holes": vias + drilled, "vias": vias, "drilledPads": drilled, "smdParts": smd, "thtParts": tht, "totalParts": smd + tht,+        "smdJoints": smd_j, "thtJoints": tht_j, "uniqueParts": unique.len(), "assemblySides": sides.into_iter().collect::<Vec<_>>()})+}++/// The price table from a price record: `{vendor, url, read, currency, pcb: [{layers, setup, perM2, promo?: {maxMm: [w,+/// h], prices: [[qty, price]]}}], thickness?: {standardMm, factor}, assembly?: {setupPerSide, stencilPerSide, perSmdJoint,+/// perThtJoint, perExtendedPart}, excludes?: [..]}`. The pcb row is the one for the fewest copper layers that still+/// covers the board.+pub fn price_table(n: &Value, prices: &Value, quantities: &[u64], assembly: bool, basic_parts: Option<u64>) -> Result<Value, String> {+    let layers = n["layers"].as_u64().unwrap_or(2);+    let rows = prices["pcb"].as_array().ok_or("the price record has no pcb rows")?;+    let row = rows.iter().filter(|r| r["layers"].as_u64().map(|l| l >= layers).unwrap_or(false)).min_by_key(|r| r["layers"].as_u64())+        .ok_or_else(|| format!("the price record has no row for {layers} copper layers"))?;+    let (setup, per_m2) = (f(&row["setup"]), f(&row["perM2"]));+    let (w, h) = (f(&n["widthMm"]), f(&n["heightMm"]));+    let area_m2 = w * h / 1_000_000.0;+    let promo = row.get("promo").filter(|p| {+        let max = (f(&p["maxMm"][0]), f(&p["maxMm"][1]));+        (w <= max.0 && h <= max.1) || (w <= max.1 && h <= max.0)+    });+    let factor = match (prices.get("thickness"), n["thicknessMm"].as_f64()) {+        (Some(t), Some(mm)) if (mm - f(&t["standardMm"])).abs() > 0.05 => f(&t["factor"]).max(1.0),+        _ => 1.0,+    };+    let a = &prices["assembly"];+    if assembly && a.is_null() { return Err("assembly was asked for, but the price record has no assembly rates".into()); }+    let sides = n["assemblySides"].as_array().map(|s| s.len()).unwrap_or(1).max(1) as f64;+    let unique = n["uniqueParts"].as_u64().unwrap_or(0);+    let extended = basic_parts.map(|b| unique.saturating_sub(b)).unwrap_or(unique);+    let mut out = Vec::new();+    for &q in quantities {+        let qf = q as f64;+        // the promotional price for the smallest quantity it covers+        let promo_price = promo.and_then(|p| p["prices"].as_array().and_then(|ps| ps.iter().filter(|e| e[0].as_u64().map(|x| x >= q).unwrap_or(false)).min_by_key(|e| e[0].as_u64()).map(|e| f(&e[1]))));+        let pcb = r2(promo_price.unwrap_or(setup + per_m2 * area_m2 * qf) * factor);+        let mut r = json!({"quantity": q, "board": pcb});+        let mut total = pcb;+        if assembly && n["totalParts"].as_u64().unwrap_or(0) > 0 {+            let asm = r2((f(&a["setupPerSide"]) + f(&a["stencilPerSide"])) * sides + (f(&n["smdJoints"]) * f(&a["perSmdJoint"]) + f(&n["thtJoints"]) * f(&a["perThtJoint"])) * qf + f(&a["perExtendedPart"]) * extended as f64);+            r["assembly"] = json!(asm);+            total += asm;+        }+        r["total"] = json!(r2(total));+        r["perBoard"] = json!(r2(total / qf.max(1.0)));+        r["currency"] = prices["currency"].clone();+        out.push(r);+    }+    let mut assumptions = vec![format!("Board: {setup} setup plus {per_m2} per square metre of boards, from the {}-layer row.", row["layers"])];+    if let Some(p) = promo { assumptions.push(format!("Boards up to {} x {} mm take the promotional prices {} where they cover the quantity.", p["maxMm"][0], p["maxMm"][1], p["prices"])); }+    if factor > 1.0 { assumptions.push(format!("A thickness other than {} mm multiplies the board price by {factor}.", prices["thickness"]["standardMm"])); }+    if assembly {+        assumptions.push(format!("Assembly: setup and stencil per assembled side ({sides} side(s)), per joint, and a loading fee per extended part ({extended} of {unique} unique parts counted as extended{}).", if basic_parts.is_some() { "" } else { "; pass basicParts to count the basic ones" }));+        assumptions.push("Component cost is not included: price the BOM with adom-parts-search.".into());+    }+    for e in prices["excludes"].as_array().into_iter().flatten() { if let Some(s) = e.as_str() { assumptions.push(format!("Not included: {s}.")); } }+    Ok(json!({"prices": out, "assumptions": assumptions}))+}++/// estimate_cost: input {board, stack?, rules?, prices?, args: {quantities?, assembly?, basicParts?}}.+pub fn estimate_cost(input: &Value) -> Value {+    let st = match crate::input::board(input) { Ok(b) => b, Err(e) => return e };+    let args = &input["args"];+    let quantities: Vec<u64> = args["quantities"].as_array().map(|a| a.iter().filter_map(|v| v.as_u64()).filter(|q| *q > 0).collect()).unwrap_or_else(|| vec![5, 10, 30, 100]);+    if quantities.is_empty() { return crate::input::refuse("bad_args", "quantities are whole numbers above 0, e.g. [5, 10, 30, 100]"); }+    let assembly = args["assembly"].as_bool().unwrap_or(false);+    let stack = crate::input::stack(input);+    let n = board_numbers(&st, stack.as_ref(), &crate::input::rules(input));+    let mut notes = Vec::new();+    if n["thicknessMm"].is_null() { notes.push("thicknessMm: no stack in the input, so the thickness is unknown and no thickness surcharge is applied"); }+    if n["minGapMm"].is_null() { notes.push("minGapMm: the board's clearance rule, and no rules came in the input"); }+    let Some(prices) = crate::input::part(input, "prices") else {+        return json!({"success": true, "board": n, "prices": Value::Null, "source": Value::Null, "notes": notes, "quantities": quantities,+            "_hint": "The board's numbers only: the engine carries no rates. Pass a price record as prices ({vendor, url, read, currency, pcb: [{layers, setup, perM2, promo?}], thickness?, assembly?, excludes?}), read from the fab's own page with the date, and the reply prices these quantities from it."});+    };+    match price_table(&n, &prices, &quantities, assembly, args["basicParts"].as_u64()) {+        Ok(t) => json!({"success": true, "board": n, "prices": t["prices"], "assumptions": t["assumptions"], "notes": notes, "rough": true,+            "source": {"name": prices["vendor"], "url": prices["url"], "read": prices["read"]},+            "_hint": "A rough estimate from the price record named in source, as of its read date: get a real quote from the fab before ordering."}),+        Err(e) => crate::input::refuse("bad_prices", &e),+    }+}++#[cfg(test)]+mod tests {+    use super::*;++    fn board() -> Value {+        json!({"outline": [[0, 0], [50, 0], [50, 40], [0, 40]],+            "tracks": [{"layer": "F.Cu", "width": 0.2, "net": "A", "start": {"x": 1, "y": 1}, "end": {"x": 5, "y": 1}}, {"layer": "B.Cu", "width": 0.15, "net": "A", "start": {"x": 1, "y": 2}, "end": {"x": 5, "y": 2}}],+            "vias": [{"drill": 0.3, "size": 0.6, "net": "A", "position": {"x": 5, "y": 1.5}}],+            "components": [{"ref": "U1", "side": "top", "pattern": "SOIC8"}, {"ref": "J1", "side": "top", "pattern": "HDR2"}, {"ref": "C1", "side": "bottom", "pattern": "0603"}, {"ref": "LOGO", "side": "top", "pattern": "LOGO"}],+            "pads": [{"ref": "U1", "drill": 0, "layer": "F.Cu"}, {"ref": "U1", "drill": 0, "layer": "F.Cu"}, {"ref": "J1", "drill": 1.0, "layer": "*.Cu", "x": 10, "y": 10, "sizeX": 1.7, "sizeY": 1.7},+                     {"ref": "J1", "drill": 1.0, "layer": "*.Cu", "x": 12.54, "y": 10, "sizeX": 1.7, "sizeY": 1.7}, {"ref": "C1", "drill": 0, "layer": "B.Cu"}, {"ref": "C1", "drill": 0, "layer": "B.Cu"}]})+    }++    fn record() -> Value {+        json!({"vendor": "Example Fab", "url": "https://fab.example/prices", "read": "2026-10-29", "currency": "USD",+            "pcb": [{"layers": 2, "setup": 2.0, "perM2": 30.0, "promo": {"maxMm": [100, 100], "prices": [[5, 2.0], [10, 5.0]]}}, {"layers": 4, "setup": 8.0, "perM2": 90.0}],+            "thickness": {"standardMm": 1.6, "factor": 1.15},+            "assembly": {"setupPerSide": 8.0, "stencilPerSide": 7.0, "perSmdJoint": 0.0017, "perThtJoint": 0.0173, "perExtendedPart": 3.0},+            "excludes": ["shipping", "tax"]})+    }++    #[test]+    fn the_numbers_come_from_the_board() {+        let n = board_numbers(&board(), None, &[json!({"kind": "clearance", "clearanceMm": 0.15})]);+        assert_eq!((n["widthMm"].as_f64(), n["heightMm"].as_f64(), n["layers"].as_u64()), (Some(50.0), Some(40.0), Some(2)));+        assert_eq!((n["minTrackMm"].as_f64(), n["minGapMm"].as_f64(), n["minDrillMm"].as_f64()), (Some(0.15), Some(0.15), Some(0.3)));+        // the logo has no pads: three parts, J1 through-hole, two sides+        assert_eq!((n["smdParts"].as_u64(), n["thtParts"].as_u64(), n["smdJoints"].as_u64(), n["thtJoints"].as_u64(), n["holes"].as_u64()), (Some(2), Some(1), Some(4), Some(2), Some(3)));+        assert_eq!(n["assemblySides"], json!(["bottom", "top"]));+        assert!(n["thicknessMm"].is_null());+        assert_eq!(board_numbers(&board(), Some(&json!({"copperLayers": 4, "totalUm": 1600})), &[])["thicknessMm"], json!(1.6));+    }++    #[test]+    fn without_a_price_record_it_answers_the_numbers_only() {+        let r = estimate_cost(&json!({"board": board(), "args": {}}));+        assert_eq!(r["success"], json!(true));+        assert!(r["prices"].is_null() && r["source"].is_null());+        assert_eq!(r["board"]["layers"], json!(2));+    }++    #[test]+    fn prices_come_from_the_record_and_name_it() {+        let r = estimate_cost(&json!({"board": board(), "prices": record(), "args": {"quantities": [5, 30], "assembly": true}}));+        assert_eq!(r["source"], json!({"name": "Example Fab", "url": "https://fab.example/prices", "read": "2026-10-29"}));+        // 5 boards: the promotional 2.00; 30: 2 + 30 * 0.002 m2 * 30 = 3.80+        assert_eq!((r["prices"][0]["board"].as_f64(), r["prices"][1]["board"].as_f64()), (Some(2.0), Some(3.8)), "{r}");+        // assembly at 5: (8 + 7) * 2 sides + (4 * 0.0017 + 2 * 0.0173) * 5 + 3 * 3 unique = 39.21+        assert_eq!(r["prices"][0]["assembly"].as_f64(), Some(39.21), "{r}");+        assert!(r["assumptions"].as_array().unwrap().iter().any(|a| a == "Not included: shipping."));+        // a 4-layer stack takes the 4-layer row; 6 layers has none+        let four = estimate_cost(&json!({"board": board(), "stack": {"copperLayers": 4, "totalUm": 1200}, "prices": record(), "args": {"quantities": [10]}}));+        assert_eq!(four["prices"][0]["board"].as_f64(), Some(r2((8.0 + 90.0 * 0.002 * 10.0) * 1.15)), "{four}");+        assert_eq!(estimate_cost(&json!({"board": board(), "stack": {"copperLayers": 6}, "prices": record(), "args": {}}))["errorCode"], "bad_prices");+    }+}
bridge-rs/vendor/adom-eda-checks/src/fab.rs+28−10
@@ -135,27 +135,45 @@ fn length_mm(text: &str) -> Option<f64> { /// A clearance rule that names another object than copper of another net: the board edge, solder mask, silkscreen, /// holes, keepouts, the courtyard, or the same net (Fusion's Solder-Mask Clearance is a mask expansion, often 0.05 mm). const NOT_COPPER_CLEARANCE: &[&str] = &["dimension", "edge", "board", "mask", "silk", "paste", "hole", "restrict", "keepout", "keep-out",-                                        "courtyard", "component", "body", "same net", "samenet", "same-net"];+                                        "courtyard", "component", "body", "plane", "same net", "samenet", "same-net"];  /// The smallest copper-to-copper clearance among the board's enabled rules, in mm. A rule gives it as a number /// (`clearanceMm`, `gapMm` or `minMm`), as a `value` with its unit ("0.1mm": Fusion's form), or in a descriptor the tool /// wrote ("Gap=10mil", "Gap=0.2mm": Altium's form). Clearance rules about anything but copper of another net are left out. pub fn min_clearance(rules: &[Value]) -> Option<f64> {+    clearances(rules).into_iter().map(|c| c.0).reduce(f64::min).map(r3)+}++/// The copper clearance a route or a via must keep: the strictest board-wide copper rule (a pad-to-via 0.15 beside a+/// wire-to-wire 0.1 means 0.15 near a pad), so a plan passes the board's DRC. A rule scoped to some nets only (a high+/// voltage class) is left out unless no board-wide rule exists, then the smallest scoped one counts (fusion-lane #21).+pub fn routing_clearance(rules: &[Value]) -> Option<f64> {+    let all = clearances(rules);+    all.iter().filter(|c| c.1).map(|c| c.0).reduce(f64::max).or_else(|| all.iter().map(|c| c.0).reduce(f64::min)).map(r3)+}++/// Every enabled copper-to-copper clearance rule as (mm, board-wide).+fn clearances(rules: &[Value]) -> Vec<(f64, bool)> {     let text = |r: &Value, k: &str| r[k].as_str().map(|s| s.to_lowercase()).unwrap_or_default();+    // board-wide: no scope, or Altium's All on both sides+    let wide = |r: &Value| ["scope1", "scope2", "scope"].iter().all(|k| r[*k].as_str().map(|s| s.is_empty() || s.eq_ignore_ascii_case("all")).unwrap_or(true));     rules.iter().filter(|r| r["kind"].as_i64() == Some(0) || text(r, "kind").contains("clearance")             || r["kindName"].as_str() == Some("Clearance") || text(r, "name").contains("clearance"))         .filter(|r| !["kind", "name", "kindName"].iter().any(|k| { let t = text(r, k); NOT_COPPER_CLEARANCE.iter().any(|w| t.contains(w)) }))         .filter(|r| r["enabled"].as_bool() != Some(false))         .filter_map(|r| {-            if let Some(v) = ["clearanceMm", "gapMm", "minMm"].iter().find_map(|k| r[*k].as_f64()) { return Some(v); }-            if let Some(v) = r["value"].as_str().and_then(length_mm) { return Some(v); }-            let d = r["descriptor"].as_str()?;-            let i = d.find("Gap=")? + 4;-            let num: String = d[i..].chars().take_while(|c| c.is_ascii_digit() || *c == '.').collect();-            let v: f64 = num.parse().ok()?;-            let unit = &d[i + num.len()..];-            Some(if unit.starts_with("mil") { v * 0.0254 } else { v })-        }).reduce(f64::min).map(r3)+            let v = if let Some(v) = ["clearanceMm", "gapMm", "minMm"].iter().find_map(|k| r[*k].as_f64()) { v }+            else if let Some(v) = r["value"].as_str().and_then(length_mm) { v }+            else {+                let d = r["descriptor"].as_str()?;+                let i = d.find("Gap=")? + 4;+                let num: String = d[i..].chars().take_while(|c| c.is_ascii_digit() || *c == '.').collect();+                let v: f64 = num.parse().ok()?;+                let unit = &d[i + num.len()..];+                if unit.starts_with("mil") { v * 0.0254 } else { v }+            };+            Some((v, wide(r)))+        }).collect() }  /// A pcb-design-rules record (one entry of `rules/records/<vendor>.json`'s `records`, with the file's `vendor`) as the
bridge-rs/vendor/adom-eda-checks/src/lib.rs+8−2
@@ -4,11 +4,12 @@ //! answers the verb under its own prefix (`kicad_return_path`). Replies keep the standard envelope (`success`, //! `errorCode`, `error`, `_hint`) and name verbs without a prefix. //!-//! Every check takes one input bundle, `{board, stack?, pours?, rules?, silk?, fab?, bodies?, sheetParts?, netlist?, args?}` (see `input`).+//! Every check takes one input bundle, `{board, stack?, pours?, rules?, silk?, fab?, bodies?, prices?, sheetParts?, netlist?, args?}` (see `input`). use serde_json::Value;  pub mod bodies; pub mod coppermap;+pub mod cost; pub mod current; pub mod fab; pub mod features;@@ -16,6 +17,7 @@ pub mod geom; pub mod impedance; pub mod input; pub mod placement;+pub mod placetools; pub mod route; pub mod writers; @@ -24,7 +26,7 @@ pub mod writers; 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", "height_check", "impedance", "placement_check", "plan_route", "return_path", "thermal_vias", "via_fence"];+pub const CHECKS: &[&str] = &["check_clearance", "copper_balance", "current_capacity", "estimate_cost", "fab_check", "height_check", "impedance", "place_decoupling", "placement_check", "plan_fanout", "plan_route", "return_path", "thermal_vias", "via_fence"];  /// Run one check or writer by its standard name. The reply carries `engine`. pub fn run(check: &str, input: &Value) -> Value {@@ -36,11 +38,15 @@ pub fn run(check: &str, input: &Value) -> Value { fn answer(check: &str, input: &Value) -> Value {     if let Some(out) = writers::run(check, input) { return out; }     match check {+        "check_clearance" => placetools::check_clearance(input),         "copper_balance" => coppermap::copper_balance(input),         "current_capacity" => current::current_capacity(input),+        "estimate_cost" => cost::estimate_cost(input),         "fab_check" => fab::fab_check(input),         "height_check" => bodies::height_check(input),         "impedance" => impedance::impedance(input),+        "place_decoupling" => placetools::place_decoupling(input),+        "plan_fanout" => placetools::plan_fanout(input),         "placement_check" => placement::placement_check(input),         "plan_route" => route::plan_route(input),         "return_path" => coppermap::return_path(input),
bridge-rs/vendor/adom-eda-checks/src/main.rs+3−3
@@ -1,5 +1,5 @@ //! adom-eda-checks <check> [bundle.json | -]-//! adom-eda-checks <check> --board b.json [--stack s.json] [--pours p.json] [--args '{...}']+//! adom-eda-checks <check> --board b.json [--stack s.json] [--pours p.json] [--prices r.json] [--args '{...}'] //! adom-eda-checks import_svg --svg art.svg --args '{"at": [10, 10], "widthMm": 20}' //! Prints the check's reply as JSON. `adom-eda-checks list` names the checks. use serde_json::{json, Value};@@ -23,7 +23,7 @@ fn bundle(rest: &[String]) -> Result<Value, String> {     while let Some(flag) = it.next() {         let val = it.next().ok_or_else(|| format!("{flag} needs a value"))?;         match flag.as_str() {-            "--board" | "--stack" | "--pours" | "--rules" | "--silk" | "--fab" | "--bodies" | "--sheet-parts" | "--netlist" => {+            "--board" | "--stack" | "--pours" | "--rules" | "--silk" | "--fab" | "--bodies" | "--prices" | "--sheet-parts" | "--netlist" => {                 let key = match flag.as_str() { "--sheet-parts" => "sheetParts", f => &f[2..] };                 b[key] = read(val)?;             }@@ -39,7 +39,7 @@ fn bundle(rest: &[String]) -> Result<Value, String> { fn main() {     let argv: Vec<String> = std::env::args().skip(1).collect();     let out = match argv.first().map(String::as_str) {-        None | Some("-h") | Some("--help") => json!({"success": true, "usage": "adom-eda-checks <check> [bundle.json | -] | <check> --board b.json [--stack s.json] [--pours p.json] [--args '{...}']", "checks": adom_eda_checks::CHECKS, "writers": adom_eda_checks::writers::WRITERS}),+        None | Some("-h") | Some("--help") => json!({"success": true, "usage": "adom-eda-checks <check> [bundle.json | -] | <check> --board b.json [--stack s.json] [--pours p.json] [--prices r.json] [--args '{...}']", "checks": adom_eda_checks::CHECKS, "writers": adom_eda_checks::writers::WRITERS}),         Some("list") => json!({"success": true, "checks": adom_eda_checks::CHECKS, "writers": adom_eda_checks::writers::WRITERS}),         Some(check) => match bundle(&argv[1..]) {             Ok(b) => adom_eda_checks::run(check, &b),
bridge-rs/vendor/adom-eda-checks/src/placement.rs+18−14
@@ -97,6 +97,23 @@ pub fn review(boxes: &BTreeMap<String, (bool, Rect)>, pads: &[Value], ring: &[(f     json!({"parts": boxes.len(), "ok": ok, "courtyardOverlaps": overlaps, "offOrOverEdge": off, "onMountingHoles": on_holes, "nearEdge": near, "marginMm": margin, "edgeMm": edge}) } +/// Whether two parts that overlap in plan view are a stack (a part under a raised one: an Adom molecule on pins, a+/// connector's overhang): their pads stay `margin` apart and no body of one meets a body of the other in 3D. A part with+/// no body cannot be shown stacked. Pure.+pub fn is_stacked(pads: &[Value], bs: &[crate::bodies::BodyBox], a: &str, b: &str, margin: f64) -> bool {+    // each pad's own box, turned with it: a molecule's pins span the part under it, so the union of its pads would too+    let pad_rects = |r: &str| -> Vec<Rect> { pads.iter().filter(|p| p["ref"].as_str() == Some(r)).map(|p| {+        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);+        (f(&p["x"]) - hx, f(&p["y"]) - hy, f(&p["x"]) + hx, f(&p["y"]) + hy)+    }).collect() };+    let (pa, pb) = (pad_rects(a), pad_rects(b));+    if pa.is_empty() || pb.is_empty() || pa.iter().any(|x| pb.iter().any(|y| hit(grow(*x, margin), grow(*y, margin)))) { return false; }+    let (ba, bb): (Vec<_>, Vec<_>) = (bs.iter().filter(|x| x.part == a).collect(), bs.iter().filter(|x| x.part == b).collect());+    if ba.is_empty() || bb.is_empty() { return false; }+    !ba.iter().any(|p| bb.iter().any(|q| hit(grow((p.x0, p.y0, p.x1, p.y1), margin), grow((q.x0, q.y0, q.x1, q.y1), margin)) && p.z0.max(q.z0) < p.z1.min(q.z1)))+}+ /// 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 {@@ -122,23 +139,10 @@ pub fn placement_check(input: &Value) -> Value {     // their pads stay clear and no body of one meets a body of the other in 3D, it is a stack, listed apart, not an     // overlap (fusion-lane #19). A part with no body cannot be shown stacked, so its overlaps stand.     if let Some(bs) = &given {-        // each pad's own box, turned with it: a molecule's pins span the part under it, so the union of its pads would too-        let pad_rects = |r: &str| -> Vec<Rect> { pads.iter().filter(|p| p["ref"].as_str() == Some(r)).map(|p| {-            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);-            (f(&p["x"]) - hx, f(&p["y"]) - hy, f(&p["x"]) + hx, f(&p["y"]) + hy)-        }).collect() };-        let meets = |a: &str, b: &str| {-            let (ba, bb): (Vec<_>, Vec<_>) = (bs.iter().filter(|x| x.part == a).collect(), bs.iter().filter(|x| x.part == b).collect());-            if ba.is_empty() || bb.is_empty() { return true; }-            ba.iter().any(|p| bb.iter().any(|q| hit(grow((p.x0, p.y0, p.x1, p.y1), margin), grow((q.x0, q.y0, q.x1, q.y1), margin)) && p.z0.max(q.z0) < p.z1.min(q.z1)))-        };         let (mut real, mut stacked) = (Vec::new(), Vec::new());         for o in out["courtyardOverlaps"].as_array().cloned().unwrap_or_default() {             let (a, b) = (o["parts"][0].as_str().unwrap_or(""), o["parts"][1].as_str().unwrap_or(""));-            let (pa, pb) = (pad_rects(a), pad_rects(b));-            let pads_meet = pa.is_empty() || pb.is_empty() || pa.iter().any(|x| pb.iter().any(|y| hit(grow(*x, margin), grow(*y, margin))));-            if pads_meet || meets(a, b) { real.push(o) } else { stacked.push(o) }+            if is_stacked(&pads, bs, a, b, margin) { stacked.push(o) } else { real.push(o) }         }         if !stacked.is_empty() {             out["ok"] = json!(real.is_empty() && out["offOrOverEdge"].as_array().map(|a| a.is_empty()).unwrap_or(true) && out["onMountingHoles"].as_array().map(|a| a.is_empty()).unwrap_or(true));
bridge-rs/vendor/adom-eda-checks/src/placetools.rsadded+797
@@ -0,0 +1,797 @@+//! Placement helpers from the KiCad bridge's place_tools.rs: the gaps between parts (their boxes or their pad copper)+//! and a plan for decoupling capacitors beside an IC's power pins, answered as move_parts arguments. The board model has+//! no courtyards, so a part is the box of its pads and, with the bodies companion, of its 3D body, as placement_check+//! measures it. Pure.+use crate::route::{pad_shape, Shape};+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 P = (f64, f64);+type Rect = (f64, f64, f64, f64);++/// The gap between two boxes, 0 when they touch or overlap.+fn rect_gap(a: Rect, b: Rect) -> f64 {+    let dx = (b.0 - a.2).max(a.0 - b.2).max(0.0);+    let dy = (b.1 - a.3).max(a.1 - b.3).max(0.0);+    (dx * dx + dy * dy).sqrt()+}++fn union(a: Rect, b: Rect) -> Rect { (a.0.min(b.0), a.1.min(b.1), a.2.max(b.2), a.3.max(b.3)) }++/// References and pad names in natural order: C2 before C10.+fn ref_key(r: &str) -> (String, u64, String) {+    let head: String = r.chars().take_while(|c| !c.is_ascii_digit()).collect();+    let rest = &r[head.len()..];+    let num: String = rest.chars().take_while(|c| c.is_ascii_digit()).collect();+    (head.to_uppercase(), num.parse().unwrap_or(0), rest[num.len()..].to_string())+}++fn prefix(r: &str) -> String { r.chars().take_while(|c| c.is_ascii_alphabetic()).collect::<String>().to_uppercase() }++pub fn is_ground(net: &str) -> bool {+    let n = net.trim_start_matches('/').to_uppercase();+    n.contains("GND") || n.starts_with("VSS") || n == "0V" || n.ends_with("_VSS")+}++/// A net named like a supply: +5V, VCC, VDD_CORE, VBAT, 3V3, 1V8.+fn power_name(net: &str) -> bool {+    let n = net.trim_start_matches('/').to_uppercase();+    let c: Vec<char> = n.chars().collect();+    n.starts_with('+') || n.starts_with('V') || ["VCC", "VDD", "VBAT", "VIN", "VBUS", "PWR", "SUPPLY"].iter().any(|k| n.contains(k))+        || (1..c.len()).any(|i| c[i] == 'V' && c[i - 1].is_ascii_digit())+}++/// The pad's box, turned with it.+fn pad_box(at: P, sx: f64, sy: f64, rot: f64) -> Rect {+    let (c, s) = (rot.to_radians().cos().abs(), rot.to_radians().sin().abs());+    let (hx, hy) = ((sx * c + sy * s) / 2.0, (sx * s + sy * c) / 2.0);+    (at.0 - hx, at.1 - hy, at.0 + hx, at.1 + hy)+}++fn turn(p: P, deg: f64) -> P {+    let (c, s) = (deg.to_radians().cos(), deg.to_radians().sin());+    (p.0 * c - p.1 * s, p.0 * s + p.1 * c)+}++/// One part: where it is, its pads and its bodies' boxes.+struct Part { at: P, rot: f64, bottom: bool, pads: Vec<Value>, bodies: Vec<Rect> }++impl Part {+    /// A point of the part, after moving the part to `at` turned to `rot` (counterclockwise as seen).+    fn moved(&self, p: P, at: P, rot: f64) -> P {+        let q = turn((p.0 - self.at.0, p.1 - self.at.1), rot - self.rot);+        (at.0 + q.0, at.1 + q.1)+    }+    /// The part's box at `at` turned to `rot`: its pads, and its bodies' boxes turned with it.+    fn box_at(&self, at: P, rot: f64) -> Option<Rect> {+        let d = rot - self.rot;+        let mut b: Option<Rect> = None;+        for p in &self.pads {+            let r = pad_box(self.moved((f(&p["x"]), f(&p["y"])), at, rot), f(&p["sizeX"]), f(&p["sizeY"]), f(&p["rotation"]) + d);+            b = Some(b.map(|x| union(x, r)).unwrap_or(r));+        }+        for x in &self.bodies {+            for c in [(x.0, x.1), (x.2, x.1), (x.2, x.3), (x.0, x.3)] {+                let q = self.moved(c, at, rot);+                let r = (q.0, q.1, q.0, q.1);+                b = Some(b.map(|x| union(x, r)).unwrap_or(r));+            }+        }+        b+    }+}++/// The board's parts by reference (as given), with their bodies when the companion came.+fn parts(st: &Value, input: &Value) -> BTreeMap<String, Part> {+    let mut m: BTreeMap<String, Part> = BTreeMap::new();+    for c in st["components"].as_array().cloned().unwrap_or_default() {+        let Some(r) = c["ref"].as_str().filter(|r| !r.is_empty()) else { continue };+        m.insert(r.to_string(), Part { at: (f(&c["x"]), f(&c["y"])), rot: f(&c["rotation"]), bottom: c["side"] == "bottom", pads: Vec::new(), bodies: Vec::new() });+    }+    for p in st["pads"].as_array().cloned().unwrap_or_default() {+        if let Some(part) = p["ref"].as_str().and_then(|r| m.get_mut(r)) { part.pads.push(p); }+    }+    for b in crate::bodies::input_boxes(input).unwrap_or_default() {+        if let Some(part) = m.get_mut(&b.part) { part.bodies.push((b.x0, b.y0, b.x1, b.y1)); }+    }+    m+}++fn find<'a>(m: &'a BTreeMap<String, Part>, r: &str) -> Option<(&'a String, &'a Part)> { m.iter().find(|(k, _)| k.eq_ignore_ascii_case(r)) }++/// check_clearance: input {board, bodies?, args: {refs?, mode?: courtyard|pads, thresholdMm?, includeSameNet?, maxPairs?}}.+/// courtyard: part boxes (pads, and 3D bodies when given) on the same side; pads: pad copper of different parts that+/// shares a copper layer, by its real outline.+pub fn check_clearance(input: &Value) -> Value {+    let st = match crate::input::board(input) { Ok(b) => b, Err(e) => return e };+    let args = &input["args"];+    let mode = args["mode"].as_str().unwrap_or("courtyard");+    if mode != "courtyard" && mode != "pads" { return crate::input::refuse("bad_args", &format!("mode is courtyard or pads, not {mode}")); }+    let threshold = args.get("thresholdMm").or_else(|| args.get("threshold")).and_then(|v| v.as_f64()).unwrap_or(if mode == "pads" { 0.2 } else { 0.25 }).max(0.0);+    let limit = args["maxPairs"].as_u64().unwrap_or(200) as usize;+    let m = parts(&st, input);+    let refs: Option<Vec<String>> = args["refs"].as_array().map(|a| a.iter().filter_map(|v| v.as_str()).map(|s| s.trim().to_uppercase()).collect());+    if let Some(rs) = &refs {+        let unknown: Vec<&String> = rs.iter().filter(|r| find(&m, r).is_none()).collect();+        if !unknown.is_empty() { return crate::input::refuse("no_such_part", &format!("not parts on this board: {unknown:?}")); }+    }+    let wanted = |r: &str| refs.as_ref().map(|rs| rs.iter().any(|x| x.eq_ignore_ascii_case(r))).unwrap_or(true);+    let order = |a: &str, b: &str| if ref_key(a) <= ref_key(b) { (a.to_string(), b.to_string()) } else { (b.to_string(), a.to_string()) };+    let (mut pairs, mut checked) = (Vec::new(), 0usize);+    let measured;+    let mut stacked = Vec::new();+    if mode == "courtyard" {+        let boxes: Vec<(&String, bool, Rect)> = m.iter().filter_map(|(r, p)| Some((r, p.bottom, p.box_at(p.at, p.rot)?))).collect();+        let bodies = crate::bodies::input_boxes(input).unwrap_or_default();+        let pads = st["pads"].as_array().cloned().unwrap_or_default();+        for i in 0..boxes.len() {+            for j in i + 1..boxes.len() {+                let ((ra, sa, a), (rb, sb, b)) = (boxes[i], boxes[j]);+                if sa != sb || !(wanted(ra) || wanted(rb)) { continue; }+                checked += 1;+                let d = rect_gap(a, b);+                if d < threshold {+                    let (x, y) = order(ra, rb);+                    let row = json!({"a": x, "b": y, "side": if sa { "bottom" } else { "top" }, "distanceMm": r3(d), "overlapping": d == 0.0});+                    // a part under a raised one (pads apart, no bodies meeting in 3D) is a stack, as placement_check says (fusion-lane #22)+                    if crate::placement::is_stacked(&pads, &bodies, ra, rb, threshold / 2.0) { stacked.push(row) } else { pairs.push(row) }+                }+            }+        }+        measured = if crate::bodies::input_boxes(input).is_some() { "part box: its pads and 3D body" } else { "part box: its pads only (pass bodies to add the 3D bodies)" };+    } else {+        let same_net = args["includeSameNet"].as_bool().unwrap_or(false);+        let pads: Vec<&Value> = m.values().flat_map(|p| p.pads.iter()).collect();+        let shapes: Vec<(Shape, Rect)> = pads.iter().map(|p| { let s = pad_shape(p); let b = s.bounds(); (s, b) }).collect();+        let through = |p: &Value| p["layer"] == "*.Cu" || f(&p["drill"]) > 0.0;+        for i in 0..pads.len() {+            for j in i + 1..pads.len() {+                let (a, b) = (pads[i], pads[j]);+                let (ra, rb) = (a["ref"].as_str().unwrap_or(""), b["ref"].as_str().unwrap_or(""));+                if ra == rb || !(wanted(ra) || wanted(rb)) { continue; }+                let (na, nb) = (a["net"].as_str().unwrap_or(""), b["net"].as_str().unwrap_or(""));+                if !same_net && !na.is_empty() && na == nb { continue; }+                if !(through(a) || through(b) || a["layer"] == b["layer"]) { continue; }+                checked += 1;+                if rect_gap(shapes[i].1, shapes[j].1) >= threshold { continue; }+                let d = shapes[i].0.gap(&shapes[j].0);+                if d < threshold {+                    let (ka, kb) = (format!("{ra}.{}", a["name"].as_str().unwrap_or("")), format!("{rb}.{}", b["name"].as_str().unwrap_or("")));+                    let ((x, nx), (y, ny)) = if ref_key(&ka) <= ref_key(&kb) { ((ka, na), (kb, nb)) } else { ((kb, nb), (ka, na)) };+                    pairs.push(json!({"a": x, "b": y, "netA": nx, "netB": ny, "distanceMm": r3(d), "touching": d == 0.0}));+                }+            }+        }+        measured = "pads: their real copper (copperPoints when given, round pads as circles or stadiums, others as their turned rectangle)";+    }+    pairs.sort_by(|x, y| f(&x["distanceMm"]).partial_cmp(&f(&y["distanceMm"])).unwrap_or(std::cmp::Ordering::Equal));+    let total = pairs.len();+    pairs.truncate(limit);+    json!({"success": true, "mode": mode, "thresholdMm": threshold, "measuredOn": measured, "pairsChecked": checked, "violationCount": total,+        "pairs": pairs, "truncated": total > limit, "clean": total == 0, "stacked": stacked,+        "_hint": if total == 0 { "No pair is closer than thresholdMm. The tool's DRC (run_drc) is the authority on copper clearance." }+                 else { "pairs are closest first. Move parts apart with move_parts (find_space finds room); overlapping or touching pairs come first. The tool's DRC (run_drc) is the authority on copper clearance." }})+}++/// The side of the box nearest a pin: its outward normal and name (y up: top is +y).+fn side_of(b: Rect, pin: P) -> (P, &'static str) {+    let d = [(pin.0 - b.0, (-1.0, 0.0), "left"), (b.2 - pin.0, (1.0, 0.0), "right"), (pin.1 - b.1, (0.0, -1.0), "bottom"), (b.3 - pin.1, (0.0, 1.0), "top")];+    let best = d.iter().min_by(|a, b| a.0.partial_cmp(&b.0).unwrap()).unwrap();+    (best.1, best.2)+}++/// A capacitor across ground and one other net: (its pad on that net, the net).+fn decoupling_role(r: &str, p: &Part) -> Option<(Value, String)> {+    if prefix(r) != "C" || p.pads.len() != 2 { return None; }+    let net = |q: &Value| q["net"].as_str().unwrap_or("").to_string();+    if p.pads.iter().filter(|q| is_ground(&net(q))).count() != 1 { return None; }+    p.pads.iter().find(|q| !net(q).is_empty() && !is_ground(&net(q))).map(|q| (q.clone(), net(q)))+}++/// place_decoupling: input {board, bodies?, args: {ic, caps?, gapMm?}}. Each cap goes `gapMm` outside the IC's box on the+/// side of the power pin it serves, turned so its power pad faces the pin and lined up with it; a spot taken by another+/// part slides along that side. Answers `moveArgs` for move_parts and checks the plan with placement_check.+pub fn place_decoupling(input: &Value) -> Value {+    let st = match crate::input::board(input) { Ok(b) => b, Err(e) => return e };+    let args = &input["args"];+    let Some(ic_ref) = args.get("ic").or_else(|| args.get("ref")).and_then(|v| v.as_str()).map(str::trim).filter(|s| !s.is_empty()) else {+        return crate::input::refuse("bad_args", "ic is required: the IC's reference (\"U1\")");+    };+    let gap = args.get("gapMm").or_else(|| args.get("gap")).and_then(|v| v.as_f64()).unwrap_or(0.3).max(0.0);+    let m = parts(&st, input);+    let Some((ic_ref, ic)) = find(&m, ic_ref) else { return crate::input::refuse("no_such_part", &format!("{ic_ref} is not a part on this board")) };+    let Some(ic_box) = ic.box_at(ic.at, ic.rot) else { return crate::input::refuse("no_pads", &format!("{ic_ref} has no pads in the board model")) };+    let net = |q: &Value| q["net"].as_str().unwrap_or("").to_string();+    let mut ic_nets: Vec<String> = ic.pads.iter().map(net).filter(|n| !n.is_empty() && !is_ground(n)).collect();+    ic_nets.sort();+    ic_nets.dedup();+    let roles: BTreeMap<&String, (Value, String)> = m.iter().filter_map(|(r, p)| Some((r, decoupling_role(r, p)?))).collect();+    // a supply: named like one, or two or more caps across it to ground (one cap on a signal is a crystal's load or a+    // filter, not decoupling)+    let mut across: BTreeMap<&str, usize> = BTreeMap::new();+    for (_, n) in roles.values() { *across.entry(n.as_str()).or_insert(0) += 1; }+    let supply = |n: &str| power_name(n) || across.get(n).copied().unwrap_or(0) >= 2;+    let supplies: Vec<String> = ic_nets.iter().filter(|n| supply(n)).cloned().collect();+    // caps given by name may sit on any of the IC's nets+    let power = if args["caps"].is_array() { ic_nets.clone() } else { supplies.clone() };+    let pad_at = |q: &Value| (f(&q["x"]), f(&q["y"]));+    let (mut left_out, mut cap_refs): (Vec<Value>, Vec<String>) = (Vec::new(), Vec::new());+    match args["caps"].as_array() {+        Some(a) => cap_refs = a.iter().filter_map(|v| v.as_str()).map(String::from).collect(),+        None => {+            // the other ICs, for caps that serve the same supply nearer another one+            let ics: Vec<(&String, &Part)> = m.iter().filter(|(r, p)| matches!(prefix(r).as_str(), "U" | "IC") && p.pads.len() >= 3 && p.bottom == ic.bottom).collect();+            for (r, (pp, n)) in &roles {+                if !ic_nets.contains(n) { continue; }+                if !supply(n) {+                    left_out.push(json!({"cap": r, "net": n, "why": "signal_net", "detail": format!("{n} has one cap to ground and is not named like a supply: a crystal's load or a filter. Pass caps to place it anyway")}));+                    continue;+                }+                let near = |p: &Part| p.pads.iter().filter(|q| net(q) == *n).map(|q| { let (a, b) = (pad_at(q), pad_at(pp)); ((a.0 - b.0).powi(2) + (a.1 - b.1).powi(2)).sqrt() }).fold(f64::MAX, f64::min);+                let own = near(ic);+                if let Some((other, _)) = ics.iter().filter(|(o, _)| *o != ic_ref).map(|(o, p)| (o, near(p))).filter(|(_, d)| *d < own).min_by(|a, b| a.1.partial_cmp(&b.1).unwrap()) {+                    left_out.push(json!({"cap": r, "net": n, "why": "nearer_another_ic", "detail": format!("{r} is nearer {other}'s {n} pin; it decouples that IC. Pass caps to place it here anyway")}));+                    continue;+                }+                cap_refs.push(r.to_string());+            }+        }+    }+    cap_refs.sort_by_key(|r| ref_key(r));+    if cap_refs.is_empty() {+        return json!({"success": false, "errorCode": "no_caps", "error": format!("no capacitor across ground and a supply of {ic_ref}: pass caps:[...]"), "icPowerNets": supplies, "leftOut": left_out});+    }+    // a cap the plan cannot place stays where it is, so its spot stays taken: plan again with it fixed until none is new+    // (fusion-lane #22: C32 was planned onto C29, which had no free spot and never moved)+    let ring = crate::coppermap::outline_ring(&st);+    let on_board = |b: Rect| ring.len() < 3 || [(b.0, b.1), (b.2, b.1), (b.2, b.3), (b.0, b.3)].iter().all(|c| crate::route::inside(*c, &ring));+    // room for the IC's fanout: a cap's pads keep clear of the stubs and vias plan_fanout would give the pins of other+    // nets (altium-lane: caps placed first sat on 5 of U4's escape stubs and vias)+    let (fan, fan_clear) = if args["leaveFanout"].as_bool() == Some(false) { (Vec::new(), 0.0) } else { fanout_room(input, ic_ref) };+    let pads_clear = |cap: &Part, at: P, rot: f64| cap.pads.iter().all(|q| {+        let mut moved = q.clone();+        let c = cap.moved(pad_at(q), at, rot);+        moved["x"] = json!(c.0); moved["y"] = json!(c.1); moved["rotation"] = json!(f(&q["rotation"]) + rot - cap.rot);+        moved.as_object_mut().map(|o| o.remove("copperPoints"));+        let s = pad_shape(&moved);+        fan.iter().all(|(n, piece)| *n == net(q) || s.gap(piece) >= fan_clear - 1e-6)+    });+    let mut stay: Vec<String> = Vec::new();+    let (mut used, mut rows, mut moves, mut skipped): (Vec<String>, Vec<Value>, Vec<(String, P, f64)>, Vec<Value>);+    loop {+        let moving: Vec<String> = cap_refs.iter().map(|r| r.to_uppercase()).filter(|r| !stay.contains(r)).collect();+        let mut taken: Vec<Rect> = m.iter().filter(|(r, p)| p.bottom == ic.bottom && !moving.contains(&r.to_uppercase())).filter_map(|(_, p)| p.box_at(p.at, p.rot)).collect();+        // a part on the other side still takes the spot of its through-hole pads, and so do the board's own holes+        for p in st["pads"].as_array().into_iter().flatten() {+            let through = p["layer"] == "*.Cu" || f(&p["drill"]) > 0.0;+            let other_side = p["ref"].as_str().and_then(|r| m.get(r)).map(|q| q.bottom != ic.bottom).unwrap_or(true);+            if through && other_side { taken.push(pad_box(pad_at(p), f(&p["sizeX"]).max(f(&p["drill"])), f(&p["sizeY"]).max(f(&p["drill"])), f(&p["rotation"]))); }+        }+        (used, rows, moves, skipped) = (Vec::new(), Vec::new(), Vec::new(), Vec::new());+        for cr in &cap_refs {+            let Some((cr, cap)) = find(&m, cr) else { skipped.push(json!({"cap": cr, "why": "no_such_part"})); continue };+            if cap.bottom != ic.bottom {+                skipped.push(json!({"cap": cr, "why": "other_side", "detail": format!("{cr} is on the other side from {ic_ref}: move it over first (move_parts with side)")}));+                continue;+            }+            let Some(pp) = cap.pads.iter().find(|q| power.contains(&net(q))) else { skipped.push(json!({"cap": cr, "why": "no_shared_power_net"})); continue };+            let n = net(pp);+            let mut pins: Vec<&Value> = ic.pads.iter().filter(|q| net(q) == n).collect();+            pins.sort_by_key(|q| (used.contains(&q["name"].as_str().unwrap_or("").to_string()), ref_key(q["name"].as_str().unwrap_or(""))));+            let pin = pins[0];+            let pin_name = pin["name"].as_str().unwrap_or("").to_string();+            used.push(pin_name.clone());+            let pin_at = pad_at(pin);+            let (nv, side) = side_of(ic_box, pin_at);+            // the turn that points the power pad at the IC+            let rel = |rot: f64| cap.moved(pad_at(pp), (0.0, 0.0), rot);+            let rot = [0.0, 90.0, 180.0, 270.0].into_iter().max_by(|a, b| {+                let (va, vb) = (rel(*a), rel(*b));+                (-(va.0 * nv.0 + va.1 * nv.1)).partial_cmp(&(-(vb.0 * nv.0 + vb.1 * nv.1))).unwrap()+            }).unwrap();+            let Some(cy) = cap.box_at((0.0, 0.0), rot) else { skipped.push(json!({"cap": cr, "why": "no_pads"})); continue };+            let v = rel(rot);+            let base = match side {+                "left" => (ic_box.0 - gap - cy.2, pin_at.1 - v.1),+                "right" => (ic_box.2 + gap - cy.0, pin_at.1 - v.1),+                "top" => (pin_at.0 - v.0, ic_box.3 + gap - cy.1),+                _ => (pin_at.0 - v.0, ic_box.1 - gap - cy.3),+            };+            let along = if nv.0 != 0.0 { (0.0, 1.0) } else { (1.0, 0.0) };+            let step = if nv.0 != 0.0 { cy.3 - cy.1 } else { cy.2 - cy.0 } + gap;+            let mut chosen = None;+            for k in 0..13 {+                let s = if k == 0 { 0.0 } else if k % 2 == 1 { ((k + 1) / 2) as f64 * step } else { -((k / 2) as f64) * step };+                let at = (r3(base.0 + along.0 * s), r3(base.1 + along.1 * s));+                let Some(b) = cap.box_at(at, rot) else { continue };+                if taken.iter().all(|t| rect_gap(*t, b) >= gap - 1e-3) && on_board(b) && pads_clear(cap, at, rot) { chosen = Some((at, b, s)); break; }+            }+            let Some((at, b, slid)) = chosen else { skipped.push(json!({"cap": cr, "why": "no_free_spot", "pin": format!("{ic_ref}.{pin_name}"), "side": side})); continue };+            taken.push(b);+            let pa = cap.moved(pad_at(pp), at, rot);+            rows.push(json!({"cap": cr, "net": n, "pin": format!("{ic_ref}.{pin_name}"), "side": side, "x": at.0, "y": at.1, "rotation": rot,+                "powerPad": format!("{cr}.{}", pp["name"].as_str().unwrap_or("")), "padToPinMm": r3(((pa.0 - pin_at.0).powi(2) + (pa.1 - pin_at.1).powi(2)).sqrt()),+                "slidMm": r3(slid), "from": {"x": cap.at.0, "y": cap.at.1, "rotation": cap.rot}}));+            moves.push((cr.clone(), at, rot));+        }+        let new: Vec<String> = skipped.iter().filter_map(|x| x["cap"].as_str()).filter(|c| find(&m, c).is_some()).map(|c| c.to_uppercase()).filter(|c| !stay.contains(c)).collect();+        if new.is_empty() { break; }+        stay.extend(new);+    }+    let validation = validate(&st, input, &m, &moves);+    let parts_arg: Vec<Value> = moves.iter().map(|(r, at, rot)| json!({"ref": r, "x": at.0, "y": at.1, "rotation": rot})).collect();+    json!({"success": true, "ic": ic_ref, "icPowerNets": supplies, "gapMm": gap, "placements": rows, "skipped": skipped, "leftOut": left_out,+        "moveArgs": {"parts": parts_arg, "expectedRevision": st["revision"]}, "validation": validation, "revision": st["revision"],+        "measuredOn": if crate::bodies::input_boxes(input).is_some() { "part boxes: pads and 3D bodies" } else { "part boxes: pads only (pass bodies to keep clear of 3D bodies too)" },+        "_hint": "Read the plan, then send moveArgs to move_parts. The caps' old tracks stay where they were: route the stubs again (plan_route, route_net) and repour. leftOut lists caps the default left for another IC or a signal net; name them in caps to place them here."})+}++/// The copper plan_fanout would put down for an IC's pins, by net, and the clearance it keeps; nothing when the IC is no+/// package fanout plans (fewer than four surface pads).+fn fanout_room(input: &Value, ic: &str) -> (Vec<(String, Shape)>, f64) {+    let mut q = input.clone();+    q["args"] = json!({"ref": ic});+    let r = plan_fanout(&q);+    if r["success"] != json!(true) { return (Vec::new(), 0.0); }+    let st = crate::input::board(input).unwrap_or_default();+    let at = |name: &str| st["pads"].as_array().into_iter().flatten().find(|p| format!("{}.{}", p["ref"].as_str().unwrap_or(""), p["name"].as_str().unwrap_or("")) == name).map(|p| (f(&p["x"]), f(&p["y"])));+    let (w, v) = (f(&r["widthMm"]) / 2.0, f(&r["via"]["size"]) / 2.0);+    let mut out = Vec::new();+    for row in r["pads"].as_array().into_iter().flatten() {+        let (Some(pa), Some(n)) = (row["pad"].as_str().and_then(at), row["net"].as_str()) else { continue };+        let pt = |x: &Value| (f(&x[0]), f(&x[1]));+        if row["stubEnd"].is_array() { out.push((n.to_string(), Shape::Cap(pa, pt(&row["stubEnd"]), w))); }+        if row["via"].is_array() { let e = pt(&row["via"]); out.push((n.to_string(), Shape::Cap(pa, e, w))); out.push((n.to_string(), Shape::Cap(e, e, v))); }+    }+    (out, f(&r["clearanceMm"]))+}++/// placement_check on the board with the caps moved, keeping what concerns them.+fn validate(st: &Value, input: &Value, m: &BTreeMap<String, Part>, moves: &[(String, P, f64)]) -> Value {+    if moves.is_empty() { return json!({"ok": false, "reason": "nothing to place"}); }+    let mut board = st.clone();+    let mut bodies = crate::input::part(input, "bodies");+    for (r, at, rot) in moves {+        let p = &m[r];+        let d = rot - p.rot;+        for c in board["components"].as_array_mut().into_iter().flatten().filter(|c| c["ref"] == json!(r)) {+            c["x"] = json!(at.0); c["y"] = json!(at.1); c["rotation"] = json!(rot);+        }+        for q in board["pads"].as_array_mut().into_iter().flatten().filter(|q| q["ref"] == json!(r)) {+            let n = p.moved((f(&q["x"]), f(&q["y"])), *at, *rot);+            q["x"] = json!(n.0); q["y"] = json!(n.1); q["rotation"] = json!((f(&q["rotation"]) + d).rem_euclid(360.0));+            q.as_object_mut().map(|o| o.remove("copperPoints"));+        }+        if let Some(b) = bodies.as_mut() {+            let rows = if b.get("bodies").is_some() { b["bodies"].as_array_mut() } else { b.as_array_mut() };+            for x in rows.into_iter().flatten().filter(|x| x["ref"] == json!(r)) {+                let cs: Vec<P> = [(f(&x["x0"]), f(&x["y0"])), (f(&x["x1"]), f(&x["y0"])), (f(&x["x1"]), f(&x["y1"])), (f(&x["x0"]), f(&x["y1"]))].iter().map(|c| p.moved(*c, *at, *rot)).collect();+                x["x0"] = json!(cs.iter().map(|c| c.0).fold(f64::MAX, f64::min)); x["x1"] = json!(cs.iter().map(|c| c.0).fold(f64::MIN, f64::max));+                x["y0"] = json!(cs.iter().map(|c| c.1).fold(f64::MAX, f64::min)); x["y1"] = json!(cs.iter().map(|c| c.1).fold(f64::MIN, f64::max));+            }+        }+    }+    let r = crate::placement::placement_check(&json!({"board": board, "bodies": bodies, "args": {}}));+    if r["success"] != json!(true) { return json!({"ok": false, "check": r}); }+    let ours = |e: &Value| moves.iter().any(|(m, _, _)| e["ref"] == json!(m) || e["parts"].as_array().map(|a| a.contains(&json!(m))).unwrap_or(false));+    let keep = |k: &str| -> Vec<Value> { r[k].as_array().cloned().unwrap_or_default().into_iter().filter(|e| ours(e)).collect() };+    let (ov, off, holes, near) = (keep("courtyardOverlaps"), keep("offOrOverEdge"), keep("onMountingHoles"), keep("nearEdge"));+    json!({"ok": ov.is_empty() && off.is_empty() && holes.is_empty(), "by": "placement_check on the board with the caps moved", "courtyardOverlaps": ov, "offOrOverEdge": off, "onMountingHoles": holes, "nearEdge": near})+}++fn median(mut v: Vec<f64>) -> Option<f64> {+    if v.is_empty() { return None; }+    v.sort_by(|a, b| a.partial_cmp(b).unwrap());+    Some(v[v.len() / 2])+}++/// The board's copper layers, top to bottom: from the stack's count when given, else the layers its copper uses.+pub(crate) fn copper_layers(st: &Value, input: &Value) -> Vec<String> {+    if let Some(n) = crate::input::stack(input).and_then(|s| s["copperLayers"].as_u64()).filter(|n| *n >= 2) {+        let mut v = vec!["F.Cu".to_string()];+        v.extend((1..n - 1).map(|i| format!("In{i}.Cu")));+        v.push("B.Cu".into());+        return v;+    }+    let mut inner: Vec<u32> = Vec::new();+    for k in ["tracks", "arcs", "pads", "polygons"] {+        for x in st[k].as_array().into_iter().flatten() {+            if let Some(i) = x["layer"].as_str().and_then(|l| l.strip_prefix("In")).and_then(|r| r.strip_suffix(".Cu")).and_then(|n| n.parse().ok()) {+                if !inner.contains(&i) { inner.push(i); }+            }+        }+    }+    inner.sort();+    std::iter::once("F.Cu".to_string()).chain(inner.iter().map(|i| format!("In{i}.Cu"))).chain(std::iter::once("B.Cu".to_string())).collect()+}++/// plan_fanout: input {board, stack?, rules?, args: {ref, style?, escapeLayer?, viaMm?, viaDrillMm?, widthMm?, clearanceMm?,+/// pitchMm?, stubMm?, surfaceOuterRing?, viaPerimeter?}}. A BGA's outer ring escapes on the surface and each inner ball+/// takes a dogbone via (or a via in the pad); a perimeter package's pads take an outward stub (with a via at its end for+/// ground or `viaPerimeter`), an exposed pad a via grid. `calls` are route_net arguments, one per net. Every via and+/// stub is measured against other nets' pads on the whole board (`conflicts`).+pub fn plan_fanout(input: &Value) -> Value {+    let st = match crate::input::board(input) { Ok(b) => b, Err(e) => return e };+    let args = &input["args"];+    let Some(r) = args["ref"].as_str().map(str::trim).filter(|s| !s.is_empty()) else { return crate::input::refuse("bad_args", "ref is required: the BGA or QFN/QFP (\"U3\")") };+    let m = parts(&st, input);+    let Some((r, part)) = find(&m, r) else { return crate::input::refuse("no_such_part", &format!("{r} is not a part on this board")) };+    let side = if part.bottom { "B.Cu" } else { "F.Cu" };+    let copper = copper_layers(&st, input);+    let escape = match args["escapeLayer"].as_str() {+        Some(l) if copper.iter().any(|c| c == l) => l.to_string(),+        Some(l) => return json!({"success": false, "errorCode": "no_such_layer", "error": format!("{l} is not a copper layer of this board"), "copperLayers": copper}),+        None => copper.iter().find(|l| l.starts_with("In")).cloned().unwrap_or_else(|| if part.bottom { "F.Cu".into() } else { "B.Cu".into() }),+    };+    let pads: Vec<&Value> = part.pads.iter().filter(|p| f(&p["drill"]) == 0.0).collect();+    if pads.len() < 4 { return crate::input::refuse("not_a_package", &format!("{r} has {} surface pads: fanout is for a BGA or a QFN/QFP", pads.len())); }+    let at = |p: &Value| (f(&p["x"]), f(&p["y"]));+    let net = |p: &Value| p["net"].as_str().unwrap_or("").to_string();+    let name = |p: &Value| format!("{r}.{}", p["name"].as_str().unwrap_or(""));+    let areas: Vec<f64> = pads.iter().map(|p| f(&p["sizeX"]) * f(&p["sizeY"])).collect();+    let med_area = median(areas.clone()).unwrap_or(0.0);+    let (thermal, signal): (Vec<usize>, Vec<usize>) = (0..pads.len()).partition(|i| areas[*i] > 4.0 * med_area);+    let d = |a: P, b: P| ((a.0 - b.0).powi(2) + (a.1 - b.1).powi(2)).sqrt();+    let nn: Vec<f64> = signal.iter().map(|&i| signal.iter().filter(|&&j| j != i).map(|&j| d(at(pads[i]), at(pads[j]))).fold(f64::MAX, f64::min)).collect();+    let pitch = match args["pitchMm"].as_f64() { Some(v) if v > 0.0 => v, _ => match median(nn) { Some(v) => r3(v), None => return crate::input::refuse("not_a_package", "no pad pitch") } };+    let (cx, cy) = (signal.iter().map(|&i| at(pads[i]).0).sum::<f64>() / signal.len() as f64, signal.iter().map(|&i| at(pads[i]).1).sum::<f64>() / signal.len() as f64);+    let bx = signal.iter().fold((f64::MAX, f64::MAX, f64::MIN, f64::MIN), |b, &i| { let p = at(pads[i]); (b.0.min(p.0), b.1.min(p.1), b.2.max(p.0), b.3.max(p.1)) });+    let interior = signal.iter().filter(|&&i| { let p = at(pads[i]); (p.0 - bx.0).min(bx.2 - p.0).min(p.1 - bx.1).min(bx.3 - p.1) > pitch * 0.5 }).count();+    let kind = if interior > 0 { "bga" } else { "perimeter" };+    let fine = pitch < 0.8 - 1e-9;+    let via_size = args.get("viaMm").or_else(|| args.get("viaSizeMm")).and_then(|v| v.as_f64()).unwrap_or(if fine { 0.4 } else if pitch < 1.0 - 1e-9 { 0.45 } else { 0.6 });+    let via_drill = args["viaDrillMm"].as_f64().unwrap_or(if via_size <= 0.45 { 0.2 } else { 0.3 });+    if via_drill >= via_size { return crate::input::refuse("bad_args", "viaDrillMm must be smaller than viaMm"); }+    let width = args["widthMm"].as_f64().unwrap_or(if fine { 0.1 } else { 0.15 });+    let rule = crate::fab::routing_clearance(&crate::input::rules(input));+    let clearance = args["clearanceMm"].as_f64().unwrap_or(0.0).max(rule.unwrap_or(0.1));+    let pad_d = median(signal.iter().map(|&i| f(&pads[i]["sizeX"]).max(f(&pads[i]["sizeY"]))).collect()).unwrap_or(0.0);+    let room = r3(pitch / 2f64.sqrt() - pad_d / 2.0 - via_size / 2.0);+    let fits = room + 1e-9 >= clearance;+    let want = args["style"].as_str().unwrap_or("auto");+    let style = match want {+        "auto" => if fits { "dogbone" } else { "via-in-pad" },+        "dogbone" | "via-in-pad" => want,+        o => return crate::input::refuse("bad_args", &format!("style is auto, dogbone or via-in-pad, not {o}")),+    };+    let mut warnings = Vec::new();+    if kind == "bga" && style == "dogbone" && !fits {+        warnings.push(format!("a {via_size} mm dogbone via leaves {room} mm to the balls at {pitch} mm pitch, under the {clearance} mm clearance: use via-in-pad or a smaller via"));+    }+    let via_perimeter = args["viaPerimeter"].as_bool().unwrap_or(false);+    let stub = args["stubMm"].as_f64().unwrap_or(0.4);+    let wp = |p: P, l: &str| json!({"x": r3(p.0), "y": r3(p.1), "layer": l});+    let sign = |v: f64| if v < -1e-9 { -1.0 } else { 1.0 };+    let (mut rows, mut calls): (Vec<Value>, BTreeMap<String, Vec<Value>>) = (Vec::new(), BTreeMap::new());+    // what the plan puts down, to measure: (pad, net, via or stub as a capsule)+    let mut pieces: Vec<(String, String, &'static str, Shape)> = Vec::new();+    type Pieces = Vec<(String, String, &'static str, Shape)>;+    fn via(pieces: &mut Pieces, calls: &mut BTreeMap<String, Vec<Value>>, rows: &mut Vec<Value>, from: String, n: &str, v: P, size: f64, path: Vec<Value>, row: Value) {+        pieces.push((from, n.to_string(), "via", Shape::Cap(v, v, size / 2.0)));+        calls.entry(n.to_string()).or_default().push(json!(path));+        rows.push(row);+    }+    // the board's routed copper: (net, layer or "" for every layer, shape, kind). Net-less tracks and arcs are a hatched+    // pour's pieces, which re-pour round new copper (altium-lane #22: a plan with "0 conflicts" shorted U4's routing)+    let mut routed: Vec<(String, String, Shape, &'static str)> = Vec::new();+    for t in st["tracks"].as_array().into_iter().flatten().filter(|t| !net(t).is_empty()) {+        routed.push((net(t), t["layer"].as_str().unwrap_or("").to_string(), Shape::Cap((f(&t["start"]["x"]), f(&t["start"]["y"])), (f(&t["end"]["x"]), f(&t["end"]["y"])), f(&t["width"]) / 2.0), "track"));+    }+    for a in st["arcs"].as_array().into_iter().flatten().filter(|a| !net(a).is_empty()) {+        let (c, rad) = ((f(&a["center"]["x"]), f(&a["center"]["y"])), f(&a["radius"]));+        let (a1, mut a2) = (f(&a["startAngle"]), f(&a["endAngle"]));+        if a2 <= a1 { a2 += 360.0; }+        let k = ((a2 - a1) / 10.0).ceil().max(1.0) as usize;+        let p = |deg: f64| (c.0 + rad * deg.to_radians().cos(), c.1 + rad * deg.to_radians().sin());+        for i in 0..k { routed.push((net(a), a["layer"].as_str().unwrap_or("").to_string(), Shape::Cap(p(a1 + (a2 - a1) * i as f64 / k as f64), p(a1 + (a2 - a1) * (i + 1) as f64 / k as f64), f(&a["width"]) / 2.0), "arc")); }+    }+    let holes: Vec<(P, f64)> = st["vias"].as_array().into_iter().flatten().map(|v| ((f(&v["position"]["x"]), f(&v["position"]["y"])), f(&v["size"]) / 2.0))+        .chain(st["pads"].as_array().into_iter().flatten().filter(|p| f(&p["drill"]) > 0.0).map(|p| (at(p), f(&p["sizeX"]).max(f(&p["sizeY"])).max(f(&p["drill"])) / 2.0))).collect();+    for v in st["vias"].as_array().into_iter().flatten().filter(|v| !net(v).is_empty()) {+        let c = (f(&v["position"]["x"]), f(&v["position"]["y"]));+        routed.push((net(v), String::new(), Shape::Cap(c, c, f(&v["size"]) / 2.0), "via"));+    }+    let include_routed = args["includeRouted"].as_bool().unwrap_or(false);+    for &i in &signal {+        let p = pads[i];+        let (pa, n) = (at(p), net(p));+        if n.is_empty() { rows.push(json!({"pad": name(p), "net": "", "action": "skip", "why": "no net"})); continue; }+        // a pin its net's copper already reaches is routed: a stub from it would run into that routing+        if !include_routed {+            let ps = pad_shape(p);+            if routed.iter().any(|(rn, l, s, _)| *rn == n && (l.is_empty() || l == side) && ps.gap(s) <= 1e-6) {+                rows.push(json!({"pad": name(p), "net": n, "action": "skip", "why": "already routed"}));+                continue;+            }+        }+        if kind == "bga" {+            let ring = ((pa.0 - bx.0) / pitch).round().min(((bx.2 - pa.0) / pitch).round()).min(((pa.1 - bx.1) / pitch).round()).min(((bx.3 - pa.1) / pitch).round()) as i64;+            if ring == 0 && args["surfaceOuterRing"].as_bool() != Some(false) {+                let (nv, _) = side_of(bx, pa);+                let end = (pa.0 + nv.0 * pitch, pa.1 + nv.1 * pitch);+                pieces.push((name(p), n.clone(), "stub", Shape::Cap(pa, end, width / 2.0)));+                calls.entry(n.clone()).or_default().push(json!([{"pad": name(p)}, wp(end, side)]));+                rows.push(json!({"pad": name(p), "net": n, "ring": ring, "action": "surface", "layer": side, "stubEnd": [r3(end.0), r3(end.1)]}));+            } else if style == "dogbone" {+                let v = (pa.0 + sign(pa.0 - cx) * pitch / 2.0, pa.1 + sign(pa.1 - cy) * pitch / 2.0);+                pieces.push((name(p), n.clone(), "stub", Shape::Cap(pa, v, width / 2.0)));+                via(&mut pieces, &mut calls, &mut rows, name(p), &n, v, via_size, vec![json!({"pad": name(p)}), wp(v, side), wp(v, &escape)],+                    json!({"pad": name(p), "net": n, "ring": ring, "action": "dogbone", "layer": escape, "via": [r3(v.0), r3(v.1)]}));+            } else {+                via(&mut pieces, &mut calls, &mut rows, name(p), &n, pa, via_size, vec![wp(pa, side), wp(pa, &escape)],+                    json!({"pad": name(p), "net": n, "ring": ring, "action": "via-in-pad", "layer": escape, "via": [r3(pa.0), r3(pa.1)], "note": "via-in-pad needs filled and capped vias (IPC-4761 type VII) from the fab"}));+            }+        } else {+            let (nv, edge) = side_of(bx, pa);+            let (c, s) = (f(&p["rotation"]).to_radians().cos().abs(), f(&p["rotation"]).to_radians().sin().abs());+            let half = if nv.0 != 0.0 { f(&p["sizeX"]) * c + f(&p["sizeY"]) * s } else { f(&p["sizeX"]) * s + f(&p["sizeY"]) * c } / 2.0;+            let with_via = via_perimeter || is_ground(&n);+            let reach = half + stub + if with_via { via_size / 2.0 } else { 0.0 };+            let end = (pa.0 + nv.0 * reach, pa.1 + nv.1 * reach);+            pieces.push((name(p), n.clone(), "stub", Shape::Cap(pa, end, width / 2.0)));+            if with_via {+                via(&mut pieces, &mut calls, &mut rows, name(p), &n, end, via_size, vec![json!({"pad": name(p)}), wp(end, side), wp(end, &escape)],+                    json!({"pad": name(p), "net": n, "edge": edge, "action": "stub+via", "layer": escape, "via": [r3(end.0), r3(end.1)]}));+            } else {+                calls.entry(n.clone()).or_default().push(json!([{"pad": name(p)}, wp(end, side)]));+                rows.push(json!({"pad": name(p), "net": n, "edge": edge, "action": "surface", "layer": side, "stubEnd": [r3(end.0), r3(end.1)]}));+            }+        }+    }+    for &i in &thermal {+        let p = pads[i];+        let n = net(p);+        if n.is_empty() { continue; }+        let (pa, w, h) = (at(p), f(&p["sizeX"]), f(&p["sizeY"]));+        let (w, h) = if (f(&p["rotation"]).rem_euclid(180.0) - 90.0).abs() < 1.0 { (h, w) } else { (w, h) };+        let vp = (via_size + 0.5).max(1.0);+        let (nx, ny) = ((((w - via_size) / vp).floor() as i64 + 1).max(1), (((h - via_size) / vp).floor() as i64 + 1).max(1));+        let (mut grid, mut kept_clear) = (Vec::new(), 0);+        for a in 0..nx {+            for b in 0..ny {+                let v = (pa.0 + (a as f64 - (nx - 1) as f64 / 2.0) * vp, pa.1 + (b as f64 - (ny - 1) as f64 / 2.0) * vp);+                // clear of the holes already there, as thermal_vias keeps them (a grid on U4's 9 GND vias was hole-to-hole)+                if holes.iter().any(|(c, r)| ((c.0 - v.0).powi(2) + (c.1 - v.1).powi(2)).sqrt() < r + via_size / 2.0 + clearance - 1e-9) { kept_clear += 1; continue; }+                pieces.push((name(p), n.clone(), "via", Shape::Cap(v, v, via_size / 2.0)));+                calls.entry(n.clone()).or_default().push(json!([wp(v, side), wp(v, &escape)]));+                grid.push(json!([r3(v.0), r3(v.1)]));+            }+        }+        rows.push(json!({"pad": name(p), "net": n, "action": "thermal-via-grid", "layer": escape, "vias": grid, "viaPitchMm": vp, "keptClearOfHoles": kept_clear}));+    }+    // each via and stub against every other net's pad on the board (vias on every layer, stubs on the part's side)+    let all: Vec<(Value, Shape)> = st["pads"].as_array().cloned().unwrap_or_default().into_iter().map(|p| { let s = pad_shape(&p); (p, s) }).collect();+    let (mut worst, mut conflicts) = (f64::MAX, Vec::new());+    for (from, n, what, s) in &pieces {+        for (p, ps) in &all {+            if net(p) == *n && !n.is_empty() { continue; }+            if *what == "stub" && !(p["layer"] == side || p["layer"] == "*.Cu" || f(&p["drill"]) > 0.0) { continue; }+            let g = s.gap(ps);+            if *what == "via" { worst = worst.min(g); }+            if g < clearance - 1e-9 {+                conflicts.push(json!({"from": from, "what": what, "with": "pad", "pad": format!("{}.{}", p["ref"].as_str().unwrap_or(""), p["name"].as_str().unwrap_or("")), "padNet": p["net"], "gapMm": r3(g)}));+            }+        }+        // and against other nets' tracks, arcs and vias: on every layer for a via, on the part's side for a stub+        for (rn, l, rs, kind) in &routed {+            if rn == n || (*what == "stub" && !l.is_empty() && l != side) { continue; }+            let g = s.gap(rs);+            if g < clearance - 1e-9 {+                let (x0, y0, x1, y1) = rs.bounds();+                conflicts.push(json!({"from": from, "what": what, "with": kind, "net": rn, "layer": if l.is_empty() { "every" } else { l.as_str() }, "near": [r3((x0 + x1) / 2.0), r3((y0 + y1) / 2.0)], "gapMm": r3(g)}));+            }+        }+    }+    // other nets' pours the plan runs into: not conflicts (a pour re-pours round new copper), but until the repour the+    // tool's DRC sees the pour's pieces as shorts (altium-lane #22), and a stub across a pour can cut it in two+    let mut crosses: Vec<Value> = Vec::new();+    for p in st["polygons"].as_array().into_iter().flatten() {+        let (pn, pl) = (net(p), p["layer"].as_str().unwrap_or("").to_string());+        let ring: Vec<P> = p["points"].as_array().into_iter().flatten().map(|q| (f(&q[0]), f(&q[1]))).collect();+        if pn.is_empty() || ring.len() < 3 { continue; }+        let poly = Shape::Poly(ring);+        let hit = pieces.iter().any(|(_, n, what, s)| *n != pn && (*what == "via" || pl == side) && s.gap(&poly) <= 1e-9);+        if hit && !crosses.iter().any(|c| c["net"] == json!(pn) && c["layer"] == json!(pl)) { crosses.push(json!({"net": pn, "layer": pl})); }+    }+    let via_count = pieces.iter().filter(|x| x.2 == "via").count();+    let calls: Vec<Value> = calls.into_iter().map(|(n, paths)| json!({"net": n, "layer": side, "width": width, "viaSize": via_size, "viaDrill": via_drill, "paths": paths})).collect();+    json!({"success": true, "ref": r, "package": kind, "padCount": pads.len(), "pitchMm": pitch, "side": side, "escapeLayer": escape, "copperLayers": copper,+        "style": if kind == "bga" { style } else { "stubs" }, "requestedStyle": want, "dogboneRoomMm": room, "dogboneFits": fits,+        "via": {"size": via_size, "drill": via_drill}, "widthMm": width, "clearanceMm": clearance,+        "pads": rows, "calls": calls, "callCount": calls.len(), "viaCount": via_count,+        "minViaToPadMm": if worst < f64::MAX { json!(r3(worst)) } else { Value::Null }, "conflicts": conflicts, "crossesPours": crosses, "warnings": warnings, "revision": st["revision"],+        "_hint": "A plan only: send each call to route_net with expectedRevision: revision. conflicts lists vias and stubs closer than clearanceMm to another net's pad, track, arc or via (vias on every layer, stubs on the part's side): apply nothing while it is not empty. Pins already reached by their net's copper are skipped (includeRouted plans them anyway); the exposed-pad grid steps round holes already there. crossesPours names other nets' pours the plan runs into: repour BEFORE running DRC (until then the pour's pieces read as shorts), then check that none of them split (splitNets). Via-in-pad needs filled and capped vias: tell the user first."})+}++#[cfg(test)]+mod tests {+    use super::*;++    fn pad(r: &str, name: &str, x: f64, y: f64, net: &str) -> Value {+        json!({"ref": r, "name": name, "x": x, "y": y, "sizeX": 0.6, "sizeY": 0.6, "rotation": 0, "layer": "F.Cu", "drill": 0, "net": net, "shape": "rect"})+    }++    /// U1: a 4-pin part at the origin with VDD on its right; C1 (VDD/GND) far away, C2 on a crystal net, C3 near U2.+    fn board() -> Value {+        json!({"revision": "r1", "outline": [[-20, -20], [20, -20], [20, 20], [-20, 20]], "nets": ["VDD", "GND", "XIN"],+            "components": [{"ref": "U1", "x": 0, "y": 0, "rotation": 0, "side": "top"}, {"ref": "U2", "x": 12, "y": 0, "rotation": 0, "side": "top"},+                           {"ref": "C1", "x": -10, "y": 10, "rotation": 0, "side": "top"}, {"ref": "C2", "x": -10, "y": -10, "rotation": 0, "side": "top"},+                           {"ref": "C3", "x": 12, "y": 3, "rotation": 0, "side": "top"}],+            "pads": [pad("U1", "1", -2.0, 1.0, "XIN"), pad("U1", "2", -2.0, -1.0, "GND"), pad("U1", "3", 2.0, -1.0, "GND"), pad("U1", "4", 2.0, 1.0, "VDD"),+                     pad("U2", "1", 11.0, 1.0, "VDD"), pad("U2", "2", 11.0, -1.0, "GND"), pad("U2", "3", 13.0, 0.0, "GND"),+                     pad("C1", "1", -10.5, 10.0, "VDD"), pad("C1", "2", -9.5, 10.0, "GND"),+                     pad("C2", "1", -10.5, -10.0, "XIN"), pad("C2", "2", -9.5, -10.0, "GND"),+                     pad("C3", "1", 11.5, 3.0, "VDD"), pad("C3", "2", 12.5, 3.0, "GND")]})+    }++    #[test]+    fn a_cap_lands_beside_its_pin_with_the_power_pad_facing_it() {+        let r = place_decoupling(&json!({"board": board(), "args": {"ic": "U1"}}));+        assert_eq!(r["success"], json!(true), "{r}");+        // C1 only: C2 sits on a crystal net, C3 is nearer U2's VDD pin+        assert_eq!(r["placements"].as_array().unwrap().len(), 1, "{r}");+        let p = &r["placements"][0];+        assert_eq!((p["cap"].as_str(), p["pin"].as_str(), p["side"].as_str()), (Some("C1"), Some("U1.4"), Some("right")));+        // U1's box ends at x 2.3; 0.3 out, the power pad (now the cap's left pad) at 2.9, level with the pin+        assert_eq!(p["rotation"], json!(0.0));+        assert!((f(&p["x"]) - 3.4).abs() < 1e-9 && (f(&p["y"]) - 1.0).abs() < 1e-9, "{p}");+        assert!((f(&p["padToPinMm"]) - 0.9).abs() < 1e-9);+        let why: Vec<&str> = r["leftOut"].as_array().unwrap().iter().map(|l| l["why"].as_str().unwrap()).collect();+        assert_eq!(why, vec!["signal_net", "nearer_another_ic"]);+        assert_eq!(r["moveArgs"]["parts"][0], json!({"ref": "C1", "x": 3.4, "y": 1.0, "rotation": 0.0}));+        assert_eq!(r["moveArgs"]["expectedRevision"], "r1");+        assert_eq!(r["validation"]["ok"], json!(true), "{r}");+        // U1's supplies only: XIN has one cap and is not named like a supply (fusion-lane #22)+        assert_eq!(r["icPowerNets"], json!(["VDD"]));+    }++    #[test]+    fn a_cap_leaves_room_for_the_ics_fanout() {+        // a second ground pin, U1.5, just under the VDD pin: its fanout via lands where C1 would go (altium-lane)+        let mut b = board();+        b["pads"].as_array_mut().unwrap().push(pad("U1", "5", 2.0, 0.4, "GND"));+        let r = place_decoupling(&json!({"board": b, "args": {"ic": "U1", "caps": ["C1"]}}));+        assert!(f(&r["placements"][0]["slidMm"]).abs() > 0.0, "{r}");+        let close = place_decoupling(&json!({"board": b, "args": {"ic": "U1", "caps": ["C1"], "leaveFanout": false}}));+        assert_eq!(close["placements"][0]["slidMm"], json!(0.0), "{close}");+    }++    #[test]+    fn a_cap_that_cannot_move_keeps_its_spot() {+        // C2 sits where C1 would go, and cannot be placed (its net is none of U1's): C1 slides past it (fusion-lane #22)+        let mut b = board();+        b["components"][3]["x"] = json!(3.4); b["components"][3]["y"] = json!(1.0);+        b["pads"][9] = pad("C2", "1", 2.9, 1.0, "OTHER");+        b["pads"][10] = pad("C2", "2", 3.9, 1.0, "GND");+        let r = place_decoupling(&json!({"board": b, "args": {"ic": "U1", "caps": ["C1", "C2"]}}));+        assert_eq!(r["skipped"][0]["why"], "no_shared_power_net", "{r}");+        assert!(f(&r["placements"][0]["slidMm"]).abs() > 0.0, "{r}");+        assert_eq!(r["validation"]["ok"], json!(true), "{r}");+    }++    #[test]+    fn a_cap_turns_to_face_the_pin_and_slides_off_a_taken_spot() {+        // C1 turned round (power pad on its right) must turn 180 to face U1's right side; a part on the spot pushes it along+        let mut b = board();+        b["pads"][7]["x"] = json!(-9.5); b["pads"][8]["x"] = json!(-10.5);+        b["components"].as_array_mut().unwrap().push(json!({"ref": "R9", "x": 3.4, "y": 1.0, "rotation": 0, "side": "top"}));+        b["pads"].as_array_mut().unwrap().push(pad("R9", "1", 3.4, 1.0, ""));+        let r = place_decoupling(&json!({"board": b, "args": {"ic": "U1", "caps": ["C1"]}}));+        let p = &r["placements"][0];+        assert_eq!(p["rotation"], json!(180.0), "{r}");+        assert!(f(&p["slidMm"]).abs() > 0.0, "{r}");+        assert_eq!(r["validation"]["ok"], json!(true), "{r}");+        // a bottom part's through-hole pad on the spot pushes it along too; its surface pads do not+        let mut b = board();+        b["components"].as_array_mut().unwrap().push(json!({"ref": "J9", "x": 3.4, "y": 1.0, "rotation": 0, "side": "bottom"}));+        b["pads"].as_array_mut().unwrap().push(pad("J9", "1", 3.4, 1.0, ""));+        assert_eq!(place_decoupling(&json!({"board": b, "args": {"ic": "U1", "caps": ["C1"]}}))["placements"][0]["slidMm"], json!(0.0));+        b["pads"][13]["layer"] = json!("*.Cu");+        b["pads"][13]["drill"] = json!(0.4);+        assert!(f(&place_decoupling(&json!({"board": b, "args": {"ic": "U1", "caps": ["C1"]}}))["placements"][0]["slidMm"]).abs() > 0.0);+    }++    #[test]+    fn the_verb_names_what_it_cannot_do() {+        assert_eq!(place_decoupling(&json!({"board": board(), "args": {}}))["errorCode"], "bad_args");+        assert_eq!(place_decoupling(&json!({"board": board(), "args": {"ic": "U7"}}))["errorCode"], "no_such_part");+        let mut b = board();+        b["components"][2]["side"] = json!("bottom");+        let r = place_decoupling(&json!({"board": b, "args": {"ic": "U1", "caps": ["C1"]}}));+        assert_eq!(r["skipped"][0]["why"], "other_side");+    }++    #[test]+    fn clearance_by_part_box_and_by_pad_copper() {+        // C3's box sits 1.4 mm above U2's+        let r = check_clearance(&json!({"board": board(), "args": {"thresholdMm": 1.5}}));+        assert_eq!(r["pairs"][0]["a"], "C3");+        assert_eq!(r["pairs"][0]["b"], "U2");+        assert!((f(&r["pairs"][0]["distanceMm"]) - 1.4).abs() < 1e-9, "{r}");+        let p = check_clearance(&json!({"board": board(), "args": {"mode": "pads", "refs": ["C3"], "thresholdMm": 2.0}}));+        // same-net VDD pads are skipped; C3.2 (GND) to U2.1 (VDD) is the closest+        assert_eq!((p["pairs"][0]["a"].as_str(), p["pairs"][0]["b"].as_str()), (Some("C3.2"), Some("U2.1")), "{p}");+        assert_eq!(check_clearance(&json!({"board": board(), "args": {"refs": ["Q1"]}}))["errorCode"], "no_such_part");+        // a part under a raised one: pads apart, bodies apart in height, listed as stacked like placement_check does+        let st = json!({"components": [{"ref": "M1", "x": 0, "y": 0, "rotation": 0, "side": "top"}, {"ref": "R1", "x": 0, "y": 0, "rotation": 0, "side": "top"}],+            "pads": [pad("M1", "1", -3.0, 0.0, "A"), pad("M1", "2", 3.0, 0.0, "B"), pad("R1", "1", -0.5, 0.0, "C"), pad("R1", "2", 0.5, 0.0, "D")]});+        let bodies = json!({"bodies": [{"ref": "M1", "side": "top", "x0": -3.5, "y0": -2.0, "x1": 3.5, "y1": 2.0, "z0": 2.0, "z1": 3.0},+                                       {"ref": "R1", "side": "top", "x0": -0.8, "y0": -0.4, "x1": 0.8, "y1": 0.4, "z0": 0.0, "z1": 0.5}]});+        let c = check_clearance(&json!({"board": st, "bodies": bodies, "args": {}}));+        assert_eq!((c["pairs"].as_array().unwrap().len(), c["stacked"].as_array().unwrap().len()), (0, 1), "{c}");+        assert_eq!(check_clearance(&json!({"board": st, "args": {}}))["pairs"].as_array().unwrap().len(), 1);+        assert_eq!(check_clearance(&json!({"board": board(), "args": {"mode": "x"}}))["errorCode"], "bad_args");+    }++    fn bga(pitch: f64, ball: f64) -> Value {+        // a 4 x 4 BGA at the origin, nets N0..N15, plus a stray resistor pad+        let mut pads = Vec::new();+        for i in 0..4 { for j in 0..4 {+            let (x, y) = ((i as f64 - 1.5) * pitch, (j as f64 - 1.5) * pitch);+            pads.push(json!({"ref": "U1", "name": format!("{}{}", (b'A' + j as u8) as char, i + 1), "x": x, "y": y, "sizeX": ball, "sizeY": ball, "rotation": 0, "layer": "F.Cu", "drill": 0, "net": format!("N{}", i * 4 + j), "shape": "round"}));+        } }+        json!({"revision": "r2", "outline": [[-10, -10], [10, -10], [10, 10], [-10, 10]], "components": [{"ref": "U1", "x": 0, "y": 0, "rotation": 0, "side": "top"}], "pads": pads})+    }++    #[test]+    fn a_bga_escapes_its_outer_ring_and_dogbones_the_rest() {+        let r = plan_fanout(&json!({"board": bga(1.0, 0.45), "stack": {"copperLayers": 4}, "args": {"ref": "U1"}}));+        assert_eq!((r["package"].as_str(), r["style"].as_str(), r["escapeLayer"].as_str()), (Some("bga"), Some("dogbone"), Some("In1.Cu")), "{r}");+        let count = |a: &str| r["pads"].as_array().unwrap().iter().filter(|p| p["action"] == a).count();+        assert_eq!((count("surface"), count("dogbone")), (12, 4));+        // B2 sits at (-0.5, -0.5): its via goes half a pitch out, away from the centre, and changes layer there+        let b2 = r["calls"].as_array().unwrap().iter().find(|c| c["paths"][0][0]["pad"] == "U1.B2").unwrap();+        assert_eq!(b2["paths"][0][1], json!({"x": -1.0, "y": -1.0, "layer": "F.Cu"}));+        assert_eq!(b2["paths"][0][2], json!({"x": -1.0, "y": -1.0, "layer": "In1.Cu"}));+        assert_eq!(r["conflicts"], json!([]), "{r}");+        // at 0.5 mm pitch the dogbone does not fit: via in pad+        let fine = plan_fanout(&json!({"board": bga(0.5, 0.3), "args": {"ref": "U1"}}));+        assert_eq!((fine["style"].as_str(), fine["escapeLayer"].as_str()), (Some("via-in-pad"), Some("B.Cu")), "{fine}");+        assert_eq!(plan_fanout(&json!({"board": bga(0.5, 0.3), "args": {"ref": "U1", "style": "dogbone"}}))["warnings"].as_array().unwrap().len(), 1);+    }++    #[test]+    fn a_qfn_takes_stubs_a_ground_via_and_a_via_grid_and_names_what_it_would_hit() {+        let mut pads = Vec::new();+        for k in 0..4 { pads.push(json!({"ref": "U2", "name": format!("{}", k + 1), "x": -2.0, "y": 0.75 - k as f64 * 0.5, "sizeX": 0.8, "sizeY": 0.25, "rotation": 0, "layer": "F.Cu", "drill": 0, "net": if k == 3 { "GND".to_string() } else { format!("S{k}") }, "shape": "rect"})); }+        for k in 0..4 { pads.push(json!({"ref": "U2", "name": format!("{}", k + 5), "x": 2.0, "y": -0.75 + k as f64 * 0.5, "sizeX": 0.8, "sizeY": 0.25, "rotation": 0, "layer": "F.Cu", "drill": 0, "net": format!("T{k}"), "shape": "rect"})); }+        pads.push(json!({"ref": "U2", "name": "9", "x": 0.0, "y": 0.0, "sizeX": 2.6, "sizeY": 2.6, "rotation": 0, "layer": "F.Cu", "drill": 0, "net": "GND", "shape": "rect"}));+        // R1's pad right where U2.5's stub ends+        pads.push(json!({"ref": "R1", "name": "1", "x": 2.9, "y": -0.75, "sizeX": 0.5, "sizeY": 0.5, "rotation": 0, "layer": "F.Cu", "drill": 0, "net": "X", "shape": "rect"}));+        let b = json!({"components": [{"ref": "U2", "x": 0, "y": 0, "rotation": 0, "side": "top"}, {"ref": "R1", "x": 2.9, "y": -0.75, "rotation": 0, "side": "top"}], "pads": pads});+        let r = plan_fanout(&json!({"board": b, "args": {"ref": "U2"}}));+        assert_eq!((r["package"].as_str(), r["pitchMm"].as_f64()), (Some("perimeter"), Some(0.5)), "{r}");+        let action = |pad: &str| r["pads"].as_array().unwrap().iter().find(|p| p["pad"] == pad).unwrap()["action"].clone();+        assert_eq!((action("U2.1"), action("U2.4"), action("U2.9")), (json!("surface"), json!("stub+via"), json!("thermal-via-grid")));+        // U2.1 at x -2 with a 0.8 mm pad: 0.4 + the 0.4 stub reaches x -2.8+        assert_eq!(r["pads"][0]["stubEnd"], json!([-2.8, 0.75]));+        assert_eq!(r["conflicts"].as_array().unwrap().iter().map(|c| c["pad"].as_str().unwrap()).collect::<Vec<_>>(), vec!["R1.1"], "{r}");+        assert_eq!(plan_fanout(&json!({"board": b, "args": {"ref": "R1"}}))["errorCode"], "not_a_package");+        // on a routed board (altium-lane #22): U2.1 already has its track, so it is skipped; another net's track across+        // U2.2's stub is a conflict; a via in the exposed pad's centre keeps the grid off it+        let mut routed = b.clone();+        routed["tracks"] = json!([{"net": "S0", "layer": "F.Cu", "width": 0.2, "start": {"x": -2.0, "y": 0.75}, "end": {"x": -4.0, "y": 0.75}},+                                  {"net": "Q", "layer": "F.Cu", "width": 0.2, "start": {"x": -2.6, "y": -2.0}, "end": {"x": -2.6, "y": 0.4}}]);+        routed["vias"] = json!([{"net": "GND", "size": 0.6, "drill": 0.3, "position": {"x": 0.0, "y": 0.0}}]);+        let r = plan_fanout(&json!({"board": routed, "args": {"ref": "U2"}}));+        assert_eq!(r["pads"][0]["why"], "already routed", "{r}");+        assert!(r["conflicts"].as_array().unwrap().iter().any(|c| c["with"] == "track" && c["net"] == "Q" && c["from"] == "U2.2"), "{r}");+        let grid = r["pads"].as_array().unwrap().iter().find(|p| p["action"] == "thermal-via-grid").unwrap();+        assert!(grid["keptClearOfHoles"].as_u64().unwrap() >= 1, "{grid}");+        assert!(grid["vias"].as_array().unwrap().iter().all(|v| (f(&v[0]).powi(2) + f(&v[1]).powi(2)).sqrt() >= 0.3 + 0.3 + 0.1 - 1e-9));+        assert_eq!(plan_fanout(&json!({"board": routed, "args": {"ref": "U2", "includeRouted": true}}))["pads"][0]["action"], "surface");+        assert_eq!(plan_fanout(&json!({"board": b, "args": {"ref": "U2", "escapeLayer": "In3.Cu"}}))["errorCode"], "no_such_layer");+    }++    #[test]+    fn pad_copper_gaps_are_exact() {+        let a = pad_shape(&json!({"x": 0.0, "y": 0.0, "sizeX": 1.0, "sizeY": 1.0, "shape": "rect"}));+        let b = pad_shape(&json!({"x": 2.0, "y": 0.0, "sizeX": 1.0, "sizeY": 1.0, "shape": "round"}));+        assert!((a.gap(&b) - 1.0).abs() < 1e-9);+        let inner = pad_shape(&json!({"x": 0.0, "y": 0.0, "sizeX": 0.2, "sizeY": 0.2, "shape": "rect"}));+        assert_eq!(a.gap(&inner), 0.0);+        assert_eq!(inner.gap(&a), 0.0);+    }+}
bridge-rs/vendor/adom-eda-checks/src/route.rs+107−16
@@ -21,13 +21,13 @@ fn seg_point(p: P, a: P, b: P) -> f64 { }  /// The distance between two segments (0 when they cross).-fn seg_seg(a: P, b: P, c: P, d: P) -> f64 {+pub(crate) fn seg_seg(a: P, b: P, c: P, d: P) -> f64 {     let cross = |p: P, q: P, r: P| (q.0 - p.0) * (r.1 - p.1) - (q.1 - p.1) * (r.0 - p.0);     if cross(a, b, c) * cross(a, b, d) < 0.0 && cross(c, d, a) * cross(c, d, b) < 0.0 { return 0.0; }     seg_point(a, c, d).min(seg_point(b, c, d)).min(seg_point(c, a, b)).min(seg_point(d, a, b)) } -fn inside(p: P, ring: &[P]) -> bool {+pub(crate) fn inside(p: P, ring: &[P]) -> bool {     let mut c = false;     for i in 0..ring.len() {         let (a, b) = (ring[i], ring[(i + 1) % ring.len()]);@@ -39,7 +39,7 @@ fn inside(p: P, ring: &[P]) -> bool { /// Copper as a shape: a capsule (a segment with a half-width: tracks, round pads, vias) or a polygon (rect pads, a /// custom pad's copperPoints). #[derive(Clone)]-enum Shape { Cap(P, P, f64), Poly(Vec<P>) }+pub(crate) enum Shape { Cap(P, P, f64), Poly(Vec<P>) }  impl Shape {     /// Edge-to-edge distance from the segment a..b (its centreline) to this copper.@@ -52,7 +52,18 @@ impl Shape {             }         }     }-    fn bounds(&self) -> (f64, f64, f64, f64) {+    /// Edge-to-edge distance between two pieces of copper, 0 when they touch or one holds the other.+    pub(crate) fn gap(&self, o: &Shape) -> f64 {+        match o {+            Shape::Cap(c, d, r) => (self.dist(*c, *d) - r).max(0.0),+            Shape::Poly(ring) => {+                let held = match self { Shape::Cap(c, _, _) => inside(*c, ring), Shape::Poly(own) => own.first().map(|p| inside(*p, ring)).unwrap_or(false) };+                if held { return 0.0; }+                (0..ring.len()).map(|i| self.dist(ring[i], ring[(i + 1) % ring.len()])).fold(f64::MAX, f64::min).max(0.0)+            }+        }+    }+    pub(crate) fn bounds(&self) -> (f64, f64, f64, f64) {         match self {             Shape::Cap(c, d, r) => (c.0.min(d.0) - r, c.1.min(d.1) - r, c.0.max(d.0) + r, c.1.max(d.1) + r),             Shape::Poly(ring) => ring.iter().fold((f64::MAX, f64::MAX, f64::MIN, f64::MIN), |b, p| (b.0.min(p.0), b.1.min(p.1), b.2.max(p.0), b.3.max(p.1))),@@ -61,7 +72,7 @@ impl Shape { }  /// A pad's copper: copperPoints when the bridge sent them, else its shape turned with it.-fn pad_shape(p: &Value) -> Shape {+pub(crate) fn pad_shape(p: &Value) -> Shape {     let (x, y, sx, sy, rot) = (f(&p["x"]), f(&p["y"]), f(&p["sizeX"]), f(&p["sizeY"]), f(&p["rotation"]).to_radians());     let pts: Vec<P> = p["copperPoints"].as_array().cloned().unwrap_or_default().iter().map(|q| (f(&q[0]), f(&q[1]))).collect();     if pts.len() >= 3 { return Shape::Poly(pts); }@@ -77,7 +88,7 @@ fn pad_shape(p: &Value) -> Shape { }  /// The copper layers a pad is on: every one for a through-hole pad (`*.Cu` or a drill), else its own.-fn pad_layers(p: &Value, all: &[String]) -> Vec<String> {+pub(crate) fn pad_layers(p: &Value, all: &[String]) -> Vec<String> {     let l = p["layer"].as_str().unwrap_or("");     if l == "*.Cu" || f(&p["drill"]) > 0.0 { all.to_vec() } else { vec![l.to_string()] } }@@ -121,20 +132,43 @@ pub fn plan_route(input: &Value) -> Value {     let allow_vias = args["allowVias"].as_bool().unwrap_or(true) && layers.len() > 1;     let via_cost = num("viaCost", 5.0);     let max_nodes = args["maxNodes"].as_u64().unwrap_or(50_000).clamp(1, 500_000) as usize;-    // the board's own clearance decides; a caller's clearanceMm can only raise it-    let rule = crate::fab::min_clearance(&rules);+    // the board's strictest board-wide copper rule decides (fusion-lane #21: a via planned at the 0.1 wire rule landed+    // 0.109 mm from a pad where 0.15 applies); a caller's clearanceMm can only raise it+    let rule = crate::fab::routing_clearance(&rules);     let clearance = num("clearanceMm", 0.0).max(rule.unwrap_or(0.2));     let edge = num("edgeClearanceMm", 0.3);     let ring = crate::coppermap::outline_ring(&st);     if ring.len() < 3 { return crate::input::refuse("no_outline", "the board has no outline"); } +    // a through via passes every copper layer of the board, not only the ones the route may use (fusion-lane #21: a via+    // planned on F.Cu and In2.Cu landed 0.094 mm from a B.Cu track)+    let mut copper = crate::placetools::copper_layers(&st, input);+    for l in &layers { if !copper.contains(l) { copper.push(l.clone()); } }+    // other nets' pours: not obstacles (they re-pour round the route), but a route across one can cut it in two, so the+    // reply names each one it crosses, and avoidPours keeps the route out of them+    // avoidPours: true keeps out of every other net's pour, a list of nets out of theirs only; pourCost makes each mm run+    // inside a pour cost 1 + pourCost mm instead, a preference rather than a wall (fusion-lane #21: on BQ25792 almost+    // every spot is under some pour, and a hard block found no path)+    let avoid_nets: Option<Vec<String>> = match &args["avoidPours"] {+        Value::Bool(true) => Some(Vec::new()),+        Value::Array(a) => Some(a.iter().filter_map(|v| v.as_str().map(|s| s.to_uppercase())).collect()),+        _ => None,+    };+    let avoids = |n: &str| avoid_nets.as_ref().map(|v| v.is_empty() || v.contains(&n.to_uppercase())).unwrap_or(false);+    let pour_cost = num("pourCost", 0.0).max(0.0);+    let pours: Vec<(String, String, Shape)> = st["polygons"].as_array().cloned().unwrap_or_default().iter()+        .filter(|p| p["net"].as_str().map(|n| !n.is_empty() && !n.eq_ignore_ascii_case(net)).unwrap_or(false))+        .filter_map(|p| {+            let ring: Vec<P> = p["points"].as_array()?.iter().map(|q| (f(&q[0]), f(&q[1]))).collect();+            (ring.len() >= 3).then(|| (p["net"].as_str().unwrap_or("").to_string(), p["layer"].as_str().unwrap_or("").to_string(), Shape::Poly(ring)))+        }).collect();     // copper of other nets, by layer; every pad for the via-in-pad rule. Net-less tracks and arcs are a hatched pour's     // pieces (Altium lists 8777 of the Bluetooth Sentinel's 9378 tracks with no net) and pours re-pour round new copper,     // so neither blocks a route: repour after placing it (the reply says so)     let same = |v: &Value| v["net"].as_str().map(|n| n.eq_ignore_ascii_case(net) || (n.is_empty() && v.get("start").or(v.get("center")).is_some())).unwrap_or(false);     let mut ob: Vec<(Shape, Vec<String>, (f64, f64, f64, f64))> = Vec::new();     let mut push = |s: Shape, ls: Vec<String>| { let b = s.bounds(); ob.push((s, ls, b)); };-    for p in pads.iter().filter(|p| !same(p)) { push(pad_shape(p), pad_layers(p, &layers)); }+    for p in pads.iter().filter(|p| !same(p)) { push(pad_shape(p), pad_layers(p, &copper)); }     for t in st["tracks"].as_array().cloned().unwrap_or_default().iter().filter(|t| !same(t)) {         push(Shape::Cap((f(&t["start"]["x"]), f(&t["start"]["y"])), (f(&t["end"]["x"]), f(&t["end"]["y"])), f(&t["width"]) / 2.0), vec![t["layer"].as_str().unwrap_or("").to_string()]);     }@@ -148,7 +182,7 @@ pub fn plan_route(input: &Value) -> Value {     }     for v in st["vias"].as_array().cloned().unwrap_or_default().iter().filter(|v| !same(v)) {         let c = (f(&v["position"]["x"]), f(&v["position"]["y"]));-        push(Shape::Cap(c, c, f(&v["size"]) / 2.0), layers.clone());+        push(Shape::Cap(c, c, f(&v["size"]) / 2.0), copper.clone());     }     let all_pads: Vec<Shape> = pads.iter().map(pad_shape).collect(); @@ -193,9 +227,10 @@ pub fn plan_route(input: &Value) -> Value {         let ok = if u.2 != v.2 {             // a through via: clear on every layer, inside the outline, in no pad             let r = via_size / 2.0;-            edge_ok(a, a, r) && layers.iter().all(|l| clear_on(a, a, r, l)) && all_pads.iter().all(|s| s.dist(a, a) >= r + clearance - 1e-9)+            edge_ok(a, a, r) && copper.iter().all(|l| clear_on(a, a, r, l)) && all_pads.iter().all(|s| s.dist(a, a) >= r + clearance - 1e-9)         } else {             edge_ok(a, b, width / 2.0) && clear_on(a, b, width / 2.0, &layers[u.2])+                && !pours.iter().any(|(n, l, s)| avoids(n) && *l == layers[u.2] && s.dist(a, b) < width / 2.0)         };         cache.insert(k, ok);         ok@@ -221,7 +256,11 @@ pub fn plan_route(input: &Value) -> Value {         if allow_vias { for l in 0..layers.len() { if l != u.2 { nb.push((u.0, u.1, l)); } } }         for v in nb {             if seen.contains(&v) || !step_ok(u, v) { continue; }-            let step = if v.2 != u.2 { via_cost } else { (xs[v.0] - xs[u.0]).abs() + (ys[v.1] - ys[u.1]).abs() };+            let step = if v.2 != u.2 { via_cost } else {+                let (a, b) = ((xs[u.0], ys[u.1]), (xs[v.0], ys[v.1]));+                let len = (b.0 - a.0).abs() + (b.1 - a.1).abs();+                if pour_cost > 0.0 && pours.iter().any(|(_, l, s)| *l == layers[u.2] && s.dist(a, b) < width / 2.0) { len * (1.0 + pour_cost) } else { len }+            };             let ng = g + step;             if ng >= cost.get(&v).copied().unwrap_or(f64::MAX) - 1e-9 { continue; }             cost.insert(v, ng);@@ -248,20 +287,27 @@ pub fn plan_route(input: &Value) -> Value {     let mut way = vec![json!({"pad": key(&ends[0])})];     let mut vias = Vec::new();     let mut length = 0.0;+    let mut crosses: Vec<Value> = Vec::new();     let last = keep.len() - 1;     for (i, w) in keep.windows(2).enumerate() {         let (a, b) = (w[0], w[1]);         let (pa, pb) = ((xs[a.0], ys[a.1]), (xs[b.0], ys[b.1]));-        if a.2 != b.2 { vias.push(json!([pa.0, pa.1])); } else { length += ((pb.0 - pa.0).powi(2) + (pb.1 - pa.1).powi(2)).sqrt(); }+        if a.2 != b.2 { vias.push(json!([pa.0, pa.1])); } else {+            length += ((pb.0 - pa.0).powi(2) + (pb.1 - pa.1).powi(2)).sqrt();+            for (n, l, s) in &pours {+                if *l == layers[a.2] && s.dist(pa, pb) < width / 2.0 && !crosses.iter().any(|c: &Value| c["net"] == json!(n) && c["layer"] == json!(l)) { crosses.push(json!({"net": n, "layer": l})); }+            }+        }         // every corner and layer change; the goal itself is the closing {pad} waypoint         if i + 1 < last { way.push(json!({"x": pb.0, "y": pb.1, "layer": layers[b.2]})); }     }     way.push(json!({"pad": key(&ends[1])}));     json!({"success": true, "found": true, "lengthMm": r3(length), "vias": vias.len(), "viaAt": vias,         "routeNet": {"net": net, "layer": layers[path[0].2], "width": width, "viaSize": via_size, "viaDrill": via_drill, "paths": [way]},-        "planner": {"algorithm": "bounded orthogonal A*", "widthFrom": width_from, "viaFrom": via_from, "gridMm": grid, "layers": layers, "clearanceMm": clearance, "edgeClearanceMm": edge, "expandedNodes": seen.len()},-        "revision": revision,-        "_hint": "A plan only: pass routeNet to route_net unchanged (with expectedRevision: revision). A layer change is two waypoints at the same point, where route_net places a via. Pours (and a hatched pour's net-less pieces) are not obstacles: repour after placing the route. The path is orthogonal on the grid: a finer gridMm finds tighter paths and searches longer."})+        "planner": {"algorithm": "bounded orthogonal A*", "widthFrom": width_from, "viaFrom": via_from, "gridMm": grid, "layers": layers, "viasCheckedOn": copper, "clearanceMm": clearance, "edgeClearanceMm": edge, "expandedNodes": seen.len()},+        "crossesPours": crosses, "avoidPours": args["avoidPours"].clone(), "pourCost": pour_cost, "revision": revision,+        "_hint": if crosses.is_empty() { "A plan only: pass routeNet to route_net unchanged (with expectedRevision: revision). A layer change is two waypoints at the same point, where route_net places a via. Pours (and a hatched pour's net-less pieces) are not obstacles: repour after placing the route. The path is orthogonal on the grid: a finer gridMm finds tighter paths and searches longer." }+                 else { "A plan only: pass routeNet to route_net unchanged (with expectedRevision: revision). The route runs through the pours in crossesPours: after the repour, check that none of those nets split in two (routing_state's splitNets), or plan again keeping out of them: avoidPours: true (or a list of the nets whose pours to keep out of), or pourCost: 2 to prefer going round them where a way exists. A layer change is two waypoints at the same point, where route_net places a via." }}) }  #[cfg(test)]@@ -339,4 +385,49 @@ mod tests {         assert_eq!(given["routeNet"]["width"], json!(0.4));         assert_eq!(plan_route(&json!({"board": board(json!([])), "args": {"net": "SIG", "from": "U1.1", "to": "J1.1"}}))["planner"]["widthFrom"], "default 0.25");     }+    #[test]+    fn a_through_via_clears_every_copper_layer_not_only_the_planned_ones() {+        // a wall on F.Cu forces two vias to In1.Cu; a GND track on B.Cu along y 5 is on no planned layer, but every via+        // passes through B.Cu (fusion-lane #21)+        let t = json!([{"net": "GND", "layer": "F.Cu", "width": 0.5, "start": {"x": 10.0, "y": 0.0}, "end": {"x": 10.0, "y": 10.0}},+                       {"net": "GND", "layer": "B.Cu", "width": 0.5, "start": {"x": 1.0, "y": 5.0}, "end": {"x": 19.0, "y": 5.0}}]);+        let r = plan_route(&json!({"board": board(t), "args": {"net": "SIG", "from": "U1.1", "to": "J1.1", "layers": ["F.Cu", "In1.Cu"]}}));+        assert_eq!(r["found"], json!(true), "{r}");+        assert_eq!(r["vias"], 2);+        for v in r["viaAt"].as_array().unwrap() { assert!((f(&v[1]) - 5.0).abs() >= 0.25 + 0.3 + 0.2 - 1e-9, "{v}"); }+        assert!(r["planner"]["viasCheckedOn"].as_array().unwrap().contains(&json!("B.Cu")));+    }++    #[test]+    fn the_strictest_board_wide_clearance_rule_decides() {+        let rules = json!([{"kind": "clearance", "name": "wire-wire", "clearanceMm": 0.1}, {"kind": "clearance", "name": "pad-via", "clearanceMm": 0.15},+                           {"name": "Clearance HV", "scope1": "InNet('HV')", "scope2": "All", "descriptor": "Clearance Constraint (Gap=0.5mm) (InNet('HV')),(All)"}]);+        let r = plan_route(&json!({"board": board(json!([])), "rules": rules, "args": {"net": "SIG", "from": "U1.1", "to": "J1.1"}}));+        assert_eq!(r["planner"]["clearanceMm"], json!(0.15), "{r}");+        // fab_check still compares the smallest with a fab's limits+        assert_eq!(crate::fab::min_clearance(rules.as_array().unwrap()), Some(0.1));+    }++    #[test]+    fn a_route_names_the_pours_it_crosses_or_keeps_out_of_them() {+        let mut b = board(json!([]));+        b["polygons"] = json!([{"net": "GND", "layer": "F.Cu", "points": [[8.0, 0.0], [12.0, 0.0], [12.0, 10.0], [8.0, 10.0]]}]);+        let r = plan_route(&json!({"board": b, "args": {"net": "SIG", "from": "U1.1", "to": "J1.1"}}));+        assert_eq!((r["vias"].as_u64(), r["crossesPours"].clone()), (Some(0), json!([{"net": "GND", "layer": "F.Cu"}])), "{r}");+        let around = plan_route(&json!({"board": b, "args": {"net": "SIG", "from": "U1.1", "to": "J1.1", "avoidPours": true}}));+        assert_eq!((around["vias"].as_u64(), around["crossesPours"].clone()), (Some(2), json!([])), "{around}");+        // by net: avoiding another net's pours only leaves this one crossable+        assert_eq!(plan_route(&json!({"board": b, "args": {"net": "SIG", "from": "U1.1", "to": "J1.1", "avoidPours": ["VBAT"]}}))["vias"], json!(0));+        assert_eq!(plan_route(&json!({"board": b, "args": {"net": "SIG", "from": "U1.1", "to": "J1.1", "avoidPours": ["gnd"]}}))["vias"], json!(2));+        // a pour over the whole board: a hard block finds no path, a cost still routes (across it)+        let mut all = board(json!([]));+        all["polygons"] = json!([{"net": "GND", "layer": "F.Cu", "points": [[0.0, 0.0], [20.0, 0.0], [20.0, 10.0], [0.0, 10.0]]}, {"net": "GND", "layer": "B.Cu", "points": [[0.0, 0.0], [20.0, 0.0], [20.0, 10.0], [0.0, 10.0]]}]);+        assert_eq!(plan_route(&json!({"board": all, "args": {"net": "SIG", "from": "U1.1", "to": "J1.1", "avoidPours": true}}))["found"], json!(false));+        assert_eq!(plan_route(&json!({"board": all, "args": {"net": "SIG", "from": "U1.1", "to": "J1.1", "pourCost": 2.0}}))["found"], json!(true));+        // and with the cost a short way round a narrow pour beats crossing it+        let mut strip = board(json!([]));+        strip["polygons"] = json!([{"net": "GND", "layer": "F.Cu", "points": [[9.0, 2.0], [11.0, 2.0], [11.0, 10.0], [9.0, 10.0]]}]);+        let soft = plan_route(&json!({"board": strip, "args": {"net": "SIG", "from": "U1.1", "to": "J1.1", "pourCost": 10.0, "allowVias": false}}));+        assert_eq!(soft["crossesPours"], json!([]), "{soft}");+    } }
dev-skills/altium-bridge-test/run_verb_tests.py+5
@@ -224,6 +224,11 @@ def matrix(w):     M["add_rule"] = dict(phase=3.5, **ok(kind="clearance", name="Battery", scope1="InNet('N1')", gap=0.3))     M["move_parts"] = dict(phase=3.5, **ok(parts=[{"ref": "U2", "x": 29, "y": 10, "rotation": 0}], expectPath=LB))     # 0.2.80: the standard's planner (#21) finds N1 across the lane board; a plan changes nothing+    # 0.2.80: the standard's decoupling planner (#22); the lane board's SOICs have no caps, so a named refusal or an empty plan+    M["place_decoupling"] = dict(phase=3.5, timeout=300, **anyo("U1 on the lane board: no caps, an empty plan", ic="U1", filePath=LB))+    M["plan_fanout"] = dict(phase=3.5, timeout=300, **anyo("U1 (SOIC-8) on the lane board: a perimeter plan", ref="U1", filePath=LB))+    M["estimate_cost"] = dict(phase=3.5, timeout=200, **ok(filePath=LB, quantities=[5, 30]),+                              check=lambda d: abs(((d.get("board") or {}).get("widthMm") or 0) - 40) < 0.5 and d.get("prices") is None)     M["plan_route"] = dict(phase=3.5, timeout=300, **ok(net="N1", **{"from": "U1.8", "to": "U2.1"}, gridMm=0.25),                            check=lambda d: d.get("found") is True and (d.get("routeNet") or {}).get("net") == "N1" and (d.get("lengthMm") or 0) > 10)     M["route_net"] = dict(phase=3.5, **ok(net="N1", width=0.25, paths=[[{"pad": "U1.8"}, {"pad": "U2.1"}]], expectPath=LB))
package.json+6−1
@@ -249,7 +249,12 @@     "route a net between two pads in altium",     "find a path for a trace in altium",     "plan a route in altium",-    "route one net in altium"+    "route one net in altium",+    "place decoupling caps in altium",+    "fan out a bga in altium",+    "escape routing for a qfn in altium",+    "estimate pcb cost from altium",+    "how much will this altium board cost"   ],   "discovery_pitch": "An AI that runs Altium Designer in the user's own session: libraries, schematics, Update PCB, stack-up, routing, DRC, Gerbers and BOMs.",   "sample_prompts": [
page.json+6−1
@@ -241,7 +241,12 @@     "route a net between two pads in altium",     "find a path for a trace in altium",     "plan a route in altium",-    "route one net in altium"+    "route one net in altium",+    "place decoupling caps in altium",+    "fan out a bga in altium",+    "escape routing for a qfn in altium",+    "estimate pcb cost from altium",+    "how much will this altium board cost"   ],   "discovery_pitch": "An AI that runs Altium Designer in the user's own session: libraries, schematics, Update PCB, stack-up, routing, DRC, Gerbers and BOMs.",   "metadata": {},
skills/altium-boards/SKILL.md+26−2
@@ -6,8 +6,8 @@ description: >-   readback, 3D heights and clearance, impedance, current capacity, copper balance, return paths, fab limits, panels   with V-score or mouse bites. Use when asked for an altium stack-up, net class, mounting holes, a 50 or 90 ohm trace   width, will a trace carry 3 A, does it fit the enclosure, copper balance, return path, place the designators, a-  via fence, route a differential pair, route one net between two pads, find a path for a net, tune a length, thermal-  vias, check the placement, or panelize a board.+  via fence, route a differential pair, route one net between two pads, find a path for a net, place decoupling caps, fan out+  a BGA or QFN, estimate the board's cost, tune a length, thermal vias, check the placement, or panelize a board. ---  Parent skill: **altium-bridge**@@ -195,6 +195,30 @@ altium_plan_route '{"net":"N1","from":"U1.8","to":"U2.1","gridMm":0.25,"apply":t   this grid and clearance, or the search bound `maxNodes`). - Use it for the nets the autorouter leaves, or one net at a time where you want to see each route before the next. +## Decoupling, fanout and cost (0.2.80)++```bash+altium_place_decoupling '{"ic":"U4"}'               # a plan: each cap beside the power pin it serves+altium_place_decoupling '{"ic":"U4","apply":true}'  # move them (one undo step)+altium_plan_fanout '{"ref":"U3"}'                   # a BGA's or QFN/QFP's escape as route_net calls+altium_estimate_cost '{"quantities":[5,30]}'        # the numbers a fab quote needs+```++- **place_decoupling** (the standard's shared planner) puts each cap just outside the IC (`gapMm`, 0.3), power pad+  facing its pin, sliding along the side when the spot is taken, and leaves room for the IC's fanout (`leaveFanout`).+  `leftOut` names the caps it skipped and why: a crystal's load cap or a filter (`signal_net`), or a cap nearer another+  IC on the same supply (`nearer_another_ic`); name them in `caps` to place them anyway. `validation` is placement_check+  on the moved board. The tracks to the caps' old spots stay: rip up and route again (`altium_plan_route`), then repour.+  Measured on the Bluetooth Sentinel: U4's six VBAT caps placed and moved, validation clean.+- **plan_fanout**: stubs, dogbone vias, an exposed pad's via grid, as route_net calls. Pins already routed are skipped+  (`includeRouted` overrides), each via and stub is measured against other nets' pads, tracks, arcs and vias+  (`conflicts`), and the exposed-pad grid steps round holes already there. `apply:true` routes every call as one undo+  step and refuses while a conflict is listed. Then `altium_repour` (a hatched pour's pieces re-pour round the new+  copper) and `altium_routing_drc`.+- **estimate_cost**: size, layers, thickness, smallest track, gap and drill, holes, parts and joints. No rates are built+  in: pass a price record read from the fab's page (`prices`, with its date) for a price table.+- **check_clearance** answers from the same engine: pads by their real outline, parts as pads plus 3D bodies.+ ## Board setup: stack-up, net classes, pairs, widths (0.2.60)  ```bash
src/agent/AdomAgent.pas.tmpl+67−17
@@ -6027,6 +6027,27 @@ Begin     If Prim.Net <> Nil Then Result := '"' + JsonEsc(Prim.Net.Name) + '"'; End; +{ A polygon's outline vertices for the board model: [x,y,0] for a line segment, [x,y,1,cx,cy,r,a1*1000,a2*1000] for an+  arc segment, as the board outline sends them. Only the vertices went before, so a round pour came back as 3 or 4+  corners (the Bluetooth Sentinel's GND pours, 2026-10-28). }+Function PolySegPts(Poly : IPCB_Polygon) : String;+Var+    Seg : TPolySegment;+    K   : Integer;+Begin+    Result := '';+    For K := 0 To Poly.PointCount - 1 Do+    Begin+        Seg := Poly.Segments[K];+        If K > 0 Then Result := Result + ',';+        If Seg.Kind = ePolySegmentArc Then+            Result := Result + '[' + IntToStr(Seg.vx) + ',' + IntToStr(Seg.vy) + ',1,' + IntToStr(Seg.cx) + ',' + IntToStr(Seg.cy) + ',' ++                IntToStr(Seg.Radius) + ',' + IntToStr(Round(Seg.Angle1 * 1000)) + ',' + IntToStr(Round(Seg.Angle2 * 1000)) + ']'+        Else+            Result := Result + '[' + IntToStr(Seg.vx) + ',' + IntToStr(Seg.vy) + ',0]';+    End;+End;+ Function CmdRoutingState(Lines : TStringList) : String; Var     Board : IPCB_Board;@@ -6107,14 +6128,7 @@ Begin         Else If Prim.ObjectId = ePolyObject Then         Begin             Poly := Prim;-            Pts := '';-            For K := 0 To Poly.PointCount - 1 Do-            Begin-                Seg := Poly.Segments[K];-                If K > 0 Then Pts := Pts + ',';-                Pts := Pts + '[' + IntToStr(Seg.vx) + ',' + IntToStr(Seg.vy) + ']';-            End;-            LG.Add('[' + NetOf(Poly) + ',' + IntToStr(Poly.Layer) + ',[' + Pts + ']]');+            LG.Add('[' + NetOf(Poly) + ',' + IntToStr(Poly.Layer) + ',[' + PolySegPts(Poly) + ']]');         End         Else If Prim.ObjectId = eConnectionObject Then             Unrouted := Unrouted + 1;@@ -6811,6 +6825,39 @@ Begin     Result := '[' + S + ']'; End; +{ rebuild_pours: rebuild every polygon on the current board through the API. Altium's own Repour All (the helper's+  PCB:ChangeObject RepourAllPolygons) left the Bluetooth Sentinel's hatched GND pours as they were, shorting new stubs,+  where Rebuild cleared them (2026-10-28). Scoped pour rules match nothing in here, so altium_repour uses it only when the+  helper's repour changed no pour. }+Function CmdRebuildPours(Lines : TStringList) : String;+Var+    Board : IPCB_Board;+    BIt   : IPCB_BoardIterator;+    Poly  : IPCB_Polygon;+    N     : Integer;+Begin+    Board := PCBServer.GetCurrentPCBBoard;+    If Board = Nil Then Begin Result := '{' + JRaw('ok','false') + ',' + JStr('error','no current PCB board (open a .PcbDoc first)') + '}'; Exit; End;+    N := 0;+    BIt := Board.BoardIterator_Create;+    BIt.AddFilter_ObjectSet(MkSet(ePolyObject));+    BIt.AddFilter_LayerSet(AllLayers);+    BIt.AddFilter_Method(eProcessAll);+    Poly := BIt.FirstPCBObject;+    While Poly <> Nil Do+    Begin+        PCBServer.PreProcess;+        Poly.Rebuild;+        Poly.GraphicallyInvalidate;+        PCBServer.PostProcess;+        N := N + 1;+        Poly := BIt.NextPCBObject;+    End;+    Board.BoardIterator_Destroy(BIt);+    Board.ViewManager_FullUpdate;+    Result := '{' + JRaw('ok','true') + ',' + JRaw('rebuilt', IntToStr(N)) + '}';+End;+ Function CmdPourState(Lines : TStringList) : String; Var     Board : IPCB_Board;@@ -6822,7 +6869,7 @@ Var     Seg   : TPolySegment;     LG    : TStringList;     Outl, Fills, Holes : String;-    K, H : Integer;+    K, H, Pieces : Integer; Begin     Board := PCBServer.GetCurrentPCBBoard;     If Board = Nil Then Begin Result := '{' + JRaw('ok','false') + ',' + JStr('error','no current PCB board (open a .PcbDoc first)') + '}'; Exit; End;@@ -6834,13 +6881,7 @@ Begin     Poly := BIt.FirstPCBObject;     While Poly <> Nil Do     Begin-        Outl := '';-        For K := 0 To Poly.PointCount - 1 Do-        Begin-            Seg := Poly.Segments[K];-            If K > 0 Then Outl := Outl + ',';-            Outl := Outl + '[' + IntToStr(Seg.vx) + ',' + IntToStr(Seg.vy) + ']';-        End;+        Outl := PolySegPts(Poly);         Fills := '';         GIt := Poly.GroupIterator_Create;         GIt.AddFilter_ObjectSet(MkSet(eRegionObject));@@ -6860,7 +6901,15 @@ Begin             Prim := GIt.NextPCBObject;         End;         Poly.GroupIterator_Destroy(GIt);-        LG.Add('[' + NetOf(Poly) + ',' + IntToStr(Poly.Layer) + ',' + IntToStr(Poly.PourIndex) + ',[' + Outl + '],[' + Fills + '],"' + JsonEsc(Poly.Name) + '"]');+        { a hatched pour is poured as tracks and arcs, not regions: count them, or it reads as unfilled }+        Pieces := 0;+        GIt := Poly.GroupIterator_Create;+        GIt.AddFilter_ObjectSet(MkSet(eTrackObject, eArcObject));+        GIt.AddFilter_LayerSet(AllLayers);+        Prim := GIt.FirstPCBObject;+        While Prim <> Nil Do Begin Pieces := Pieces + 1; Prim := GIt.NextPCBObject; End;+        Poly.GroupIterator_Destroy(GIt);+        LG.Add('[' + NetOf(Poly) + ',' + IntToStr(Poly.Layer) + ',' + IntToStr(Poly.PourIndex) + ',[' + Outl + '],[' + Fills + '],"' + JsonEsc(Poly.Name) + '",' + IntToStr(Pieces) + ']');         Poly := BIt.NextPCBObject;     End;     Board.BoardIterator_Destroy(BIt);@@ -9982,6 +10031,7 @@ Begin     Else If Cmd = 'edit_board' Then Result := CmdEditBoard(Lines, Payload)     Else If Cmd = 'apply_pours' Then Result := CmdApplyPours(Lines, Payload)     Else If Cmd = 'pour_state' Then Result := CmdPourState(Lines)+    Else If Cmd = 'rebuild_pours' Then Result := CmdRebuildPours(Lines)     Else If Cmd = 'remove_pours' Then Result := CmdRemovePours(Lines, Payload)     Else If Cmd = 'routing_drc' Then Result := CmdRoutingDrc(Lines)     Else If Cmd = 'build_board' Then Result := CmdBuildBoard(Lines, Payload)
src/bridge.json+4−1
@@ -191,6 +191,9 @@     "altium_ripup_nets",     "altium_route_net",     "altium_plan_route",+    "altium_place_decoupling",+    "altium_plan_fanout",+    "altium_estimate_cost",     "altium_route_pair",     "altium_routing_drc",     "altium_routing_state",@@ -284,7 +287,7 @@       "launch": 240,       "panelize": 240,       "impedance": 120,-      "current_capacity": 120, "plan_route": 300,+      "current_capacity": 120, "plan_route": 300, "place_decoupling": 300, "plan_fanout": 300, "estimate_cost": 120,       "height_check": 150,       "copper_balance": 240,       "return_path": 240,