by adom
Let an AI (Claude, ChatGPT, Codex or any agent) run Altium Designer for you: create symbols and footprints, place parts (also from Altium 365), wire and annotate schematics, Update PCB, set the stack-up and rules, route, pour copper, add mounting holes and stitching vias, run ERC and DRC, and make Gerbers, BOMs and STEP. Free in Hydrogen; bring your own AI and Altium licence.
← Commit history
0.2.76 source, continued (still unreleased): board edits from the standard's batch 3 (remove_parts, edit_parts, align_parts, set_layer_count, copy_routing, check_clearance, remove_graphics); the agent lint refuses duplicate routine names; 230 verbs
11 files changed
+748−15
CHANGELOG.md+9@@ -24,6 +24,15 @@ stream; flat names made them overwrite each other) and reads Altium's binary pin records. - `fixtures/`: the lane and pair boards with the bridge's saved replies and expected check results, for the EDA Bridge Standard's shared checks engine (`ADOM_EDA_FIXTURES`).+- **Board edits** (7 new verbs, the standard's batch 3): `remove_parts` (locked parts refused unless allowLocked),+ `edit_parts` (designator, value, lock, BOM exclusion; DNP, mount and fields answer not_supported with where Altium+ keeps them), `align_parts` (edges, centres or even spacing, refusing overlaps and parts off the board, applied+ through move_parts), `set_layer_count` (2/4/6/8, board thickness kept, layers carrying copper refused),+ `copy_routing` (tracks and through vias in a box, nets remapped by part pairs; a copy that adds DRC errors is+ taken back out), `check_clearance` (part boxes or pads, closest first), `remove_graphics` (board-level lines,+ arcs, texts, rectangles, regions and dimensions by id, or by layer and kind).+- `scripts/release.py`: the agent lint refuses two routines of one name (DelphiScript ignores case; a duplicate+ halted the engine at compile with "Identifier redeclared"). - `altium_bodies` (new): every part's 3D bodies as boxes in mm, the standard's bodies model (`{ref, side, x0, y0, x1, y1, z0, z1}`), plus the parts with no body. The data `height_check` already read, now its own verb, so the shared checks engine and other tools can read it.
README.md+11−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 -223 commands, tested on Altium Designer 26.11 and Altium Designer Develop. It runs in **Hydrogen**, Adom's free+230 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. 223 verbs; each row names the ones+Tested on Altium Designer 26.11.1 and Altium Designer Develop. 230 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 223 `altium_*` verbs.+**DelphiScript agent** inside it, and gives the AI 230 `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 223 verbs, by area (prefix `altium_`). `altium_describe` returns the live catalog with every input, output, hint and example.+All 230 verbs, by area (prefix `altium_`). `altium_describe` returns the live catalog with every input, output, hint and example. ### Running Altium: launch, close, health, dialogs @@ -245,6 +245,13 @@ All 223 verbs, by area (prefix `altium_`). `altium_describe` returns the live ca - `altium_routing_state`: The WHOLE current board as data, in mm: tracks, arcs, vias, pads (with owner and net), components (ref, x, y, rotation, side), polygon pours, the outline, the unrouted (ratsnest) count, and a revision hash. - `altium_route_net`: Route one net as tracks, segment by segment; a waypoint on another layer drops a via there. - `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_remove_parts`: Remove placed parts from the board by designator, as one undo step.+- `altium_edit_parts`: Edit placed parts: value, designator, any field (add, change, remove), do-not-populate, exclusion from the BOM or position files, mounting type and the lock.+- `altium_align_parts`: Line parts up on a common left, right, top, bottom or centre line, or space them evenly, by courtyard box or by anchor point.+- `altium_set_layer_count`: Set the board's copper layer count (2, 4, 6 or 8): the layer table and the stack-up, keeping the board thickness.+- `altium_copy_routing`: Copy the tracks and vias inside a box to an offset, remapping nets by pairing parts (a designator map or pattern), so a repeated channel gets the same routing.+- `altium_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.+- `altium_remove_graphics`: Remove board graphics (lines, rectangles, circles, arcs, polygons, texts, dimensions) by id, or every one on a layer and of a kind. - `altium_place_vias`: Place vias (through, top to bottom). - `altium_board_features`: Add the furniture every real board needs in one undo step: mounting holes (at points or the four corners), fiducials, keepout areas, and a stitching-via grid on a net that keeps clear of every other net's copper, every pad and the board edge. - `altium_sch_sheet_symbol`: Make a design hierarchical: a sheet symbol on the parent sheet for a child sheet, its entries joined to the parent's nets, and matching ports on the child.
bridge-rs/src/boardedit.rsadded+501@@ -0,0 +1,501 @@+//! Board edits from the EDA Bridge Standard's batch 3 (proposed by kicad-lane): remove, edit and align parts, set the+//! copper layer count, copy a channel's routing, measure part clearances and remove board graphics. Millimetres, the+//! board frame, KiCad layer names; every edit takes expectedRevision and dryRun and answers the board's new revision.+use crate::placement::part_boxes;+use crate::routing::{self, apply, guarded, layer_id, layer_name, raw, PER_MM, BOTTOM, TOP};+use crate::sch::{agent_data, clean, st as sv};+use crate::agent;+use serde_json::{json, Value};+use std::collections::{BTreeMap, BTreeSet};+use std::time::Duration;++type Rect = (f64, f64, f64, f64);++fn r3(v: f64) -> f64 { (v * 1000.0).round() / 1000.0 }+fn f(v: &Value) -> f64 { v.as_f64().unwrap_or(0.0) }+fn bad(msg: impl Into<String>) -> Value { json!({"success": false, "errorCode": "bad_args", "error": msg.into()}) }+fn dry(args: &Value) -> bool { args.get("dryRun").and_then(|v| v.as_bool()) == Some(true) }+fn refs_of(v: Option<&Value>) -> Vec<String> { v.and_then(|x| x.as_array()).map(|a| a.iter().map(sv).filter(|s| !s.is_empty()).collect()).unwrap_or_default() }++fn open_board(args: &Value) -> Option<Value> {+ if let Some(g) = crate::support::need_licensed() { return Some(g); }+ crate::support::s(args, "filePath").and_then(|p| crate::support::must_open(&p, 60))+}++// -- remove_parts ---------------------------------------------------------------------------------------------------------++/// altium_remove_parts {refs, allowLocked?, expectedRevision?, dryRun?}+pub fn remove_parts(args: &Value) -> Value {+ if let Some(e) = open_board(args) { return e; }+ let refs = refs_of(args.get("refs"));+ if refs.is_empty() { return bad("refs: [\"R7\", ...] is required"); }+ let st = match guarded(args) { Ok(s) => s, Err(e) => return e };+ let have: BTreeSet<String> = st["components"].as_array().cloned().unwrap_or_default().iter().filter_map(|c| c["ref"].as_str().map(|s| s.to_uppercase())).collect();+ let missing: Vec<&String> = refs.iter().filter(|r| !have.contains(&r.to_uppercase())).collect();+ if !missing.is_empty() { return json!({"success": false, "errorCode": "part_not_found", "error": format!("not on the board: {missing:?}")}); }+ let nets_of = |r: &str| -> Vec<String> { let mut n: Vec<String> = st["pads"].as_array().cloned().unwrap_or_default().iter().filter(|p| p["ref"].as_str().map(|x| x.eq_ignore_ascii_case(r)).unwrap_or(false)).map(|p| st_net(p)).filter(|n| !n.is_empty()).collect(); n.sort(); n.dedup(); n };+ if dry(args) { return json!({"success": true, "dryRun": true, "removed": refs.iter().map(|r| json!({"ref": r, "nets": nets_of(r)})).collect::<Vec<_>>(), "revision": st["revision"]}); }+ let allow = if args.get("allowLocked").and_then(|v| v.as_bool()) == Some(true) { "1" } else { "0" };+ let ops: Vec<String> = refs.iter().map(|r| format!("R|{}|{allow}", clean(r))).collect();+ let mut out = apply(&ops, &st, "remove_parts");+ let res = out["results"].as_array().cloned().unwrap_or_default();+ let (mut removed, mut failed) = (vec![], vec![]);+ for (r, x) in refs.iter().zip(res.iter()) {+ let s = st_str(x);+ match s.strip_prefix("ok:") {+ Some(n) => removed.push(json!({"ref": r, "nets": n.split(';').filter(|x| !x.is_empty()).collect::<Vec<_>>()})),+ None => failed.push(json!({"ref": r, "error": if s.contains("part_locked") { "part_locked: pass allowLocked:true".to_string() } else { s.trim_start_matches("err:").to_string() }})),+ }+ }+ if !failed.is_empty() { out["success"] = json!(false); out["errorCode"] = json!(if failed.iter().any(|f| f["error"].as_str().map(|e| e.starts_with("part_locked")).unwrap_or(false)) { "part_locked" } else { "some_not_removed" }); }+ out["removed"] = json!(removed); out["failedParts"] = json!(failed);+ out.as_object_mut().map(|o| o.remove("state"));+ out["_hint"] = json!("Tracks and vias that met the pads stay: altium_routing_state shows them (unconnected and splitNets). A part still on the schematic comes back at the next altium_update_pcb.");+ out+}++fn st_net(p: &Value) -> String { p["net"].as_str().unwrap_or("").to_string() }+fn st_str(v: &Value) -> String { v.as_str().unwrap_or("").to_string() }++// -- edit_parts -----------------------------------------------------------------------------------------------------------++/// altium_edit_parts {edits:[{ref, value?, newRef?, locked?, excludeFromBom?, ...}], expectedRevision?, dryRun?}+pub fn edit_parts(args: &Value) -> Value {+ if let Some(e) = open_board(args) { return e; }+ let Some(edits) = args.get("edits").and_then(|v| v.as_array()).filter(|a| !a.is_empty()) else { return bad("edits: [{ref, value?, newRef?, locked?, excludeFromBom?}] is required") };+ let st = match guarded(args) { Ok(s) => s, Err(e) => return e };+ let have: BTreeSet<String> = st["components"].as_array().cloned().unwrap_or_default().iter().filter_map(|c| c["ref"].as_str().map(|s| s.to_uppercase())).collect();+ let mut ops = Vec::new();+ let mut owner = Vec::new();+ let mut failed = Vec::new();+ for e in edits {+ let r = st_str(&e["ref"]);+ if !have.contains(&r.to_uppercase()) { failed.push(json!({"ref": r, "error": "part_not_found"})); continue; }+ // what Altium keeps elsewhere: do-not-populate is a variant, mounting comes from the footprint, parameters from the schematic+ for (k, why) in [("dnp", "do-not-populate is an assembly variant in Altium: altium_variants"), ("excludeFromPos", "Altium has no per-part pick-and-place exclusion on the board"),+ ("mount", "the mounting type comes from the footprint's pads in Altium"), ("fields", "a placed part's parameters come from the schematic in Altium: altium_sheet_params")] {+ if e.get(k).is_some() { failed.push(json!({"ref": r, "field": k, "error": format!("not_supported: {why}")})); }+ }+ if let Some(n) = e.get("newRef").and_then(|v| v.as_str()) {+ if have.contains(&n.to_uppercase()) && !n.eq_ignore_ascii_case(&r) { failed.push(json!({"ref": r, "error": format!("designator_taken: {n} is on the board")})); continue; }+ ops.push(format!("E|{}|designator|{}", clean(&r), clean(n)));+ owner.push(r.clone());+ }+ let cur = e.get("newRef").and_then(|v| v.as_str()).unwrap_or(&r).to_string();+ if let Some(v) = e.get("value").and_then(|v| v.as_str()) { ops.push(format!("E|{}|comment|{}", clean(&cur), clean(v))); owner.push(r.clone()); }+ if let Some(b) = e.get("locked").and_then(|v| v.as_bool()) { ops.push(format!("E|{}|locked|{}", clean(&cur), if b { 1 } else { 0 })); owner.push(r.clone()); }+ // Altium's component kinds: 0 Standard, 5 Standard (no BOM)+ if let Some(b) = e.get("excludeFromBom").and_then(|v| v.as_bool()) { ops.push(format!("E|{}|kind|{}", clean(&cur), if b { 5 } else { 0 })); owner.push(r.clone()); }+ }+ if ops.is_empty() { return json!({"success": false, "errorCode": "nothing_to_do", "error": "no edit Altium can make on the board", "failed": failed}); }+ if dry(args) { return json!({"success": true, "dryRun": true, "steps": ops.len(), "failed": failed, "revision": st["revision"]}); }+ let mut out = apply(&ops, &st, "edit_parts");+ let res = out["results"].as_array().cloned().unwrap_or_default();+ let mut after: BTreeMap<String, Value> = BTreeMap::new();+ for (r, x) in owner.iter().zip(res.iter()) {+ let s = st_str(x);+ if s.starts_with("err") { failed.push(json!({"ref": r, "error": s.trim_start_matches("err:")})); continue; }+ let p: Vec<&str> = s.trim_start_matches("ok:").split('|').collect();+ after.insert(r.clone(), json!({"ref": p.first(), "value": p.get(1), "locked": p.get(2).map(|x| *x == "true"), "excludeFromBom": p.get(3).map(|x| *x == "5" || *x == "4")}));+ }+ out["edited"] = json!(after.into_iter().map(|(r, a)| json!({"ref": r, "after": a})).collect::<Vec<_>>());+ if !failed.is_empty() { out["success"] = json!(false); out["errorCode"] = json!("some_not_applied"); }+ out["failed"] = json!(failed);+ out.as_object_mut().map(|o| o.remove("state"));+ out["_hint"] = json!("Designators and values the schematic owns come back at the next altium_update_pcb: change them on the sheet too (altium_sch_edit). excludeFromBom sets Altium's component kind Standard (no BOM).");+ out+}++// -- align_parts ----------------------------------------------------------------------------------------------------------++/// Where each part's anchor goes so its box (or anchor) lines up. Pure.+pub fn align_plan(parts: &[(String, f64, f64, Rect)], mode: &str, to: Option<f64>, gap: Option<f64>, by_anchor: bool) -> Result<Vec<(String, f64, f64)>, String> {+ if parts.len() < 2 { return Err("align needs at least two parts".into()); }+ let left = |p: &(String, f64, f64, Rect)| if by_anchor { p.1 } else { p.3 .0 };+ let right = |p: &(String, f64, f64, Rect)| if by_anchor { p.1 } else { p.3 .2 };+ let bottom = |p: &(String, f64, f64, Rect)| if by_anchor { p.2 } else { p.3 .1 };+ let top = |p: &(String, f64, f64, Rect)| if by_anchor { p.2 } else { p.3 .3 };+ let cx = |p: &(String, f64, f64, Rect)| if by_anchor { p.1 } else { (p.3 .0 + p.3 .2) / 2.0 };+ let cy = |p: &(String, f64, f64, Rect)| if by_anchor { p.2 } else { (p.3 .1 + p.3 .3) / 2.0 };+ let n = parts.len() as f64;+ let out: Vec<(String, f64, f64)> = match mode {+ "left" => { let t = to.unwrap_or_else(|| parts.iter().map(left).fold(f64::MAX, f64::min)); parts.iter().map(|p| (p.0.clone(), p.1 + t - left(p), p.2)).collect() }+ "right" => { let t = to.unwrap_or_else(|| parts.iter().map(right).fold(f64::MIN, f64::max)); parts.iter().map(|p| (p.0.clone(), p.1 + t - right(p), p.2)).collect() }+ "bottom" => { let t = to.unwrap_or_else(|| parts.iter().map(bottom).fold(f64::MAX, f64::min)); parts.iter().map(|p| (p.0.clone(), p.1, p.2 + t - bottom(p))).collect() }+ "top" => { let t = to.unwrap_or_else(|| parts.iter().map(top).fold(f64::MIN, f64::max)); parts.iter().map(|p| (p.0.clone(), p.1, p.2 + t - top(p))).collect() }+ "centerX" => { let t = to.unwrap_or_else(|| parts.iter().map(cx).sum::<f64>() / n); parts.iter().map(|p| (p.0.clone(), p.1 + t - cx(p), p.2)).collect() }+ "centerY" => { let t = to.unwrap_or_else(|| parts.iter().map(cy).sum::<f64>() / n); parts.iter().map(|p| (p.0.clone(), p.1, p.2 + t - cy(p))).collect() }+ "distributeX" | "distributeY" => {+ let xax = mode == "distributeX";+ let mut v: Vec<&(String, f64, f64, Rect)> = parts.iter().collect();+ v.sort_by(|a, b| (if xax { cx(a) } else { cy(a) }).partial_cmp(&(if xax { cx(b) } else { cy(b) })).unwrap());+ let (first, last) = (if xax { cx(v[0]) } else { cy(v[0]) }, if xax { cx(v[v.len() - 1]) } else { cy(v[v.len() - 1]) });+ let step = gap.unwrap_or((last - first) / (v.len() - 1) as f64);+ v.iter().enumerate().map(|(i, p)| { let t = first + step * i as f64; if xax { (p.0.clone(), p.1 + t - cx(p), p.2) } else { (p.0.clone(), p.1, p.2 + t - cy(p)) } }).collect()+ }+ o => return Err(format!("mode {o}: left, right, top, bottom, centerX, centerY, distributeX or distributeY")),+ };+ Ok(out.into_iter().map(|(r, x, y)| (r, r3(x), r3(y))).collect())+}++fn hit(a: Rect, b: Rect) -> bool { a.0 < b.2 && b.0 < a.2 && a.1 < b.3 && b.1 < a.3 }++fn in_poly(p: (f64, f64), poly: &[(f64, f64)]) -> bool {+ let mut inside = false;+ let n = poly.len();+ for k in 0..n { let (a, b) = (poly[k], poly[(k + n - 1) % n]); if (a.1 > p.1) != (b.1 > p.1) && p.0 < (b.0 - a.0) * (p.1 - a.1) / (b.1 - a.1) + a.0 { inside = !inside; } }+ inside+}++/// altium_align_parts {refs, mode, by?, to?, gapMm?, allowOverlap?, allowOutside?, expectedRevision?, dryRun?}+pub fn align_parts(args: &Value) -> Value {+ if let Some(e) = open_board(args) { return e; }+ let refs = refs_of(args.get("refs"));+ let Some(mode) = args.get("mode").and_then(|v| v.as_str()) else { return bad("mode is required: left, right, top, bottom, centerX, centerY, distributeX, distributeY") };+ let st = match guarded(args) { Ok(s) => s, Err(e) => return e };+ let boxes = part_boxes(&st, &BTreeMap::new());+ let mut parts = Vec::new();+ for r in &refs {+ let Some(c) = st["components"].as_array().and_then(|a| a.iter().find(|c| c["ref"].as_str().map(|x| x.eq_ignore_ascii_case(r)).unwrap_or(false))) else { return json!({"success": false, "errorCode": "part_not_found", "error": format!("{r} is not on the board")}) };+ let b = boxes.get(st_str(&c["ref"]).as_str()).map(|x| x.1).unwrap_or((f(&c["x"]), f(&c["y"]), f(&c["x"]), f(&c["y"])));+ parts.push((st_str(&c["ref"]), f(&c["x"]), f(&c["y"]), b));+ }+ let by_anchor = args.get("by").and_then(|v| v.as_str()) == Some("anchor");+ let plan = match align_plan(&parts, mode, args.get("to").and_then(|v| v.as_f64()), args.get("gapMm").and_then(|v| v.as_f64()), by_anchor) { Ok(p) => p, Err(e) => return bad(e) };+ // the checks move_parts would make: no courtyard overlap with another part, inside the outline+ let moved: BTreeMap<&str, Rect> = plan.iter().zip(parts.iter()).map(|((r, x, y), p)| (r.as_str(), (p.3 .0 + x - p.1, p.3 .1 + y - p.2, p.3 .2 + x - p.1, p.3 .3 + y - p.2))).collect();+ let mut problems = Vec::new();+ if args.get("allowOverlap").and_then(|v| v.as_bool()) != Some(true) {+ for (r, b) in &moved {+ let side = boxes.get(*r).map(|x| x.0).unwrap_or(false);+ for (o, (os, ob)) in &boxes {+ if o.as_str() == *r || *os != side { continue; }+ let ob = moved.get(o.as_str()).copied().unwrap_or(*ob);+ if hit(*b, ob) && r < &o.as_str() || (hit(*b, ob) && !moved.contains_key(o.as_str())) { problems.push(json!({"ref": r, "problem": "overlap", "with": o})); }+ }+ }+ }+ let ring: Vec<(f64, f64)> = st["outline"].as_array().cloned().unwrap_or_default().iter().map(|p| (f(&p[0]), f(&p[1]))).collect();+ if args.get("allowOutside").and_then(|v| v.as_bool()) != Some(true) && ring.len() >= 3 {+ for (r, b) in &moved { if [(b.0, b.1), (b.2, b.1), (b.2, b.3), (b.0, b.3)].iter().any(|p| !in_poly(*p, &ring)) { problems.push(json!({"ref": r, "problem": "outside_board"})); } }+ }+ let targets: Vec<Value> = plan.iter().map(|(r, x, y)| json!({"ref": r, "x": x, "y": y})).collect();+ if !problems.is_empty() { return json!({"success": false, "errorCode": "align_blocked", "error": "the aligned parts would overlap or leave the board", "problems": problems, "targets": targets, "_hint": "Pass allowOverlap or allowOutside to align anyway, or choose another line (to)."}); }+ if dry(args) { return json!({"success": true, "dryRun": true, "targets": targets, "revision": st["revision"]}); }+ let mut out = routing::move_parts(&json!({"parts": targets, "expectedRevision": st["revision"]}));+ out["targets"] = json!(targets);+ out.as_object_mut().map(|o| o.remove("state"));+ out+}++// -- set_layer_count ---------------------------------------------------------------------------------------------------------++/// altium_set_layer_count {count: 2|4|6|8, expectedRevision?, dryRun?}+pub fn set_layer_count(args: &Value) -> Value {+ if let Some(e) = open_board(args) { return e; }+ let Some(count) = args.get("count").and_then(|v| v.as_i64()).filter(|c| [2, 4, 6, 8].contains(c)) else { return bad("count: 2, 4, 6 or 8") };+ let st = match guarded(args) { Ok(s) => s, Err(e) => return e };+ let stack = match agent_data(&agent::call("layer_stack", &[], None, Duration::from_secs(60))) { Ok(d) => d, Err(e) => return e };+ let layers = stack["layers"].as_array().cloned().unwrap_or_default();+ let inner: Vec<&Value> = layers.iter().filter(|l| l["mid"].as_i64().is_some() || l["plane"].as_i64().is_some()).collect();+ let now = inner.len() as i64 + 2;+ let total_mm = stack["totalUm"].as_f64().map(|u| u / 1000.0);+ let mut edit = json!({});+ if count > now {+ edit["add"] = json!((0..(count - now)).map(|_| json!({"kind": "signal"})).collect::<Vec<_>>());+ } else if count < now {+ // remove inner layers from the bottom of the stack up, refusing any that carries copper+ let used = layers_with_copper(&st);+ let drop: Vec<&&Value> = inner.iter().rev().take((now - count) as usize).collect();+ let busy: Vec<String> = drop.iter().filter_map(|l| { let n = copper_names(&[json!({}), (**l).clone(), json!({})])[1].clone(); if used.contains(&n) { Some(format!("{} ({n})", st_str(&l["name"]))) } else { None } }).collect();+ if !busy.is_empty() { return json!({"success": false, "errorCode": "layer_in_use", "error": format!("these layers still carry copper: {busy:?}"), "_hint": "Clear them first (altium_layers_in_use shows what is on each)."}); }+ edit["remove"] = json!(drop.iter().map(|l| json!({"name": l["name"]})).collect::<Vec<_>>());+ } else {+ return json!({"success": true, "changed": false, "layers": copper_names(&layers), "stackup": stack, "revision": st["revision"]});+ }+ if let Some(t) = total_mm { edit["totalMm"] = json!(t); }+ if dry(args) { return json!({"success": true, "dryRun": true, "from": now, "to": count, "plan": edit, "revision": st["revision"]}); }+ let r = crate::design::layer_stack_edit(&edit);+ if r.get("success").and_then(|b| b.as_bool()) != Some(true) { return r; }+ let after = routing::routing_state(&json!({}));+ json!({"success": true, "changed": true, "from": now, "to": count, "layers": copper_names(r["layers"].as_array().map(|v| v.as_slice()).unwrap_or(&[])), "stackup": {"layers": r["layers"], "totalUm": r["totalUm"]},+ "revision": after["revision"], "_hint": "New inner layers are signal layers with even dielectrics keeping the board's thickness: re-check an impedance-controlled stack-up with altium_layer_stack. Rules and classes are unchanged; altium_save keeps it."})+}++/// The stack's copper layers by the board model's names, top to bottom: F.Cu, the inner layers, B.Cu. Altium names a+/// mid layer by its number (In<n>.Cu) and an internal plane by its layer id (L<38+n>) in the board model.+fn copper_names(layers: &[Value]) -> Vec<String> {+ let n = layers.len();+ layers.iter().enumerate().map(|(i, l)| {+ if let Some(m) = l["mid"].as_i64() { format!("In{m}.Cu") } else if let Some(p) = l["plane"].as_i64() { format!("L{}", 38 + p) }+ else if i == 0 { "F.Cu".into() } else if i + 1 == n { "B.Cu".into() } else { st_str(&l["name"]) }+ }).collect()+}++/// The copper layers the board model shows copper on (tracks, arcs, pads on one layer, pours).+fn layers_with_copper(st: &Value) -> BTreeSet<String> {+ let mut s = BTreeSet::new();+ for k in ["tracks", "arcs", "pads", "polygons"] { for x in st[k].as_array().cloned().unwrap_or_default() { s.insert(st_str(&x["layer"])); } }+ s+}++// -- copy_routing ---------------------------------------------------------------------------------------------------------++/// The net each source net becomes, by pairing parts: a pad's net maps to its partner pad's net. Pure.+pub fn net_map(pads: &[Value], pairs: &[(String, String)]) -> Result<BTreeMap<String, String>, Vec<String>> {+ let key = |r: &str, n: &str| format!("{}.{}", r.to_uppercase(), n.to_uppercase());+ let net_at: BTreeMap<String, String> = pads.iter().filter_map(|p| Some((key(p["ref"].as_str()?, p["name"].as_str()?), st_net(p)))).collect();+ let mut m: BTreeMap<String, String> = BTreeMap::new();+ let mut conflicts = Vec::new();+ for (a, b) in pairs {+ for p in pads.iter().filter(|p| p["ref"].as_str().map(|x| x.eq_ignore_ascii_case(a)).unwrap_or(false)) {+ let (from, Some(to)) = (st_net(p), net_at.get(&key(b, p["name"].as_str().unwrap_or("")))) else { continue };+ if from.is_empty() || to.is_empty() { continue; }+ match m.get(&from) { Some(t) if t != to => conflicts.push(format!("{from} -> {t} and {to}")), _ => { m.insert(from, to.clone()); } }+ }+ }+ if conflicts.is_empty() { Ok(m) } else { Err(conflicts) }+}++fn glob(pat: &str, s: &str) -> Option<String> {+ // one * matches any run; returns what it matched+ let (pre, post) = pat.split_once('*')?;+ let u = s.to_uppercase();+ if u.starts_with(&pre.to_uppercase()) && u.ends_with(&post.to_uppercase()) && u.len() >= pre.len() + post.len() { Some(s[pre.len()..s.len() - post.len()].to_string()) } else { None }+}++/// altium_copy_routing {box, offset, refMap? | refPattern?, netMap?, keepUnmappedNets?, layers?, validate?, expectedRevision?, dryRun?}+pub fn copy_routing(args: &Value) -> Value {+ if let Some(e) = open_board(args) { return e; }+ let bx: Vec<f64> = args.get("box").and_then(|v| v.as_array()).map(|a| a.iter().filter_map(|x| x.as_f64()).collect()).unwrap_or_default();+ let off: Vec<f64> = args.get("offset").and_then(|v| v.as_array()).map(|a| a.iter().filter_map(|x| x.as_f64()).collect()).unwrap_or_default();+ if bx.len() != 4 || off.len() != 2 { return bad("box: [x1, y1, x2, y2] and offset: [dx, dy] mm are required"); }+ let (x0, x1, y0, y1) = (bx[0].min(bx[2]), bx[0].max(bx[2]), bx[1].min(bx[3]), bx[1].max(bx[3]));+ let inside = |x: f64, y: f64| x >= x0 && x <= x1 && y >= y0 && y <= y1;+ let st = match guarded(args) { Ok(s) => s, Err(e) => return e };+ let comps: Vec<String> = st["components"].as_array().cloned().unwrap_or_default().iter().map(|c| st_str(&c["ref"])).collect();+ let mut pairs: Vec<(String, String)> = args.get("refMap").and_then(|v| v.as_object()).map(|o| o.iter().map(|(a, b)| (a.clone(), sv(b))).collect()).unwrap_or_default();+ if let Some(p) = args.get("refPattern") {+ let (from, to) = (st_str(&p["from"]), st_str(&p["to"]));+ for c in &comps { if let Some(m) = glob(&from, c) { let t = to.replacen('*', &m, 1); if comps.iter().any(|x| x.eq_ignore_ascii_case(&t)) { pairs.push((c.clone(), t)); } } }+ }+ let mut map = match net_map(st["pads"].as_array().map(|v| v.as_slice()).unwrap_or(&[]), &pairs) {+ Ok(m) => m,+ Err(c) => return json!({"success": false, "errorCode": "net_map_conflict", "error": "a source net maps to two target nets", "conflicts": c, "_hint": "Settle each with netMap {source: target}."}),+ };+ if let Some(o) = args.get("netMap").and_then(|v| v.as_object()) { for (a, b) in o { map.insert(a.clone(), sv(b)); } }+ let keep = args.get("keepUnmappedNets").and_then(|v| v.as_bool()) == Some(true);+ let only: Option<Vec<String>> = args.get("layers").and_then(|v| v.as_array()).map(|a| a.iter().map(sv).collect());+ let (dx, dy) = (off[0], off[1]);+ let mut ops = Vec::new();+ let mut skipped = Vec::new();+ let (mut nt, mut nv) = (0, 0);+ let target = |net: &str| -> Option<String> { if net.is_empty() { return Some(String::new()); } map.get(net).cloned().or(if keep { Some(net.to_string()) } else { None }) };+ for t in st["tracks"].as_array().cloned().unwrap_or_default() {+ let (a, b) = (&t["start"], &t["end"]);+ if !(inside(f(&a["x"]), f(&a["y"])) && inside(f(&b["x"]), f(&b["y"]))) { continue; }+ let layer = st_str(&t["layer"]);+ if let Some(o) = &only { if !o.contains(&layer) { continue; } }+ let Some(lid) = layer_id(&t["layerId"]).or_else(|| layer_id(&t["layer"])) else { continue };+ match target(&st_net(&t)) {+ Some(n) => { ops.push(format!("T|{}|{}|{}|{}|{}|{lid}|{}", raw(f(&a["x"]) + dx), raw(f(&a["y"]) + dy), raw(f(&b["x"]) + dx), raw(f(&b["y"]) + dy), raw(f(&t["width"])), clean(&n))); nt += 1; }+ None => skipped.push(json!({"item": "track", "net": st_net(&t), "why": "net not mapped (pass refMap, netMap or keepUnmappedNets)"})),+ }+ }+ for v in st["vias"].as_array().cloned().unwrap_or_default() {+ let p = &v["position"];+ if !inside(f(&p["x"]), f(&p["y"])) { continue; }+ let ls: Vec<String> = v["layers"].as_array().map(|a| a.iter().map(sv).collect()).unwrap_or_default();+ if ls != ["F.Cu", "B.Cu"] { skipped.push(json!({"item": "via", "at": [f(&p["x"]), f(&p["y"])], "why": "blind or buried: only through vias are copied"})); continue; }+ match target(&st_net(&v)) {+ Some(n) => { ops.push(format!("V|{}|{}|{}|{}|{TOP}|{BOTTOM}|{}", raw(f(&p["x"]) + dx), raw(f(&p["y"]) + dy), raw(f(&v["size"])), raw(f(&v["drill"])), clean(&n))); nv += 1; }+ None => skipped.push(json!({"item": "via", "net": st_net(&v), "why": "net not mapped"})),+ }+ }+ for a in st["arcs"].as_array().cloned().unwrap_or_default() {+ if inside(f(&a["center"]["x"]), f(&a["center"]["y"])) { skipped.push(json!({"item": "arc", "why": "arcs are not copied yet"})); }+ }+ let copied = json!({"tracks": nt, "vias": nv});+ if ops.is_empty() { return json!({"success": false, "errorCode": "nothing_to_do", "error": "no track or via of a mapped net inside the box", "netMap": map, "skipped": skipped}); }+ if dry(args) { return json!({"success": true, "dryRun": true, "copied": copied, "netMap": map, "skipped": skipped, "revision": st["revision"]}); }+ let validate = args.get("validate").and_then(|v| v.as_bool()) != Some(false);+ let errs_before = if validate { routing::routing_drc(&json!({}))["errors"].as_i64() } else { None };+ let mut out = apply(&ops, &st, "copy_routing");+ out.as_object_mut().map(|o| o.remove("state"));+ out["copied"] = copied; out["netMap"] = json!(map); out["skipped"] = json!(skipped);+ if validate {+ let after = routing::routing_drc(&json!({}));+ let new = after["errors"].as_i64().zip(errs_before).map(|(a, b)| a - b);+ out["drc"] = json!({"ran": true, "before": errs_before, "after": after["errors"], "newErrors": new});+ if new.unwrap_or(0) > 0 {+ // take the copy back out: the same tracks and vias, by their exact coordinates+ let undo: Vec<String> = ops.iter().filter_map(|o| { let p: Vec<&str> = o.split('|').collect(); match p[0] {+ "T" => Some(format!("D|T|{}|{}|{}|{}|{}", p[1], p[2], p[3], p[4], p[6])), "V" => Some(format!("D|V|{}|{}", p[1], p[2])), _ => None } }).collect();+ let st2 = routing::routing_state(&json!({}));+ let _ = apply(&undo, &st2, "copy_routing undo");+ out["success"] = json!(false); out["errorCode"] = json!("drc_errors"); out["rolledBack"] = json!(true);+ out["error"] = json!(format!("the copy added {} DRC errors and was taken back out", new.unwrap_or(0)));+ out["revision"] = routing::routing_state(&json!({}))["revision"].clone();+ out["violations"] = after["violations"].clone();+ }+ }+ out["_hint"] = json!("The copy connects where the target parts sit at the same offset (place them first: altium_replicate_layout). Check netMap; altium_routing_drc shows what the copy did.");+ out+}++// -- 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?}+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."})+}++// -- remove_graphics ---------------------------------------------------------------------------------------------------------++/// A board graphic from its agent key (kind:layer:numbers[:text]): id, kind, layer and points in mm. Pure.+pub fn graphic(key: &str) -> Value {+ let mut it = key.splitn(4, ':');+ let (kind, layer, nums, text) = (it.next().unwrap_or(""), it.next().unwrap_or("0").parse::<i64>().unwrap_or(0), it.next().unwrap_or(""), it.next());+ let n: Vec<f64> = nums.split(',').filter_map(|x| x.parse::<f64>().ok()).collect();+ let mm = |v: f64| r3(v / PER_MM);+ let pts: Vec<Value> = match kind {+ "line" | "rect" | "polygon" | "dimension" if n.len() >= 4 => vec![json!([mm(n[0]), mm(n[1])]), json!([mm(n[2]), mm(n[3])])],+ "arc" if n.len() >= 3 => vec![json!([mm(n[0]), mm(n[1])])],+ "text" if n.len() >= 2 => vec![json!([mm(n[0]), mm(n[1])])],+ _ => vec![],+ };+ let mut v = json!({"id": format!("{kind}-{}", &crate::routing::fnv(key)[..10]), "kind": kind, "layer": layer_name(layer), "layerId": layer, "points": pts});+ if kind == "arc" && n.len() >= 5 { v["radius"] = json!(mm(n[2])); v["startAngle"] = json!(n[3] / 1000.0); v["endAngle"] = json!(n[4] / 1000.0); }+ if let Some(t) = text { v["text"] = json!(t); }+ v+}++/// altium_remove_graphics {ids? | layer? + kinds?, expectedRevision?, dryRun?}+pub fn remove_graphics(args: &Value) -> Value {+ if let Some(e) = open_board(args) { return e; }+ let st = match guarded(args) { Ok(s) => s, Err(e) => return e };+ let g = match agent_data(&agent::call("board_graphics", &[], None, Duration::from_secs(120))) { Ok(d) => d, Err(e) => return e };+ let all: Vec<(String, Value)> = g["graphics"].as_array().cloned().unwrap_or_default().iter().map(|k| { let k = st_str(k); let v = graphic(&k); (k, v) }).collect();+ let ids = refs_of(args.get("ids"));+ let layer = args.get("layer").and_then(|v| v.as_str()).map(str::to_string);+ let kinds: Option<Vec<String>> = args.get("kinds").and_then(|v| v.as_array()).map(|a| a.iter().map(sv).collect());+ if ids.is_empty() && layer.is_none() && kinds.is_none() {+ return json!({"success": true, "graphics": all.iter().map(|(_, v)| v.clone()).collect::<Vec<_>>(), "count": all.len(),+ "_hint": "Listed only: pass ids, or layer and kinds, to remove (dry-run a filter first)."});+ }+ let unknown: Vec<&String> = ids.iter().filter(|i| !all.iter().any(|(_, v)| v["id"] == json!(i))).collect();+ if !unknown.is_empty() { return json!({"success": false, "errorCode": "unknown_ids", "error": format!("no board graphic {unknown:?}"), "_hint": "Call with no filter to list the graphics and their ids."}); }+ let layer_match = |v: &Value| layer.as_ref().map(|l| v["layer"] == json!(l) || layer_id(&json!(l)).map(|id| v["layerId"] == json!(id)).unwrap_or(false)).unwrap_or(true);+ let picked: Vec<&(String, Value)> = all.iter().filter(|(_, v)| if !ids.is_empty() { ids.iter().any(|i| v["id"] == json!(i)) } else { layer_match(v) && kinds.as_ref().map(|k| k.iter().any(|x| v["kind"] == json!(x))).unwrap_or(true) }).collect();+ let removed: Vec<Value> = picked.iter().map(|(_, v)| v.clone()).collect();+ if picked.is_empty() { return json!({"success": false, "errorCode": "nothing_to_do", "error": "no graphic matches"}); }+ if dry(args) { return json!({"success": true, "dryRun": true, "removed": removed, "revision": st["revision"]}); }+ let ops: Vec<String> = picked.iter().map(|(k, _)| format!("G|{}", k.replace('|', " "))).collect();+ let mut out = apply(&ops, &st, "remove_graphics");+ out.as_object_mut().map(|o| o.remove("state"));+ out["removed"] = json!(removed);+ out["_hint"] = json!("Board-level graphics only (not in a part, not on a net). Removing the outline layer's lines removes the board shape.");+ out+}++#[cfg(test)]+mod tests {+ use super::*;++ fn p(r: &str, x: f64, y: f64, w: f64, h: f64) -> (String, f64, f64, Rect) { (r.into(), x, y, (x - w / 2.0, y - h / 2.0, x + w / 2.0, y + h / 2.0)) }++ #[test]+ fn align_lines_up_edges_and_spreads_evenly() {+ let parts = vec![p("C1", 10.0, 5.0, 2.0, 1.0), p("C2", 14.0, 7.0, 4.0, 1.0), p("C3", 30.0, 6.0, 2.0, 1.0)];+ let l = align_plan(&parts, "left", None, None, false).unwrap();+ assert_eq!(l, vec![("C1".into(), 10.0, 5.0), ("C2".into(), 11.0, 7.0), ("C3".into(), 10.0, 6.0)]);+ let b = align_plan(&parts, "bottom", None, None, false).unwrap();+ assert!(b.iter().all(|(_, _, y)| (*y - 5.0).abs() < 1e-9));+ let d = align_plan(&parts, "distributeX", None, None, true).unwrap();+ assert_eq!(d.iter().map(|x| x.1).collect::<Vec<_>>(), vec![10.0, 20.0, 30.0]);+ }++ #[test]+ fn nets_map_through_paired_parts_and_conflicts_are_refused() {+ let pad = |r: &str, n: &str, net: &str| json!({"ref": r, "name": n, "net": net});+ let pads = vec![pad("U1", "1", "A1"), pad("U1", "2", "B1"), pad("U2", "1", "A2"), pad("U2", "2", "B2")];+ let m = net_map(&pads, &[("U1".into(), "U2".into())]).unwrap();+ assert_eq!(m.get("A1"), Some(&"A2".to_string()));+ let pads2 = vec![pad("U1", "1", "A1"), pad("U1", "2", "A1"), pad("U2", "1", "A2"), pad("U2", "2", "B2")];+ assert!(net_map(&pads2, &[("U1".into(), "U2".into())]).is_err());+ 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));+ let g = graphic(&k);+ assert_eq!(g["kind"], "line");+ assert_eq!(g["points"], json!([[1.0, 2.0], [11.0, 2.0]]));+ assert_eq!(g["layer"], "L57");+ assert!(g["id"].as_str().unwrap().starts_with("line-"));+ }+}
bridge-rs/src/main.rs+1@@ -14,6 +14,7 @@ mod schdoc; mod schreview; mod schwire; mod schsheet;+mod boardedit; mod design; mod dialogs; mod health;
bridge-rs/src/verbs.rs+36−1@@ -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", "move_parts", "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", "move_parts", "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",@@ -728,6 +728,34 @@ fn describe() -> Value { json!({"sheet": "path to the schematic sheet file (required)", "width": "int px, default 2000", "outputDir": "folder for the image (default beside the project)", "baseline": "set|compare", "threshold": "percent of pixels, default 0.5 (compare)", "drawingSheet": "bool, default true: include the frame and title block"}), json!({"png": "path", "width": "int", "height": "int", "driftPercent": "number (compare)", "pass": "bool (compare)", "changedRegionMm": "[x1, y1, x2, y2] (compare)", "diffPng": "path: the changed pixels in red (compare)", "rendererChanged": "bool: the tool's plotter changed since the baseline"}), 400, "A sub-sheet renders with its real designators. compare renders at the baseline's width and passes when driftPercent <= threshold. show_* verbs open a window; this one does not.", &["export_pdf", "show_schematic"], &["Anti-aliasing differs between tool versions: rendererChanged:true means drift may not be a design change.", "A baseline is per sheet and per width; a paper size change reads as 100 percent drift.", "Altium prints the sheet to PDF (through its project when one beside it lists the sheet) and Windows renders it.", "Altium's print now and then leaves the title block's special strings (=Title, sheet numbers) unfilled; a failed comparison prints once more and keeps the closer image (reprinted:true), so drift confined to the title block is usually that."], json!({"sheet": "C:/proj/Power.SchDoc", "baseline": "compare"})),+ verb_doc("remove_parts", "Remove placed parts from the board by designator, as one undo step. The library is not touched (that is remove_footprint).",+ 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", "refs": "[\"R7\", \"R8\"] (required)", "allowLocked": "bool, default false", "dryRun": "bool, default false: answer the plan and change nothing"}),+ json!({"removed": "[{ref, nets: [string]}]", "failed": "[{ref, error}]", "revision": "string: the board's new revision"}), 300,+ "Each removed part lists the nets its pads carried. A locked part is refused (part_locked) unless allowLocked:true.", &["routing_state", "move_parts"], &["Tracks and vias that met the pads stay: routing_state shows what is left dangling.", "A part still in the schematic comes back at the next update_pcb.", "Altium's lock is the part's Moveable flag."], json!({"filePath": "C:/proj/Board.PcbDoc", "refs": ["TP3"], "expectedRevision": "<rev>"})),+ verb_doc("edit_parts", "Edit placed parts: value, designator, any field (add, change, remove), do-not-populate, exclusion from the BOM or position files, mounting type and the lock. 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", "edits": "[{ref, value?, newRef?, fields?: {name: value | null (remove)}, dnp?: bool, excludeFromBom?: bool, excludeFromPos?: bool, mount?: smd|through_hole|other, locked?: bool}] (required)", "dryRun": "bool, default false: answer the plan and change nothing"}),+ json!({"edited": "[{ref, before, after}]", "failed": "[{ref, error}]", "revision": "string: the board's new revision"}), 300,+ "Fields the tool requires (designator, value) cannot be removed. Read the parts first with component_data.", &["routing_state", "move_parts"], &["Board-side edits of what the schematic owns are lost at the next update_pcb: change the schematic instead (sch_edit).", "A designator already taken is refused.", "On Altium the board edits designator, value (comment), the lock and BOM exclusion (component kind Standard (no BOM)); do-not-populate is a variant (altium_variants), mounting comes from the footprint and parameters from the schematic: those answer not_supported per field."], json!({"filePath": "C:/proj/Board.PcbDoc", "edits": [{"ref": "R7", "value": "4k7", "dnp": true}], "expectedRevision": "<rev>"})),+ verb_doc("align_parts", "Line parts up on a common left, right, top, bottom or centre line, or space them evenly, by courtyard box or by anchor point. One undo step, with move_parts' checks.",+ 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", "refs": "[\"C1\", \"C2\", \"C3\"] (required)", "mode": "left|right|top|bottom|centerX|centerY|distributeX|distributeY (required)", "by": "courtyard|anchor, default courtyard", "to": "mm: the line to align on (default from the group)", "gapMm": "number: the spacing for distribute (default even spacing between the outer two)", "allowOverlap": "bool, default false", "allowOutside": "bool, default false", "dryRun": "bool, default false: answer the plan and change nothing"}),+ json!({"targets": "[{ref, x, y}]", "mismatches": "[{ref, asked, got}]", "revision": "string: the board's new revision"}), 300,+ "Without to, left takes the group's smallest x, right the largest, top the highest edge and bottom the lowest (y up); centre lines take the mean. distribute keeps the outer two in place.", &["routing_state", "move_parts"], &["Rotation and side are kept: align parts of the same orientation for a clean row.", "A courtyard collision or a part off the board is refused, as in move_parts.", "Altium courtyards are not read: the part box is its pads' extent."], json!({"filePath": "C:/proj/Board.PcbDoc", "refs": ["C4", "C5", "C6"], "mode": "top", "expectedRevision": "<rev>"})),+ verb_doc("set_layer_count", "Set the board's copper layer count (2, 4, 6 or 8): the layer table and the stack-up, keeping the board thickness.",+ json!({"filePath": "path to the board file (default: the board open in the tool)", "count": "2|4|6|8 (required)", "expectedRevision": "string: the revision you last read (routing_state); refused with stale_board if the board changed", "dryRun": "bool, default false: answer the plan and change nothing"}),+ json!({"layers": "[string]: the copper layers now", "stackup": "the new stack-up, as layer_stack answers it", "revision": "string: the board's new revision"}), 300,+ "New inner layers are signal layers In1.Cu ... Read the result with layer_stack.", &["routing_state", "move_parts"], &["A layer being removed that still carries copper or graphics is refused (layers_in_use, with the counts per layer).", "New dielectrics are generic: re-check an impedance-controlled stack-up with layer_stack.", "Net classes and design rules are not changed.", "Altium adds inner signal layers (Mid-Layers) and removes inner layers from the bottom up; the board thickness is kept by spreading the dielectrics evenly."], json!({"filePath": "C:/proj/Board.PcbDoc", "count": 4})),+ verb_doc("copy_routing", "Copy the tracks and vias inside a box to an offset, remapping nets by pairing parts (a designator map or pattern), so a repeated channel gets the same routing. 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", "box": "[x1, y1, x2, y2] mm (required): the source", "offset": "[dx, dy] mm (required)", "refMap": "{\"U1\": \"U5\"}: pair parts, so each pad's net maps to the partner pad's net", "refPattern": "{from: \"CH1_*\", to: \"CH2_*\"}: pair parts by designator pattern", "netMap": "{\"SIG\": \"SIG2\"}: overrides", "keepUnmappedNets": "bool, default false", "layers": "[layer]: copy only these", "validate": "bool, default true: run the tool's DRC on the result before committing", "dryRun": "bool, default false: answer the plan and change nothing"}),+ json!({"copied": "{tracks: int, vias: int}", "netMap": "{from: to}: the pairing used", "skipped": "[{item, why}]", "drc": "{ran, newErrors}", "revision": "string: the board's new revision"}), 300,+ "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})),+ 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,+ "Board-level graphics only; graphics inside parts are footprint_primitives. An unknown id refuses the whole call (unknown_ids).", &["routing_state", "move_parts"], &["Removing Edge.Cuts graphics removes the board outline.", "A layer or kind filter without ids removes every match: dry-run it first.", "With no ids, layer or kinds it only lists the board graphics with their ids (Altium items have none: an id is a hash of kind, layer and geometry)."], json!({"filePath": "C:/proj/Board.PcbDoc", "layer": "Dwgs.User", "dryRun": true})), verb_doc("sch_connect", "Connect pins of placed parts: a wire stub from each pin's outer end plus a net label (kind label), a power port (kind power: GND-like nets get a ground symbol) or the stub alone (kind wire); or mark a pin left open on purpose with a No ERC marker (kind noerc, no net). One undo step.", json!({"sheet": "path to the .SchDoc (required)", "connections": "[{designator, pin (number or name), net, kind: label|power|wire|noerc|port (default label), io?: input|output|bidirectional (port), stubMil (default 200)}] (required)", "save": "bool, default true"}), json!({"connected": "int", "results": "[{designator, pin, net, kind, result, endMil}]", "failed": "[..]", "saved": "bool"}), 90,@@ -1883,6 +1911,13 @@ pub fn dispatch(command: &str, args: &Value, _forwarded: &[(String, String)]) -> "sheet_params" => crate::bom::sheet_params(args), "sch_place_part" => crate::sch::place_part(args), "sch_connect" => crate::sch::connect(args),+ "remove_parts" => crate::boardedit::remove_parts(args),+ "edit_parts" => crate::boardedit::edit_parts(args),+ "align_parts" => crate::boardedit::align_parts(args),+ "set_layer_count" => crate::boardedit::set_layer_count(args),+ "copy_routing" => crate::boardedit::copy_routing(args),+ "check_clearance" => crate::boardedit::check_clearance(args),+ "remove_graphics" => crate::boardedit::remove_graphics(args), "render_schematic" => crate::schsheet::render_schematic(args), "sch_page" => crate::schsheet::page(args), "sch_create" => crate::schsheet::create(args),
package.json+6−1@@ -215,7 +215,12 @@ "create a new schematic sheet in altium", "altium sheet hierarchy page numbers", "render an altium schematic to an image",- "update altium symbols from library"+ "update altium symbols from library",+ "remove a part from the altium board",+ "align parts in altium",+ "change altium board layer count to 4",+ "copy routing to another channel in altium",+ "altium part clearance check" ], "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@@ -207,7 +207,12 @@ "create a new schematic sheet in altium", "altium sheet hierarchy page numbers", "render an altium schematic to an image",- "update altium symbols from library"+ "update altium symbols from library",+ "remove a part from the altium board",+ "align parts in altium",+ "change altium board layer count to 4",+ "copy routing to another channel in altium",+ "altium part clearance check" ], "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": {},
scripts/release.py+8@@ -200,6 +200,14 @@ def lint_agent_script(): body = re.sub(r"Function AdomFloat\(.*?^End;|Function AdomInt\(.*?^End;", "", code, flags=re.S | re.M) for m in re.finditer(r"(?<![A-Za-z_])(StrToFloat|StrToInt)\(", body): hits.append(f"raw {m.group(1)}( outside AdomFloat/AdomInt -> ...{body[max(0, m.start() - 40):m.end() + 25].strip()}...")+ # Two routines of one name halt the engine at compile ("Identifier redeclared", 2026-10-27): DelphiScript+ # ignores case, so compare lower-cased+ seen = {}+ for m in re.finditer(r"^(?:Function|Procedure)\s+([A-Za-z_][A-Za-z0-9_]*)", code, flags=re.M):+ n = m.group(1).lower()+ if n in seen:+ hits.append(f"routine {m.group(1)} is declared twice (lines {seen[n]} and {code[:m.start()].count(chr(10)) + 1})")+ seen.setdefault(n, code[:m.start()].count(chr(10)) + 1) if hits: raise SystemExit("agent template uses engine-halting identifiers (see ENGINE_HALTING):\n " + "\n ".join(hits))
skills/altium-boards/SKILL.md+17@@ -400,6 +400,23 @@ altium_auto_classes '{"apply":true}' # GND / Power / - `auto_classes` proposes classes from net names (GND; Power: VCC, VDD, VBAT, VBUS, 3V3...; Clock; HighSpeed: USB, ETH, HDMI, PCIe, DDR, MIPI, LVDS, SATA...) and pairs from _P/_N, +/-, DP/DN; `apply` writes them, Power with a width rule. +## Board edits in the standard's words (0.2.76)++The EDA Bridge Standard's board verbs, the same on KiCad and Fusion: mm, KiCad layer names, `expectedRevision` and+`dryRun` on every edit.++| Job | Verb |+|---|---|+| Flip a part to the other side | `altium_move_parts {parts:[{ref, x, y, side:"bottom"}]}` or `flip:true` |+| Remove placed parts (a locked part needs allowLocked) | `altium_remove_parts {refs}` |+| Change designator, value, lock, BOM exclusion | `altium_edit_parts {edits:[{ref, newRef?, value?, locked?, excludeFromBom?}]}` |+| Line parts up or space them evenly | `altium_align_parts {refs, mode: left\|right\|top\|bottom\|centerX\|centerY\|distributeX\|distributeY}` |+| 2, 4, 6 or 8 copper layers, thickness kept | `altium_set_layer_count {count}` |+| Copy a channel's tracks and vias with nets remapped by part pairs | `altium_copy_routing {box, offset, refMap \| refPattern}` (a copy that adds DRC errors is taken back out) |+| Parts or pads closer than a gap | `altium_check_clearance {mode: courtyard\|pads, thresholdMm}` |+| List or remove board graphics (lines, arcs, text, rectangles, regions, dimensions) | `altium_remove_graphics` (no filter lists them with ids) |+| Every part's 3D bodies as boxes | `altium_bodies` |+ ## Lengths, length rules, rooms and teardrops (0.2.68) ```bash
src/agent/AdomAgent.pas.tmpl+138−7@@ -2611,15 +2611,15 @@ End; 1 and 49 (every pad named 49 listed), plus the track count and their nets. } Function CompNets(Comp : IPCB_Component) : String; Var- GIt : IPCB_GroupIterator;+ PadIt : IPCB_GroupIterator; Pad : IPCB_Pad; S, N : String; Begin S := '';- GIt := Comp.GroupIterator_Create;- GIt.AddFilter_ObjectSet(MkSet(ePadObject));- GIt.AddFilter_LayerSet(AllLayers);- Pad := GIt.FirstPCBObject;+ PadIt := Comp.GroupIterator_Create;+ PadIt.AddFilter_ObjectSet(MkSet(ePadObject));+ PadIt.AddFilter_LayerSet(AllLayers);+ Pad := PadIt.FirstPCBObject; While Pad <> Nil Do Begin If (Pad.Name = '1') Or (Pad.Name = '49') Then@@ -2629,9 +2629,9 @@ Begin If S <> '' Then S := S + ';'; S := S + Pad.Name + '=' + N; End;- Pad := GIt.NextPCBObject;+ Pad := PadIt.NextPCBObject; End;- Comp.GroupIterator_Destroy(GIt);+ Comp.GroupIterator_Destroy(PadIt); Result := S; End; @@ -6063,6 +6063,99 @@ Begin PCBServer.SendMessageToRobots(Board.I_ObjectAddress, c_Broadcast, PCBM_BoardRegisteration, Prim.I_ObjectAddress); End; +{ the nets a part's pads carry, ; separated }+Function PartNetList(Comp : IPCB_Component) : String;+Var+ GIt : IPCB_GroupIterator;+ Pd : IPCB_Pad;+Begin+ Result := '';+ GIt := Comp.GroupIterator_Create;+ GIt.AddFilter_ObjectSet(MkSet(ePadObject));+ Pd := GIt.FirstPCBObject;+ While Pd <> Nil Do+ Begin+ If Pd.Net <> Nil Then+ If Pos(';' + Pd.Net.Name + ';', ';' + Result + ';') = 0 Then+ Begin+ If Result <> '' Then Result := Result + ';';+ Result := Result + Pd.Net.Name;+ End;+ Pd := GIt.NextPCBObject;+ End;+ Comp.GroupIterator_Destroy(GIt);+End;++{ A board graphic's key: kind, layer and raw geometry (Altium gives free primitives no stable id). Board-level+ graphics only: not in a part, not on a net. }+Function GraphicKey(Prim : IPCB_Primitive) : String;+Begin+ Result := '';+ If Prim.ObjectId = eTrackObject Then Result := 'line:' + IntToStr(Prim.Layer) + ':' + IntToStr(Prim.X1) + ',' + IntToStr(Prim.Y1) + ',' + IntToStr(Prim.X2) + ',' + IntToStr(Prim.Y2) + ',' + IntToStr(Prim.Width)+ Else If Prim.ObjectId = eArcObject Then Result := 'arc:' + IntToStr(Prim.Layer) + ':' + IntToStr(Prim.XCenter) + ',' + IntToStr(Prim.YCenter) + ',' + IntToStr(Prim.Radius) + ',' + IntToStr(Round(Prim.StartAngle * 1000)) + ',' + IntToStr(Round(Prim.EndAngle * 1000)) + ',' + IntToStr(Prim.LineWidth)+ Else If Prim.ObjectId = eTextObject Then Result := 'text:' + IntToStr(Prim.Layer) + ':' + IntToStr(Prim.XLocation) + ',' + IntToStr(Prim.YLocation) + ':' + Prim.Text+ Else If Prim.ObjectId = eFillObject Then Result := 'rect:' + IntToStr(Prim.Layer) + ':' + IntToStr(Prim.X1Location) + ',' + IntToStr(Prim.Y1Location) + ',' + IntToStr(Prim.X2Location) + ',' + IntToStr(Prim.Y2Location)+ Else If Prim.ObjectId = eRegionObject Then Result := 'polygon:' + IntToStr(Prim.Layer) + ':' + IntToStr(Prim.BoundingRectangle.Left) + ',' + IntToStr(Prim.BoundingRectangle.Bottom) + ',' + IntToStr(Prim.BoundingRectangle.Right) + ',' + IntToStr(Prim.BoundingRectangle.Top)+ Else If Prim.ObjectId = eDimensionObject Then Result := 'dimension:' + IntToStr(Prim.Layer) + ':' + IntToStr(Prim.BoundingRectangle.Left) + ',' + IntToStr(Prim.BoundingRectangle.Bottom) + ',' + IntToStr(Prim.BoundingRectangle.Right) + ',' + IntToStr(Prim.BoundingRectangle.Top);+End;++Function IsBoardGraphic(Prim : IPCB_Primitive) : Boolean;+Begin+ Result := (Not Prim.InComponent) And (Prim.InPolygon = False);+ If Result And (Prim.ObjectId <> eTextObject) And (Prim.ObjectId <> eDimensionObject) Then+ Result := (Prim.Net = Nil) And (Not ((Prim.Layer >= eTopLayer) And (Prim.Layer <= eBottomLayer)));+End;++Function GraphicByKey(Board : IPCB_Board; Key : String) : IPCB_Primitive;+Var+ BIt : IPCB_BoardIterator;+ Prim : IPCB_Primitive;+Begin+ Result := Nil;+ BIt := Board.BoardIterator_Create;+ BIt.AddFilter_ObjectSet(MkSet(eTrackObject, eArcObject, eTextObject, eFillObject, eRegionObject, eDimensionObject));+ BIt.AddFilter_LayerSet(AllLayers);+ BIt.AddFilter_Method(eProcessAll);+ Prim := BIt.FirstPCBObject;+ While Prim <> Nil Do+ Begin+ If IsBoardGraphic(Prim) And (GraphicKey(Prim) = Key) Then Begin Result := Prim; Break; End;+ Prim := BIt.NextPCBObject;+ End;+ Board.BoardIterator_Destroy(BIt);+End;++{ board_graphics: every board-level graphic (lines, arcs, texts, rectangles, regions, dimensions not in a part and+ not on a net) with its key; raw units. }+Function CmdBoardGraphics(Lines : TStringList) : String;+Var+ Board : IPCB_Board;+ BIt : IPCB_BoardIterator;+ Prim : IPCB_Primitive;+ S : String;+Begin+ Board := PCBServer.GetCurrentPCBBoard;+ If Board = Nil Then Begin Result := '{' + JRaw('ok','false') + ',' + JStr('errorCode','no_current_board') + ',' + JStr('error','no current PCB board (open a .PcbDoc first)') + '}'; Exit; End;+ S := '';+ BIt := Board.BoardIterator_Create;+ BIt.AddFilter_ObjectSet(MkSet(eTrackObject, eArcObject, eTextObject, eFillObject, eRegionObject, eDimensionObject));+ BIt.AddFilter_LayerSet(AllLayers);+ BIt.AddFilter_Method(eProcessAll);+ Prim := BIt.FirstPCBObject;+ While Prim <> Nil Do+ Begin+ If IsBoardGraphic(Prim) Then+ Begin+ If S <> '' Then S := S + ',';+ S := S + '"' + JsonEsc(GraphicKey(Prim)) + '"';+ End;+ Prim := BIt.NextPCBObject;+ End;+ Board.BoardIterator_Destroy(BIt);+ Result := '{' + JRaw('ok','true') + ',' + JRaw('k', IntToStr(MilsToCoord(1000))) + ',' + JRaw('ox', IntToStr(Board.XOrigin)) + ',' + JRaw('oy', IntToStr(Board.YOrigin)) + ',' + JRaw('graphics', '[' + S + ']') + '}';+End;++ Function CmdEditBoard(Lines : TStringList; Payload : String) : String; Var Board : IPCB_Board;@@ -6209,6 +6302,43 @@ Begin If Prim = Nil Then Res := 'err:not found' Else Board.RemovePCBObject(Prim); End+ Else If Kind = 'R' Then+ Begin+ { R|ref|allowLocked(1/0): remove a placed part; the nets its pads carried answer as ok:NET1;NET2 }+ Comp := FindCompByDes(Board, FieldP(Op, 2));+ If Comp = Nil Then Res := 'err:no component ' + FieldP(Op, 2)+ Else If (Not Comp.Moveable) And (FieldP(Op, 3) <> '1') Then Res := 'err:part_locked'+ Else+ Begin+ Res := 'ok:' + PartNetList(Comp);+ Board.RemovePCBObject(Comp);+ End;+ End+ Else If Kind = 'E' Then+ Begin+ { E|ref|field|value: designator, comment (the value), locked (1/0), kind (an Altium TComponentKind) }+ Comp := FindCompByDes(Board, FieldP(Op, 2));+ If Comp = Nil Then Res := 'err:no component ' + FieldP(Op, 2)+ Else+ Begin+ Comp.BeginModify;+ If FieldP(Op, 3) = 'designator' Then Comp.Name.Text := FieldP(Op, 4)+ Else If FieldP(Op, 3) = 'comment' Then Comp.Comment.Text := FieldP(Op, 4)+ Else If FieldP(Op, 3) = 'locked' Then Comp.Moveable := FieldP(Op, 4) <> '1'+ Else If FieldP(Op, 3) = 'kind' Then Comp.ComponentKind := AdomInt(FieldP(Op, 4))+ Else Res := 'err:unknown field ' + FieldP(Op, 3);+ Comp.EndModify;+ Comp.GraphicallyInvalidate;+ Res := Res + ':' + Comp.Name.Text + '|' + Comp.Comment.Text + '|' + JBool(Not Comp.Moveable) + '|' + IntToStr(Comp.ComponentKind);+ End;+ End+ Else If Kind = 'G' Then+ Begin+ { G|key: delete the board graphic with that key (board_graphics) }+ Prim := GraphicByKey(Board, FieldP(Op, 2));+ If Prim = Nil Then Res := 'err:not found: the graphic changed since it was read'+ Else Board.RemovePCBObject(Prim);+ End Else If Kind = 'N' Then Begin N := 0;@@ -9162,6 +9292,7 @@ Begin Else If Cmd = 'sheet_params' Then Result := CmdSheetParams(Lines) Else If Cmd = 'sch_connect' Then Result := CmdSchConnect(Lines, Payload) Else If Cmd = 'sch_dump' Then Result := CmdSchDump(Lines)+ Else If Cmd = 'board_graphics' Then Result := CmdBoardGraphics(Lines) Else If Cmd = 'sch_ops' Then Result := CmdSchOps(Lines, Payload) Else If Cmd = 'sheet_symbol' Then Result := CmdSheetSymbol(Lines, Payload) Else If Cmd = 'sheet_ports' Then Result := CmdSheetPorts(Lines, Payload)
src/bridge.json+15−1@@ -41,6 +41,7 @@ "altium_agent_start", "altium_agent_status", "altium_agent_stop",+ "altium_align_parts", "altium_animate_view", "altium_annotate", "altium_apply_pours",@@ -59,6 +60,7 @@ "altium_build_footprint", "altium_build_schematic", "altium_build_symbol_modes",+ "altium_check_clearance", "altium_check_dialogs", "altium_check_orientation", "altium_cleanup_libs",@@ -74,6 +76,7 @@ "altium_copper_balance", "altium_copper_layers", "altium_copy_footprint",+ "altium_copy_routing", "altium_create_footprint", "altium_create_symbol", "altium_cross_check",@@ -85,6 +88,7 @@ "altium_diff_pairs", "altium_dismiss_dialogs", "altium_doc_params",+ "altium_edit_parts", "altium_ensure_licensed", "altium_eval", "altium_export_bom",@@ -151,7 +155,9 @@ "altium_read_symbol", "altium_readiness", "altium_remove_footprint",+ "altium_remove_graphics", "altium_remove_items",+ "altium_remove_parts", "altium_remove_pours", "altium_remove_symbol", "altium_rename_footprint",@@ -205,6 +211,7 @@ "altium_selection", "altium_selftest_script_error", "altium_set_design_rules",+ "altium_set_layer_count", "altium_set_layer_visibility", "altium_set_models", "altium_set_outline",@@ -419,7 +426,14 @@ "sch_sheet_pins": 320, "sch_reset_fields": 320, "sch_update_from_library": 320,- "render_schematic": 420+ "render_schematic": 420,+ "remove_parts": 320,+ "edit_parts": 320,+ "align_parts": 320,+ "set_layer_count": 320,+ "copy_routing": 320,+ "check_clearance": 320,+ "remove_graphics": 320 }, "prefixes": [ {