← Commit history
CHANGELOG.md+8
@@ -1,5 +1,13 @@ # Changelog +## 0.2.117++- **New verb `altium_sim_copy`: simulate a drawn design without touching it.** A schematic drawn for the board has no stimulus and no load, so it cannot simulate. `sim_copy` copies the project's sheets into `AdomSim\<project>` beside it and draws the sources and loads you name on the copy: voltage and current sources (DC, AC, sine, pulse, piecewise linear) and R, C, L loads, each joined to its nets (a net name, or `R1.2` for the net on a pin). It compiles the copy and reads the netlist back, so `checks` proves every pin landed on its net. Then `altium_simulate` runs the copy.+- Each source carries Altium's own built-in source model with the SPICE element as its netlist line, and the reply gives that line as Altium netlists it (`VVSIM1 IN 0 DC 0 AC 1 0`), so the same circuit runs in ngspice for a comparison.+- By default every R, C and L on the copy with no simulation model gets Altium's generic one, at its Value parameter or else its comment (`genericPassives`).+- **`altium_add_sim_model` attaches Altium's generic resistor, capacitor or inductor** (`"generic": "resistor"`), in the form its Simulation Generic Components library uses: no model file, and each placed part simulates at its own Value parameter. The reply's `value` says when the symbol has no Value parameter.+- Tested on Altium Designer 26.11.1 and on Develop with an RC low-pass drawn by `altium_build_schematic` (no models, no source). The AC run on the copy matched ngspice on the same netlist to every printed digit (-4.10552 dB at 2 kHz, -55.9636 dB at 1 MHz). A pulse transient on a second design, whose R and C took their generic models from the library, matched 1 - e^(-t/RC) to six digits.+ ## 0.2.116  - **`altium_export_3d` works in a fresh Altium.** It opened Altium's Parasolid or VRML exporter as the n-th entry of File > Export, but Altium fills that menu only when it is first opened in a session: in an Altium just started (every battery run) the entry did not exist, and the verb answered `exporter_not_found`. It now runs Altium's own Parasolid / VRML output, from the same generator as STEP, through an OutJob on a throwaway project, as `altium_export_step` does: headless, no window raised, no input approval. The menu route stays as the fallback when the OutJob writes nothing (`lane: menu`, with `outjobFirst` saying why).
README.md+5−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 -284 commands, tested on Altium Designer 26.11 and Altium Designer Develop. It runs in **Hydrogen**, Adom's free+285 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. 284 verbs; each row names the ones+Tested on Altium Designer 26.11.1 and Altium Designer Develop. 285 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 284 `altium_*` verbs.+**DelphiScript agent** inside it, and gives the AI 285 `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 284 verbs, by area (prefix `altium_`). `altium_describe` returns the live catalog with every input, output, hint and example.+All 285 verbs, by area (prefix `altium_`). `altium_describe` returns the live catalog with every input, output, hint and example.  ### Running Altium: launch, close, health, dialogs @@ -456,6 +456,7 @@ All 284 verbs, by area (prefix `altium_`). `altium_describe` returns the live ca - `altium_symbol_prims`: Read a SchLib component's drawing: primitive counts by kind, body rectangle, polyline bounding box, display mode and the footprint models. - `altium_set_models`: Replace every footprint model on a SchLib component with ONE PCBLIB model (set_params footprint and add_models APPEND, which is how a symbol ends up with two). - `altium_add_sim_model`: Put a SPICE model (.MODEL or .SUBCKT from a .mdl/.lib/.ckt file) on a SchLib symbol, as Altium's Sim Model dialog does, so the placed part simulates in Altium and the model goes into an IntLib.+- `altium_sim_copy`: Make a simulation copy of a design's sheets and put sources and loads on it, so a schematic drawn for the board (no stimulus, no load) simulates in Altium while the design stays untouched: voltage and current sources (DC, AC, sine, pulse, piecewise linear) and R, C, L loads, each joined to its nets, and Altium's generic model on every R, C and L that has none. - `altium_selftest_script_error`: Regression test for the script-error safety net (from 0.2.23): makes the agent raise a REAL DelphiScript runtime error on purpose and checks that the bridge photographs Altium's Error box, stops the halted script itself and leaves no dialog behind. - `altium_install`: Install Altium Designer on this machine, STAGED, with the rules in the verb (from 0.2.29). 
bridge-rs/src/main.rs+2−1
@@ -13,6 +13,7 @@ mod fplayers; mod layermap; mod layermap_verb; mod simmodel;+mod simcopy; mod autoclass; mod board; mod bodies;@@ -88,7 +89,7 @@ use tiny_http::{Header, Method, Response, Server}; /// Attached to every failed reply (see the /command handler). const REPORT_ISSUES: &str = "If this looks like an altium-bridge BUG (not a refusal you expected), report it: check for a duplicate with `adom-wiki issue list adom/altium-bridge`, then `adom-wiki issue create adom/altium-bridge --title \"<verb>: <one-line symptom>\" --category bug-report --body \"<what you ran, what you expected, what happened, the VERBATIM response JSON (and errorShot if present), bridgeVersion, the Altium version from altium_status, the OS>\"`. A relay, routing, toast or lifecycle problem belongs on adom/adom-bridge instead. Reports from real machines are how this bridge gets correct: three different Altium builds behaved three different ways in one weekend."; -pub const BRIDGE_VERSION: &str = "0.2.116";+pub const BRIDGE_VERSION: &str = "0.2.117";  fn json_response(status: u16, body: &serde_json::Value) -> Response<std::io::Cursor<Vec<u8>>> {     let data = serde_json::to_vec(body).unwrap_or_else(|_| b"{}".to_vec());
bridge-rs/src/sim.rs+1−1
@@ -364,7 +364,7 @@ fn probe_name(p: &Value) -> Option<String> { }  /// The sheet and the project it belongs to (a .PrjPcb beside it that lists it, else the only one there).-fn sheet_and_project(args: &Value) -> Result<(PathBuf, PathBuf), Value> {+pub(crate) fn sheet_and_project(args: &Value) -> Result<(PathBuf, PathBuf), Value> {     let bad = |c: &str, m: String| json!({"success": false, "errorCode": c, "error": m});     let Some(p) = crate::support::s(args, "schematic").or_else(|| crate::support::s(args, "filePath")) else {         return Err(bad("bad_args", "schematic is the .SchDoc to simulate (filePath works too)".into()));
bridge-rs/src/simcopy.rsadded+422
@@ -0,0 +1,422 @@+//! altium_sim_copy: a simulation copy of a project's sheets with sources and loads on it, so a design drawn for the+//! board (no stimulus, no load) simulates in Altium without being touched. The copy lives in its own folder beside the+//! project; each source or load is a two-pin part drawn on the copy with a built-in SIM model whose netlist line is the+//! SPICE element itself (Altium's Kind/SubKind for it, as its Simulation Generic Components library has them), joined+//! to its nets by net labels or power ports; R, C and L parts with no model get Altium's generic one. The netlist of the+//! copy is read back to prove every source pin landed on the net it was meant for.+use crate::support::{self, s};+use crate::{agent, sch};+use serde_json::{json, Value};+use std::path::{Path, PathBuf};+use std::time::Duration;++/// One source or load to draw.+#[derive(Clone, Debug, PartialEq)]+pub struct Elem {+    pub designator: String,+    pub prefix: &'static str,+    pub kind: &'static str,+    pub subkind: &'static str,+    /// the SPICE text after the nodes: `DC 12 AC 1 0 PULSE(0 5 0 10n 10n 5u 10u)`, `10k`+    pub tail: String,+    pub plus: String,+    pub minus: String,+}++impl Elem {+    /// The SPICE element as Altium netlists it: its prefix before the designator (VVSIM1, RRSIM1, as it writes RR1 for+    /// R1) and GND as node 0 (measured in the .nsx, AD 26.11, 2026-12-01).+    pub fn spice(&self) -> String { format!("{}{} {} {} {}", self.prefix, self.designator, node(&self.plus), node(&self.minus), self.tail) }+    /// The model's netlist template: the designator and the two pins, then the literal tail.+    pub fn template(&self) -> String { format!("@DESIGNATOR %1 %2 {}", self.tail) }+}++/// A net as a SPICE node in Altium's netlist: GND is node 0.+pub fn node(n: &str) -> String { if n.eq_ignore_ascii_case("GND") { "0".into() } else { n.to_string() } }++/// A SPICE number from a JSON number or a string such as `10k`, `4.7u`, `1meg`, `100nF`. Template characters and+/// spaces are refused: the text goes into Altium's netlist line as it is.+pub fn num(v: &Value) -> Result<String, String> {+    if let Some(f) = v.as_f64() {+        if !f.is_finite() { return Err(format!("{v} is not a number")); }+        let a = f.abs();+        return Ok(if a != 0.0 && !(1e-3..1e6).contains(&a) { format!("{f:e}") } else { format!("{f}") });+    }+    let Some(t) = v.as_str().map(str::trim) else { return Err(format!("{v}: a number, or a SPICE value such as 10k or 4.7u")) };+    let b = t.as_bytes();+    let mut i = 0;+    if i < b.len() && (b[i] == b'+' || b[i] == b'-') { i += 1; }+    let digits_start = i;+    while i < b.len() && (b[i].is_ascii_digit() || b[i] == b'.') { i += 1; }+    if i == digits_start || t[digits_start..i].chars().filter(|c| *c == '.').count() > 1 || &t[digits_start..i] == "." {+        return Err(format!("{t}: a SPICE value such as 10k, 4.7u or 1e-6"));+    }+    if i < b.len() && (b[i] == b'e' || b[i] == b'E') && b.get(i + 1).map(|c| c.is_ascii_digit() || *c == b'+' || *c == b'-').unwrap_or(false) {+        i += 2;+        while i < b.len() && b[i].is_ascii_digit() { i += 1; }+    }+    if !t[i..].chars().all(|c| c.is_ascii_alphabetic()) { return Err(format!("{t}: a SPICE value such as 10k, 4.7u or 1e-6 (no spaces or symbols)")); }+    Ok(t.to_string())+}++fn field<'a>(o: &'a Value, keys: &[&str]) -> Option<&'a Value> { keys.iter().find_map(|k| o.get(*k)).filter(|v| !v.is_null()) }++fn nums(o: &Value, keys: &[(&[&str], Option<&str>)], what: &str) -> Result<Vec<String>, String> {+    keys.iter().map(|(names, dflt)| match field(o, names) {+        Some(v) => num(v).map_err(|e| format!("{what}.{}: {e}", names[0])),+        None => dflt.map(str::to_string).ok_or_else(|| format!("{what}.{} is required", names[0])),+    }).collect()+}++fn net_of(o: &Value, keys: &[&str], dflt: Option<&str>) -> Result<String, String> {+    match field(o, keys).and_then(|v| v.as_str()).map(str::trim).filter(|v| !v.is_empty()) {+        Some(n) if n.chars().any(|c| c.is_whitespace() || "|@%?#&~".contains(c)) => Err(format!("{}: {n} is not a net name", keys[0])),+        Some(n) => Ok(n.to_string()),+        None => dflt.map(str::to_string).ok_or_else(|| format!("{} is required: the net (or Ref.Pin) the part's first pin goes to", keys[0])),+    }+}++/// A source: {type: voltage|current, plus, minus (GND), dc?, ac?: magnitude | {magnitude, phase}, sin? | pulse? | pwl?}.+pub fn source(o: &Value, designator: String) -> Result<Elem, String> {+    let ty = o.get("type").and_then(|v| v.as_str()).unwrap_or("voltage").to_ascii_lowercase();+    let (prefix, kind) = match ty.as_str() { "voltage" | "v" => ("V", "Voltage Source"), "current" | "i" => ("I", "Current Source"), t => return Err(format!("source type {t}: voltage or current")) };+    let mut tail = Vec::new();+    if let Some(v) = field(o, &["dc"]) { tail.push(format!("DC {}", num(v).map_err(|e| format!("dc: {e}"))?)); }+    let mut subkind = "DC Source";+    let waves = ["sin", "pulse", "pwl"].iter().filter(|k| field(o, &[k]).is_some()).count();+    if waves > 1 { return Err("give one of sin, pulse or pwl".into()); }+    if let Some(w) = field(o, &["sin"]) {+        let n = nums(w, &[(&["offset"], Some("0")), (&["amplitude"], None), (&["frequency"], None), (&["delay"], Some("0")), (&["damping"], Some("0")), (&["phase"], Some("0"))], "sin")?;+        tail.push(format!("SIN({})", n.join(" ")));+        subkind = "Sinusoidal";+    } else if let Some(w) = field(o, &["pulse"]) {+        let n = nums(w, &[(&["initial", "v1", "i1"], Some("0")), (&["pulsed", "v2", "i2"], None), (&["delay"], Some("0")), (&["rise"], Some("1n")), (&["fall"], Some("1n")), (&["width"], None), (&["period"], None)], "pulse")?;+        tail.push(format!("PULSE({})", n.join(" ")));+        subkind = "Pulse";+    } else if let Some(w) = field(o, &["pwl"]) {+        let pts = w.as_array().filter(|a| !a.is_empty()).ok_or("pwl: [[time, value], ...]")?;+        let mut ps = Vec::new();+        for p in pts {+            let (Some(t), Some(v)) = (p.get(0), p.get(1)) else { return Err("pwl: each point is [time, value]".into()) };+            ps.push(format!("{} {}", num(t)?, num(v)?));+        }+        tail.push(format!("PWL({})", ps.join(" ")));+        subkind = "Piecewise Linear";+    }+    if let Some(a) = field(o, &["ac"]) {+        let (m, p) = if a.is_object() { (field(a, &["magnitude"]).cloned().unwrap_or(json!(1)), field(a, &["phase"]).cloned().unwrap_or(json!(0))) } else { (a.clone(), json!(0)) };+        tail.push(format!("AC {} {}", num(&m).map_err(|e| format!("ac: {e}"))?, num(&p).map_err(|e| format!("ac phase: {e}"))?));+    }+    if tail.is_empty() { return Err("a source needs dc, ac, sin, pulse or pwl".into()); }+    Ok(Elem { designator, prefix, kind, subkind, tail: tail.join(" "), plus: net_of(o, &["plus", "net", "pos"], None)?, minus: net_of(o, &["minus", "neg"], Some("GND"))? })+}++/// A load: {type: resistor|capacitor|inductor, value, plus, minus (GND), ic?}.+pub fn load(o: &Value, designator: String) -> Result<Elem, String> {+    let ty = o.get("type").and_then(|v| v.as_str()).unwrap_or("resistor");+    let Some((sub, prefix)) = crate::simmodel::generic_kind(ty) else { return Err(format!("load type {ty}: resistor, capacitor or inductor")) };+    let v = field(o, &["value"]).ok_or("value is required: 10, 4.7u, 1k ...")?;+    let mut tail = num(v).map_err(|e| format!("value: {e}"))?;+    if let Some(ic) = field(o, &["ic"]) { tail.push_str(&format!(" IC={}", num(ic).map_err(|e| format!("ic: {e}"))?)); }+    Ok(Elem { designator, prefix, kind: "General", subkind: sub, tail, plus: net_of(o, &["plus", "net", "pos"], None)?, minus: net_of(o, &["minus", "neg"], Some("GND"))? })+}++/// The sources and loads of a call, each with its designator (given, or VSIM1, ISIM1, RSIM1, ... in order).+pub fn elems(args: &Value) -> Result<Vec<Elem>, String> {+    let mut out: Vec<Elem> = Vec::new();+    let next = |prefix: &str, given: Option<&str>, out: &Vec<Elem>| -> Result<String, String> {+        if let Some(g) = given.map(str::trim).filter(|g| !g.is_empty()) {+            if g.chars().any(|c| !c.is_ascii_alphanumeric() && c != '_') { return Err(format!("designator {g}: letters, digits and _ only")); }+            if !g.to_ascii_uppercase().starts_with(prefix) { return Err(format!("designator {g}: SPICE names a {prefix} element by its first letter, so start it with {prefix}")); }+            return Ok(g.to_string());+        }+        let mut n = 1;+        loop {+            let d = format!("{prefix}SIM{n}");+            if !out.iter().any(|e| e.designator.eq_ignore_ascii_case(&d)) { return Ok(d); }+            n += 1;+        }+    };+    for (key, is_src) in [("sources", true), ("loads", false)] {+        for (i, o) in args.get(key).and_then(|v| v.as_array()).cloned().unwrap_or_default().iter().enumerate() {+            let prefix = if is_src { if o.get("type").and_then(|v| v.as_str()).map(|t| t.eq_ignore_ascii_case("current") || t.eq_ignore_ascii_case("i")).unwrap_or(false) { "I" } else { "V" } }+                else { crate::simmodel::generic_kind(o.get("type").and_then(|v| v.as_str()).unwrap_or("resistor")).map(|g| g.1).unwrap_or("R") };+            let d = next(prefix, o.get("designator").and_then(|v| v.as_str()), &out).map_err(|e| format!("{key}[{i}]: {e}"))?;+            let e = if is_src { source(o, d) } else { load(o, d) }.map_err(|e| format!("{key}[{i}]: {e}"))?;+            if out.iter().any(|x| x.designator.eq_ignore_ascii_case(&e.designator)) { return Err(format!("{key}[{i}]: designator {} is used twice", e.designator)); }+            out.push(e);+        }+    }+    Ok(out)+}++/// A net that is ground: its pin gets a ground power port.+pub fn ground_like(n: &str) -> bool { matches!(n.to_ascii_uppercase().as_str(), "GND" | "0" | "AGND" | "DGND" | "PGND" | "GNDA" | "GNDD" | "VSS") }++/// `R1.2` -> (R1, 2) when it reads as a part's pin.+pub fn pin_ref(n: &str) -> Option<(String, String)> {+    let (d, p) = n.split_once('.')?;+    (d.chars().next().map(|c| c.is_ascii_alphabetic()).unwrap_or(false) && d.chars().any(|c| c.is_ascii_digit()) && !p.is_empty()).then(|| (d.to_string(), p.to_string()))+}++/// The copy's project file: the original's text with only its sheets (at their new relative paths) and its schematic+/// libraries (absolute, for the models they hold) as documents, renumbered; everything else of the project (its+/// options, its net identifier scope, its variants) kept.+pub fn copy_project_text(text: &str, dir: &Path, sheets_rel: &[(String, String)]) -> String {+    let mut out: Vec<String> = Vec::new();+    let mut docs: Vec<String> = Vec::new();+    let mut skip = false;+    for raw in text.lines() {+        let l = raw.trim_end();+        let t = l.trim();+        if t.starts_with('[') && t.ends_with(']') {+            let low = t[1..t.len() - 1].to_ascii_lowercase();+            skip = low.starts_with("document") || low.starts_with("devicesheet") || low.starts_with("generateddocument");+            if !skip { out.push(l.to_string()); }+            continue;+        }+        if skip {+            if let Some(d) = t.strip_prefix("DocumentPath=") {+                let low = d.to_ascii_lowercase();+                if low.ends_with(".schlib") || low.ends_with(".intlib") {+                    let p = if Path::new(d).is_absolute() || d.contains(':') { d.to_string() } else { dir.join(d.replace('\\', "/")).to_string_lossy().replace('/', "\\") };+                    docs.push(p);+                }+            }+            continue;+        }+        out.push(l.to_string());+    }+    let mut text = out.join("\r\n");+    while text.ends_with("\r\n\r\n") { text.truncate(text.len() - 2); }+    if !text.ends_with("\r\n") { text.push_str("\r\n"); }+    let mut n = 0;+    for (_, rel) in sheets_rel { n += 1; text.push_str(&format!("\r\n[Document{n}]\r\nDocumentPath={rel}\r\nAnnotationEnabled=1\r\n")); }+    for p in docs { n += 1; text.push_str(&format!("\r\n[Document{n}]\r\nDocumentPath={p}\r\n")); }+    text+}++/// Where a sheet goes in the copy: its path under the project folder kept, a sheet from elsewhere by its name.+pub fn rel_in_copy(prj_dir: &Path, sheet: &str) -> String {+    let r = crate::routing::rel_to(&prj_dir.to_string_lossy(), sheet);+    if r.contains(':') || r.starts_with("..") || r.starts_with('\\') { Path::new(&sheet.replace('\\', "/")).file_name().map(|f| f.to_string_lossy().to_string()).unwrap_or(r) } else { r }+}++const MARKER: &str = "adom-sim-copy.json";++/// The parts stand in one column, this far apart: a part spans 800 mil pin end to pin end and each pin's stub adds 200,+/// so 2000 leaves 800 between one part's top stub and the next one's bottom stub, room for the ground symbol and the+/// label. At 1000 the stubs overlapped and joined every net to GND (measured 2026-12-01; the netlist check caught it);+/// at 1600 they were apart but the ground symbol touched the next label.+const PITCH_MIL: i64 = 2000;++fn fail(code: &str, msg: String) -> Value { json!({"success": false, "errorCode": code, "error": msg}) }++/// Close the copy's documents in Altium (they are ours) and remove its folder, which must be one this verb made.+fn clear_copy(dir: &Path, prj: &Path) -> Result<(), Value> {+    if !dir.exists() { return Ok(()); }+    if !dir.join(MARKER).exists() && std::fs::read_dir(dir).map(|mut r| r.next().is_some()).unwrap_or(false) {+        return Err(json!({"success": false, "errorCode": "copy_dir_not_ours", "error": format!("{} exists and is not a simulation copy this verb made", dir.display()),+            "_hint": "Give copyDir a new or empty folder."}));+    }+    if prj.exists() {+        let (open, _) = crate::routing::project_members(prj);+        crate::routing::close_project_saved(&prj.to_string_lossy(), &open);+    }+    std::fs::remove_dir_all(dir).map_err(|e| fail("write_failed", format!("{}: {e} (a document of the copy may still be open)", dir.display())))+}++/// altium_sim_copy {schematic, sources?, loads?, genericPassives? (true), copyDir?}+pub fn sim_copy(args: &Value) -> Value {+    if let Some(g) = support::need_licensed() { return g; }+    let (sheet, prj) = match crate::sim::sheet_and_project(args) { Ok(x) => x, Err(e) => return e };+    let elems = match elems(args) { Ok(e) => e, Err(m) => return fail("bad_args", m) };+    let generic = args.get("genericPassives").and_then(|b| b.as_bool()).unwrap_or(true);+    if elems.is_empty() && !generic { return fail("bad_args", "nothing to do: give sources, loads or genericPassives".into()); }+    let sheet_s = sheet.to_string_lossy().to_string();+    if crate::project::has_changes(&sheet_s) == Some(true) {+        return json!({"success": false, "errorCode": "unsaved_changes", "error": format!("{sheet_s} has unsaved changes: the copy is made from the file"), "_hint": "altium_save it first."});+    }+    let prj_dir = prj.parent().unwrap_or(Path::new(".")).to_path_buf();+    let stem = prj.file_stem().map(|s| s.to_string_lossy().to_string()).unwrap_or_else(|| "Project".into());+    let copy_dir = s(args, "copyDir").map(|d| PathBuf::from(d.replace('/', "\\"))).unwrap_or_else(|| prj_dir.join("AdomSim").join(&stem));+    let copy_prj = copy_dir.join(format!("{stem}_sim.PrjPcb"));+    if let Err(e) = clear_copy(&copy_dir, &copy_prj) { return e; }+    let text = match std::fs::read(&prj) { Ok(b) => String::from_utf8_lossy(&b).to_string(), Err(e) => return fail("file_not_found", format!("{}: {e}", prj.display())) };+    let sheets = crate::bom::parse_project(&text, &prj_dir).sheets;+    let rels: Vec<(String, String)> = sheets.iter().map(|s| (s.clone(), rel_in_copy(&prj_dir, s))).collect();+    let norm = |p: &str| p.replace('/', "\\").to_ascii_lowercase();+    let mut target: Option<String> = None;+    for (src, rel) in &rels {+        let dst = copy_dir.join(rel.replace('\\', "/"));+        if let Some(p) = dst.parent() { let _ = std::fs::create_dir_all(p); }+        if let Err(e) = std::fs::copy(src, &dst) { return fail("write_failed", format!("{src} -> {}: {e}", dst.display())); }+        if norm(src) == norm(&sheet_s) { target = Some(dst.to_string_lossy().replace('/', "\\")); }+    }+    let Some(target) = target else {+        return fail("sheet_not_in_project", format!("{} does not list {}", prj.display(), sheet.display()));+    };+    if let Err(e) = std::fs::write(&copy_prj, copy_project_text(&text, &prj_dir, &rels)) { return fail("write_failed", format!("{}: {e}", copy_prj.display())); }+    let _ = std::fs::write(copy_dir.join(MARKER), serde_json::to_string_pretty(&json!({"source": prj.to_string_lossy(), "sheet": sheet_s, "made": crate::report::iso_utc(chrono_now())})).unwrap_or_default());+    let copy_prj_s = copy_prj.to_string_lossy().replace('/', "\\");+    agent::call("open", &[("path", copy_prj_s.clone())], None, Duration::from_secs(120));++    // R, C and L with no model get Altium's generic one, on every sheet of the copy+    let mut passives: Vec<Value> = Vec::new();+    if generic {+        for (_, rel) in &rels {+            let p = copy_dir.join(rel.replace('\\', "/")).to_string_lossy().replace('/', "\\");+            if let Some(e) = support::must_open(&p, 60) { return e; }+            let r = agent::call("sim_generic", &[], None, Duration::from_secs(90));+            match sch::agent_data(&r) { Ok(d) => passives.extend(d["parts"].as_array().cloned().unwrap_or_default()), Err(e) => return e }+            sch::maybe_save(&json!({}), &p);+        }+    }++    // nets named by a part's pin (R1.2): their compiled names+    let mut nets_before: Option<serde_json::Map<String, Value>> = None;+    let mut resolve = |n: &str| -> Result<String, Value> {+        let Some((d, p)) = pin_ref(n) else { return Ok(n.to_string()) };+        if nets_before.is_none() {+            let r = crate::hier::netlist(&json!({"projectPath": copy_prj_s}));+            nets_before = Some(r["nets"].as_object().cloned().unwrap_or_default());+        }+        let want = format!("{d}.{p}").to_ascii_uppercase();+        nets_before.as_ref().unwrap().iter().find(|(_, pins)| pins.as_array().map(|a| a.iter().any(|x| x.as_str().map(|s| s.to_ascii_uppercase() == want).unwrap_or(false))).unwrap_or(false))+            .map(|(k, _)| k.clone()).map(Ok).unwrap_or_else(|| if nets_before.as_ref().unwrap().contains_key(n) { Ok(n.to_string()) } else {+                Err(json!({"success": false, "errorCode": "net_not_found", "error": format!("{n}: no pin {d}.{p} in the copy's netlist (and no net of that name)"), "copy": {"project": copy_prj_s}}))+            })+    };+    let mut placed: Vec<Elem> = Vec::new();+    for e in &elems {+        let mut r = e.clone();+        r.plus = match resolve(&e.plus) { Ok(n) => n, Err(v) => return v };+        r.minus = match resolve(&e.minus) { Ok(n) => n, Err(v) => return v };+        placed.push(r);+    }++    let mut out_parts: Vec<Value> = Vec::new();+    let mut checks: Vec<Value> = Vec::new();+    if !placed.is_empty() {+        if let Some(e) = support::must_open(&target, 60) { return e; }+        // a net a power port names on this sheet joins by a power port; any other by a net label+        let items = crate::schwire::items(&json!({"sheet": target, "kinds": ["powerPorts"]}));+        let ports: Vec<String> = items["powerPorts"].as_array().cloned().unwrap_or_default().iter().filter_map(|p| p["net"].as_str().map(|s| s.to_ascii_uppercase())).collect();+        let kind = |n: &str| if ground_like(n) || ports.contains(&n.to_ascii_uppercase()) { "power" } else { "label" };+        let mut conns = Vec::new();+        let mut col = "auto".to_string();+        for (i, e) in placed.iter().enumerate() {+            let (plus, minus) = (&e.plus, &e.minus);+            let (pn1, pn2) = if e.prefix == "V" || e.prefix == "I" { ("+", "-") } else { ("1", "2") };+            let r = agent::call("sim_part", &[("des", e.designator.clone()), ("x", col.clone()), ("y", (1000 + PITCH_MIL * i as i64).to_string()),+                ("comment", e.tail.clone()), ("name", format!("ADOM_{}", e.designator)), ("desc", format!("{} (altium_sim_copy)", e.subkind)),+                ("kind", e.kind.into()), ("subkind", e.subkind.into()), ("prefix", e.prefix.into()), ("netlist", e.template()), ("pn1", pn1.into()), ("pn2", pn2.into())],+                None, Duration::from_secs(60));+            let d = match sch::agent_data(&r) { Ok(d) => d, Err(v) => return v };+            // the rest in one column under the first+            if let Some(x) = d["atMil"].get(0).and_then(|x| x.as_i64()) { col = x.to_string(); }+            conns.push(json!({"designator": e.designator, "pin": "1", "net": plus, "kind": kind(plus)}));+            conns.push(json!({"designator": e.designator, "pin": "2", "net": minus, "kind": kind(minus)}));+            out_parts.push(json!({"designator": e.designator, "kind": e.kind, "subKind": e.subkind, "plus": plus, "minus": minus,+                "spice": e.spice(), "atMil": d["atMil"]}));+        }+        let c = sch::connect(&json!({"sheet": target, "connections": conns, "save": true}));+        if c["success"] != json!(true) {+            let mut v = c.clone();+            v["copy"] = json!({"project": copy_prj_s, "schematic": target});+            return v;+        }+        // proof: every pin of every source and load on the net it was meant for, with other pins beside it+        let n = crate::hier::netlist(&json!({"projectPath": copy_prj_s}));+        let nets = n["nets"].as_object().cloned().unwrap_or_default();+        for e in &placed {+            for (pin, want) in [("1", &e.plus), ("2", &e.minus)] {+                let key = format!("{}.{}", e.designator, pin).to_ascii_uppercase();+                let hit = nets.iter().find(|(_, ps)| ps.as_array().map(|a| a.iter().any(|x| x.as_str().map(|s| s.to_ascii_uppercase() == key).unwrap_or(false))).unwrap_or(false));+                let (net, others) = hit.map(|(k, ps)| (k.clone(), ps.as_array().map(|a| a.len().saturating_sub(1)).unwrap_or(0))).unwrap_or_default();+                let ok = !net.is_empty() && others > 0 && (net.eq_ignore_ascii_case(want) || (ground_like(want) && ground_like(&net)));+                checks.push(json!({"pin": format!("{}.{}", e.designator, pin), "want": want, "net": if net.is_empty() { Value::Null } else { json!(net) }, "otherPins": others, "ok": ok}));+            }+        }+    }+    let bad: Vec<&Value> = checks.iter().filter(|c| c["ok"] != json!(true)).collect();+    let no_value: Vec<Value> = passives.iter().filter(|p| p["result"] == json!("no_value") || p["result"] == json!("not_two_pins")).cloned().collect();+    json!({"success": bad.is_empty(), "errorCode": if bad.is_empty() { Value::Null } else { json!("not_connected") },+        "copy": {"project": copy_prj_s, "schematic": target, "dir": copy_dir.to_string_lossy().replace('/', "\\")},+        "parts": out_parts, "checks": checks, "genericPassives": passives, "passivesWithoutValue": no_value,+        "_hint": if bad.is_empty() {+            "The copy is ready: altium_simulate {schematic: copy.schematic, analysis: ...} runs it (probe nets by name; GND is SPICE's node 0). The design itself is untouched. Calling again rebuilds the copy from the design."+        } else {+            "A source or load pin is not on the net it was meant for (checks): the net may be named only on another sheet, or by a port. Name it on this sheet, or pass Ref.Pin (R1.2) as plus/minus."+        }})+}++fn chrono_now() -> i64 { std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map(|d| d.as_secs() as i64).unwrap_or(0) }++#[cfg(test)]+mod tests {+    use super::*;++    #[test]+    fn spice_numbers_are_kept_or_refused() {+        assert_eq!(num(&json!(12)).unwrap(), "12");+        assert_eq!(num(&json!(4.7e-6)).unwrap(), "4.7e-6");+        assert_eq!(num(&json!(1e6)).unwrap(), "1e6");+        assert_eq!(num(&json!("10k")).unwrap(), "10k");+        assert_eq!(num(&json!("100nF")).unwrap(), "100nF");+        assert_eq!(num(&json!("1e-3")).unwrap(), "1e-3");+        assert_eq!(num(&json!("-2.5meg")).unwrap(), "-2.5meg");+        for bad in ["10 k", "@VALUE", "1|2", "", ".", "k10", "1.2.3"] { assert!(num(&json!(bad)).is_err(), "{bad}"); }+    }++    #[test]+    fn a_source_is_written_as_spice_writes_it() {+        let e = source(&json!({"plus": "VIN", "dc": 12, "ac": 1}), "VSIM1".into()).unwrap();+        assert_eq!(e.spice(), "VVSIM1 VIN 0 DC 12 AC 1 0");+        assert_eq!((e.prefix, e.kind, e.subkind), ("V", "Voltage Source", "DC Source"));+        assert_eq!(e.template(), "@DESIGNATOR %1 %2 DC 12 AC 1 0");+        let p = source(&json!({"plus": "SW", "minus": "0", "pulse": {"v2": 5, "width": "5u", "period": "10u"}}), "V2".into()).unwrap();+        assert_eq!(p.tail, "PULSE(0 5 0 1n 1n 5u 10u)");+        assert_eq!(p.subkind, "Pulse");+        let s = source(&json!({"type": "current", "plus": "OUT", "sin": {"amplitude": "1m", "frequency": "1k"}}), "I1".into()).unwrap();+        assert_eq!((s.prefix, s.tail.as_str()), ("I", "SIN(0 1m 1k 0 0 0)"));+        let w = source(&json!({"plus": "A", "pwl": [[0, 0], ["1u", 5]]}), "V3".into()).unwrap();+        assert_eq!(w.tail, "PWL(0 0 1u 5)");+        assert!(source(&json!({"plus": "A"}), "V4".into()).is_err(), "no value");+        assert!(source(&json!({"dc": 1}), "V4".into()).is_err(), "no net");+        assert!(source(&json!({"plus": "A", "sin": {"amplitude": 1, "frequency": 1}, "pulse": {}}), "V4".into()).is_err());+    }++    #[test]+    fn loads_and_designators() {+        let l = load(&json!({"type": "capacitor", "plus": "OUT", "value": "10u", "ic": 0}), "CSIM1".into()).unwrap();+        assert_eq!(l.spice(), "CCSIM1 OUT 0 10u IC=0");+        assert_eq!((l.prefix, l.kind, l.subkind), ("C", "General", "Capacitor"));+        let es = elems(&json!({"sources": [{"plus": "VIN", "dc": 5}, {"plus": "EN", "dc": 1}, {"type": "current", "plus": "X", "dc": "1m"}], "loads": [{"plus": "OUT", "value": 10}]})).unwrap();+        assert_eq!(es.iter().map(|e| e.designator.as_str()).collect::<Vec<_>>(), vec!["VSIM1", "VSIM2", "ISIM1", "RSIM1"]);+        assert!(elems(&json!({"sources": [{"designator": "U9", "plus": "A", "dc": 1}]})).is_err(), "a V element named U");+        assert!(elems(&json!({"sources": [{"designator": "V1", "plus": "A", "dc": 1}, {"designator": "v1", "plus": "B", "dc": 1}]})).is_err());+    }++    #[test]+    fn pin_refs_and_ground() {+        assert_eq!(pin_ref("R1.2"), Some(("R1".into(), "2".into())));+        assert_eq!(pin_ref("U3.VIN"), Some(("U3".into(), "VIN".into())));+        assert_eq!(pin_ref("VIN"), None);+        assert_eq!(pin_ref("NET.A"), None, "no digit: a net name");+        assert!(ground_like("gnd") && ground_like("0") && !ground_like("VIN"));+    }++    #[test]+    fn the_copy_project_lists_its_sheets_and_libraries_only() {+        let prj = "[Design]\r\nVersion=1.0\r\nHierarchyMode=0\r\n\r\n[Document1]\r\nDocumentPath=Main.SchDoc\r\nAnnotationEnabled=1\r\n\r\n[Document2]\r\nDocumentPath=Board.PcbDoc\r\n\r\n[Document3]\r\nDocumentPath=Lib\\Parts.SchLib\r\n\r\n[Document4]\r\nDocumentPath=Sub\\Power.SchDoc\r\n\r\n[GeneratedDocument1]\r\nDocumentPath=Out\\x.csv\r\n\r\n[ProjectVariant1]\r\nDescription=Lite\r\n";+        let rels = vec![("C:\\p\\Main.SchDoc".to_string(), "Main.SchDoc".to_string()), ("C:\\p\\Sub\\Power.SchDoc".to_string(), "Sub\\Power.SchDoc".to_string())];+        let t = copy_project_text(prj, Path::new("C:/p"), &rels);+        assert!(t.contains("HierarchyMode=0") && t.contains("[ProjectVariant1]\r\nDescription=Lite"), "{t}");+        assert!(t.contains("[Document1]\r\nDocumentPath=Main.SchDoc") && t.contains("[Document2]\r\nDocumentPath=Sub\\Power.SchDoc"), "{t}");+        assert!(t.contains("[Document3]\r\nDocumentPath=C:") && t.contains("Parts.SchLib"), "{t}");+        assert!(!t.contains("PcbDoc") && !t.contains("GeneratedDocument") && !t.contains("[Document4]"), "{t}");+        assert_eq!(rel_in_copy(Path::new("C:\\p"), "C:\\p\\Sub\\Power.SchDoc"), "Sub\\Power.SchDoc");+        assert_eq!(rel_in_copy(Path::new("C:\\p"), "D:\\shared\\Io.SchDoc"), "Io.SchDoc");+    }+}
bridge-rs/src/simmodel.rs+76−2
@@ -154,12 +154,76 @@ pub fn clean_file(m: &Model, all: &[Model], source: &str) -> String {     t } -/// altium_add_sim_model {libraryPath, symbolName, modelPath, modelName?, pinMap?, replace?, dryRun?}+/// Altium's generic passive for a `generic` argument: (SubKind, Spice Prefix), as its Simulation Generic Components+/// library has them (Kind General). None for anything else.+pub fn generic_kind(g: &str) -> Option<(&'static str, &'static str)> {+    match g.trim().to_ascii_lowercase().as_str() {+        "resistor" | "r" | "res" => Some(("Resistor", "R")),+        "capacitor" | "c" | "cap" => Some(("Capacitor", "C")),+        "inductor" | "l" | "ind" => Some(("Inductor", "L")),+        _ => None,+    }+}++/// The netlist line of a generic passive: the part's own Value parameter, as Altium's generic library writes it.+pub const GENERIC_NETLIST: &str = "@DESIGNATOR %1 %2 @VALUE";++/// altium_add_sim_model {libraryPath, symbolName, generic: resistor|capacitor|inductor, pinMap?, replace?, dryRun?}+fn add_generic(args: &Value, lib: &str, sym: &str, g: &str) -> Value {+    let Some((sub, prefix)) = generic_kind(g) else {+        return json!({"success": false, "errorCode": "bad_args", "error": format!("generic {g}: resistor, capacitor or inductor")});+    };+    if let Some(e) = crate::support::must_open(lib, 60) { return e; }+    let read = crate::agent::call("lib_symbol_pins", &[("libref", sym.to_string())], None, std::time::Duration::from_secs(60));+    if read.pointer("/data/ok") != Some(&json!(true)) {+        return json!({"success": false, "errorCode": "symbol_not_found", "error": format!("no symbol {sym} in {lib}"), "reply": read.get("data")});+    }+    let pins: Vec<(String, String)> = read.pointer("/data/pins").and_then(|p| p.as_array()).map(|a| a.iter().filter_map(|p| Some((p.get(0)?.as_str()?.to_string(), p.get(1).and_then(|x| x.as_str()).unwrap_or("").to_string()))).collect()).unwrap_or_default();+    let map = match pin_map(args.get("pinMap"), &pins, 2, "") { Ok(x) => x, Err(e) => return json!({"success": false, "errorCode": "pin_map", "error": e, "pins": pins}) };+    if args.get("pinMap").is_none() && pins.len() != 2 {+        return json!({"success": false, "errorCode": "pin_map", "error": format!("{sym} has {} pins: a generic {} has two; give pinMap", pins.len(), sub.to_lowercase()), "pins": pins});+    }+    let name = sub.to_ascii_uppercase();+    let plan = json!({"model": {"name": name, "kind": "generic", "nodes": 2}, "file": Value::Null,+        "altium": {"description": sub, "kind": "General", "subKind": sub, "spicePrefix": prefix, "netlist": GENERIC_NETLIST},+        "pinMap": map, "symbolPins": pins.iter().map(|(d, n)| json!([d, n])).collect::<Vec<_>>()});+    if args.get("dryRun").and_then(|b| b.as_bool()) == Some(true) {+        let mut r = plan; r["success"] = json!(true); r["dryRun"] = json!(true);+        r["_hint"] = json!("Nothing changed. The model reads each placed part's Value parameter; call again without dryRun.");+        return r;+    }+    let replace = args.get("replace").and_then(|b| b.as_bool()).unwrap_or(true);+    let r = crate::agent::call("add_sim", &[("libref", sym.to_string()), ("name", name.clone()), ("file", String::new()), ("fkind", String::new()),+        ("desc", sub.into()), ("kind", "General".into()), ("subkind", sub.into()), ("prefix", prefix.into()), ("netlist", GENERIC_NETLIST.into()),+        ("map", map_string(&map)), ("replace", if replace { "1".into() } else { "0".into() })], None, std::time::Duration::from_secs(60));+    let d = r.get("data").cloned().unwrap_or(json!({}));+    if d["ok"] != true { let mut e = r.clone(); e["success"] = json!(false); return e; }+    let value = d["value"].as_str().unwrap_or("").to_string();+    let mut out = plan;+    out["success"] = json!(true);+    out["replaced"] = d["replaced"].clone();+    out["models"] = d["models"].clone();+    out["value"] = json!(value);+    out["saved"] = json!(false);+    out["_hint"] = json!(if value.trim().is_empty() {+        "Altium's generic model is on the symbol, but the symbol has no Value parameter: the model netlists each placed part's Value (10k, 100n, 4.7u), so give the placed parts one (or the symbol, with altium_set_params). altium_save {filePath: libraryPath} keeps the model."+    } else {+        "Altium's generic model is on the symbol: each placed part simulates at its own Value parameter. altium_save {filePath: libraryPath} keeps it."+    });+    out+}++/// altium_add_sim_model {libraryPath, symbolName, modelPath | generic, modelName?, pinMap?, replace?, dryRun?} pub fn add_sim_model(args: &Value) -> Value {     let s = |k: &str| crate::support::s(args, k);     let bad = |m: String| json!({"success": false, "errorCode": "bad_args", "error": m});+    if let (Some(lib), Some(sym), Some(g)) = (s("libraryPath"), s("symbolName"), s("generic")) {+        if s("modelPath").is_some() { return bad("give modelPath (a SPICE file) or generic (Altium's own R, C, L), not both".into()); }+        if !lib.to_lowercase().ends_with(".schlib") { return bad(format!("{lib} is not a .SchLib")); }+        return add_generic(args, &lib, &sym, &g);+    }     let (Some(lib), Some(sym), Some(mpath)) = (s("libraryPath"), s("symbolName"), s("modelPath")) else {-        return bad("libraryPath (.SchLib), symbolName and modelPath (the .mdl/.lib/.ckt SPICE file on this machine) are required".into());+        return bad("libraryPath (.SchLib), symbolName and modelPath (the .mdl/.lib/.ckt SPICE file on this machine) or generic (resistor, capacitor, inductor) are required".into());     };     if !lib.to_lowercase().ends_with(".schlib") { return bad(format!("{lib} is not a .SchLib")); }     let text = match std::fs::read(&mpath) {@@ -269,6 +333,16 @@ mod tests {         assert!(pin_map(None, &q[..2], 3, "NPN").is_err());     } +    #[test]+    fn generic_passives_are_altiums_own() {+        assert_eq!(generic_kind("Resistor"), Some(("Resistor", "R")));+        assert_eq!(generic_kind("c"), Some(("Capacitor", "C")));+        assert_eq!(generic_kind("inductor"), Some(("Inductor", "L")));+        assert_eq!(generic_kind("diode"), None);+        let two = vec![("2".to_string(), "".to_string()), ("1".to_string(), "".to_string())];+        assert_eq!(map_string(&pin_map(None, &two, 2, "").unwrap()), "(1:1),(2:2)");+    }+     #[test]     fn a_three_pin_mosfet_ties_its_body_to_its_source() {         assert_eq!(netlist(3, true), "@DESIGNATOR %1 %2 %3 %3 @MODEL");
bridge-rs/src/verbs.rs+15−7
@@ -37,7 +37,7 @@ pub const KNOWN: &[&str] = &[     "clone_symbol", "rename_symbol", "rename_footprint", "remove_symbol", "remove_footprint",     "copy_footprint", "xcopy_footprint", "swap_footprint", "symbol_mode", "cleanup_libs",     "install_library", "install_library_bundle", "install_receipt", "compile_intlib", "extract_intlib",-    "place_on_sch", "place_on_pcb", "import_part", "add_symbol_art", "symbol_prims", "set_models", "add_sim_model", "selftest_script_error", "install",+    "place_on_sch", "place_on_pcb", "import_part", "add_symbol_art", "symbol_prims", "set_models", "add_sim_model", "sim_copy", "selftest_script_error", "install",     // licence / account     "license", "license_status", "ensure_licensed", "setup_trial", "signin", "signin_status",     "connect_workspace",@@ -148,13 +148,20 @@ fn describe() -> Value {         verb_doc("set_models", "Replace every footprint model on a SchLib component with ONE PCBLIB model (set_params footprint and add_models APPEND, which is how a symbol ends up with two).",             json!({"libraryPath": "path (.SchLib)", "symbolName": "string", "footprint": "string (PcbLib footprint name)"}), json!({"removed": "int: the footprint (PCBLIB) models replaced", "kept": "[model type]: the other models left as they were (SIM, STRESS, PCB3D, ...)", "footprint": "string"}), 60,             "altium_save the SchLib afterwards. Only footprint models are replaced: a simulation or signal-integrity model stays.", &["symbol_prims", "set_params", "add_models"], &["Before 0.2.114 it removed every model, simulation models included (#42)."], json!({})),-        verb_doc("add_sim_model", "Put a SPICE model (.MODEL or .SUBCKT from a .mdl/.lib/.ckt file) on a SchLib symbol, as Altium's Sim Model dialog does, so the placed part simulates in Altium and the model goes into an IntLib. Diodes, BJTs, MOSFETs, JFETs and subcircuits.",-            json!({"libraryPath": "path to the .SchLib (required)", "symbolName": "the symbol (required)", "modelPath": "the SPICE file on this machine (required): a vendor .lib/.mdl is read and a clean copy written beside the library", "modelName": "which model, when the file holds several", "pinMap": "{symbolPin: modelNode} optional, nodes from 1: SPICE's order is anode-cathode (diode), collector-base-emitter (BJT), drain-gate-source-body (FET). Without it, pins named for their role (A/K, C/B/E, D/G/S/B) go to that node, else the pins in number order", "replace": "bool, default true: remove the symbol's other SIM models first", "dryRun": "bool: answer the plan (model, file, pin map, netlist) and change nothing"}),-            json!({"model": "{name, kind, nodes}", "file": "the clean model file written beside the library", "altium": "{description, kind, subKind, spicePrefix, netlist}", "pinMap": "{symbolPin: modelNode}", "replaced": "int: SIM models removed", "models": "[model type] on the symbol now", "saved": "false"}), 60,-            "Then altium_save the library. A placed part keeps the model (altium_sch_place_part places through Altium's own library placement), altium_simulate runs it, and altium_compile_intlib packs the model file into the IntLib.",-            &["set_models", "sch_place_part", "simulate", "export_spice", "compile_intlib", "read_symbol"],-            &["An encrypted model ($CDNENCSTART, as many PSpice packages are) is refused: only PSpice runs it.", "A vendor file's uncommented title line is dropped from the clean copy (SPICE reads a first line as a title).", "Passive models (R, C, L, switches) are not attached by this verb.", "A MOSFET symbol with three pins ties the body to the source."],+        verb_doc("add_sim_model", "Put a SPICE model (.MODEL or .SUBCKT from a .mdl/.lib/.ckt file) on a SchLib symbol, as Altium's Sim Model dialog does, so the placed part simulates in Altium and the model goes into an IntLib. Diodes, BJTs, MOSFETs, JFETs and subcircuits; or Altium's own generic resistor, capacitor or inductor, which simulates at each placed part's Value.",+            json!({"libraryPath": "path to the .SchLib (required)", "symbolName": "the symbol (required)", "modelPath": "the SPICE file on this machine (this or generic): a vendor .lib/.mdl is read and a clean copy written beside the library", "generic": "resistor | capacitor | inductor (this or modelPath): Altium's built-in model, no file; it netlists the placed part's Value parameter (10k, 100n, 4.7u)", "modelName": "which model, when the file holds several", "pinMap": "{symbolPin: modelNode} optional, nodes from 1: SPICE's order is anode-cathode (diode), collector-base-emitter (BJT), drain-gate-source-body (FET). Without it, pins named for their role (A/K, C/B/E, D/G/S/B) go to that node, else the pins in number order", "replace": "bool, default true: remove the symbol's other SIM models first", "dryRun": "bool: answer the plan (model, file, pin map, netlist) and change nothing"}),+            json!({"model": "{name, kind, nodes}", "file": "the clean model file written beside the library (null for generic)", "altium": "{description, kind, subKind, spicePrefix, netlist}", "pinMap": "{symbolPin: modelNode}", "replaced": "int: SIM models removed", "models": "[model type] on the symbol now", "value": "generic: the symbol's own Value parameter ('' when it has none)", "saved": "false"}), 60,+            "Then altium_save the library. A placed part keeps the model (altium_sch_place_part places through Altium's own library placement), altium_simulate runs it, and altium_compile_intlib packs the model file into the IntLib. To simulate a drawn design without touching it, altium_sim_copy gives its R, C and L the generic model on a copy instead.",+            &["set_models", "sch_place_part", "simulate", "sim_copy", "export_spice", "compile_intlib", "read_symbol"],+            &["An encrypted model ($CDNENCSTART, as many PSpice packages are) is refused: only PSpice runs it.", "A vendor file's uncommented title line is dropped from the clean copy (SPICE reads a first line as a title).", "generic covers resistors, capacitors and inductors; switches and other passives are not attached.", "A generic part with no Value parameter cannot netlist: give it one.", "A MOSFET symbol with three pins ties the body to the source."],             json!({"libraryPath": "C:/lib/Diodes.SchLib", "symbolName": "1N4148WS", "modelPath": "C:/vendor/1N4148WS.lib"})),+        verb_doc("sim_copy", "Make a simulation copy of a design's sheets and put sources and loads on it, so a schematic drawn for the board (no stimulus, no load) simulates in Altium while the design stays untouched: voltage and current sources (DC, AC, sine, pulse, piecewise linear) and R, C, L loads, each joined to its nets, and Altium's generic model on every R, C and L that has none. The copy's netlist is read back to prove each source sits on its net.",+            json!({"schematic": "the .SchDoc to simulate (filePath works too); it must belong to a .PrjPcb beside it (required)", "sources": "[{type?: voltage|current (default voltage), plus: net or Ref.Pin (R1.2), minus?: net (default GND), dc?, ac?: magnitude | {magnitude, phase}, sin?: {offset?, amplitude, frequency, delay?, damping?, phase?} | pulse?: {initial?, pulsed, delay?, rise?, fall?, width, period} | pwl?: [[time, value], ...], designator?: V.../I... (default VSIM1, ISIM1, ...)}]: values are numbers or SPICE values (10k, 4.7u)", "loads": "[{type?: resistor|capacitor|inductor (default resistor), value, plus, minus?: GND, ic?, designator? (default RSIM1, CSIM1, ...)}]", "genericPassives": "bool, default true: every R, C and L of the copy with no simulation model gets Altium's generic one (its Value parameter, else its comment)", "copyDir": "folder for the copy (default AdomSim\\<project> beside the project); rebuilt on every call, and refused when it holds files this verb did not make"}),+            json!({"copy": "{project, schematic, dir}: simulate copy.schematic", "parts": "[{designator, kind, subKind, plus, minus, spice: the SPICE element as Altium netlists it (VVSIM1 IN 0 DC 12: the prefix before the designator, GND as node 0), atMil}]", "checks": "[{pin, want, net, otherPins, ok}]: each source and load pin in the compiled netlist", "genericPassives": "[{designator, kind, value, from: value|comment, result: ok|has_model|no_value|not_two_pins}]", "passivesWithoutValue": "[the R, C, L that could not get a model]"}), 300,+            "Then altium_simulate {schematic: copy.schematic, analysis, probes}: a dc analysis sweeps a source by its designator (VSIM1). Each source is a two-pin part to the right of the drawing whose SIM model's netlist line is the SPICE element itself, so the same line runs in ngspice for a comparison. Calling again rebuilds the copy from the design (edits made on the copy are lost).",+            &["simulate", "export_spice", "add_sim_model", "netlist"],+            &["A net named only on another sheet (a hierarchical design) may not reach a label on this sheet: checks shows it; pass Ref.Pin (R1.2) instead.", "The design's unsaved changes are refused (unsaved_changes): the copy is made from the files.", "Parts with no simulation model other than R, C and L still stop the netlister: give them one with altium_add_sim_model."],+            json!({"schematic": "C:/proj/Buck.SchDoc", "sources": [{"plus": "VIN", "dc": 12}, {"plus": "EN", "pulse": {"pulsed": 5, "delay": "10u", "width": "1", "period": "2"}}], "loads": [{"plus": "VOUT", "value": 3.3}]})),         verb_doc("add_symbol_art", "Draw the chip-outline artwork (the chip-thumbnailer polylines adom-symbol baked into the KiCad symbol) into a SchLib component, fitted to its body rectangle, so the Altium symbol shows the same chip as KiCad and Fusion.",             json!({"libraryPath": "path (.SchLib)", "symbolName": "string (LibReference)", "kicadSym": "Windows path to the .kicad_sym that carries the baked outline (stage it with send_files)", "clear": "bool, default true: remove the component's existing polylines/lines first", "mode": "lines (default) | polyline"}),             json!({"polylines": "int", "points": "int", "bodyRectMil": "[x0,y0,x1,y1]"}), 180,@@ -2393,6 +2400,7 @@ pub fn dispatch(command: &str, args: &Value, _forwarded: &[(String, String)]) ->         "symbol_prims" => library::symbol_prims(args),         "set_models" => library::set_models(args),         "add_sim_model" => crate::simmodel::add_sim_model(args),+        "sim_copy" => crate::simcopy::sim_copy(args),         "place_on_pcb" => library::place_on_pcb(args),         "import_part" => library::import_part(args),         // ---- licence / account ----
dev-skills/altium-bridge-test/run_verb_tests.py+3
@@ -579,6 +579,9 @@ def matrix(w):                          check=lambda d: len(d.get("signals") or []) == 3 and abs(d["signals"][2]["y"][-1] - 12.816) < 0.01                                          and d["signals"][2].get("step") == "R4 = 900" and d["signals"][0]["xUnit"] == "Hz")     M["export_spice"] = dict(phase=4, timeout=900, **ok(schematic=SIM), check=lambda d: len(d.get("elements") or []) >= 8 and bool(d.get("analyses")))+    # 0.2.117: a simulation copy of the amplifier with a load on OUT; its pins must land on OUT and GND in the copy's netlist+    M["sim_copy"] = dict(phase=4, timeout=600, **ok(schematic=SIM, loads=[{"plus": "OUT", "value": "10k"}]),+                         check=lambda d: len(d.get("checks") or []) == 2 and all(c.get("ok") for c in d["checks"]) and "AdomSim" in str((d.get("copy") or {}).get("schematic")))     M["generate_body"] = dict(phase=4, **ok(family="qfn", outputPath=D + "/bodies/QFN16.step", marking="STM32\nG031"),                               check=lambda d: abs(((d.get("bboxMm") or {}).get("x") or 0) - 4.0) < 0.01 and d.get("marking") and not d.get("notApplied"))     # 0.2.88: the standard's import_step: generate_body's STEP placed with the lane board as free geometry, 5 mm up
package.json+1−1
@@ -1,6 +1,6 @@ {   "slug": "altium-bridge",-  "version": "0.2.116",+  "version": "0.2.117",   "type": "app",   "description": "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.",   "tags": [
page.json+2−2
@@ -4,7 +4,7 @@   "type": "app",   "title": "Altium Bridge: AI for Altium Designer",   "brief": "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.",-  "version": "0.2.116",+  "version": "0.2.117",   "hero": {     "type": "image",     "path": "screenshots/hero.png"@@ -159,4 +159,4 @@     "tools/symbol_modes.py",     "uninstall.sh"   ]-}\ No newline at end of file+}
skills/altium-schematic-edit/SKILL.md+28
@@ -263,6 +263,34 @@ altium_add_sim_model '{"libraryPath":"C:/lib/Diodes.SchLib","symbolName":"1N4148   link written with kind `MDL` saved and simulated but did not reach the IntLib. The `.mdl` need not be in the LibPkg. - `altium_set_models` replaces only footprint models (0.2.114): a SIM or STRESS model stays. - A simulation run opens its own window with a second Altium taskbar icon; it is not a second Altium.+- **Resistors, capacitors, inductors** (0.2.117): `"generic": "resistor"` (or `capacitor`, `inductor`) instead of+  `modelPath` puts Altium's own generic model on the symbol (Kind General, SubKind Resistor/Capacitor/Inductor, no+  model file, netlist `@DESIGNATOR %1 %2 @VALUE`, as its Simulation Generic Components library has it). Each placed part+  simulates at its own Value parameter; the reply's `value` is '' when the symbol has none, and then each placed part+  needs one.++### Simulate a drawn design untouched: `altium_sim_copy` (0.2.117)++```+altium_sim_copy '{"schematic":"C:/proj/Buck.SchDoc","sources":[{"plus":"VIN","dc":12},{"plus":"EN","pulse":{"pulsed":5,"delay":"10u","width":1,"period":2}}],"loads":[{"plus":"VOUT","value":3.3}]}'+altium_simulate '{"schematic":"<copy.schematic from the reply>","analysis":{"type":"tran","step":"1u","stop":"2m"},"probes":[{"net":"VOUT"}]}'+```++- A schematic drawn for the board has no stimulus and no load. `sim_copy` copies the project's sheets into+  `AdomSim\<project>` beside it (its own `<project>_sim.PrjPcb` listing the sheets and the schematic libraries), draws+  each source and load as a two-pin part to the right of the drawing, joins its pins to the nets you name (a power port+  where the sheet names that net with one, GND too; a net label otherwise; `R1.2` names a net by a pin), saves, compiles+  and reads the netlist back: `checks` proves each pin is on its net with other pins beside it.+- Each source's SIM model is Altium's built-in one for its kind (Voltage/Current Source, DC Source, Sinusoidal, Pulse,+  Piecewise Linear) with the SPICE element as its netlist line, so `parts[].spice` (`VVSIM1 VIN 0 DC 12`) is exactly+  what runs: the same line goes into ngspice for a comparison. Altium names every element by its prefix before the+  designator (`RR1` for R1, `VVSIM1` for VSIM1) and GND is node 0. Measured on an RC low-pass: Altium's AC run and+  ngspice on the netlist `altium_export_spice` returns agree to every printed digit, and the transient matches+  1 - e^(-t/RC) to six.+- `genericPassives` (default true): every R, C and L of the copy with no simulation model gets Altium's generic one, at+  its Value parameter, else its comment (`10k`). `passivesWithoutValue` names the ones it could not give one.+- Calling again rebuilds the copy from the design; edits on the copy are lost. A folder the verb did not make is never+  cleared (`copy_dir_not_ours`).  ## Title block and PDF 
src/BRIDGE_VERSION+1−1
@@ -1 +1 @@-0.2.116+0.2.117
src/agent/AdomAgent.pas.tmpl+250−25
@@ -11700,6 +11700,106 @@ End;   the model file linked by its full path with kind mdl (lower case: a user's MDL did not pack), no component-library use   and no locked data links, the Kind/SubKind/Spice Prefix/Netlist parameters on the model, the pin map as   (symbolPin:modelNode). replace=1 removes the symbol's SIM models first. }+{ A SIM model on a part (a library symbol or a part on a sheet), in the form Altium's Sim Model dialog writes: the+  model file linked by its full path with kind mdl/ckt (none for a built-in model: Altium's generic R, C, L and its+  sources carry no file, measured in its Simulation Generic Components library 2026-12-01), no component-library use, no+  locked data links, the Kind/SubKind/Spice Prefix/Netlist parameters on the model, the pin map as (pin:node). Any other+  SIM model the part keeps stops being current. }+Function AddSimImpl(C : ISch_Component; MName, Desc, FilePath, FKind, Kind, SubKind, Prefix, Netlist, Map : String) : ISch_Implementation;+Var+    It : ISch_Iterator;+    Impl : ISch_Implementation;+Begin+    It := C.SchIterator_Create;+    It.AddFilter_ObjectSet(MkSet(eImplementation));+    Impl := It.FirstSchObject;+    While Impl <> Nil Do+    Begin+        If UpperCase(Impl.ModelType) = 'SIM' Then Impl.IsCurrent := False;+        Impl := It.NextSchObject;+    End;+    C.SchIterator_Destroy(It);+    Impl := C.AddSchImplementation;+    Impl.ModelType := 'SIM';+    Impl.ModelName := MName;+    Impl.Description := Desc;+    Impl.ClearAllDatafileLinks;+    If FilePath <> '' Then Impl.AddDataFileLink(MName, FilePath, LowerCase(FKind));+    Try Impl.UseComponentLibrary := False; Except End;+    Try Impl.DatalinksLocked := False; Except End;+    If Map <> '' Then Impl.MapAsString := Map;+    AddImplParam(Impl, 'Kind', Kind);+    AddImplParam(Impl, 'SubKind', SubKind);+    AddImplParam(Impl, 'Spice Prefix', Prefix);+    AddImplParam(Impl, 'Netlist', Netlist);+    Impl.IsCurrent := True;+    Result := Impl;+End;++{ True when the part carries a SIM model. }+Function HasSimImpl(C : ISch_Component) : Boolean;+Var+    It : ISch_Iterator;+    Impl : ISch_Implementation;+Begin+    Result := False;+    It := C.SchIterator_Create;+    It.AddFilter_ObjectSet(MkSet(eImplementation));+    Impl := It.FirstSchObject;+    While Impl <> Nil Do+    Begin+        If UpperCase(Impl.ModelType) = 'SIM' Then Result := True;+        Impl := It.NextSchObject;+    End;+    C.SchIterator_Destroy(It);+End;++{ A part's own parameter (not a model's), '' when it has none. }+Function OwnParamText(C : ISch_Component; PName : String) : String;+Var+    It : ISch_Iterator;+    Pm : ISch_Parameter;+Begin+    Result := '';+    It := C.SchIterator_Create;+    It.SetState_IterationDepth(eIterateFirstLevel);+    It.AddFilter_ObjectSet(MkSet(eParameter));+    Pm := It.FirstSchObject;+    While Pm <> Nil Do+    Begin+        If UpperCase(Pm.Name) = UpperCase(PName) Then Begin Result := Pm.Text; Break; End;+        Pm := It.NextSchObject;+    End;+    C.SchIterator_Destroy(It);+End;++{ The pin map of a two-pin part onto a two-node model: its pin numbers in order, '' when it does not have exactly two. }+Function TwoPinMap(C : ISch_Component) : String;+Var+    It : ISch_Iterator;+    Pin : ISch_Pin;+    Ds : TStringList;+Begin+    Result := '';+    Ds := TStringList.Create;+    Ds.Sorted := True;+    Ds.Duplicates := dupIgnore;+    It := C.SchIterator_Create;+    It.AddFilter_ObjectSet(MkSet(ePin));+    Pin := It.FirstSchObject;+    While Pin <> Nil Do+    Begin+        Ds.Add(Pin.Designator);+        Pin := It.NextSchObject;+    End;+    C.SchIterator_Destroy(It);+    If Ds.Count = 2 Then Result := '(' + Ds[0] + ':1),(' + Ds[1] + ':2)';+    Ds.Free;+End;++{ add_sim (#42): a SPICE model on a SchLib symbol, which a placed part simulates with and the IntLib compiler packs+  (MDL/0.mdl and a SIM row in LibCrossRef.Txt, measured on AD 26.11, 2026-12-01). file='' attaches a built-in model+  (generic R, C, L). replace=1 removes the symbol's SIM models first. } Function CmdAddSim(Lines : TStringList) : String; Var     SLib : ISch_Lib;@@ -11733,33 +11833,156 @@ Begin             Replaced := Replaced + 1;         End;     End;-    { the new model is the current SIM model: any other one the symbol keeps stops being current }-    It := C.SchIterator_Create;-    It.AddFilter_ObjectSet(MkSet(eImplementation));-    Impl := It.FirstSchObject;-    While Impl <> Nil Do-    Begin-        If UpperCase(Impl.ModelType) = 'SIM' Then Impl.IsCurrent := False;-        Impl := It.NextSchObject;-    End;-    C.SchIterator_Destroy(It);-    Impl := C.AddSchImplementation;-    Impl.ModelType := 'SIM';-    Impl.ModelName := Param(Lines, 'name');-    Impl.Description := Param(Lines, 'desc');-    Impl.ClearAllDatafileLinks;-    Impl.AddDataFileLink(Param(Lines, 'name'), Param(Lines, 'file'), LowerCase(Param(Lines, 'fkind')));-    Try Impl.UseComponentLibrary := False; Except End;-    Try Impl.DatalinksLocked := False; Except End;-    Impl.MapAsString := Param(Lines, 'map');-    AddImplParam(Impl, 'Kind', Param(Lines, 'kind'));-    AddImplParam(Impl, 'SubKind', Param(Lines, 'subkind'));-    AddImplParam(Impl, 'Spice Prefix', Param(Lines, 'prefix'));-    AddImplParam(Impl, 'Netlist', Param(Lines, 'netlist'));-    Impl.IsCurrent := True;+    Impl := AddSimImpl(C, Param(Lines, 'name'), Param(Lines, 'desc'), Param(Lines, 'file'), Param(Lines, 'fkind'), Param(Lines, 'kind'),+        Param(Lines, 'subkind'), Param(Lines, 'prefix'), Param(Lines, 'netlist'), Param(Lines, 'map'));     SLib.GraphicallyInvalidate;     Result := '{' + JRaw('ok','true') + ',' + JStr('libref', C.LibReference) + ',' + JRaw('replaced', IntToStr(Replaced)) + ',' +-        JStr('map', Impl.MapAsString) + ',' + JRaw('models', ImplTypesJson(C)) + '}';+        JStr('map', Impl.MapAsString) + ',' + JRaw('models', ImplTypesJson(C)) + ',' + JStr('value', OwnParamText(C, 'Value')) + '}';+End;++{ sim_part: a two-pin simulation part drawn on the current sheet (altium_sim_copy's sources and loads): a 200 x 400 mil+  body at x,y (mil), pin 1 (pn1) on top and pin 2 (pn2) below, each 200 mil long, the designator and the comment to the+  right, and a built-in SIM model whose netlist line is the SPICE element itself. }+Function CmdSimPart(Lines : TStringList) : String;+Var+    Doc : ISch_Document;+    C : ISch_Component;+    R : ISch_Rectangle;+    Pin : ISch_Pin;+    It : ISch_Iterator;+    C2 : ISch_Component;+    BR : TCoordRect;+    X, Y, MaxX : Integer;+Begin+    Doc := SchServer.GetCurrentSchDocument;+    If (Doc = Nil) Or (Doc.ObjectID = eSchLib) Then Begin Result := '{' + JRaw('ok','false') + ',' + JStr('errorCode','no_current_schematic') + ',' + JStr('error','no current schematic sheet') + '}'; Exit; End;+    If SheetCompsOf(Doc, Param(Lines, 'des')).Count > 0 Then Begin Result := '{' + JRaw('ok','false') + ',' + JStr('errorCode','designator_taken') + ',' + JStr('error', Param(Lines, 'des') + ' is already on the sheet') + '}'; Exit; End;+    X := StrToIntDef(Param(Lines, 'x'), 1000);+    { x=auto: 1000 mil right of the rightmost part on the sheet }+    If Param(Lines, 'x') = 'auto' Then+    Begin+        MaxX := 0;+        It := Doc.SchIterator_Create;+        It.AddFilter_ObjectSet(MkSet(eSchComponent));+        C2 := It.FirstSchObject;+        While C2 <> Nil Do+        Begin+            BR := C2.BoundingRectangle;+            If Round(CoordToMils(BR.Right)) > MaxX Then MaxX := Round(CoordToMils(BR.Right));+            C2 := It.NextSchObject;+        End;+        Doc.SchIterator_Destroy(It);+        X := ((MaxX + 1000) Div 100) * 100;+    End;+    Y := StrToIntDef(Param(Lines, 'y'), 1000);+    SchServer.ProcessControl.PreProcess(Doc, '');+    C := SchServer.SchObjectFactory(eSchComponent, eCreate_Default);+    C.CurrentPartID := 1;+    C.DisplayMode := 0;+    C.LibReference := 'ADOM_SIM_' + Param(Lines, 'prefix');+    C.ComponentDescription := Param(Lines, 'desc');+    C.Location := Point(MilsToCoord(X), MilsToCoord(Y));+    R := SchServer.SchObjectFactory(eRectangle, eCreate_Default);+    R.OwnerPartId := 1;+    R.OwnerPartDisplayMode := 0;+    R.Location := Point(MilsToCoord(X), MilsToCoord(Y));+    R.Corner := Point(MilsToCoord(X + 200), MilsToCoord(Y + 400));+    R.IsSolid := True;+    C.AddSchObject(R);+    Pin := SchServer.SchObjectFactory(ePin, eCreate_Default);+    Pin.OwnerPartId := 1;+    Pin.OwnerPartDisplayMode := 0;+    Pin.Designator := '1';+    Pin.Name := Param(Lines, 'pn1');+    Pin.PinLength := MilsToCoord(200);+    Pin.Orientation := eRotate90;+    Pin.Location := Point(MilsToCoord(X + 100), MilsToCoord(Y + 400));+    C.AddSchObject(Pin);+    Pin := SchServer.SchObjectFactory(ePin, eCreate_Default);+    Pin.OwnerPartId := 1;+    Pin.OwnerPartDisplayMode := 0;+    Pin.Designator := '2';+    Pin.Name := Param(Lines, 'pn2');+    Pin.PinLength := MilsToCoord(200);+    Pin.Orientation := eRotate270;+    Pin.Location := Point(MilsToCoord(X + 100), MilsToCoord(Y));+    C.AddSchObject(Pin);+    AddSimImpl(C, Param(Lines, 'name'), Param(Lines, 'desc'), '', '', Param(Lines, 'kind'), Param(Lines, 'subkind'), Param(Lines, 'prefix'),+        Param(Lines, 'netlist'), '(1:1),(2:2)');+    C.Designator.Text := Param(Lines, 'des');+    C.Designator.IsHidden := False;+    C.Designator.Location := Point(MilsToCoord(X + 300), MilsToCoord(Y + 250));+    C.Comment.Text := Param(Lines, 'comment');+    C.Comment.IsHidden := False;+    C.Comment.Location := Point(MilsToCoord(X + 300), MilsToCoord(Y + 100));+    Doc.RegisterSchObjectInContainer(C);+    SchServer.RobotManager.SendMessage(Doc.I_ObjectAddress, c_BroadCast, SCHM_PrimitiveRegistration, C.I_ObjectAddress);+    SchServer.ProcessControl.PostProcess(Doc, '');+    Doc.GraphicallyInvalidate;+    Result := '{' + JRaw('ok','true') + ',' + JStr('designator', C.Designator.Text) + ',' + JRaw('models', ImplTypesJson(C)) + ',' + JRaw('atMil', '[' + IntToStr(X) + ',' + IntToStr(Y) + ']') + '}';+End;++{ sim_generic: every R, C and L on the current sheet without a SIM model (designator R/C/L then a digit, two pins) gets+  Altium's generic model (Kind General, SubKind Resistor/Capacitor/Inductor, as its Simulation Generic Components+  library has them): @VALUE when the part has a Value parameter, else its comment as the value. }+Function CmdSimGeneric(Lines : TStringList) : String;+Var+    Doc : ISch_Document;+    It : ISch_Iterator;+    C : ISch_Component;+    Des, L1, Sub, Pre, Val, How, Map, Res, S : String;+    N : Integer;+Begin+    Doc := SchServer.GetCurrentSchDocument;+    If (Doc = Nil) Or (Doc.ObjectID = eSchLib) Then Begin Result := '{' + JRaw('ok','false') + ',' + JStr('errorCode','no_current_schematic') + ',' + JStr('error','no current schematic sheet') + '}'; Exit; End;+    S := ''; N := 0;+    SchServer.ProcessControl.PreProcess(Doc, '');+    It := Doc.SchIterator_Create;+    It.AddFilter_ObjectSet(MkSet(eSchComponent));+    C := It.FirstSchObject;+    While C <> Nil Do+    Begin+        Des := C.Designator.Text;+        L1 := UpperCase(Copy(Des, 1, 1));+        Sub := '';+        If (Length(Des) > 1) And (Pos(Copy(Des, 2, 1), '0123456789') > 0) Then+        Begin+            If L1 = 'R' Then Sub := 'Resistor'+            Else If L1 = 'C' Then Sub := 'Capacitor'+            Else If L1 = 'L' Then Sub := 'Inductor';+        End;+        If Sub <> '' Then+        Begin+            Pre := L1;+            Val := OwnParamText(C, 'Value');+            How := 'value';+            If Trim(Val) = '' Then+            Begin+                Val := C.Comment.Text;+                How := 'comment';+                If (Copy(Val, 1, 1) = '=') Or (Val = '*') Then Val := '';+            End;+            Map := TwoPinMap(C);+            Res := 'ok';+            If HasSimImpl(C) Then Res := 'has_model'+            Else If Map = '' Then Res := 'not_two_pins'+            Else If Trim(Val) = '' Then Res := 'no_value'+            Else+            Begin+                If How = 'value' Then+                    AddSimImpl(C, UpperCase(Sub), Sub, '', '', 'General', Sub, Pre, '@DESIGNATOR %1 %2 @VALUE', Map)+                Else+                    AddSimImpl(C, UpperCase(Sub), Sub, '', '', 'General', Sub, Pre, '@DESIGNATOR %1 %2 ' + Trim(Val), Map);+                N := N + 1;+            End;+            If S <> '' Then S := S + ',';+            S := S + '{' + JStr('designator', Des) + ',' + JStr('kind', Sub) + ',' + JStr('value', Val) + ',' + JStr('from', How) + ',' + JStr('result', Res) + '}';+        End;+        C := It.NextSchObject;+    End;+    Doc.SchIterator_Destroy(It);+    SchServer.ProcessControl.PostProcess(Doc, '');+    Result := '{' + JRaw('ok','true') + ',' + JRaw('added', IntToStr(N)) + ',' + JRaw('parts', '[' + S + ']') + '}'; End;  Function Dispatch(Cmd : String; Lines : TStringList; Payload : String) : String;@@ -11802,6 +12025,8 @@ Begin     Else If Cmd = 'set_models' Then Result := CmdSetModels(Lines)     Else If Cmd = 'lib_symbol_pins' Then Result := CmdLibSymbolPins(Lines)     Else If Cmd = 'add_sim' Then Result := CmdAddSim(Lines)+    Else If Cmd = 'sim_part' Then Result := CmdSimPart(Lines)+    Else If Cmd = 'sim_generic' Then Result := CmdSimGeneric(Lines)     Else If Cmd = 'place_on_pcb' Then Result := CmdPlaceOnPcb(Lines)     Else If Cmd = 'pcb_report' Then Result := CmdPcbReport(Lines)     Else If Cmd = 'list_designators' Then Result := CmdListDesignators(Lines)
src/bridge.json+3−2
@@ -2,7 +2,7 @@   "manifest_version": 1,   "name": "altium",   "displayName": "Altium Designer",-  "version": "0.2.116",+  "version": "0.2.117",   "description": "Drive Altium Designer from Adom: a resident DelphiScript agent (eval + the 1,100-command process launcher), the X2 -R command line, UIA over the VCL shell, dialogs by PID, screenshots of every Altium window, and Altium 365.",   "homepage": "https://wiki.adom.inc/adom/altium-bridge",   "docs": "https://wiki.adom.inc/adom/altium-bridge",@@ -268,6 +268,7 @@     "altium_set_layer_visibility",     "altium_set_models",     "altium_add_sim_model",+    "altium_sim_copy",     "altium_set_outline",     "altium_set_params",     "altium_set_track_width",@@ -317,7 +318,7 @@       "eval": 600,       "panelize": 240,       "impedance": 120,-      "current_capacity": 120, "plan_route": 300, "place_decoupling": 300, "plan_fanout": 300, "estimate_cost": 120, "simulate": 900, "export_spice": 900, "update_footprints_from_library": 600, "lint_library": 600, "export_pos": 120, "verb_times": 15, "prewarm": 120, "render_board": 300, "log_tail": 60, "sch_batch": 900, "import_step": 180, "edit_pours": 600, "export_3d": 360, "tool_update": 150, "import_design": 900, "sch_no_connect": 150, "sch_label": 150, "sch_wire": 150, "edit_tracks": 300, "select_items": 60, "preferences": 60, "extensions": 60, "cancel_run": 15, "physical_properties": 15, "model_check": 180, "place_parts": 600,+      "current_capacity": 120, "plan_route": 300, "place_decoupling": 300, "plan_fanout": 300, "estimate_cost": 120, "simulate": 900, "export_spice": 900, "sim_copy": 600, "update_footprints_from_library": 600, "lint_library": 600, "export_pos": 120, "verb_times": 15, "prewarm": 120, "render_board": 300, "log_tail": 60, "sch_batch": 900, "import_step": 180, "edit_pours": 600, "export_3d": 360, "tool_update": 150, "import_design": 900, "sch_no_connect": 150, "sch_label": 150, "sch_wire": 150, "edit_tracks": 300, "select_items": 60, "preferences": 60, "extensions": 60, "cancel_run": 15, "physical_properties": 15, "model_check": 180, "place_parts": 600,       "height_check": 150,       "copper_balance": 240,       "return_path": 240,