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.82 (unreleased): engine 0.17.2 (standard 0.20.2: plan_route smoothing, pour exemptions); agent_start waits for a dialog the reaper answers
23 files changed
+2440−26
CHANGELOG.md+12bridge-rs/Cargo.lock+1−1bridge-rs/src/lifecycle.rs+11−3bridge-rs/src/verbs.rs+1−1bridge-rs/vendor/README.md+1−1bridge-rs/vendor/adom-eda-checks/Cargo.toml+1−1bridge-rs/vendor/adom-eda-checks/README.md+19−2bridge-rs/vendor/adom-eda-checks/src/assembly.rs+158bridge-rs/vendor/adom-eda-checks/src/autoclass.rs+84bridge-rs/vendor/adom-eda-checks/src/lengths.rs+135bridge-rs/vendor/adom-eda-checks/src/lengthtune.rs+138bridge-rs/vendor/adom-eda-checks/src/lib.rs+23−1bridge-rs/vendor/adom-eda-checks/src/main.rs+1−1bridge-rs/vendor/adom-eda-checks/src/pairroute.rs+195bridge-rs/vendor/adom-eda-checks/src/report.rs+180bridge-rs/vendor/adom-eda-checks/src/review.rs+247bridge-rs/vendor/adom-eda-checks/src/route.rs+112−12bridge-rs/vendor/adom-eda-checks/src/schreview.rs+252bridge-rs/vendor/adom-eda-checks/src/silkplace.rs+220bridge-rs/vendor/adom-eda-checks/src/space.rs+239bridge-rs/vendor/adom-eda-checks/src/writers/ipc2581.rs+398bridge-rs/vendor/adom-eda-checks/src/writers/mod.rs+5−3bridge-rs/vendor/adom-eda-checks/tests/fixtures.rs+7CHANGELOG.md+12@@ -1,5 +1,17 @@ # Changelog +## 0.2.82 (unreleased)++- **The standard's shared engine at 0.17.2** (standard 0.20.2, vendored as published). For Altium that brings the+ routing fixes: `plan_route` straightens its grid path into straight and 45-degree runs with the same clearance+ (`smooth`, on by default; Fusion's DRC flagged every vertex of a staircase), exempts a pour that holds the route's own+ end pad from `avoidPours` and names it (`avoidExempt`), and says so when keeping out of the pours is what finds no path.+ The engine's other new modules are ports of this bridge's own checks; Altium keeps answering those natively.+- **`agent_start` waits for a dialog the bridge answers itself.** AD 26's startup "new versions of extensions" Confirm,+ which the dialog reaper declines, refused agent_start while the reaper was still photographing it (the first AD 26+ battery of 0.2.80 lost 60 verbs to the cascade). A dialog with a safe answer now gets up to 12 s to go; save prompts+ and anything without one still refuse at once.+ ## 0.2.81 - **`altium_simulate` and `altium_export_spice`: Altium's mixed-signal simulator, no clicks** (EDA Bridge Standard #23,
bridge-rs/Cargo.lock+1−1@@ -10,7 +10,7 @@ checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa" [[package]] name = "adom-eda-checks"-version = "0.10.3"+version = "0.17.2" dependencies = [ "roxmltree", "serde_json",
bridge-rs/src/lifecycle.rs+11−3@@ -157,9 +157,17 @@ fn spawn_helper(exe: &str, arg: &str) -> Result<std::process::Child, String> { // notices (2026-10-16). The script Error box is the one dialog recover answers itself, so it does // not block; anything else (a save prompt, a reload confirm) does. if !arg.is_empty() {- if let Some(d) = blocking_dialog() {- return Err(format!("blocked_by_dialog: '{}' is open on Altium's main window; answer it first (altium_check_dialogs / altium_dismiss_dialogs)",- d.get("title").and_then(|t| t.as_str()).unwrap_or("?")));+ // a dialog the reaper answers by itself (AD 26's startup "new versions of extensions" Confirm, which it declines)+ // is given time to go: agent_start refused over it while the reaper was still photographing it (2026-10-29).+ // Save prompts and anything without a safe answer refuse at once+ let t0 = Instant::now();+ while let Some(d) = blocking_dialog() {+ let reaped = d.get("safeAction").and_then(|a| a.as_str()).map(|a| !a.is_empty()).unwrap_or(false);+ if !reaped || t0.elapsed() > Duration::from_secs(12) {+ return Err(format!("blocked_by_dialog: '{}' is open on Altium's main window; answer it first (altium_check_dialogs / altium_dismiss_dialogs)",+ d.get("title").and_then(|t| t.as_str()).unwrap_or("?")));+ }+ std::thread::sleep(Duration::from_millis(700)); } } let mut cmd = std::process::Command::new(exe);
bridge-rs/src/verbs.rs+1−1@@ -413,7 +413,7 @@ fn describe() -> Value { "Coordinates are mm in Altium's frame, the same as altium_routing_state. There is no clearance check here yet: run your own DRC (AI Flow's gate) or altium_run_drc after.", &["routing_state", "place_vias", "remove_items", "ripup_nets"], &["Needs the board current.", "A net name must already exist on the board (nets come from the schematic / pads)."], json!({"net": "VOUT", "width": 0.5, "paths": [[{"pad": "L1.2"}, [120.0, 90.0], {"pad": "C6.1"}]]})), verb_doc("plan_route", "Find a path for one net between two pads, clear of other nets' copper by the board's clearance rule, on the copper layers you allow, with vias between them (the standard's shared planner). A plan: apply:true routes it.",- json!({"net": "string (required)", "from": "Ref.Pad (required), e.g. U1.3", "to": "Ref.Pad (required)", "widthMm": "track width, default the board's Width rule (Preferred), else 0.25", "layers": "[F.Cu, B.Cu, In<n>.Cu] - default F.Cu and B.Cu", "allowVias": "bool, default true", "viaSizeMm": "mm, default the board's Routing Via rule, else 0.6", "viaDrillMm": "mm, default the Routing Via rule, else 0.3", "gridMm": "search grid, default 0.5; 0.1 for fine-pitch pads", "clearanceMm": "only raises the board's rule", "edgeClearanceMm": "mm from the outline", "maxNodes": "search bound, default 50000", "avoidPours": "true keeps out of every other net's pour, [net] out of those nets' pours only; default false (a route may cross them, crossesPours names each)", "pourCost": "number, default 0 - each mm inside another net's pour costs 1 + pourCost mm: a preference, not a wall", "apply": "bool, default false - route it with altium_route_net, guarded by the revision it was planned on", "filePath": "the .PcbDoc (opened first; else the current board)"}),+ json!({"net": "string (required)", "from": "Ref.Pad (required), e.g. U1.3", "to": "Ref.Pad (required)", "widthMm": "track width, default the board's Width rule (Preferred), else 0.25", "layers": "[F.Cu, B.Cu, In<n>.Cu] - default F.Cu and B.Cu", "allowVias": "bool, default true", "viaSizeMm": "mm, default the board's Routing Via rule, else 0.6", "viaDrillMm": "mm, default the Routing Via rule, else 0.3", "gridMm": "search grid, default 0.5; 0.1 for fine-pitch pads", "clearanceMm": "only raises the board's rule", "edgeClearanceMm": "mm from the outline", "maxNodes": "search bound, default 50000", "avoidPours": "true keeps out of every other net's pour, [net] out of those nets' pours only; default false (a route may cross them, crossesPours names each)", "pourCost": "number, default 0 - each mm inside another net's pour costs 1 + pourCost mm: a preference, not a wall", "smooth": "bool, default true - straighten the grid path into straight and 45-degree runs with the same clearance; false keeps the grid path", "apply": "bool, default false - route it with altium_route_net, guarded by the revision it was planned on", "filePath": "the .PcbDoc (opened first; else the current board)"}), json!({"found": "bool", "routeNet": "altium_route_net's own arguments {net, layer, width, viaSize, viaDrill, paths}", "lengthMm": "float", "vias": "int", "viaAt": "[[x, y]]", "revision": "string - pass as expectedRevision", "reason": "string - why no path, when found is false", "crossesPours": "[the other nets' pours the route runs through: check after the repour that none split]", "applied": "{success, applied, failed, unconnected} - with apply", "engine": "string"}), 300, "A plan changes nothing: read it, then call again with apply:true, or pass routeNet to altium_route_net yourself. Pours are not obstacles: repour after. The path is orthogonal on the grid: a 0.5 mm pitch part needs gridMm 0.1 to escape its pads. found:false says why (no room at this grid and clearance, or the search bound).", &["route_net", "routing_state", "repour", "routing_drc", "route_pair"], &["Pours are ignored: a route through a pour's area cuts it until the repour.", "A coarse grid misses paths between fine-pitch pads: try gridMm 0.1 before giving up."], json!({"net": "N1", "from": "U1.8", "to": "U2.1", "gridMm": 0.25})),
bridge-rs/vendor/README.md+1−1@@ -2,7 +2,7 @@ | Folder | From | Version | |---|---|---|-| `adom-eda-checks/` | adom/eda-bridge-standard `engine/` (the shared checks engine) | standard 0.13.3, engine 0.10.3 |+| `adom-eda-checks/` | adom/eda-bridge-standard `engine/` (the shared checks engine) | standard 0.20.2, engine 0.17.2 | | `pcb-design-rules/records/` | adom/pcb-design-rules `rules/records/` (each fab's published limits, with sources and dates) | head of 2026-10-27 | The wiki has no git protocol, so these are copied at a version: refresh both from their pages, then run the tests.
bridge-rs/vendor/adom-eda-checks/Cargo.toml+1−1@@ -1,6 +1,6 @@ [package] name = "adom-eda-checks"-version = "0.10.3"+version = "0.17.2" edition = "2021" description = "The EDA Bridge Standard's checks and board-file writers, computed from the board model JSON: no bridge calls, no tool." license = "MIT"
bridge-rs/vendor/adom-eda-checks/README.md+19−2@@ -11,18 +11,30 @@ boards the engine gives the same answers the Altium bridge 0.2.76 gives. | Check | Reads | What it answers | |---|---|---|+| `assembly_check` | board, stack? | the board against JLCPCB's two PCBA tiers as published (with the page and its read date): size (or `panelMm`), thickness and layers from the stack, one or two sides, the smallest two-pad part and the finest IC pitch, fiducials, and parts without an LCSC number (`lcscMissing` from the bridge's BOM). Pads sharing one centre are one land, and a component with no pads is no part. `service` is the cheaper tier every rule allows. Matches the Altium bridge's answers on its test boards. From its assembly.rs |+| `auto_classes` | board | net classes from the names the nets already have (GND, Power, Clock, HighSpeed) and differential pairs from their suffixes (`_P`/`_N`, `DP`/`DN`, `+`/`-`), with `applyArgs`: the net_classes and diff_pairs calls that write them (Power with a `powerWidthMm` width rule). From the Altium bridge's autoclass.rs |+| `board_report` | board, and every companion it can use | every check the engine has, run on this bundle, as one self-contained HTML page (`text`), dark by default: fab limits (with `fab`), JLCPCB assembly, schematic review and symbols against footprints (with `sheetParts` and `netlist`), impedance, return paths and copper balance (with `stack`), 3D heights (with `bodies`), the design review, and the tool's own DRC (`drc`) and a base64 PNG of the board (`picture`) when the bridge passes them; `args` carries `lcscMissing`, `panelMm`, `gridMm` and `alwaysChecked` to those checks. A section whose input is missing says which to pass. From the Altium bridge's report.rs | | `check_clearance` | board, bodies? | pairs of parts closer than `thresholdMm`, closest first: `mode: courtyard` (default 0.25) measures part boxes (pads, and 3D bodies when given) on the same side; `mode: pads` (default 0.2) measures pad copper of different parts that shares a layer, by its real outline, skipping same-net pairs unless `includeSameNet`; `refs` keeps pairs involving those parts. A part under a raised one (pads apart, bodies apart in 3D) is listed in `stacked`, not `pairs`, as placement_check lists it. From the KiCad bridge's place_tools |+| `check_orientation` | board | advisory: each two-pad part's quarter turns scored by airline length (MST of a routable net with the pad there, distance to the nearest pad of a plane-like net such as GND); turns saving `minImprovementMm` (0.6) or more are suggested, nothing moves. From the Altium bridge's design.rs | | `copper_balance` | board, stack, pours | copper per layer and how evenly mirrored layers match (bow and twist) | | `return_path` | board, stack, pours | signal tracks running over a gap in the neighbouring layer's reference copper, with a pour plan that closes each gap (`apply_pours`) | | `estimate_cost` | board, stack?, rules?, prices? | the numbers a fab quote needs (size, copper layers, thickness from the stack, smallest track, gap from the clearance rule, smallest drill, holes, SMD and through-hole parts and joints, unique parts, assembled sides) and, with a `prices` record, a rough table at `quantities` (default 5, 10, 30, 100), with assembly when asked, every assumption stated and the record named in `source`. The engine carries no rates: without `prices` the reply is the numbers only. From the KiCad bridge's fab.rs |+| `find_space` | board, bodies? | free spots for a part (`part`, or `sizeMm`) near another (`near`) or a point (`at`): clear of other part boxes on that side by `clearanceMm`, of that side's routed tracks and the vias, `edgeMm` inside the outline (arcs sampled), nearest first, as where the part's origin goes; `check: true` lists parts that overlap (and, with bodies, those `stacked` under a raised one) or have pads off the outline, as placement_check judges them. Pours do not block (they re-pour). From the Altium bridge's design.rs | | `fab_check` | board, stack?, rules?, silk?, fab? | the board's smallest features, compared with a fab's limits from adom/pcb-design-rules; each finding names the fab's page and the date it was read | | `impedance` | stack | the track width (and pair gap) for a target impedance on each copper layer; `apply` answers `add_rule` arguments | | `current_capacity` | board, stack? | per net and layer, the narrowest copper against the width the current needs (IPC-2221), and the vias a layer change needs | | `height_check` | bodies, board? | each part's height on its side, parts over `maxTopMm`/`maxBottomMm` or under a lid region (`regions`), body collisions and near misses (`minGapMm`); `noBody` and `complete: false` when a part has no 3D body |+| `pin_pad_check` | board, sheetParts | each symbol's pins against its footprint's pads: pins with no pad (a net that can never reach copper), pads with no pin (mounting and exposed pads excepted), parts only on the sheets or only on the board. From the Altium bridge's schreview.rs | | `place_decoupling` | board, bodies? | positions for an IC's decoupling caps (`ic`, `caps?`, `gapMm` 0.3): each just outside the IC's box on the side of the power pin it serves, turned so its power pad faces the pin and level with it, sliding along when the spot is taken (by a part on the same side, or a through-hole pad from the other). Without `caps` it takes caps across ground and a supply of the IC, leaving out (`leftOut`) a signal net with one cap (a crystal's load) and a cap nearer another IC's pin on that supply. Each cap's pads keep clear of the stubs and vias plan_fanout would give the IC's other pins (`leaveFanout`, default true), so the fanout still fits after. A cap it cannot place stays where it is and keeps its spot. `icPowerNets` lists the IC's supplies. `moveArgs` is move_parts' arguments; `validation` is placement_check on the moved board. From the KiCad bridge's place_tools |+| `length_tune` | board, rules? | a serpentine on the net's longest straight track with room beside it, its bumps sized to add exactly what `targetMm` (or `matchTo`, another net's length) asks, every bump `clearance` (the board's strictest rule) from other nets' pads, routed tracks and vias and inside the board; answered as the track to `remove` and the `routeNet` that replaces it. From the Altium bridge's lengthtune.rs |+| `net_lengths` | board | the routed length of each net (tracks and arcs, by layer, with its vias), the skew of each differential pair (`pairs`, else found by net name: `_P`/`_N`, `+`/`-`) and the spread of each matched-length group against its tolerance (`groups`). From the Altium bridge's lengths.rs | | `placement_check` | board, bodies? | courtyard overlaps (pads and bodies, grown by `marginMm`), parts off or over the edge, pads within `edgeMm` of the edge, parts on mounting holes; `stacked` lists plan-view overlaps where one part sits wholly above the other (a part under a raised molecule: pads apart, no bodies meeting in 3D); `bodiesUsed: false` when no bodies were given | | `plan_fanout` | board, stack?, rules? | the fanout of a BGA or QFN/QFP (`ref`): pitch and package from its pads; a BGA's outer ring escapes on the surface and each inner ball takes a dogbone via, or a via in the pad when the dogbone does not fit (`style` auto); a perimeter pad takes an outward stub, with a via at its end for ground or `viaPerimeter`, and an exposed pad a via grid. `calls` are route_net arguments, one per net; `conflicts` lists each via and stub closer than the clearance to another net's pad, track, arc or via anywhere on the board. A pin its net's copper already reaches is skipped (`includeRouted` plans it anyway), the exposed-pad grid keeps clear of holes already there, and `crossesPours` names other nets' pours the plan runs into (repour before DRC). From the KiCad bridge's place_tools |-| `plan_route` | board, rules? | a path between two pads of a net (`from`, `to` as Ref.Pad) on any listed copper `layers`, with through vias between them: a bounded orthogonal A* on `gridMm`, width and via from the args, else the board's width and via rules (`planner.widthFrom`, `viaFrom`), keeping `widthMm/2` + the board's strictest board-wide copper clearance rule from other nets' copper (pads by their real outline), inside the outline, no via in a pad; a through via is checked on every copper layer of the board (`planner.viasCheckedOn`), not only the planned ones. `routeNet` is route_net's arguments, unchanged. Pours are not obstacles (repour after), but `crossesPours` names each other net's pour the route runs through, since that can split it; `avoidPours: true` keeps the route out of them (or a list of nets: out of theirs only), and `pourCost` makes a mm inside one cost 1 + pourCost mm, a preference where a hard block finds no path |+| `plan_route` | board, rules? | a path between two pads of a net (`from`, `to` as Ref.Pad) on any listed copper `layers`, with through vias between them: a bounded orthogonal A* on `gridMm`, width and via from the args, else the board's width and via rules (`planner.widthFrom`, `viaFrom`), keeping `widthMm/2` + the board's strictest board-wide copper clearance rule from other nets' copper (pads by their real outline), inside the outline, no via in a pad; a through via is checked on every copper layer of the board (`planner.viasCheckedOn`), not only the planned ones. `routeNet` is route_net's arguments, unchanged. Pours are not obstacles (repour after), but `crossesPours` names each other net's pour the route runs through, since that can split it; `avoidPours: true` keeps the route out of them (or a list of nets: out of theirs only), and `pourCost` makes a mm inside one cost 1 + pourCost mm, a preference where a hard block finds no path; a pour that holds the route's own end pad is exempt and named (`planner.avoidExempt`); with no path, `ends` names the avoided pours at each end pad and whether they are exempt, and `withoutAvoid` says whether a path exists through them. The grid path is smoothed to straight and 45-degree segments where they keep the same clearance (`smooth: false` keeps it) |+| `review_board` | board, sheetParts?, rules? | small design-review checks, errors first: placeholder values, single-pin nets, duplicate designators, parts with pads off the outline polygon or near the edge (`edgeMm`), parts with no footprint name, off-grid parts (with `gridMm`); from the sheet parts, missing Mouser/DigiKey/LCSC numbers and datasheets and placeholder comments; from the rules, disabled ones, missing clearance/width/hole-size/short-circuit rules and same-priority ties (rules classed from a standard kind, a descriptor, Altium's ordinal or the rule's own name; `alwaysChecked` names classes a tool always checks, like EAGLE's shorts). `skipped` and `notImplemented` say what was not judged. From the Altium bridge's review.rs |+| `route_pair` | board, stack?, rules? | a differential pair planned as one centreline (pad midpoints through `via` waypoints) with each net offset half a pitch to its own side, mitred corners and a `fanMm` fan-out; width and gap given, or from `diffOhms` and the stack. `problems` names a crossing or other copper (pads by outline, routed tracks, vias) closer than the clearance; `routeNet` holds both nets' route_net arguments and `widthRule` the pair's add_rule. From the Altium bridge's pairroute.rs |+| `schematic_review` | sheetParts, netlist | every placed pin, with its electrical type, against the compiled netlist: power pins on no net and outputs driving each other (errors); unconnected pins, one-pin nets, inputs nothing drives and IC supplies with no capacitor to ground (warnings; a regulator's switch node on an inductor is no missing capacitor). From the Altium bridge's schreview.rs |+| `silk_designators` | board, silk | a place for each reference designator: one size (`size`, stepping down to `minSize`), beside its own part, clear of every pad by `padClearance`, of other parts' bodies and of other labels, inside the board. `applyArgs` is apply_silkscreen's arguments; parts with no clear spot are listed, not forced. From the Altium bridge's silkplace.rs | | `thermal_vias` | board, rules? | a grid of vias in a part's exposed pad (`ref`, `pad?`), clear of vias already there; `apply` is `place_vias` arguments | | `via_fence` | board, rules? | vias of `viaNet` both sides of the named nets' tracks and/or round the board edge (`edge`), at `pitchMm` or lambda/20 at `freqGHz`, clear of other copper; `apply` is `place_vias` arguments | @@ -43,6 +55,7 @@ regions, with `writtenFrom`, and the bridge writes the file or places the region |---|---|---| | `export_gencad` | board | GenCAD 1.4 text, in inches: outline, pads and padstacks, shapes, components (a bottom part `MIRRORX FLIP`, as KiCad writes it), devices, signals, routes | | `export_dxf` | board, pours? | one DXF (R12) per layer in `args.layers`: Edge.Cuts as lines and arcs or one closed polyline (`contours`), copper as tracks, arcs, pads, vias and pours. With `pours` a copper layer shows the copper actually poured; without, `poursAsDrawn` names the layers that show the pour as drawn |+| `export_ipc2581` | board, stack?, pours? | IPC-2581 revision C (mm) for assembly and test, valid against the IPC-2581C schema: layers and stack-up, outline (arcs as curves), one package per footprint with its pins in the footprint's frame, components (a bottom part mirrored) and BOM, nets with their pins, and on each copper layer the pads, traces, arcs, vias and, with `pours`, the poured copper island by island with its holes, plus the drills (a hole with no ring is non-plated). `args.date` sets the history date (default now). No mask, paste or silkscreen. From the Fusion bridge's routing_script.py | | `generate_body` | args only | a part's 3D body as STEP AP214 text from its package family and JEDEC letters (`family`, `dimensionsMm` with `pins` the total pin count and `D2`/`E2` an exposed pad, `marking?`), plus its box in the bodies companion's form; families chip, soic, qfn, qfp, sot23, dfn, bga, melf, ecap, crystal, header (#20) | | `import_svg` | svg (text) | `regions` in board mm (y up) for a layer: each shape with its holes as one contour reaching the holes through zero-width slits | @@ -64,6 +77,10 @@ Every check takes one JSON object: | `silk` | `<prefix>_silk_state` | | `fab` | one record from adom/pcb-design-rules `rules/records/<vendor>.json`, with `vendor` | | `prices` | a price record read from the fab's own page: `{vendor, url, read, currency, pcb: [{layers, setup, perM2, promo?: {maxMm: [w, h], prices: [[qty, price]]}}], thickness?: {standardMm, factor}, assembly?: {setupPerSide, stencilPerSide, perSmdJoint, perThtJoint, perExtendedPart}, excludes?}`. The pcb row used is the one for the fewest copper layers that covers the board |+| `sheetParts` | every sheet's parts as `<prefix>_read_sheet_file` gives them: `[{designator, comment?, params?: [{name, value}], pins: [{number, name, electrical}]}]` (or a reply with `components`). `electrical` is a type name (input, output, io, passive, power, supply, open_collector, hiz, not_connected) or Altium's code; a part whose pins have no numbers (a package-less supply symbol) is no part |+| `netlist` | the compiled netlist: `{nets: {net: ["U1.8", ...]}}` |+| `drc` | board_report only: the tool's own DRC reply (`run_drc`: errors, unconnected, violations) |+| `picture` | board_report only: a base64 PNG of the board, embedded in the page | | `args` | the check's own arguments, as the standard verb documents them | Each part may be the bare model or the bridge's whole reply: the model's keys at the top level, or under `data`.@@ -95,7 +112,7 @@ adom-eda-checks import_svg --svg logo.svg --args '{"at": [10, 10], "widthMm": 20 Replies keep the standard envelope (`success`, `errorCode`, `error`, `_hint`) and name verbs without a prefix (`apply_pours`, `add_rule`, `place_vias`): a bridge adds its own. Every reply also carries `engine`-(`"adom-eda-checks 0.10.3"`), so a bridge reports the engine it runs without writing the version by hand.+(`"adom-eda-checks 0.17.2"`), so a bridge reports the engine it runs without writing the version by hand. ## Tests
bridge-rs/vendor/adom-eda-checks/src/assembly.rsadded+158@@ -0,0 +1,158 @@+//! Ready for JLCPCB assembly? The board against both of JLCPCB's PCBA tiers as published+//! (jlcpcb.com/capabilities/pcb-assembly-capabilities, read 2026-10-26): size, thickness and layers, one or two sides,+//! the smallest package and the finest pin pitch, fiducials, and which parts have no LCSC number. It answers the tier+//! the board can be ordered in. From the Altium bridge's assembly.rs.+use serde_json::{json, Value};+use std::collections::BTreeMap;++fn f(v: &Value) -> f64 { v.as_f64().unwrap_or(0.0) }+fn r3(v: f64) -> f64 { (v * 1000.0).round() / 1000.0 }++/// What the board offers the assembly line, from the board model. Pure.+pub fn facts(st: &Value) -> Value {+ let pads = st["pads"].as_array().cloned().unwrap_or_default();+ let comps = st["components"].as_array().cloned().unwrap_or_default();+ let mut by: BTreeMap<String, Vec<(f64, f64)>> = BTreeMap::new();+ for p in pads.iter().filter(|p| f(&p["drill"]) == 0.0) {+ if let Some(r) = p["ref"].as_str().filter(|r| !r.is_empty()) { by.entry(r.to_string()).or_default().push((f(&p["x"]), f(&p["y"]))); }+ }+ // the finest pitch: the closest pad centres within one part with 3 or more SMD pads (an IC, a BGA, a connector)+ let mut pitch: Option<(f64, String)> = None;+ // the smallest two-pad part: its pad centres (an 0402 is about 1.0 mm apart, an 0201 0.5, an 01005 0.35)+ let mut chip: Option<(f64, String)> = None;+ for (r, ps) in &by {+ let mut d = f64::MAX;+ // pads with one centre are one land (a MOSFET's drain pads drawn as one polygon, fusion-lane #24), not a 0 mm pitch+ for i in 0..ps.len() { for j in i + 1..ps.len() { let e = ((ps[i].0 - ps[j].0).powi(2) + (ps[i].1 - ps[j].1).powi(2)).sqrt(); if e > 0.01 { d = d.min(e); } } }+ if d == f64::MAX { continue; }+ if ps.len() >= 3 && pitch.as_ref().map(|p| d < p.0).unwrap_or(true) { pitch = Some((d, r.clone())); }+ if ps.len() == 2 && chip.as_ref().map(|p| d < p.0).unwrap_or(true) { chip = Some((d, r.clone())); }+ }+ let named = |c: &Value, pat: &[&str]| { let p = c["pattern"].as_str().unwrap_or("").to_ascii_uppercase(); pat.iter().any(|x| p.contains(x)) };+ let tiny: Vec<Value> = comps.iter().filter(|c| named(c, &["0201", "01005", "0603M", "0402M"])).map(|c| json!({"ref": c["ref"], "footprint": c["pattern"]})).collect();+ let fid = |s: &str| s.to_ascii_uppercase().starts_with("FID");+ let fiducials = comps.iter().filter(|c| c["ref"].as_str().map(fid).unwrap_or(false) || named(c, &["FIDUCIAL"])).count()+ + pads.iter().filter(|p| p["ref"].as_str().map(|r| r.is_empty()).unwrap_or(true) && p["name"].as_str().map(fid).unwrap_or(false)).count();+ // a part is a component with pads: a logo or an icon has none and is never placed (fusion-lane #24)+ let placed = |c: &Value| pads.iter().any(|p| p["ref"] == c["ref"]);+ let bottom: Vec<Value> = comps.iter().filter(|c| c["side"] == "bottom" && placed(c)).map(|c| c["ref"].clone()).collect();+ let tht = pads.iter().filter(|p| f(&p["drill"]) > 0.0 && p["ref"].as_str().map(|r| !r.is_empty()).unwrap_or(false))+ .filter_map(|p| p["ref"].as_str().map(String::from)).collect::<std::collections::BTreeSet<_>>();+ json!({"parts": comps.iter().filter(|c| placed(c)).count(), "bottomSideParts": bottom, "finestPitch": pitch.map(|(d, r)| json!({"mm": r3(d), "ref": r})),+ "smallestChip": chip.map(|(d, r)| json!({"padCentresMm": r3(d), "ref": r})), "tinyFootprints": tiny, "fiducials": fiducials,+ "throughHoleParts": tht.into_iter().collect::<Vec<_>>()})+}++fn rule(name: &str, ok: Option<bool>, detail: String) -> Value { json!({"rule": name, "ok": ok, "detail": detail}) }++/// The board against one tier ("economic" or "standard"). `size` is [w, h] mm (the board, or the panel it ships in),+/// `lcsc_missing` the purchased lines with no LCSC number (None: not checked). Pure.+pub fn tier(name: &str, fa: &Value, size: (f64, f64), thick: Option<f64>, layers: Option<i64>, lcsc_missing: Option<usize>, panel: bool) -> Value {+ let eco = name == "economic";+ let mut rs = Vec::new();+ let (w, h) = (size.0.min(size.1), size.0.max(size.1));+ let (lo, hi): ((f64, f64), (f64, f64)) = match (eco, panel) { (true, false) => ((10.0, 10.0), (470.0, 500.0)), (true, true) => ((10.0, 10.0), (250.0, 250.0)), (false, false) => ((70.0, 70.0), (460.0, 500.0)), (false, true) => ((70.0, 70.0), (250.0, 250.0)) };+ let ok = w >= lo.0 && h >= lo.1 && w <= hi.0.min(hi.1) && h <= hi.0.max(hi.1);+ rs.push(rule(&format!("{} {} x {} to {} x {} mm", if panel { "panel" } else { "board" }, lo.0, lo.1, hi.0, hi.1), Some(ok), format!("{} x {} mm{}", r3(size.0), r3(size.1), if !ok && !eco && !panel { ": a panel (panelize) can bring it to 70 x 70" } else { "" })));+ if eco {+ rs.push(match thick { Some(t) => rule("board 0.8 to 1.6 mm thick", Some((0.8 - 1e-6..=1.6 + 1e-6).contains(&t)), format!("{} mm", r3(t))), None => rule("board 0.8 to 1.6 mm thick", None, "thickness not read: pass the stack".into()) });+ rs.push(match layers { Some(n) => rule("2, 4 or 6 layers", Some([2, 4, 6].contains(&n)), format!("{n} layers")), None => rule("2, 4 or 6 layers", None, "layers not read: pass the stack".into()) });+ let bot = fa["bottomSideParts"].as_array().map(|a| a.len()).unwrap_or(0);+ rs.push(rule("parts on one side only", Some(bot == 0), if bot == 0 { "all on top".into() } else { format!("{bot} part(s) on the bottom: {}", fa["bottomSideParts"]) }));+ }+ let (chip_min, pitch_min) = if eco { (0.8, 0.4) } else { (0.3, 0.35) };+ let tiny = fa["tinyFootprints"].as_array().map(|a| a.len()).unwrap_or(0);+ let chip = fa["smallestChip"]["padCentresMm"].as_f64();+ let chip_ok = (eco && tiny == 0 || !eco) && chip.map(|c| c >= chip_min).unwrap_or(true);+ rs.push(rule(if eco { "smallest package 0402" } else { "smallest package 01005" }, Some(chip_ok),+ format!("smallest two-pad part {} (pad centres {} mm){}", fa["smallestChip"]["ref"].as_str().unwrap_or("-"), chip.map(r3).unwrap_or(0.0), if tiny > 0 { format!("; footprints named under 0402: {}", fa["tinyFootprints"]) } else { String::new() })));+ let pitch = fa["finestPitch"]["mm"].as_f64();+ rs.push(rule(&format!("IC pin pitch {pitch_min} mm or more (BGA {} mm)", if eco { 0.5 } else { 0.3 }), Some(pitch.map(|p| p + 1e-6 >= pitch_min).unwrap_or(true)),+ format!("finest {} mm on {}", pitch.map(r3).unwrap_or(0.0), fa["finestPitch"]["ref"].as_str().unwrap_or("-"))));+ if !eco {+ let n = fa["fiducials"].as_u64().unwrap_or(0);+ rs.push(rule("fiducials and edge rails", Some(n >= 2 || panel), if panel { "on the panel rails (panelize adds three)".into() } else { format!("{n} fiducial(s) on the board: add 3 (board_features fiducials) or ship it in a panel with rails") }));+ }+ rs.push(match lcsc_missing { Some(0) => rule("every purchased part has an LCSC number", Some(true), "all lines".into()),+ Some(n) => rule("every purchased part has an LCSC number", Some(false), format!("{n} line(s) without one: find them (adom-parts-search, adom-jlcpcb) or consign them")),+ None => rule("every purchased part has an LCSC number", None, "not checked: pass lcscMissing from the bridge's bom".into()) });+ let ok = rs.iter().all(|r| r["ok"] != json!(false));+ json!({"tier": name, "ok": ok, "rules": rs})+}++/// assembly_check: input {board, stack?, args: {panelMm?: [w, h], lcscMissing?: count or the BOM lines without one}}.+pub fn assembly_check(input: &Value) -> Value {+ let st = match crate::input::board(input) { Ok(b) => b, Err(e) => return e };+ let args = &input["args"];+ let Some((x0, y0, x1, y1)) = crate::geom::outline_bbox(&st) else { return crate::input::refuse("no_outline", "the board has no outline") };+ let panel = args["panelMm"].as_array().filter(|a| a.len() == 2).map(|a| (f(&a[0]), f(&a[1])));+ let size = panel.unwrap_or((x1 - x0, y1 - y0));+ let stack = crate::input::stack(input);+ let thick = stack.as_ref().and_then(|s| s["totalUm"].as_f64()).map(|u| u / 1000.0);+ let layers = stack.as_ref().and_then(|s| s["copperLayers"].as_i64());+ let (lcsc_missing, lcsc_lines) = match &args["lcscMissing"] {+ Value::Array(a) => (Some(a.len()), Value::Array(a.clone())),+ v if v.as_u64().is_some() => (v.as_u64().map(|n| n as usize), Value::Null),+ _ => (None, Value::Null),+ };+ let fa = facts(&st);+ let eco = tier("economic", &fa, size, thick, layers, lcsc_missing, panel.is_some());+ let std_ = tier("standard", &fa, size, thick, layers, lcsc_missing, panel.is_some());+ let service = if eco["ok"] == json!(true) { json!("economic") } else if std_["ok"] == json!(true) { json!("standard") } else { Value::Null };+ json!({"success": true, "fab": {"name": "JLCPCB", "source": "https://jlcpcb.com/capabilities/pcb-assembly-capabilities", "read": "2026-10-26"},+ "service": service, "economic": eco, "standard": std_, "board": fa, "linesWithoutLcsc": lcsc_lines,+ "_hint": "service is the cheapest JLCPCB assembly tier every rule allows (null: fix what the rules mark false). Rotation: JLCPCB's part orientation can differ from the tool's for some packages; check every part in JLCPCB's placement preview after uploading the BOM and pick-and-place."})+}++#[cfg(test)]+mod tests {+ use super::*;++ fn board() -> Value {+ json!({"components": [{"ref": "U1", "side": "top", "pattern": "QFN-20"}, {"ref": "C1", "side": "top", "pattern": "C0402"}, {"ref": "R9", "side": "bottom", "pattern": "R0603"}],+ "pads": [{"ref": "U1", "name": "1", "x": 0.0, "y": 0.0, "drill": 0.0}, {"ref": "U1", "name": "2", "x": 0.5, "y": 0.0, "drill": 0.0}, {"ref": "U1", "name": "3", "x": 1.0, "y": 0.0, "drill": 0.0},+ {"ref": "C1", "name": "1", "x": 5.0, "y": 0.0, "drill": 0.0}, {"ref": "C1", "name": "2", "x": 6.0, "y": 0.0, "drill": 0.0},+ {"ref": "R9", "name": "1", "x": 9.0, "y": 0.0, "drill": 0.0}, {"ref": "R9", "name": "2", "x": 10.5, "y": 0.0, "drill": 0.0}],+ "outline": [[0, 0], [40, 0], [40, 20], [0, 20]]})+ }++ #[test]+ fn facts_find_pitch_the_smallest_chip_and_the_bottom_side() {+ let fa = facts(&board());+ assert_eq!(fa["finestPitch"], json!({"mm": 0.5, "ref": "U1"}));+ assert_eq!(fa["smallestChip"], json!({"padCentresMm": 1.0, "ref": "C1"}));+ assert_eq!(fa["bottomSideParts"], json!(["R9"]));+ // fusion-lane #24: pads sharing one centre are one land, and a pad-less icon on the bottom is no part+ let mut b = board();+ b["components"].as_array_mut().unwrap().push(json!({"ref": "Q1", "side": "top", "pattern": "PowerPAK"}));+ b["components"].as_array_mut().unwrap().push(json!({"ref": "LOGO1", "side": "bottom", "pattern": "ICON"}));+ for k in 5..=8 { b["pads"].as_array_mut().unwrap().push(json!({"ref": "Q1", "name": k.to_string(), "x": 20.0, "y": 0.0, "drill": 0.0})); }+ b["pads"].as_array_mut().unwrap().push(json!({"ref": "Q1", "name": "1", "x": 20.0, "y": 1.27, "drill": 0.0}));+ let fa = facts(&b);+ assert_eq!(fa["finestPitch"], json!({"mm": 0.5, "ref": "U1"}));+ assert_eq!((fa["bottomSideParts"].clone(), fa["parts"].clone()), (json!(["R9"]), json!(4)));+ }++ #[test]+ fn a_small_two_sided_board_needs_standard_in_a_panel() {+ let fa = facts(&board());+ let eco = tier("economic", &fa, (40.0, 20.0), Some(1.6), Some(2), Some(0), false);+ assert_eq!(eco["ok"], json!(false)); // R9 on the bottom+ let std_ = tier("standard", &fa, (40.0, 20.0), Some(1.6), Some(2), Some(0), false);+ assert_eq!(std_["ok"], json!(false)); // under 70 x 70 and no fiducials+ let std_panel = tier("standard", &fa, (90.0, 80.0), Some(1.6), Some(2), Some(0), true);+ assert_eq!(std_panel["ok"], json!(true));+ assert_eq!(tier("economic", &fa, (40.0, 20.0), Some(0.4), Some(2), None, false)["rules"][1]["ok"], json!(false));+ }++ #[test]+ fn the_verb_reads_the_stack_and_the_bridges_lcsc_lines() {+ let r = assembly_check(&json!({"board": board(), "stack": {"totalUm": 1600, "copperLayers": 2}, "args": {"panelMm": [90, 80], "lcscMissing": [{"comment": "10k", "designators": "R9"}]}}));+ assert_eq!(r["service"], Value::Null, "{r}");+ assert_eq!(r["linesWithoutLcsc"][0]["designators"], "R9");+ let lcsc = r["standard"]["rules"].as_array().unwrap().last().unwrap().clone();+ assert_eq!(lcsc["ok"], json!(false));+ assert_eq!(assembly_check(&json!({"board": board(), "stack": {"totalUm": 1600, "copperLayers": 2}, "args": {"panelMm": [90, 80], "lcscMissing": 0}}))["service"], "standard");+ assert_eq!(assembly_check(&json!({"board": {"pads": []}, "args": {}}))["errorCode"], "no_outline");+ }+}
bridge-rs/vendor/adom-eda-checks/src/autoclass.rsadded+84@@ -0,0 +1,84 @@+//! Net classes from the names a designer already gave the nets: ground, power, clocks, the fast interfaces (USB,+//! Ethernet, HDMI, PCIe, DDR, MIPI, LVDS, SATA), and the differential pairs their _P/_N (+/-, DP/DN) suffixes spell;+//! proposed, with the net_classes and diff_pairs arguments that write them. From the Altium bridge's autoclass.rs.+use serde_json::{json, Value};+use std::collections::BTreeMap;++/// The class a net's name puts it in, if any. Pure.+pub fn classify(net: &str) -> Option<&'static str> {+ let n = net.to_ascii_uppercase();+ let core = n.trim_start_matches(['+', '-', '/', '\\']);+ if crate::placetools::is_ground(&n) || core.starts_with("GND") { return Some("GND"); }+ let power = core.contains("VBUS") || core.starts_with("VCC") || core.starts_with("VDD") || core.starts_with("VBAT") || core.starts_with("VIN") || core.starts_with("VBUS")+ || core.starts_with("VSYS") || core.starts_with("VREF") || core.starts_with("PWR") || core.starts_with("VCORE") || core.starts_with("VOUT")+ || (core.starts_with('V') && core.len() > 1 && core.as_bytes()[1].is_ascii_digit())+ || core.chars().next().map(|c| c.is_ascii_digit()).unwrap_or(false) && (core.contains('V'));+ // a supply's name wins over what it feeds (VDD_XTAL is the crystal's supply, not a clock)+ if power { return Some("Power"); }+ let fast = ["USB", "ETH", "RGMII", "RMII", "SGMII", "HDMI", "PCIE", "DDR", "MIPI", "CSI", "DSI", "LVDS", "SATA", "SERDES", "QSPI", "SDIO", "EMMC"];+ if fast.iter().any(|f| core.contains(f)) { return Some("HighSpeed"); }+ if core.contains("CLK") || core.contains("XTAL") || core.contains("OSC") || core.ends_with("SCK") { return Some("Clock"); }+ None+}++/// Differential pairs by name: X_P/X_N, XP/XN, X+/X-, X_DP/X_DM. Pure.+pub fn pairs(nets: &[String]) -> Vec<(String, String, String)> {+ let set: BTreeMap<String, &String> = nets.iter().map(|n| (n.to_ascii_uppercase(), n)).collect();+ let mut out = Vec::new();+ for (u, orig) in &set {+ // longest suffixes first: USB_DP must pair as USB (DP/DN), not as USB_D (P/N)+ for (p, q) in [("_DP", "_DN"), ("_DP", "_DM"), ("DP", "DN"), ("DP", "DM"), ("_P", "_N"), ("+", "-"), ("P", "N")] {+ if let Some(stem) = u.strip_suffix(p) {+ if stem.is_empty() { continue; }+ if let Some(neg) = set.get(&format!("{stem}{q}")) {+ let name = stem.trim_end_matches('_').to_string();+ if !out.iter().any(|(n, _, _): &(String, String, String)| *n == name) { out.push((name, (*orig).clone(), (*neg).clone())); }+ break;+ }+ }+ }+ }+ out+}++/// auto_classes: input {board, args: {powerWidthMm?}}. A proposal from the net names, and `applyArgs`: one net_classes+/// call per class (Power with a width rule) and one diff_pairs call per pair, for the bridge to run.+pub fn auto_classes(input: &Value) -> Value {+ let st = match crate::input::board(input) { Ok(b) => b, Err(e) => return e };+ let nets: Vec<String> = st["nets"].as_array().cloned().unwrap_or_default().iter().filter_map(|n| n.as_str().map(String::from)).collect();+ let mut classes: BTreeMap<&str, Vec<String>> = BTreeMap::new();+ for n in &nets { if let Some(c) = classify(n) { classes.entry(c).or_default().push(n.clone()); } }+ let prs = pairs(&nets);+ let width = input["args"]["powerWidthMm"].as_f64().unwrap_or(0.5);+ let net_classes: Vec<Value> = classes.iter().map(|(c, members)| { let mut a = json!({"name": c, "nets": members}); if *c == "Power" { a["width"] = json!(width); } a }).collect();+ let diff_pairs: Vec<Value> = prs.iter().map(|(n, p, q)| json!({"name": n, "pos": p, "neg": q})).collect();+ json!({"success": true, "applied": false, "proposal": {"classes": classes, "pairs": diff_pairs, "unclassified": nets.iter().filter(|n| classify(n).is_none()).count()},+ "applyArgs": {"net_classes": net_classes, "diff_pairs": diff_pairs},+ "_hint": "A proposal from the net names. Check it, then run each applyArgs.net_classes entry through net_classes (Power gets a width rule, powerWidthMm) and each applyArgs.diff_pairs entry through diff_pairs. Then impedance sizes the pairs and current_capacity checks the power nets."})+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn names_sort_into_classes_and_pairs() {+ for (n, c) in [("GND", Some("GND")), ("AGND", Some("GND")), ("+3V3", Some("Power")), ("VDD_CORE", Some("Power")), ("5V", Some("Power")), ("VBUS", Some("Power")),+ ("USB_DP", Some("HighSpeed")), ("ETH_TX_P", Some("HighSpeed")), ("MCLK", Some("Clock")), ("VDD_XTAL", Some("Power")), ("USB_VBUS", Some("Power")), ("XTAL_IN", Some("Clock")), ("SPI_SCK", Some("Clock")), ("N1", None), ("LED_RED", None)] {+ assert_eq!(classify(n), c, "{n}");+ }+ let nets: Vec<String> = ["USB_DP", "USB_DN", "ETH_TX_P", "ETH_TX_N", "LVDS0+", "LVDS0-", "SDA"].iter().map(|s| s.to_string()).collect();+ let p = pairs(&nets);+ assert_eq!(p.len(), 3);+ assert!(p.iter().any(|(n, a, b)| n == "USB" && a == "USB_DP" && b == "USB_DN"));+ assert!(p.iter().any(|(n, a, b)| n == "LVDS0" && a == "LVDS0+" && b == "LVDS0-"));+ }++ #[test]+ fn the_verb_answers_the_arguments_that_write_them() {+ let r = auto_classes(&json!({"board": {"nets": ["GND", "+3V3", "USB_DP", "USB_DN", "LED"]}, "args": {"powerWidthMm": 0.6}}));+ assert_eq!(r["proposal"]["unclassified"], json!(1));+ assert!(r["applyArgs"]["net_classes"].as_array().unwrap().iter().any(|c| c["name"] == "Power" && c["width"] == json!(0.6)));+ assert_eq!(r["applyArgs"]["diff_pairs"], json!([{"name": "USB", "pos": "USB_DP", "neg": "USB_DN"}]));+ }+}
bridge-rs/vendor/adom-eda-checks/src/lengths.rsadded+135@@ -0,0 +1,135 @@+//! Routed length per net from the board model (tracks and arcs, per layer, with the vias), the skew inside each+//! differential pair, and the spread of a matched-length group against its tolerance. From the Altium bridge's lengths.rs.+use serde_json::{json, Map, Value};+use std::collections::BTreeMap;++fn f(v: &Value) -> f64 { v.as_f64().unwrap_or(0.0) }+fn r3(v: f64) -> f64 { (v * 1000.0).round() / 1000.0 }++/// Per net: total routed length (mm), length by layer, via count and segment count. Pure, for the tests.+pub fn lengths(state: &Value) -> BTreeMap<String, Value> {+ let mut acc: BTreeMap<String, (f64, BTreeMap<String, f64>, usize, usize)> = BTreeMap::new();+ let mut add = |net: &str, layer: &str, len: f64| {+ if net.is_empty() { return; }+ let e = acc.entry(net.to_string()).or_default();+ e.0 += len;+ *e.1.entry(layer.to_string()).or_insert(0.0) += len;+ e.3 += 1;+ };+ for t in state["tracks"].as_array().cloned().unwrap_or_default() {+ let len = ((f(&t["end"]["x"]) - f(&t["start"]["x"])).powi(2) + (f(&t["end"]["y"]) - f(&t["start"]["y"])).powi(2)).sqrt();+ add(t["net"].as_str().unwrap_or(""), t["layer"].as_str().unwrap_or("?"), len);+ }+ for a in state["arcs"].as_array().cloned().unwrap_or_default() {+ let mut span = f(&a["endAngle"]) - f(&a["startAngle"]);+ if span <= 0.0 { span += 360.0; }+ add(a["net"].as_str().unwrap_or(""), a["layer"].as_str().unwrap_or("?"), f(&a["radius"]) * span.to_radians());+ }+ for v in state["vias"].as_array().cloned().unwrap_or_default() {+ if let Some(n) = v["net"].as_str().filter(|n| !n.is_empty()) { acc.entry(n.to_string()).or_default().2 += 1; }+ }+ acc.into_iter().map(|(n, (len, by, vias, segs))| {+ let by: Map<String, Value> = by.into_iter().map(|(k, v)| (k, json!(r3(v)))).collect();+ (n.clone(), json!({"net": n, "lengthMm": r3(len), "byLayer": by, "vias": vias, "segments": segs}))+ }).collect()+}++fn len_of(l: &BTreeMap<String, Value>, net: &str) -> f64 {+ l.iter().find(|(k, _)| k.eq_ignore_ascii_case(net)).map(|(_, v)| f(&v["lengthMm"])).unwrap_or(0.0)+}++/// Skew of each pair (pos minus neg). Pure, for the tests.+pub fn pair_skew(l: &BTreeMap<String, Value>, pairs: &[Value]) -> Vec<Value> {+ pairs.iter().map(|p| {+ let (pos, neg) = (p["pos"].as_str().unwrap_or(""), p["neg"].as_str().unwrap_or(""));+ let (a, b) = (len_of(l, pos), len_of(l, neg));+ json!({"name": p.get("name").cloned().unwrap_or(json!(format!("{pos}/{neg}"))), "pos": pos, "neg": neg, "posMm": r3(a), "negMm": r3(b), "skewMm": r3(a - b)})+ }).collect()+}++/// A matched-length group: its shortest and longest net and whether the spread is within the tolerance. Pure.+pub fn group(l: &BTreeMap<String, Value>, nets: &[String], tol: f64) -> Value {+ let vals: Vec<(String, f64)> = nets.iter().map(|n| (n.clone(), len_of(l, n))).collect();+ let (min, max) = vals.iter().fold((f64::MAX, f64::MIN), |a, v| (a.0.min(v.1), a.1.max(v.1)));+ let spread = if vals.is_empty() { 0.0 } else { max - min };+ let longest = vals.iter().max_by(|a, b| a.1.partial_cmp(&b.1).unwrap()).map(|v| v.0.clone());+ json!({"nets": vals.iter().map(|(n, v)| json!({"net": n, "lengthMm": r3(*v), "shortByMm": r3(max - v)})).collect::<Vec<_>>(),+ "minMm": r3(if vals.is_empty() { 0.0 } else { min }), "maxMm": r3(if vals.is_empty() { 0.0 } else { max }), "spreadMm": r3(spread),+ "toleranceMm": tol, "withinTolerance": spread <= tol + 1e-9, "longest": longest})+}++/// Differential pairs by their net names: X_P/X_N, XP/XN (after a separator), X+/X-. Pure.+pub fn pairs_by_name(l: &BTreeMap<String, Value>) -> Vec<Value> {+ let mut out = Vec::new();+ for n in l.keys() {+ let u = n.to_uppercase();+ for (p, q) in [("_P", "_N"), ("+", "-"), ("_DP", "_DM"), ("_D+", "_D-")] {+ if let Some(base) = u.strip_suffix(p) {+ let want = format!("{base}{q}");+ if let Some(neg) = l.keys().find(|k| k.to_uppercase() == want) {+ out.push(json!({"name": &n[..base.len()], "pos": n, "neg": neg}));+ }+ }+ }+ }+ out+}++/// net_lengths: input {board, args: {nets?, pairs?: [{name?, pos, neg}], groups?: [{nets, toleranceMm}]}}. Without+/// pairs, the pairs come from the net names (pairsFrom says which).+pub fn net_lengths(input: &Value) -> Value {+ let st = match crate::input::board(input) { Ok(b) => b, Err(e) => return e };+ let args = &input["args"];+ let all = lengths(&st);+ let want: Vec<String> = args.get("nets").and_then(|n| n.as_array()).map(|a| a.iter().filter_map(|x| x.as_str().map(str::to_string)).collect()).unwrap_or_default();+ let nets: Vec<Value> = if want.is_empty() { all.values().cloned().collect() } else {+ want.iter().map(|n| all.iter().find(|(k, _)| k.eq_ignore_ascii_case(n)).map(|(_, v)| v.clone()).unwrap_or(json!({"net": n, "lengthMm": 0.0, "unrouted": true}))).collect()+ };+ let (pairs, from): (Vec<Value>, &str) = match args.get("pairs").and_then(|p| p.as_array()) {+ Some(p) => (p.clone(), "args"),+ None => (pairs_by_name(&all), "net names (_P/_N, +/-): pass pairs for the board's own differential pairs"),+ };+ let groups: Vec<Value> = args.get("groups").and_then(|g| g.as_array()).cloned().unwrap_or_default().iter().map(|g| {+ let n: Vec<String> = g["nets"].as_array().cloned().unwrap_or_default().iter().filter_map(|x| x.as_str().map(str::to_string)).collect();+ group(&all, &n, g.get("toleranceMm").and_then(|t| t.as_f64()).unwrap_or(0.5))+ }).collect();+ let out_of_tol = groups.iter().filter(|g| g["withinTolerance"] == json!(false)).count();+ json!({"success": true, "units": "mm", "nets": nets, "pairs": pair_skew(&all, &pairs), "pairsFrom": from, "groups": groups, "groupsOutOfTolerance": out_of_tol,+ "_hint": "Lengths are the routed copper of each net (tracks and arcs; vias counted, not added). A net with branches sums all of them, so read a multi-pin net as total copper, not pin to pin. Lengthen the short nets of a group (length_tune, or route_net with a detour) until spreadMm is within toleranceMm; add a matched-length rule with add_rule."})+}++#[cfg(test)]+mod tests {+ use super::*;++ fn board() -> Value {+ json!({"tracks": [+ {"start": {"x": 0.0, "y": 0.0}, "end": {"x": 10.0, "y": 0.0}, "layer": "F.Cu", "net": "USB_P"},+ {"start": {"x": 10.0, "y": 0.0}, "end": {"x": 10.0, "y": 5.0}, "layer": "B.Cu", "net": "USB_P"},+ {"start": {"x": 0.0, "y": 1.0}, "end": {"x": 12.0, "y": 1.0}, "layer": "F.Cu", "net": "USB_N"}],+ "arcs": [{"center": {"x": 0.0, "y": 0.0}, "radius": 2.0, "startAngle": 0.0, "endAngle": 90.0, "layer": "F.Cu", "net": "CLK"}],+ "vias": [{"position": {"x": 10.0, "y": 0.0}, "net": "USB_P"}]})+ }++ #[test]+ fn lengths_add_tracks_and_arcs_per_layer() {+ let l = lengths(&board());+ assert_eq!(l["USB_P"]["lengthMm"], json!(15.0));+ assert_eq!(l["USB_P"]["byLayer"]["B.Cu"], json!(5.0));+ assert_eq!(l["USB_P"]["vias"], json!(1));+ assert_eq!(l["CLK"]["lengthMm"], json!(3.142));+ }++ #[test]+ fn pairs_report_skew_and_groups_their_spread() {+ let l = lengths(&board());+ let s = pair_skew(&l, &[json!({"name": "USB", "pos": "USB_P", "neg": "USB_N"})]);+ assert_eq!(s[0]["skewMm"], json!(3.0));+ let g = group(&l, &["USB_P".into(), "usb_n".into()], 2.0);+ assert_eq!((g["spreadMm"].clone(), g["withinTolerance"].clone(), g["longest"].clone()), (json!(3.0), json!(false), json!("USB_P")));+ assert_eq!(g["nets"][1]["shortByMm"], json!(3.0));+ // the verb finds USB_P/USB_N by name when no pairs are given+ let r = net_lengths(&json!({"board": board(), "args": {}}));+ assert_eq!((r["pairs"][0]["name"].clone(), r["pairs"][0]["skewMm"].clone()), (json!("USB"), json!(3.0)), "{r}");+ }+}
bridge-rs/vendor/adom-eda-checks/src/lengthtune.rsadded+138@@ -0,0 +1,138 @@+//! Length tuning: a serpentine in the net's longest straight track that has room beside it, its bumps sized to add+//! exactly the length a target (or another net's length) asks for, every bump clear of other copper and inside the+//! board, or a refusal that says why. From the Altium bridge's lengthtune.rs; the plan is answered as the track to+//! remove and the route_net arguments that replace it, for the bridge to apply in one undo step.+use crate::route::{pad_shape, Shape};+use serde_json::{json, Value};++fn f(v: &Value) -> f64 { v.as_f64().unwrap_or(0.0) }+fn r3(v: f64) -> f64 { (v * 1000.0).round() / 1000.0 }+type P = (f64, f64);++/// The serpentine's points replacing a track a->b: `n` rectangular bumps of height `amp` to the side `side` (+1 left,+/// -1 right), each `pitch` long along the track, centred on it. Pure.+pub fn meander(a: P, b: P, n: usize, amp: f64, pitch: f64, side: f64) -> Vec<P> {+ let len = ((b.0 - a.0).powi(2) + (b.1 - a.1).powi(2)).sqrt();+ let (ux, uy) = ((b.0 - a.0) / len, (b.1 - a.1) / len);+ let (nx, ny) = (-uy * side, ux * side);+ let at = |s: f64, h: f64| (a.0 + ux * s + nx * h, a.1 + uy * s + ny * h);+ let start = (len - n as f64 * pitch) / 2.0;+ let mut pts = vec![a];+ for k in 0..n {+ let s = start + k as f64 * pitch;+ pts.push(at(s, 0.0));+ pts.push(at(s, amp));+ pts.push(at(s + pitch / 2.0, amp));+ pts.push(at(s + pitch / 2.0, 0.0));+ }+ pts.push(b);+ pts.dedup_by(|p, q| (p.0 - q.0).abs() < 1e-9 && (p.1 - q.1).abs() < 1e-9);+ pts+}++/// How many bumps and how tall, to add `extra` mm along a track `len` long: as few bumps as fit at `max_amp`, each+/// `pitch` long, leaving `margin` at both ends. None when it cannot fit. Pure.+pub fn sizing(extra: f64, len: f64, pitch: f64, max_amp: f64, margin: f64) -> Option<(usize, f64)> {+ if extra <= 0.0 { return None; }+ let room = ((len - 2.0 * margin) / pitch).floor() as usize;+ if room == 0 { return None; }+ let n = ((extra / (2.0 * max_amp)).ceil() as usize).max(1);+ if n > room { return None; }+ Some((n, extra / (2.0 * n as f64)))+}++/// length_tune: input {board, rules?, args: {net, targetMm? | matchTo?, maxAmplitudeMm?, pitchMm?, clearance?}}.+pub fn length_tune(input: &Value) -> Value {+ let st = match crate::input::board(input) { Ok(b) => b, Err(e) => return e };+ let args = &input["args"];+ let Some(net) = args["net"].as_str().map(String::from) else { return crate::input::refuse("bad_args", "net is the net to lengthen") };+ let lens = crate::lengths::lengths(&st);+ let len_of = |n: &str| lens.iter().find(|(k, _)| k.eq_ignore_ascii_case(n)).map(|(_, v)| f(&v["lengthMm"]));+ let Some(now) = len_of(&net) else { return crate::input::refuse("not_routed", &format!("{net} has no routed track")) };+ let target = match (args["targetMm"].as_f64(), args["matchTo"].as_str()) {+ (Some(t), _) => t,+ (None, Some(m)) => match len_of(m) { Some(l) => l, None => return crate::input::refuse("not_routed", &format!("{m} has no routed track to match")) },+ _ => return crate::input::refuse("bad_args", "targetMm (mm) or matchTo (a net) says how long it should be"),+ };+ let extra = target - now;+ if extra <= 0.01 { return json!({"success": true, "changed": false, "net": net, "lengthMm": r3(now), "targetMm": r3(target), "_hint": "Already at or past the target: tuning only lengthens. Shorten the other net, or route this one more directly."}); }+ let num = |k: &str, d: f64| args[k].as_f64().unwrap_or(d);+ let rule = crate::fab::routing_clearance(&crate::input::rules(input));+ let clearance = num("clearance", 0.0).max(rule.unwrap_or(0.2));+ let same = |v: &Value| v["net"].as_str().map(|n| n.eq_ignore_ascii_case(&net)).unwrap_or(false);+ // other nets' copper by layer ("*" every layer): routed tracks (a hatched pour's net-less pieces re-pour round the+ // bumps), vias, and pads by their real outline+ let mut other: Vec<(String, Shape)> = Vec::new();+ for t in st["tracks"].as_array().into_iter().flatten().filter(|t| !same(t) && t["net"].as_str().map(|n| !n.is_empty()).unwrap_or(false)) {+ other.push((t["layer"].as_str().unwrap_or("").into(), Shape::Cap((f(&t["start"]["x"]), f(&t["start"]["y"])), (f(&t["end"]["x"]), f(&t["end"]["y"])), f(&t["width"]) / 2.0)));+ }+ for v in st["vias"].as_array().into_iter().flatten().filter(|v| !same(v)) {+ let c = (f(&v["position"]["x"]), f(&v["position"]["y"]));+ other.push(("*".into(), Shape::Cap(c, c, f(&v["size"]) / 2.0)));+ }+ for p in st["pads"].as_array().into_iter().flatten().filter(|p| !same(p)) {+ let l = if p["layer"] == "*.Cu" || f(&p["drill"]) > 0.0 { "*".to_string() } else { p["layer"].as_str().unwrap_or("").to_string() };+ other.push((l, pad_shape(p)));+ }+ let ring = crate::coppermap::outline_ring(&st);+ // the net's tracks, longest first; for each, a side where the serpentine fits+ let mut tracks: Vec<Value> = st["tracks"].as_array().cloned().unwrap_or_default().into_iter().filter(same).collect();+ let tlen = |t: &Value| ((f(&t["end"]["x"]) - f(&t["start"]["x"])).powi(2) + (f(&t["end"]["y"]) - f(&t["start"]["y"])).powi(2)).sqrt();+ tracks.sort_by(|a, b| tlen(b).partial_cmp(&tlen(a)).unwrap());+ let mut why = Vec::new();+ for t in &tracks {+ let (a, b) = ((f(&t["start"]["x"]), f(&t["start"]["y"])), (f(&t["end"]["x"]), f(&t["end"]["y"])));+ let w = f(&t["width"]);+ let layer = t["layer"].as_str().unwrap_or("F.Cu").to_string();+ let pitch = num("pitchMm", (4.0 * w).max(4.0 * clearance + 2.0 * w));+ let Some((n, amp)) = sizing(extra, tlen(t), pitch, num("maxAmplitudeMm", 3.0), 2.0 * w) else { why.push(json!({"track": [[r3(a.0), r3(a.1)], [r3(b.0), r3(b.1)]], "why": "too short for the bumps this needs at this amplitude"})); continue };+ for side in [1.0, -1.0] {+ let pts = meander(a, b, n, amp, pitch, side);+ let clear = pts.windows(2).all(|s| other.iter().filter(|o| o.0 == layer || o.0 == "*").all(|o| o.1.dist(s[0], s[1]) >= w / 2.0 + clearance - 1e-9))+ && (ring.len() < 3 || pts.iter().all(|p| crate::route::inside(*p, &ring)));+ if !clear { continue; }+ let added: f64 = pts.windows(2).map(|s| ((s[1].0 - s[0].0).powi(2) + (s[1].1 - s[0].1).powi(2)).sqrt()).sum::<f64>() - tlen(t);+ let way: Vec<Value> = pts.iter().map(|p| json!({"x": r3(p.0), "y": r3(p.1), "layer": layer})).collect();+ return json!({"success": true, "changed": false, "net": net, "lengthMm": r3(now), "targetMm": r3(target), "expectedMm": r3(now + added), "clearanceMm": clearance,+ "plan": {"layer": layer, "replaces": [[r3(a.0), r3(a.1)], [r3(b.0), r3(b.1)]], "bumps": n, "amplitudeMm": r3(amp), "pitchMm": r3(pitch), "side": if side > 0.0 { "left" } else { "right" }, "addsMm": r3(added)},+ "remove": {"tracks": [{"net": net, "layer": layer, "start": {"x": a.0, "y": a.1}, "end": {"x": b.0, "y": b.1}}]},+ "routeNet": {"net": net, "layer": layer, "width": w, "paths": [way]}, "revision": st["revision"],+ "_hint": "A plan: remove the one track in `remove` and route `routeNet` in its place, in one undo step, with expectedRevision: revision. net_lengths then shows the new length; every bump keeps clearanceMm from other nets' pads, routed tracks and vias."});+ }+ why.push(json!({"track": [[r3(a.0), r3(a.1)], [r3(b.0), r3(b.1)]], "why": "no clear room on either side for the bumps"}));+ }+ json!({"success": false, "errorCode": "no_room", "error": format!("no track of {net} has room for {:.2} mm more", extra), "lengthMm": r3(now), "targetMm": r3(target), "tried": why,+ "_hint": "Lower maxAmplitudeMm for more, shorter bumps, raise it for fewer, or reroute the net with a longer straight run in open space."})+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn a_meander_adds_exactly_twice_its_height_per_bump() {+ let (n, amp) = sizing(6.0, 30.0, 1.2, 1.0, 0.4).unwrap();+ assert_eq!(n, 3);+ assert!((amp - 1.0).abs() < 1e-9);+ let pts = meander((0.0, 0.0), (30.0, 0.0), n, amp, 1.2, 1.0);+ let len: f64 = pts.windows(2).map(|s| ((s[1].0 - s[0].0).powi(2) + (s[1].1 - s[0].1).powi(2)).sqrt()).sum();+ assert!((len - 36.0).abs() < 1e-9, "{len}");+ assert!(sizing(100.0, 5.0, 1.2, 1.0, 0.4).is_none());+ assert!(sizing(-1.0, 30.0, 1.2, 1.0, 0.4).is_none());+ }++ #[test]+ fn the_verb_plans_round_other_copper_to_match_a_net() {+ let t = |net: &str, y: f64, x1: f64| json!({"net": net, "layer": "F.Cu", "width": 0.2, "start": {"x": 2.0, "y": y}, "end": {"x": x1, "y": y}});+ // A is 30 mm, B 24 mm; another net runs just above A, so the bumps go below it+ let b = json!({"outline": [[0, -20], [40, -20], [40, 20], [0, 20]], "revision": "r3",+ "tracks": [t("A", 0.0, 32.0), t("B", 10.0, 26.0), json!({"net": "X", "layer": "F.Cu", "width": 0.2, "start": {"x": 2.0, "y": 0.6}, "end": {"x": 32.0, "y": 0.6}})]});+ let r = length_tune(&json!({"board": b, "args": {"net": "B", "matchTo": "A"}}));+ assert_eq!(r["success"], json!(true), "{r}");+ assert!((f(&r["expectedMm"]) - 30.0).abs() < 1e-6, "{r}");+ let a = length_tune(&json!({"board": b, "args": {"net": "A", "targetMm": 34.0}}));+ assert_eq!(a["plan"]["side"], "right", "{a}");+ assert_eq!(length_tune(&json!({"board": b, "args": {"net": "A", "targetMm": 20.0}}))["changed"], json!(false));+ assert_eq!(length_tune(&json!({"board": b, "args": {"net": "Q", "targetMm": 20.0}}))["errorCode"], "not_routed");+ }+}
bridge-rs/vendor/adom-eda-checks/src/lib.rs+23−1@@ -7,6 +7,8 @@ //! Every check takes one input bundle, `{board, stack?, pours?, rules?, silk?, fab?, bodies?, prices?, sheetParts?, netlist?, args?}` (see `input`). use serde_json::Value; +pub mod assembly;+pub mod autoclass; pub mod bodies; pub mod coppermap; pub mod cost;@@ -16,9 +18,17 @@ pub mod features; pub mod geom; pub mod impedance; pub mod input;+pub mod lengths;+pub mod lengthtune;+pub mod pairroute;+pub mod report;+pub mod review; pub mod placement; pub mod placetools; pub mod route;+pub mod schreview;+pub mod silkplace;+pub mod space; pub mod writers; /// This engine's version. Every reply carries it as `engine` ("adom-eda-checks 0.3.0"), so a bridge never writes it by hand@@ -26,7 +36,7 @@ pub mod writers; pub const VERSION: &str = env!("CARGO_PKG_VERSION"); /// The checks this build answers, by standard verb name.-pub const CHECKS: &[&str] = &["check_clearance", "copper_balance", "current_capacity", "estimate_cost", "fab_check", "height_check", "impedance", "place_decoupling", "placement_check", "plan_fanout", "plan_route", "return_path", "thermal_vias", "via_fence"];+pub const CHECKS: &[&str] = &["assembly_check", "auto_classes", "board_report", "check_clearance", "check_orientation", "copper_balance", "current_capacity", "estimate_cost", "fab_check", "find_space", "height_check", "impedance", "length_tune", "net_lengths", "pin_pad_check", "place_decoupling", "placement_check", "plan_fanout", "plan_route", "return_path", "review_board", "route_pair", "schematic_review", "silk_designators", "thermal_vias", "via_fence"]; /// Run one check or writer by its standard name. The reply carries `engine`. pub fn run(check: &str, input: &Value) -> Value {@@ -38,18 +48,30 @@ pub fn run(check: &str, input: &Value) -> Value { fn answer(check: &str, input: &Value) -> Value { if let Some(out) = writers::run(check, input) { return out; } match check {+ "assembly_check" => assembly::assembly_check(input),+ "auto_classes" => autoclass::auto_classes(input),+ "board_report" => report::board_report(input), "check_clearance" => placetools::check_clearance(input),+ "check_orientation" => space::check_orientation(input), "copper_balance" => coppermap::copper_balance(input), "current_capacity" => current::current_capacity(input), "estimate_cost" => cost::estimate_cost(input),+ "find_space" => space::find_space(input), "fab_check" => fab::fab_check(input), "height_check" => bodies::height_check(input), "impedance" => impedance::impedance(input),+ "length_tune" => lengthtune::length_tune(input),+ "net_lengths" => lengths::net_lengths(input),+ "pin_pad_check" => schreview::pin_pad_check(input), "place_decoupling" => placetools::place_decoupling(input), "plan_fanout" => placetools::plan_fanout(input), "placement_check" => placement::placement_check(input), "plan_route" => route::plan_route(input), "return_path" => coppermap::return_path(input),+ "review_board" => review::review_board(input),+ "route_pair" => pairroute::route_pair(input),+ "schematic_review" => schreview::schematic_review(input),+ "silk_designators" => silkplace::silk_designators(input), "thermal_vias" => features::thermal_vias(input), "via_fence" => features::via_fence(input), _ => input::refuse("not_supported", &format!("{check} is not a verb this engine answers (checks: {}; writers: {})", CHECKS.join(", "), writers::WRITERS.join(", "))),
bridge-rs/vendor/adom-eda-checks/src/main.rs+1−1@@ -23,7 +23,7 @@ fn bundle(rest: &[String]) -> Result<Value, String> { while let Some(flag) = it.next() { let val = it.next().ok_or_else(|| format!("{flag} needs a value"))?; match flag.as_str() {- "--board" | "--stack" | "--pours" | "--rules" | "--silk" | "--fab" | "--bodies" | "--prices" | "--sheet-parts" | "--netlist" => {+ "--board" | "--stack" | "--pours" | "--rules" | "--silk" | "--fab" | "--bodies" | "--prices" | "--sheet-parts" | "--netlist" | "--drc" => { let key = match flag.as_str() { "--sheet-parts" => "sheetParts", f => &f[2..] }; b[key] = read(val)?; }
bridge-rs/vendor/adom-eda-checks/src/pairroute.rsadded+195@@ -0,0 +1,195 @@+//! A differential pair planned as a pair: one centreline from the midpoint of the source pads through waypoints to the+//! midpoint of the destination pads, each net offset half a pitch (width + gap) to its own side with mitred corners, a+//! short fan-out from each pad, both lengths and the skew, and what the plan would run into. From the Altium bridge's+//! pairroute.rs; the plan is answered as route_net arguments (and the pair's add_rule width rule), for the bridge to+//! apply.+use crate::route::{pad_shape, Shape};+use serde_json::{json, Value};++fn f(v: &Value) -> f64 { v.as_f64().unwrap_or(0.0) }+fn r3(v: f64) -> f64 { (v * 1000.0).round() / 1000.0 }+type P = (f64, f64);++fn sub(a: P, b: P) -> P { (a.0 - b.0, a.1 - b.1) }+fn norm(a: P) -> P { let l = (a.0 * a.0 + a.1 * a.1).sqrt(); if l > 0.0 { (a.0 / l, a.1 / l) } else { (0.0, 0.0) } }+fn left(d: P) -> P { (-d.1, d.0) }++/// The polyline offset `d` to the left (negative: right), corners mitred. Pure.+pub fn offset(path: &[P], d: f64) -> Vec<P> {+ let n = path.len();+ (0..n).map(|i| {+ let din = if i > 0 { norm(sub(path[i], path[i - 1])) } else { norm(sub(path[1], path[0])) };+ let dout = if i + 1 < n { norm(sub(path[i + 1], path[i])) } else { din };+ let (n1, n2) = (left(din), left(dout));+ let m = norm((n1.0 + n2.0, n1.1 + n2.1));+ let k = (m.0 * n1.0 + m.1 * n1.1).max(0.2); // a hairpin would blow the mitre up: cap it at 5x+ (path[i].0 + m.0 * d / k, path[i].1 + m.1 * d / k)+ }).collect()+}++fn length(p: &[P]) -> f64 { p.windows(2).map(|w| ((w[1].0 - w[0].0).powi(2) + (w[1].1 - w[0].1).powi(2)).sqrt()).sum() }++/// Both nets' points from pad to pad: the centreline from the pad midpoints through `via`, each net on the side its+/// source pad is on, `fan` mm of fan-out at each end. Pure.+pub fn plan(pos: (P, P), neg: (P, P), via: &[P], width: f64, gap: f64, fan: f64) -> (Vec<P>, Vec<P>) {+ let s = ((pos.0 .0 + neg.0 .0) / 2.0, (pos.0 .1 + neg.0 .1) / 2.0);+ let e = ((pos.1 .0 + neg.1 .0) / 2.0, (pos.1 .1 + neg.1 .1) / 2.0);+ let mut centre = vec![s];+ centre.extend_from_slice(via);+ centre.push(e);+ // pull the ends in by the fan-out so each pad has room to reach its own side+ let d0 = norm(sub(centre[1], centre[0]));+ let k = centre.len();+ let d1 = norm(sub(centre[k - 1], centre[k - 2]));+ centre[0] = (s.0 + d0.0 * fan, s.1 + d0.1 * fan);+ centre[k - 1] = (e.0 - d1.0 * fan, e.1 - d1.1 * fan);+ let half = (width + gap) / 2.0;+ // the positive net goes on the side its source pad is on+ let side = { let v = sub(pos.0, s); let n = left(d0); if v.0 * n.0 + v.1 * n.1 >= 0.0 { 1.0 } else { -1.0 } };+ let mut p = vec![pos.0]; p.extend(offset(¢re, half * side)); p.push(pos.1);+ let mut n = vec![neg.0]; n.extend(offset(¢re, -half * side)); n.push(neg.1);+ (p, n)+}++fn crosses(a: P, b: P, c: P, d: P) -> bool {+ let o = |p: P, q: P, r: P| (q.0 - p.0) * (r.1 - p.1) - (q.1 - p.1) * (r.0 - p.0);+ let (d1, d2, d3, d4) = (o(c, d, a), o(c, d, b), o(a, b, c), o(a, b, d));+ (d1 > 0.0) != (d2 > 0.0) && (d3 > 0.0) != (d4 > 0.0)+}++/// What is wrong with a planned pair before it touches the board: the two nets crossing each other (the pads swap sides+/// between the ends), or a segment closer than the clearance to another net's copper on the layer. `copper` is+/// (what, net, shape). Pure.+pub(crate) fn check(p: &[P], n: &[P], copper: &[(String, String, Shape)], nets: (&str, &str), width: f64, clearance: f64) -> Vec<Value> {+ let mut out = Vec::new();+ for i in 0..p.len().saturating_sub(1) {+ for j in 0..n.len().saturating_sub(1) {+ if crosses(p[i], p[i + 1], n[j], n[j + 1]) {+ out.push(json!({"problem": "pair_crosses", "at": [r3((p[i].0 + p[i + 1].0) / 2.0), r3((p[i].1 + p[i + 1].1) / 2.0)],+ "fix": "the pads are on swapped sides at the two ends: route to a via pair and cross on another layer, or swap the pins"}));+ return out;+ }+ }+ }+ for (path, net) in [(p, nets.0), (n, nets.1)] {+ // the first and last segments leave their own pads: those pads are the net's own, so any copper they touch is checked too+ 'segs: for w in path.windows(2) {+ for (what, on, s) in copper {+ if on.eq_ignore_ascii_case(net) { continue; }+ let d = s.dist(w[0], w[1]);+ if d < width / 2.0 + clearance - 1e-9 {+ out.push(json!({"problem": if what.contains('.') { "over_a_pad" } else { "over_copper" }, "net": net, "with": what, "withNet": on, "gapMm": r3((d - width / 2.0).max(0.0)),+ "fix": "add waypoints (via) that lead the pair out of the part and round other copper"}));+ break 'segs;+ }+ }+ }+ }+ out+}++/// route_pair: input {board, stack?, rules?, args: {pos, neg, from: {pos, neg}, to: {pos, neg}, via?: [[x, y]], layer?,+/// width?, gap?, diffOhms?, fanMm?, clearance?}}. The plan: `routeNet` for each net, the pair's `widthRule`, lengths,+/// skew, and `problems` (the plan answers success: false while there are any).+pub fn route_pair(input: &Value) -> Value {+ let st = match crate::input::board(input) { Ok(b) => b, Err(e) => return e };+ let args = &input["args"];+ let s = |k: &str| args[k].as_str().map(String::from);+ let (Some(pn), Some(nn)) = (s("pos"), s("neg")) else { return crate::input::refuse("bad_args", "pos and neg are the pair's two nets") };+ let pad = |o: &str, k: &str| args[o][k].as_str().map(String::from);+ let (Some(pf), Some(nf), Some(pt), Some(nt)) = (pad("from", "pos"), pad("from", "neg"), pad("to", "pos"), pad("to", "neg")) else {+ return crate::input::refuse("bad_args", "from: {pos: \"U1.3\", neg: \"U1.4\"} and to: {pos, neg} name the pads at each end");+ };+ let pads = st["pads"].as_array().cloned().unwrap_or_default();+ let key = |p: &Value| format!("{}.{}", p["ref"].as_str().unwrap_or(""), p["name"].as_str().unwrap_or(""));+ let at = |k: &str| pads.iter().find(|p| key(p).eq_ignore_ascii_case(k)).map(|p| (f(&p["x"]), f(&p["y"])));+ let (Some(a), Some(b), Some(c), Some(d)) = (at(&pf), at(&nf), at(&pt), at(&nt)) else {+ return crate::input::refuse("no_such_pad", &format!("one of {pf}, {nf}, {pt}, {nt} is not a pad on the board"));+ };+ let layer = args["layer"].as_str().unwrap_or("F.Cu").to_string();+ // width and gap: given, or solved from the stack-up for diffOhms on this layer+ let (mut width, mut gap, mut sized) = (args["width"].as_f64(), args["gap"].as_f64(), Value::Null);+ if let (Some(z), Some(stack)) = (args["diffOhms"].as_f64(), crate::input::stack(input)) {+ let geo = crate::impedance::geometry(&stack);+ let names = crate::coppermap::stack_layers(&stack);+ if let Some(i) = names.iter().position(|n| n.0 == layer) {+ if i < geo.len() {+ let rows = crate::impedance::widths(&geo[i..=i], None, Some(z), gap);+ if let (Some(w), Some(g)) = (rows[0]["diffWidth"].as_f64(), rows[0]["diffGap"].as_f64()) { width = width.or(Some(w)); gap = gap.or(Some(g)); sized = rows[0].clone(); }+ }+ }+ }+ let (Some(width), Some(gap)) = (width, gap) else { return crate::input::refuse("bad_args", "give width and gap (mm), or diffOhms with the stack to solve them") };+ let via: Vec<P> = args["via"].as_array().map(|a| a.iter().map(|p| (f(&p[0]), f(&p[1]))).collect()).unwrap_or_default();+ let fan = args["fanMm"].as_f64().unwrap_or(1.0);+ let (pp, np) = plan((a, c), (b, d), &via, width, gap, fan);+ // other nets' copper on the layer: pads by their outline, routed tracks and vias (a hatched pour's net-less pieces+ // re-pour round the pair)+ let rule = crate::fab::routing_clearance(&crate::input::rules(input));+ let clearance = args["clearance"].as_f64().unwrap_or(0.0).max(rule.unwrap_or(0.15));+ let mut copper: Vec<(String, String, Shape)> = pads.iter().filter(|p| p["layer"] == layer || p["layer"] == "*.Cu" || f(&p["drill"]) > 0.0)+ .map(|p| (key(p), p["net"].as_str().unwrap_or("").to_string(), pad_shape(p))).collect();+ for t in st["tracks"].as_array().into_iter().flatten().filter(|t| t["layer"] == json!(layer) && t["net"].as_str().map(|n| !n.is_empty()).unwrap_or(false)) {+ copper.push(("track".into(), t["net"].as_str().unwrap_or("").into(), Shape::Cap((f(&t["start"]["x"]), f(&t["start"]["y"])), (f(&t["end"]["x"]), f(&t["end"]["y"])), f(&t["width"]) / 2.0)));+ }+ for v in st["vias"].as_array().into_iter().flatten() {+ let c = (f(&v["position"]["x"]), f(&v["position"]["y"]));+ copper.push(("via".into(), v["net"].as_str().unwrap_or("").into(), Shape::Cap(c, c, f(&v["size"]) / 2.0)));+ }+ let problems = check(&pp, &np, &copper, (&pn, &nn), width, clearance);+ let path = |v: &[P], first: &str, last: &str| -> Value {+ let mut out = vec![json!({"pad": first})];+ for p in &v[1..v.len() - 1] { out.push(json!({"x": r3(p.0), "y": r3(p.1), "layer": layer})); }+ out.push(json!({"pad": last}));+ json!([out])+ };+ let (lp, ln) = (length(&pp), length(&np));+ let ok = problems.is_empty();+ json!({"success": ok, "errorCode": if ok { Value::Null } else { json!("pair_plan_blocked") }, "error": if ok { Value::Null } else { json!("the planned pair would run into copper or cross itself") },+ "problems": problems, "widthMm": r3(width), "gapMm": r3(gap), "sizedFor": sized, "layer": layer, "clearanceMm": clearance,+ "routeNet": [{"net": pn, "layer": layer, "width": r3(width), "paths": path(&pp, &pf, &pt)}, {"net": nn, "layer": layer, "width": r3(width), "paths": path(&np, &nf, &nt)}],+ "widthRule": {"kind": "width", "name": format!("Pair {pn} {nn}"), "scope1": format!("InNet('{pn}') Or InNet('{nn}')"), "min": r3(width * 0.9), "preferred": r3(width), "max": r3(width * 1.1)},+ "lengthsMm": {pn.clone(): r3(lp), nn.clone(): r3(ln)}, "skewMm": r3((lp - ln).abs()), "revision": st["revision"],+ "_hint": if ok { "A plan: send each routeNet entry to route_net (with expectedRevision: revision), then widthRule to add_rule so the board's default width rule does not flag the pair. skewMm is the length difference from the fan-outs and corners: net_lengths measures it routed, length_tune evens it." }+ else { "Nothing to apply while problems is not empty: add waypoints (via) that lead the pair out of the parts and round other copper, or change layer where the pair must cross, and plan again." }})+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn offset_keeps_the_pitch_round_a_corner() {+ let l = offset(&[(0.0, 0.0), (10.0, 0.0), (10.0, 10.0)], 0.5);+ assert!((l[0].1 - 0.5).abs() < 1e-9);+ assert!((l[1].0 - 9.5).abs() < 1e-9 && (l[1].1 - 0.5).abs() < 1e-9);+ assert!((l[2].0 - 9.5).abs() < 1e-9);+ }++ #[test]+ fn plan_puts_each_net_on_its_pads_side_and_check_catches_crossings_and_copper() {+ let (p, n) = plan(((0.0, 0.5), (20.0, 0.5)), ((0.0, -0.5), (20.0, -0.5)), &[], 0.2, 0.15, 1.0);+ assert!(p[1].1 > 0.0 && n[1].1 < 0.0);+ assert!((p[1].1 - n[1].1 - 0.35).abs() < 1e-9);+ assert!((length(&p) - length(&n)).abs() < 1e-9);+ let (x, y) = plan(((0.0, 0.5), (20.0, -0.5)), ((0.0, -0.5), (20.0, 0.5)), &[], 0.2, 0.15, 1.0);+ assert_eq!(check(&x, &y, &[], ("P", "N"), 0.2, 0.15)[0]["problem"], "pair_crosses");+ let pad = pad_shape(&json!({"x": 10.0, "y": 0.175, "sizeX": 0.6, "sizeY": 0.6, "shape": "round"}));+ assert_eq!(check(&p, &n, &[("U1.8".into(), "X".into(), pad)], ("P", "N"), 0.2, 0.15)[0]["problem"], "over_a_pad");+ let track = Shape::Cap((10.0, -3.0), (10.0, 3.0), 0.1);+ assert_eq!(check(&p, &n, &[("track".into(), "X".into(), track)], ("P", "N"), 0.2, 0.15)[0]["problem"], "over_copper");+ assert!(check(&p, &n, &[], ("P", "N"), 0.2, 0.15).is_empty());+ }++ #[test]+ fn the_verb_answers_route_net_arguments_for_both_nets() {+ let pad = |r: &str, n: &str, x: f64, y: f64, net: &str| json!({"ref": r, "name": n, "x": x, "y": y, "sizeX": 0.3, "sizeY": 0.3, "rotation": 0, "layer": "F.Cu", "drill": 0, "net": net, "shape": "rect"});+ let b = json!({"revision": "r7", "pads": [pad("U1", "1", 0.0, 0.5, "USB_P"), pad("U1", "2", 0.0, -0.5, "USB_N"), pad("J1", "1", 20.0, 0.5, "USB_P"), pad("J1", "2", 20.0, -0.5, "USB_N")]});+ let r = route_pair(&json!({"board": b, "args": {"pos": "USB_P", "neg": "USB_N", "from": {"pos": "U1.1", "neg": "U1.2"}, "to": {"pos": "J1.1", "neg": "J1.2"}, "width": 0.2, "gap": 0.15}}));+ assert_eq!(r["success"], json!(true), "{r}");+ assert_eq!(r["routeNet"][0]["paths"][0][0], json!({"pad": "U1.1"}));+ assert_eq!(r["skewMm"], json!(0.0));+ assert_eq!(r["widthRule"]["preferred"], json!(0.2));+ assert_eq!(route_pair(&json!({"board": b, "args": {"pos": "USB_P", "neg": "USB_N", "from": {"pos": "U9.1", "neg": "U1.2"}, "to": {"pos": "J1.1", "neg": "J1.2"}, "width": 0.2, "gap": 0.15}}))["errorCode"], "no_such_pad");+ }+}
bridge-rs/vendor/adom-eda-checks/src/report.rsadded+180@@ -0,0 +1,180 @@+//! One shareable page per board: every check the engine has, run against one bundle, written as a single self-contained+//! HTML page with the board's picture when the bridge passes one. From the Altium bridge's report.rs.+use serde_json::{json, Value};++fn esc(s: &str) -> String { s.replace('&', "&").replace('<', "<").replace('>', ">").replace('"', """) }+fn txt(v: &Value) -> String {+ match v {+ Value::String(s) => s.clone(),+ Value::Null => String::new(),+ // lists read as plain text, not JSON+ Value::Array(a) => a.iter().map(txt).filter(|s| !s.is_empty()).collect::<Vec<_>>().join(", "),+ other => other.to_string(),+ }+}++/// One section of the page: a title, a verdict (true, false, None = information) and rows of (label, value). Pure.+pub struct Section { pub title: String, pub ok: Option<bool>, pub summary: String, pub rows: Vec<(String, String)> }++/// The sections from the checks' replies (any may be an error reply: it shows as such). Pure.+pub fn sections(c: &Value) -> Vec<Section> {+ let mut out = Vec::new();+ let failed = |r: &Value| r.get("success").and_then(|b| b.as_bool()) == Some(false);+ let err = |title: &str, r: &Value| Section { title: title.into(), ok: None, summary: format!("not run: {}", txt(r.get("error").unwrap_or(&Value::Null))), rows: vec![] };+ // design rules+ let d = &c["drc"];+ out.push(if d.is_null() { Section { title: "Design rules (the tool's DRC)".into(), ok: None, summary: "not run: pass the tool's DRC reply (run_drc) as drc".into(), rows: vec![] } } else if failed(d) { err("Design rules (the tool's DRC)", d) } else {+ // each tool counts in its own words: Altium errors/unconnected, Fusion violationCount/airwires+ let errs = d["errors"].as_i64().or(d["violationCount"].as_i64());+ let open = d["unconnected"].as_i64().or(d["airwires"].as_i64()).or(d["unrouted"].as_i64());+ let shown = |v: Option<i64>| v.map(|n| n.to_string()).unwrap_or_else(|| "?".into());+ Section { title: "Design rules (the tool's DRC)".into(), ok: match (errs, open) { (Some(e), Some(u)) => Some(e == 0 && u == 0), (Some(e), None) if e > 0 => Some(false), _ => None },+ summary: format!("{} violations, {} unconnected", shown(errs), shown(open)),+ rows: d["violations"].as_array().cloned().unwrap_or_default().iter().take(30).map(|v| (txt(&v["rule"]), txt(&v["objects"]))).collect() } });+ let f = &c["fab"];+ // the vendor as each finding's source names it, else the record's own name+ let vendor = f["outsideLimits"][0]["source"]["name"].as_str().or(f["fab"]["vendor"].as_str()).or(f["fab"]["name"].as_str()).unwrap_or("").to_string();+ let fab_title = format!("Fab limits ({})", vendor.chars().take(40).collect::<String>());+ let fab_title = if fab_title == "Fab limits ()" { "Fab limits".to_string() } else { fab_title };+ out.push(if failed(f) { err(&fab_title, f) } else {+ let mut rows: Vec<(String, String)> = f["outsideLimits"].as_array().cloned().unwrap_or_default().iter().map(|o| (txt(&o["limit"]), format!("board {} mm, limit {} mm", txt(&o["boardMm"]), txt(&o["limitMm"])))).collect();+ for k in ["track", "viaDrill", "padHole", "edgeClearance", "silkText", "boardSize"] { if let Some(m) = f["measured"].get(k) { rows.push((format!("measured {k}"), format!("{} mm", txt(&m["mm"])))); } }+ Section { title: fab_title.clone(), ok: f["fits"].as_bool(), summary: format!("{} outside the fab's limits", f["outsideLimits"].as_array().map(|a| a.len()).unwrap_or(0)), rows } });+ let a = &c["assembly"];+ out.push(if failed(a) { err("JLCPCB assembly", a) } else {+ let rows = ["economic", "standard"].iter().flat_map(|t| a[*t]["rules"].as_array().cloned().unwrap_or_default().into_iter().filter(|r| r["ok"] == json!(false)).map(move |r| (format!("{t}: {}", txt(&r["rule"])), txt(&r["detail"])))).collect();+ Section { title: "JLCPCB assembly".into(), ok: Some(!a["service"].is_null()), summary: format!("tier: {}", if a["service"].is_null() { "none passes yet".to_string() } else { txt(&a["service"]) }), rows } });+ let s = &c["schematic"];+ out.push(if failed(s) { err("Schematic review", s) } else {+ let rows = s["errors"].as_array().cloned().unwrap_or_default().iter().chain(s["warnings"].as_array().cloned().unwrap_or_default().iter()).take(30)+ .map(|w| (txt(&w["check"]), [w.get("pin"), w.get("net"), w.get("ics")].iter().flatten().map(|v| txt(v)).collect::<Vec<_>>().join(" "))).collect();+ Section { title: "Schematic review".into(), ok: s["ok"].as_bool(), summary: format!("{} errors, {} warnings, {} pins on {} nets", s["errors"].as_array().map(|a| a.len()).unwrap_or(0), s["warnings"].as_array().map(|a| a.len()).unwrap_or(0), txt(&s["pins"]), txt(&s["nets"])), rows } });+ let p = &c["pinPad"];+ out.push(if failed(p) { err("Symbols against footprints", p) } else {+ Section { title: "Symbols against footprints".into(), ok: p["ok"].as_bool(), summary: format!("{} of {} parts match", txt(&p["matching"]), txt(&p["partsChecked"])),+ rows: p["mismatches"].as_array().cloned().unwrap_or_default().iter().map(|m| (txt(&m["ref"]), format!("pins without pad {} / pads without pin {}", txt(&m["pinsWithoutPad"]), txt(&m["padsWithoutPin"])))).collect() } });+ let i = &c["impedance"];+ out.push(if failed(i) { err("Controlled impedance", i) } else {+ Section { title: "Controlled impedance (50 ohm, 90 ohm pairs)".into(), ok: None, summary: "track widths from the stack-up".into(),+ rows: i["layers"].as_array().cloned().unwrap_or_default().iter().map(|l| (txt(&l["layer"]), format!("{}: 50 ohm {} mm; 90 ohm pair {} / {} mm", txt(&l["model"]), txt(&l["width"]), txt(&l["diffWidth"]), txt(&l["diffGap"])))).collect() } });+ let r = &c["returnPath"];+ out.push(if failed(r) { err("Return paths", r) } else {+ Section { title: "Return paths".into(), ok: r["ok"].as_bool(), summary: format!("{} net-layer runs over a gap in the reference copper", r["nets"].as_array().map(|a| a.len()).unwrap_or(0)),+ rows: r["nets"].as_array().cloned().unwrap_or_default().iter().take(20).map(|n| (format!("{} on {}", txt(&n["net"]), txt(&n["layer"])), format!("{} mm of {} mm ({}%)", txt(&n["unreferencedMm"]), txt(&n["lengthMm"]), txt(&n["percent"])))).collect() } });+ let b = &c["balance"];+ out.push(if failed(b) { err("Copper balance", b) } else {+ Section { title: "Copper balance".into(), ok: b["balanced"].as_bool(), summary: "copper share per layer; mirrored pairs within 20 points".into(),+ rows: b["layers"].as_array().cloned().unwrap_or_default().iter().map(|l| (txt(&l["layer"]), format!("{}% ({} mm2)", txt(&l["percent"]), txt(&l["copperMm2"])))).collect() } });+ let h = &c["heights"];+ out.push(if failed(h) { err("3D heights and clearance", h) } else {+ let mut rows: Vec<(String, String)> = h["heights"].as_array().cloned().unwrap_or_default().iter().take(8).map(|x| (txt(&x["ref"]), format!("{} mm, {}", txt(&x["heightMm"]), txt(&x["side"])))).collect();+ for col in h["collisions"].as_array().cloned().unwrap_or_default() { rows.push(("collision".into(), format!("{} by {} mm", txt(&col["parts"]), txt(&col["overlapMm"])))); }+ Section { title: "3D heights and clearance".into(), ok: Some(h["collisions"].as_array().map(|a| a.is_empty()).unwrap_or(true)), summary: format!("{} bodies; {} parts without a 3D body", txt(&h["bodies"]), h["noBody"].as_array().map(|a| a.len()).unwrap_or(0)), rows } });+ let v = &c["review"];+ out.push(if failed(v) { err("Design review", v) } else {+ Section { title: "Design review".into(), ok: Some(v["counts"]["error"].as_i64() == Some(0)), summary: format!("{} errors, {} warnings, {} notes", txt(&v["counts"]["error"]), txt(&v["counts"]["warning"]), txt(&v["counts"]["info"])),+ rows: v["findings"].as_array().cloned().unwrap_or_default().iter().take(30).map(|x| (format!("{} ({})", txt(&x["check"]), txt(&x["severity"])), txt(&x["message"]))).collect() } });+ out+}++/// The page. Dark by default with a light scheme, tokens on :root. Pure.+pub fn page(board: &str, when: &str, version: &str, shot: Option<&str>, secs: &[Section]) -> String {+ let badge = |ok: Option<bool>| match ok { Some(true) => "<span class=\"b ok\">pass</span>", Some(false) => "<span class=\"b no\">needs work</span>", None => "<span class=\"b info\">info</span>" };+ let mut body = String::new();+ for s in secs {+ body.push_str(&format!("<section><h2>{} {}</h2><p class=\"sum\">{}</p>", esc(&s.title), badge(s.ok), esc(&s.summary)));+ if !s.rows.is_empty() {+ body.push_str("<table>");+ for (k, v) in &s.rows { body.push_str(&format!("<tr><th>{}</th><td>{}</td></tr>", esc(k), esc(v))); }+ body.push_str("</table>");+ }+ body.push_str("</section>");+ }+ let pass = secs.iter().filter(|s| s.ok == Some(true)).count();+ let work = secs.iter().filter(|s| s.ok == Some(false)).count();+ let img = shot.map(|b| format!("<img alt=\"the board\" src=\"data:image/png;base64,{b}\">")).unwrap_or_default();+ format!(r#"<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">+<meta name="color-scheme" content="dark"><title>Board report</title><style>+:root{{--bg:#101418;--panel:#182028;--ink:#e6edf3;--dim:#9aa7b4;--line:#2a3542;--ok:#3fb950;--no:#f0883e;--info:#58a6ff}}+body{{margin:0;background:var(--bg);color:var(--ink);font:15px/1.5 system-ui,-apple-system,Segoe UI,sans-serif}}+main{{max-width:960px;margin:0 auto;padding:24px 16px}} h1{{font-size:24px;margin:0 0 4px}} .meta{{color:var(--dim);margin:0 0 16px}}+img{{width:100%;border:1px solid var(--line);border-radius:8px;margin:8px 0 16px}}+section{{background:var(--panel);border:1px solid var(--line);border-radius:8px;padding:12px 16px;margin:12px 0}}+h2{{font-size:17px;margin:0;display:flex;gap:8px;align-items:center}} .sum{{color:var(--dim);margin:4px 0 8px}}+.b{{font-size:12px;border-radius:999px;padding:1px 8px;border:1px solid}} .ok{{color:var(--ok)}} .no{{color:var(--no)}} .info{{color:var(--info)}}+table{{width:100%;border-collapse:collapse;font-size:13px}} th,td{{text-align:left;padding:4px 6px;border-top:1px solid var(--line);vertical-align:top;overflow-wrap:anywhere}} th{{width:34%;color:var(--dim);font-weight:500}}+</style></head><body><main><h1>{}</h1><p class="meta">{} · {} pass, {} need work · {}</p>{}{}</main></body></html>"#,+ esc(board), esc(when), pass, work, esc(version), img, body)+}++/// board_report: input {board, stack?, pours?, rules?, bodies?, fab?, sheetParts?, netlist?, drc?, picture?, args: {title?,+/// date?, lcscMissing?, panelMm?, gridMm?, alwaysChecked?}}; the last four go to assembly_check and review_board. Every check the engine has, run on this bundle, as one self-contained HTML page (`text`), with the tool's+/// own DRC reply (`drc`) and a base64 PNG of the board (`picture`) when the bridge passes them. A section whose input+/// is missing says so instead of passing.+pub fn board_report(input: &Value) -> Value {+ if let Err(e) = crate::input::board(input) { return e; }+ let with = |args: Value| { let mut i = input.clone(); i["args"] = args; i };+ let need = |k: &str, what: &str| crate::input::part(input, k).is_none().then(|| json!({"success": false, "error": format!("pass {what} as {k}")}));+ let mut c = json!({});+ c["schematic"] = need("sheetParts", "the sheets' parts").or_else(|| need("netlist", "the compiled netlist")).unwrap_or_else(|| crate::run("schematic_review", &with(json!({}))));+ c["pinPad"] = need("sheetParts", "the sheets' parts").unwrap_or_else(|| crate::run("pin_pad_check", &with(json!({}))));+ c["fab"] = need("fab", "a pcb-design-rules record").unwrap_or_else(|| crate::run("fab_check", &with(json!({}))));+ // the bridge's BOM lines without an LCSC number, when it passes them (fusion-lane: without, the tier read economic)+ c["assembly"] = crate::run("assembly_check", &with(json!({"lcscMissing": input["args"]["lcscMissing"], "panelMm": input["args"]["panelMm"]})));+ c["impedance"] = need("stack", "the stack-up").unwrap_or_else(|| crate::run("impedance", &with(json!({"z0": 50, "diff": 90}))));+ c["returnPath"] = need("stack", "the stack-up").unwrap_or_else(|| crate::run("return_path", &with(json!({}))));+ c["balance"] = need("stack", "the stack-up").unwrap_or_else(|| crate::run("copper_balance", &with(json!({}))));+ c["heights"] = need("bodies", "the 3D bodies").unwrap_or_else(|| crate::run("height_check", &with(json!({}))));+ c["review"] = crate::run("review_board", &with(json!({"gridMm": input["args"]["gridMm"], "alwaysChecked": input["args"]["alwaysChecked"]})));+ c["drc"] = crate::input::part(input, "drc").unwrap_or(Value::Null);+ let secs = sections(&c);+ let args = &input["args"];+ let title = args["title"].as_str().unwrap_or("board");+ let date = args["date"].as_str().map(String::from).unwrap_or_else(|| crate::writers::ipc2581::now().replace('T', " ").replace('Z', " UTC"));+ let picture = input["picture"].as_str();+ let text = page(title, &date, &format!("adom-eda-checks {}", crate::VERSION), picture, &secs);+ json!({"success": true, "text": text, "sections": secs.iter().map(|s| json!({"title": s.title, "ok": s.ok, "summary": s.summary})).collect::<Vec<_>>(),+ "pass": secs.iter().filter(|s| s.ok == Some(true)).count(), "needsWork": secs.iter().filter(|s| s.ok == Some(false)).count(), "picture": picture.is_some(),+ "_hint": "text is a single self-contained HTML page: the bridge writes it beside the project and opens or sends it. Each section's verdict comes from the engine check named in it: run that check for the full reply. A section marked 'not run' names the companion to pass."})+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn sections_read_every_check_and_the_page_escapes() {+ let c = json!({"drc": {"success": true, "errors": 0, "unconnected": 0, "violations": []},+ "fab": {"success": true, "fits": false, "fab": {"vendor": "JLCPCB"}, "outsideLimits": [{"limit": "minTrack", "boardMm": 0.08, "limitMm": 0.1}], "measured": {"track": {"mm": 0.08}}},+ "assembly": {"success": false, "error": "no outline"},+ "schematic": {"success": true, "ok": true, "errors": [], "warnings": [{"check": "single_pin_net", "net": "<X>"}], "pins": 10, "nets": 4}});+ let s = sections(&c);+ assert_eq!(s[0].ok, Some(true));+ assert_eq!((s[1].title.as_str(), s[1].ok), ("Fab limits (JLCPCB)", Some(false)));+ assert!(s[2].summary.starts_with("not run"));+ let html = page("lane", "2026-10-26", "adom-eda-checks", None, &s);+ assert!(html.contains("<X>") && !html.contains("<X>"));+ assert_eq!(txt(&json!(["Pad U2-5", "Pad U3-4"])), "Pad U2-5, Pad U3-4");+ }++ #[test]+ fn the_report_runs_the_engines_checks_and_names_what_is_missing() {+ let st = json!({"outline": [[0, 0], [40, 0], [40, 20], [0, 20]], "components": [{"ref": "R1", "x": 10.0, "y": 10.0, "rotation": 0.0, "side": "top", "pattern": "0603"}],+ "pads": [{"ref": "R1", "name": "1", "x": 9.2, "y": 10.0, "sizeX": 0.8, "sizeY": 0.9, "rotation": 0, "layer": "F.Cu", "drill": 0, "net": "A", "shape": "rect"},+ {"ref": "R1", "name": "2", "x": 10.8, "y": 10.0, "sizeX": 0.8, "sizeY": 0.9, "rotation": 0, "layer": "F.Cu", "drill": 0, "net": "B", "shape": "rect"}]});+ let r = board_report(&json!({"board": st, "args": {"title": "Test", "date": "2026-10-29 12:00 UTC"}}));+ assert_eq!(r["success"], json!(true), "{r}");+ let text = r["text"].as_str().unwrap();+ assert!(text.starts_with("<!doctype html>") && text.contains("<h1>Test</h1>"));+ let sec = |t: &str| r["sections"].as_array().unwrap().iter().find(|s| s["title"].as_str().unwrap_or("").starts_with(t)).cloned().unwrap();+ assert!(sec("Design rules")["summary"].as_str().unwrap().contains("pass the tool's DRC"));+ assert!(sec("Fab limits")["summary"].as_str().unwrap().contains("not run"));+ assert_eq!(sec("Design review")["ok"], json!(true), "{r}");+ assert!(sec("JLCPCB assembly")["summary"].as_str().unwrap().starts_with("tier"));+ // Fusion's DRC counts in its own words; the bridge's LCSC gaps reach the assembly section+ let f = board_report(&json!({"board": st, "drc": {"violationCount": 3, "airwires": 0}, "args": {"lcscMissing": 2}}));+ let sec = |t: &str| f["sections"].as_array().unwrap().iter().find(|s| s["title"].as_str().unwrap_or("").starts_with(t)).cloned().unwrap();+ assert_eq!((sec("Design rules")["summary"].clone(), sec("Design rules")["ok"].clone()), (json!("3 violations, 0 unconnected"), json!(false)));+ assert_eq!(sec("JLCPCB assembly")["ok"], json!(false), "{f}");+ }+}
bridge-rs/vendor/adom-eda-checks/src/review.rsadded+247@@ -0,0 +1,247 @@+//! Design review: small checks, each a pure function over the board model, the sheet parts and the board's rules. From+//! the Altium bridge's review.rs, on the standard model: components off the board are judged against the outline+//! polygon (Altium's read carried only a bounding box), and rules are classed from a standard kind, a descriptor's+//! leading words or Altium's rule ordinal. What the model cannot answer is named in `notImplemented`.+use serde_json::{json, Map, Value};+use std::collections::{BTreeMap, BTreeSet};++fn f(v: &Value) -> f64 { v.as_f64().unwrap_or(0.0) }+fn s<'a>(v: &'a Value, k: &str) -> &'a str { v.get(k).and_then(|x| x.as_str()).unwrap_or("") }++const PLACEHOLDER_VALUES: [&str; 12] = ["comment", "value", "*", "?", "n/a", "na", "tbd", "xxx", "component", "designator", "part", "unknown"];++/// Adom house rule: Mouser is the preferred vendor, and every purchased part carries Mouser, DigiKey and LCSC numbers.+const VENDOR_PATTERNS: [(&str, &[&str]); 3] = [("Mouser", &["mouser"]), ("DigiKey", &["digikey", "digi-key", "digi key"]), ("LCSC", &["lcsc", "jlcpcb"])];++/// Designator prefixes that carry no vendor part number.+const NON_PURCHASED: [&str; 8] = ["TP", "FID", "MH", "H", "LOGO", "NET", "PWR", "GND"];++/// The rules a fab relies on: clearance, width, hole size, short circuit.+const CRITICAL: [&str; 4] = ["clearance", "width", "hole size", "short circuit"];++pub const NOT_IMPLEMENTED: [(&str, &str); 4] = [+ ("unused_mechanical_layers", "the board model carries no mechanical layers"),+ ("unrouted_connections", "needs the ratsnest: routing_drc or the tool's DRC"),+ ("silkscreen_over_pad", "silk_designators reports labels on pads (onPadsBefore)"),+ ("missing_decoupling", "schematic_review checks each IC supply for a capacitor to ground"),+];++fn finding(check: &str, severity: &str, key: (&str, &str), message: String) -> Value {+ let mut v = json!({"check": check, "severity": severity, "message": message});+ if !key.1.is_empty() { v[key.0] = json!(key.1); }+ v+}++fn purchased(designator: &str) -> bool {+ let prefix: String = designator.to_uppercase().chars().take_while(|c| c.is_ascii_alphabetic()).collect();+ !NON_PURCHASED.contains(&prefix.as_str())+}++fn params_of(c: &Value) -> Vec<(String, String)> {+ c["params"].as_array().map(|a| a.iter().filter_map(|p| {+ let name = p["name"].as_str()?.trim().to_lowercase();+ (!name.is_empty()).then(|| (name, p["value"].as_str().unwrap_or("").trim().to_string()))+ }).collect()).unwrap_or_default()+}++/// A rule's class: a standard kind, the descriptor's leading words, or Altium's rule ordinal. Pure.+pub fn rule_class(r: &Value) -> String {+ if let Some(k) = r["kind"].as_str() {+ let k = k.to_lowercase();+ for c in CRITICAL { if k.replace(['_', '-'], " ").contains(c) || (c == "hole size" && k == "hole") || (c == "short circuit" && k == "short") { return c.into(); } }+ return k;+ }+ let d = s(r, "descriptor").to_lowercase().replace('-', " ");+ for (prefix, c) in [("clearance constraint", "clearance"), ("width constraint", "width"), ("hole size constraint", "hole size"), ("short circuit constraint", "short circuit")] {+ if d.starts_with(prefix) { return c.into(); }+ }+ match r["kind"].as_i64() {+ Some(0) => return "clearance".into(), Some(2) => return "width".into(), Some(42) => return "hole size".into(), Some(15) => return "short circuit".into(),+ // any other Altium ordinal is no critical rule: its descriptor names it ("Routing Topology Rule (Shortest)" is+ // no short-circuit rule, "Polygon Connect (Conductor Width ...)" no width rule)+ Some(_) => return d.split('(').next().unwrap_or("").trim().to_string(),+ None => {}+ }+ // a tool's own rule names (Fusion's EAGLE rules: wire-wire, pad-via, minimum width, minimum drill, ...)+ let t = format!("{} {} {}", s(r, "kindName"), s(r, "name"), d).to_lowercase().replace(['_', '-'], " ");+ if t.contains("short circuit") || t.contains("shortcircuit") { return "short circuit".into(); }+ if (t.contains("width") || t.contains("minimum wire")) && !t.contains("annular") && !t.contains("conductor") { return "width".into(); }+ if t.contains("drill") || t.contains("hole size") || t.contains("holesize") { return "hole size".into(); }+ let copper = !["silk", "mask", "paste", "edge", "board", "courtyard", "component", "hole to hole", "plane"].iter().any(|w| t.contains(w));+ if copper && (t.contains("clearance") || t.contains("wire wire") || t.contains("pad via") || t.contains("pad pad")) { return "clearance".into(); }+ d.split('(').next().unwrap_or("").trim().to_string()+}++/// The checks over the board model, the sheet parts (read_sheet_file's components, or none) and the rules. Returns the+/// findings (errors first), the checks run and those skipped with why. Pure.+pub fn run_checks(st: &Value, sheet: Option<&[Value]>, rules: &[Value], grid: f64, edge: f64, wanted: Option<&[String]>, always: &[String]) -> (Vec<Value>, Vec<String>, Map<String, Value>) {+ let comps = st["components"].as_array().cloned().unwrap_or_default();+ let pads = st["pads"].as_array().cloned().unwrap_or_default();+ let ring = crate::coppermap::outline_ring(st);+ let want = |n: &str| wanted.map(|w| w.iter().any(|x| x == n)).unwrap_or(true);+ let (mut out, mut ran, mut skipped) = (Vec::new(), Vec::new(), Map::new());+ let mut run = |name: &str, needs: Option<&str>, out: &mut Vec<Value>, f: &dyn Fn() -> Vec<Value>| {+ if !want(name) { return; }+ if let Some(why) = needs { skipped.insert(name.into(), json!(why)); return; }+ ran.push(name.to_string());+ out.extend(f());+ };+ let placed: Vec<&Value> = comps.iter().filter(|c| pads.iter().any(|p| p["ref"] == c["ref"])).collect();+ let own = |r: &str| -> Vec<(f64, f64)> { pads.iter().filter(|p| p["ref"].as_str() == Some(r)).map(|p| (f(&p["x"]), f(&p["y"]))).collect() };+ run("placeholder_values", None, &mut out, &|| placed.iter().filter_map(|c| {+ let v = c.get("value").or(c.get("comment")).and_then(|v| v.as_str()).unwrap_or("").trim().to_string();+ PLACEHOLDER_VALUES.contains(&v.to_lowercase().as_str()).then(|| finding("placeholder_values", "error", ("designator", s(c, "ref")), format!("{} has the placeholder value {v:?}: it will reach the BOM as is.", s(c, "ref"))))+ }).collect());+ run("single_pin_nets", None, &mut out, &|| {+ let mut n: BTreeMap<&str, usize> = BTreeMap::new();+ for p in &pads { if let Some(net) = p["net"].as_str().filter(|x| !x.is_empty()) { *n.entry(net).or_default() += 1; } }+ n.into_iter().filter(|(_, k)| *k == 1).map(|(net, _)| finding("single_pin_nets", "warning", ("net", net), format!("Net {net:?} has a single pad: it connects to nothing."))).collect()+ });+ run("off_grid_components", if grid > 0.0 { None } else { Some("no placement grid: pass gridMm (a 5 mil grid is 0.127)") }, &mut out, &|| placed.iter().filter_map(|c| {+ let off = |v: f64| { let k = v / grid; (k - k.round()).abs() * grid > 0.001 };+ (off(f(&c["x"])) || off(f(&c["y"]))).then(|| finding("off_grid_components", "info", ("designator", s(c, "ref")), format!("{} sits at ({}, {}) mm, off the {grid} mm grid.", s(c, "ref"), f(&c["x"]), f(&c["y"]))))+ }).collect());+ run("duplicate_designators", None, &mut out, &|| {+ let mut v = Vec::new();+ let mut count = |label: &str, names: Vec<String>| {+ let mut seen: BTreeMap<String, u32> = BTreeMap::new();+ for d in names.into_iter().filter(|d| !d.is_empty()) { *seen.entry(d).or_default() += 1; }+ for (d, n) in seen { if n > 1 { v.push(finding("duplicate_designators", "error", ("designator", &d), format!("Designator {d} occurs {n} times on the {label}."))); } }+ };+ count("board", comps.iter().map(|c| s(c, "ref").to_string()).collect());+ // a multi-part chip appears once per part on the sheets: count each designator once per part id+ if let Some(sh) = sheet {+ let mut uniq: BTreeSet<(String, String)> = BTreeSet::new();+ let names: Vec<String> = sh.iter().filter(|c| uniq.insert((s(c, "designator").to_string(), format!("{}{}", s(c, "uniqueId"), c["partId"])))).map(|c| s(c, "designator").to_string()).collect();+ let multi: BTreeSet<String> = sh.iter().filter(|c| c["partCount"].as_i64().unwrap_or(1) > 1).map(|c| s(c, "designator").to_string()).collect();+ count("sheets", names.into_iter().filter(|d| !multi.contains(d)).collect());+ }+ v+ });+ run("components_outside_board_outline", if ring.len() < 3 { Some("the board has no outline") } else { None }, &mut out, &|| placed.iter().filter_map(|c| {+ let ps = own(s(c, "ref"));+ let outside = ps.iter().filter(|p| !crate::route::inside(**p, &ring)).count();+ (outside > 0).then(|| finding("components_outside_board_outline", "error", ("designator", s(c, "ref")),+ format!("{} has {outside} of {} pad(s) outside the board outline.", s(c, "ref"), ps.len())))+ }).collect());+ run("components_near_board_edge", if ring.len() < 3 { Some("the board has no outline") } else { None }, &mut out, &|| placed.iter().filter_map(|c| {+ let ps = own(s(c, "ref"));+ if ps.iter().any(|p| !crate::route::inside(*p, &ring)) { return None; }+ let seg = |p: (f64, f64), a: (f64, f64), b: (f64, f64)| {+ let (dx, dy) = (b.0 - a.0, b.1 - a.1);+ let l2 = dx * dx + dy * dy;+ let t = if l2 == 0.0 { 0.0 } else { (((p.0 - a.0) * dx + (p.1 - a.1) * dy) / l2).clamp(0.0, 1.0) };+ ((p.0 - a.0 - t * dx).powi(2) + (p.1 - a.1 - t * dy).powi(2)).sqrt()+ };+ let d = ps.iter().map(|p| (0..ring.len()).map(|i| seg(*p, ring[i], ring[(i + 1) % ring.len()])).fold(f64::MAX, f64::min)).fold(f64::MAX, f64::min);+ (d < edge).then(|| finding("components_near_board_edge", "warning", ("designator", s(c, "ref")), format!("{} has a pad centre {:.3} mm from the board edge (under {edge} mm).", s(c, "ref"), d)))+ }).collect());+ let no_sheet = sheet.is_none().then_some("no sheet parts: pass sheetParts");+ let sheet_parts: Vec<Value> = sheet.map(|x| x.to_vec()).unwrap_or_default();+ run("vendor_part_numbers", no_sheet, &mut out, &|| sheet_parts.iter().filter(|c| purchased(s(c, "designator"))).filter_map(|c| {+ let blob = params_of(c).iter().map(|(k, v)| format!("{k} {v}")).collect::<Vec<_>>().join(" ").to_lowercase();+ let missing: Vec<&str> = VENDOR_PATTERNS.iter().filter(|(_, keys)| !keys.iter().any(|k| blob.contains(k))).map(|(v, _)| *v).collect();+ if missing.is_empty() { return None; }+ let mut x = finding("vendor_part_numbers", "warning", ("designator", s(c, "designator")), format!("{} has no {} part number (house rule: Mouser preferred, all three required).", s(c, "designator"), missing.join(" / ")));+ x["missing"] = json!(missing);+ Some(x)+ }).collect());+ run("missing_datasheets", no_sheet, &mut out, &|| sheet_parts.iter().filter(|c| purchased(s(c, "designator"))).filter_map(|c| {+ let has = params_of(c).iter().any(|(k, _)| k.contains("datasheet") || k == "helpurl");+ (!has).then(|| finding("missing_datasheets", "info", ("designator", s(c, "designator")), format!("{} has no Datasheet parameter.", s(c, "designator"))))+ }).collect());+ run("schematic_placeholder_values", no_sheet, &mut out, &|| sheet_parts.iter().filter_map(|c| {+ let v = s(c, "comment").trim().to_string();+ PLACEHOLDER_VALUES.contains(&v.to_lowercase().as_str()).then(|| finding("schematic_placeholder_values", "error", ("designator", s(c, "designator")), format!("{} on the sheet has the placeholder Comment {v:?}.", s(c, "designator"))))+ }).collect());+ let no_rules = rules.is_empty().then_some("no rules: pass read_rules as rules");+ run("disabled_design_rules", no_rules, &mut out, &|| rules.iter().filter(|r| r["enabled"] == json!(false)).map(|r| {+ let c = rule_class(r);+ let sev = if CRITICAL.contains(&c.as_str()) { "error" } else { "warning" };+ finding("disabled_design_rules", sev, ("rule", s(r, "name")), format!("Design rule {:?} ({c}) is disabled: DRC passes without ever applying it.", s(r, "name")))+ }).collect());+ run("missing_critical_rules", no_rules, &mut out, &|| {+ // a tool that always checks a class (EAGLE's DRC always checks shorts) passes it in alwaysChecked+ let mut have: BTreeSet<String> = rules.iter().filter(|r| r["enabled"] != json!(false)).map(rule_class).collect();+ have.extend(always.iter().map(|a| a.to_lowercase().replace(['_', '-'], " ")));+ CRITICAL.iter().filter(|c| !have.contains(**c)).map(|c| finding("missing_critical_rules", "error", ("rule", c), format!("No enabled {c} rule on this board."))).collect()+ });+ run("duplicate_rule_priority", no_rules, &mut out, &|| {+ let mut seen: BTreeMap<(String, String), Vec<String>> = BTreeMap::new();+ for r in rules.iter().filter(|r| r["enabled"] != json!(false) && !r["priority"].is_null()) { seen.entry((rule_class(r), r["priority"].to_string())).or_default().push(s(r, "name").to_string()); }+ seen.into_iter().filter(|(_, n)| n.len() > 1).map(|((c, p), mut n)| { n.sort(); finding("duplicate_rule_priority", "info", ("rule", &n.join(", ")), format!("{} enabled {c} rules share priority {p} ({}): which one wins is not readable from the board.", n.len(), n.join(", "))) }).collect()+ });+ run("components_without_footprint", None, &mut out, &|| placed.iter().filter(|c| s(c, "pattern").trim().is_empty())+ .map(|c| finding("components_without_footprint", "warning", ("designator", s(c, "ref")), format!("{} has no footprint pattern name: it cannot be matched back to a library.", s(c, "ref")))).collect());+ let order = |x: &Value| match s(x, "severity") { "error" => 0, "warning" => 1, _ => 2 };+ out.sort_by(|a, b| order(a).cmp(&order(b)).then_with(|| s(a, "check").cmp(s(b, "check"))));+ (out, ran, skipped)+}++/// review_board: input {board, sheetParts?, rules?, args: {checks?, gridMm?, edgeMm?, alwaysChecked?: ["short circuit", ...]}}.+pub fn review_board(input: &Value) -> Value {+ let st = match crate::input::board(input) { Ok(b) => b, Err(e) => return e };+ let args = &input["args"];+ let sheet: Option<Vec<Value>> = crate::input::part(input, "sheetParts").and_then(|p| p.get("components").or(Some(&p)).and_then(|x| x.as_array()).cloned());+ let wanted: Option<Vec<String>> = args["checks"].as_array().map(|a| a.iter().filter_map(|x| x.as_str().map(String::from)).collect());+ let always: Vec<String> = args["alwaysChecked"].as_array().map(|a| a.iter().filter_map(|x| x.as_str().map(String::from)).collect()).unwrap_or_default();+ let (findings, ran, skipped) = run_checks(&st, sheet.as_deref(), &crate::input::rules(input), args["gridMm"].as_f64().unwrap_or(0.0), args["edgeMm"].as_f64().unwrap_or(0.5), wanted.as_deref(), &always);+ let mut counts = json!({"error": 0, "warning": 0, "info": 0});+ for x in &findings { let k = s(x, "severity").to_string(); counts[&k] = json!(counts[&k].as_i64().unwrap_or(0) + 1); }+ json!({"success": true, "findings": findings, "counts": counts, "checks": ran, "skipped": skipped,+ "notImplemented": NOT_IMPLEMENTED.iter().map(|(k, v)| (k.to_string(), json!(v))).collect::<Map<String, Value>>(),+ "_hint": "Findings are errors first. skipped names the checks a missing companion stopped (pass sheetParts and rules for all of them); notImplemented names what this review does not judge, so silence there is not a clean board."})+}++#[cfg(test)]+mod tests {+ use super::*;++ fn pad(r: &str, n: &str, x: f64, y: f64, net: &str) -> Value { json!({"ref": r, "name": n, "x": x, "y": y, "net": net}) }++ #[test]+ fn each_check_finds_its_problem() {+ let st = json!({"outline": [[0, 0], [20, 0], [20, 10], [0, 10]],+ "components": [{"ref": "U1", "x": 5.0, "y": 5.0, "pattern": "SOIC8", "value": "TBD"}, {"ref": "R1", "x": 19.8, "y": 5.0, "pattern": ""}, {"ref": "R1", "x": 10.0, "y": 5.0, "pattern": "0603"}, {"ref": "J1", "x": 25.0, "y": 5.0, "pattern": "HDR"}],+ "pads": [pad("U1", "1", 4.0, 5.0, "A"), pad("U1", "2", 6.0, 5.0, "LONE"), pad("R1", "1", 19.8, 5.0, "A"), pad("J1", "1", 25.0, 5.0, "")]});+ let sheet = vec![json!({"designator": "U1", "comment": "LM358", "params": [{"name": "Mouser Part Number", "value": "595-LM358"}]}), json!({"designator": "TP1", "comment": "Comment"})];+ let rules = vec![json!({"name": "Clearance", "kind": 0, "enabled": true, "priority": 1, "descriptor": "Clearance Constraint (Gap=0.1mm)"}),+ json!({"name": "Short", "kind": 15, "enabled": false, "priority": 1, "descriptor": "Short-Circuit Constraint (Allowed=No)"}),+ json!({"name": "W1", "kind": "width", "enabled": true, "priority": 2}), json!({"name": "W2", "kind": "width", "enabled": true, "priority": 2})];+ let (f, ran, _) = run_checks(&st, Some(&sheet), &rules, 0.127, 0.5, None, &[]);+ let has = |c: &str, key: &str, v: &str| f.iter().any(|x| x["check"] == c && x[key] == v);+ assert!(has("placeholder_values", "designator", "U1"));+ assert!(has("single_pin_nets", "net", "LONE"));+ assert!(has("duplicate_designators", "designator", "R1"));+ assert!(has("components_outside_board_outline", "designator", "J1"));+ assert!(has("components_near_board_edge", "designator", "R1"));+ assert!(has("components_without_footprint", "designator", "R1"));+ assert!(f.iter().any(|x| x["check"] == "vendor_part_numbers" && x["designator"] == "U1" && x["missing"] == json!(["DigiKey", "LCSC"])));+ assert!(!f.iter().any(|x| x["check"] == "vendor_part_numbers" && x["designator"] == "TP1"), "a test point is not purchased");+ assert!(has("schematic_placeholder_values", "designator", "TP1"));+ assert!(f.iter().any(|x| x["check"] == "disabled_design_rules" && x["severity"] == "error"));+ assert!(has("missing_critical_rules", "rule", "hole size") && has("missing_critical_rules", "rule", "short circuit"));+ assert!(f.iter().any(|x| x["check"] == "duplicate_rule_priority"));+ assert_eq!(f[0]["severity"], "error");+ assert_eq!(ran.len(), 13);+ let (_, _, skipped) = run_checks(&st, None, &[], 0.127, 0.5, None, &[]);+ assert!(skipped.contains_key("vendor_part_numbers") && skipped.contains_key("missing_critical_rules"));+ // EAGLE always checks shorts: passed in alwaysChecked, a missing short-circuit rule is no finding+ let (f2, _, _) = run_checks(&st, Some(&sheet), &rules, 0.0, 0.5, Some(&["missing_critical_rules".to_string()]), &["short_circuit".to_string()]);+ assert!(!f2.iter().any(|x| x["rule"] == "short circuit"), "{f2:?}");+ }++ #[test]+ fn rules_are_classed_three_ways() {+ assert_eq!(rule_class(&json!({"kind": 42})), "hole size");+ assert_eq!(rule_class(&json!({"kind": 99, "descriptor": "Width Constraint (Min=0.1mm)"})), "width");+ assert_eq!(rule_class(&json!({"kind": "short_circuit"})), "short circuit");+ // a tool's own names (Fusion's EAGLE rules), and a silk clearance is no copper clearance+ assert_eq!(rule_class(&json!({"name": "Wire-Wire", "value": "0.1mm"})), "clearance");+ assert_eq!(rule_class(&json!({"name": "Minimum Drill"})), "hole size");+ assert_eq!(rule_class(&json!({"name": "Silk Clearance"})), "");+ // Altium's other ordinals stay what their descriptor says, whatever words they hold+ assert_eq!(rule_class(&json!({"kind": 7, "name": "RoutingTopology", "descriptor": "Routing Topology Rule(Topology=Shortest) (All)"})), "routing topology rule");+ assert_eq!(rule_class(&json!({"kind": 6, "name": "PlaneConnect", "descriptor": "Power Plane Connect Rule(Relief Connect )(Conductor Width=0.254mm)"})), "power plane connect rule");+ }+}
bridge-rs/vendor/adom-eda-checks/src/route.rs+112−12@@ -43,7 +43,7 @@ pub(crate) enum Shape { Cap(P, P, f64), Poly(Vec<P>) } impl Shape { /// Edge-to-edge distance from the segment a..b (its centreline) to this copper.- fn dist(&self, a: P, b: P) -> f64 {+ pub(crate) fn dist(&self, a: P, b: P) -> f64 { match self { Shape::Cap(c, d, r) => seg_seg(a, b, *c, *d) - r, Shape::Poly(ring) => {@@ -162,6 +162,15 @@ pub fn plan_route(input: &Value) -> Value { let ring: Vec<P> = p["points"].as_array()?.iter().map(|q| (f(&q[0]), f(&q[1]))).collect(); (ring.len() >= 3).then(|| (p["net"].as_str().unwrap_or("").to_string(), p["layer"].as_str().unwrap_or("").to_string(), Shape::Poly(ring))) }).collect();+ // a pour that holds the route's own end pad cannot be kept out of (fusion-lane #21: SW1.2 sits inside VBAT's F.Cu+ // pour, so avoidPours: ["VBAT"] found no path): it is exempt, and the reply names it+ let held: Vec<usize> = (0..pours.len()).filter(|&i| {+ let (_, l, s) = &pours[i];+ let Shape::Poly(ring) = s else { return false };+ ends.iter().any(|p| pad_layers(p, &copper).contains(l) && inside((f(&p["x"]), f(&p["y"])), ring))+ }).collect();+ let blocks = |i: usize| avoids(&pours[i].0) && !held.contains(&i);+ let exempt: Vec<Value> = held.iter().filter(|&&i| avoids(&pours[i].0)).map(|&i| json!({"net": pours[i].0, "layer": pours[i].1, "why": "it holds an end pad of the route"})).collect(); // copper of other nets, by layer; every pad for the via-in-pad rule. Net-less tracks and arcs are a hatched pour's // pieces (Altium lists 8777 of the Bluetooth Sentinel's 9378 tracks with no net) and pours re-pour round new copper, // so neither blocks a route: repour after placing it (the reply says so)@@ -230,7 +239,7 @@ pub fn plan_route(input: &Value) -> Value { edge_ok(a, a, r) && copper.iter().all(|l| clear_on(a, a, r, l)) && all_pads.iter().all(|s| s.dist(a, a) >= r + clearance - 1e-9) } else { edge_ok(a, b, width / 2.0) && clear_on(a, b, width / 2.0, &layers[u.2])- && !pours.iter().any(|(n, l, s)| avoids(n) && *l == layers[u.2] && s.dist(a, b) < width / 2.0)+ && !(0..pours.len()).any(|i| blocks(i) && pours[i].1 == layers[u.2] && pours[i].2.dist(a, b) < width / 2.0) }; cache.insert(k, ok); ok@@ -271,19 +280,68 @@ pub fn plan_route(input: &Value) -> Value { let revision = st["revision"].clone(); let Some(goal_node) = found else { let why = if seen.len() >= max_nodes { "no path within the search limit (maxNodes): try a coarser gridMm or a higher maxNodes" } else { "no legal path on this grid: other copper, the outline or the clearance blocks every way. A fine-pitch pad (0.5 mm pitch) usually needs gridMm 0.1 to escape; more layers give more room" };- return json!({"success": true, "found": false, "reason": why, "expandedNodes": seen.len(), "revision": revision});+ // what an avoided pour does at each end: a pour the end pad sits in is exempt; one that only touches the pad's+ // first step out still walls it in (fusion-lane #21: avoidPours ["VBAT"] found no path from SW1.2)+ let near_ends: Vec<Value> = ends.iter().map(|p| {+ let c = (f(&p["x"]), f(&p["y"]));+ let reach = grid + width / 2.0 + clearance;+ let touching: Vec<Value> = (0..pours.len()).filter(|&i| avoids(&pours[i].0) && pad_layers(p, &copper).contains(&pours[i].1) && pours[i].2.dist(c, c) <= reach)+ .map(|i| json!({"net": pours[i].0, "layer": pours[i].1, "exempt": held.contains(&i)})).collect();+ json!({"pad": key(p), "avoidedPoursHere": touching})+ }).collect();+ let walled = near_ends.iter().any(|e| e["avoidedPoursHere"].as_array().map(|a| a.iter().any(|x| x["exempt"] == json!(false))).unwrap_or(false));+ // when keeping out of the pours is what fails, say so: plan again through them (fusion-lane #21: VBAT's pour wraps+ // SW1.2 in a notch it never touches)+ let mut through = Value::Null;+ if avoid_nets.is_some() && seen.len() < max_nodes {+ let mut again = input.clone();+ again["args"].as_object_mut().map(|o| o.remove("avoidPours"));+ let r = plan_route(&again);+ if r["found"] == json!(true) { through = json!({"found": true, "lengthMm": r["lengthMm"], "vias": r["vias"], "crossesPours": r["crossesPours"]}); }+ }+ let why = if avoid_nets.is_some() && walled { "no legal path: an avoided pour touches an end pad without holding it (avoidedPoursHere), so the route cannot leave the pad without entering it. Try pourCost instead of avoidPours, or drop that net from avoidPours".to_string() }+ else if !through.is_null() { format!("no path keeps out of the avoided pours: every way between the pads crosses one (a path through them exists: withoutAvoid). Use pourCost to go round them where it can, or drop a net from avoidPours") }+ else { why.to_string() };+ return json!({"success": true, "found": false, "reason": why, "expandedNodes": seen.len(), "revision": revision, "ends": near_ends, "withoutAvoid": through,+ "planner": {"algorithm": "bounded orthogonal A*", "widthFrom": width_from, "viaFrom": via_from, "gridMm": grid, "layers": layers, "viasCheckedOn": copper, "clearanceMm": clearance, "edgeClearanceMm": edge,+ "avoidPours": args["avoidPours"].clone(), "avoidExempt": exempt, "pourCost": pour_cost, "expandedNodes": seen.len()}}); }; let mut path = vec![goal_node]; while let Some(p) = parent.get(path.last().unwrap()) { path.push(*p); } path.reverse();+ // smooth the grid path: from each point, the farthest later point on the same layer that a straight or 45-degree+ // segment reaches with the same clearance, inside the outline and into no pour the grid path kept out of. Staircases+ // become diagonals (fusion-lane #21: Fusion's DRC flags every vertex of a staircase). smooth: false keeps the grid path.+ let at = |u: (usize, usize, usize)| (xs[u.0], ys[u.1]);+ let pours_hit = |a: P, b: P, l: usize| -> Vec<usize> { (0..pours.len()).filter(|&i| pours[i].1 == layers[l] && pours[i].2.dist(a, b) < width / 2.0).collect() };+ let octilinear = |a: P, b: P| { let (dx, dy) = ((b.0 - a.0).abs(), (b.1 - a.1).abs()); dx < 1e-9 || dy < 1e-9 || (dx - dy).abs() < 1e-9 };+ let smooth = args["smooth"].as_bool().unwrap_or(true);+ let mut pts = vec![path[0]];+ let mut i = 0;+ while i + 1 < path.len() {+ if path[i + 1].2 != path[i].2 || !smooth { pts.push(path[i + 1]); i += 1; continue; }+ let (mut best, mut j) = (i + 1, i + 2);+ let mut grid_pours: Vec<usize> = pours_hit(at(path[i]), at(path[i + 1]), path[i].2);+ while j < path.len() && path[j].2 == path[i].2 {+ for p in pours_hit(at(path[j - 1]), at(path[j]), path[i].2) { if !grid_pours.contains(&p) { grid_pours.push(p); } }+ let (a, b) = (at(path[i]), at(path[j]));+ if octilinear(a, b) && edge_ok(a, b, width / 2.0) && clear_on(a, b, width / 2.0, &layers[path[i].2])+ && pours_hit(a, b, path[i].2).iter().all(|p| grid_pours.contains(p) && !blocks(*p)) { best = j; }+ j += 1;+ }+ pts.push(path[best]);+ i = best;+ } // keep the corners and the layer changes- let mut keep = vec![path[0]];- for w in path.windows(3) {+ let mut keep = vec![pts[0]];+ for w in pts.windows(3) { let (a, b, c) = (w[0], w[1], w[2]);- if a.2 == b.2 && b.2 == c.2 && ((a.0 == b.0 && b.0 == c.0) || (a.1 == b.1 && b.1 == c.1)) { continue; }+ let (pa, pb, pc) = (at(a), at(b), at(c));+ let straight = ((pb.0 - pa.0) * (pc.1 - pb.1) - (pb.1 - pa.1) * (pc.0 - pb.0)).abs() < 1e-9 && (pb.0 - pa.0) * (pc.0 - pb.0) + (pb.1 - pa.1) * (pc.1 - pb.1) >= 0.0;+ if a.2 == b.2 && b.2 == c.2 && straight { continue; } keep.push(b); }- if path.len() > 1 { keep.push(*path.last().unwrap()); }+ if pts.len() > 1 { keep.push(*pts.last().unwrap()); } let mut way = vec![json!({"pad": key(&ends[0])})]; let mut vias = Vec::new(); let mut length = 0.0;@@ -304,7 +362,8 @@ pub fn plan_route(input: &Value) -> Value { way.push(json!({"pad": key(&ends[1])})); json!({"success": true, "found": true, "lengthMm": r3(length), "vias": vias.len(), "viaAt": vias, "routeNet": {"net": net, "layer": layers[path[0].2], "width": width, "viaSize": via_size, "viaDrill": via_drill, "paths": [way]},- "planner": {"algorithm": "bounded orthogonal A*", "widthFrom": width_from, "viaFrom": via_from, "gridMm": grid, "layers": layers, "viasCheckedOn": copper, "clearanceMm": clearance, "edgeClearanceMm": edge, "expandedNodes": seen.len()},+ "planner": {"algorithm": if smooth { "bounded orthogonal A*, smoothed to straight and 45-degree segments" } else { "bounded orthogonal A*" }, "widthFrom": width_from, "viaFrom": via_from, "gridMm": grid, "layers": layers, "viasCheckedOn": copper, "clearanceMm": clearance, "edgeClearanceMm": edge,+ "avoidPours": args["avoidPours"].clone(), "avoidExempt": exempt, "pourCost": pour_cost, "smooth": smooth, "expandedNodes": seen.len()}, "crossesPours": crosses, "avoidPours": args["avoidPours"].clone(), "pourCost": pour_cost, "revision": revision, "_hint": if crosses.is_empty() { "A plan only: pass routeNet to route_net unchanged (with expectedRevision: revision). A layer change is two waypoints at the same point, where route_net places a via. Pours (and a hatched pour's net-less pieces) are not obstacles: repour after placing the route. The path is orthogonal on the grid: a finer gridMm finds tighter paths and searches longer." } else { "A plan only: pass routeNet to route_net unchanged (with expectedRevision: revision). The route runs through the pours in crossesPours: after the repour, check that none of those nets split in two (routing_state's splitNets), or plan again keeping out of them: avoidPours: true (or a list of the nets whose pours to keep out of), or pourCost: 2 to prefer going round them where a way exists. A layer change is two waypoints at the same point, where route_net places a via." }})@@ -419,15 +478,56 @@ mod tests { // by net: avoiding another net's pours only leaves this one crossable assert_eq!(plan_route(&json!({"board": b, "args": {"net": "SIG", "from": "U1.1", "to": "J1.1", "avoidPours": ["VBAT"]}}))["vias"], json!(0)); assert_eq!(plan_route(&json!({"board": b, "args": {"net": "SIG", "from": "U1.1", "to": "J1.1", "avoidPours": ["gnd"]}}))["vias"], json!(2));- // a pour over the whole board: a hard block finds no path, a cost still routes (across it)+ // a wall of pours across both layers: a hard block finds no path, a cost still routes (across it)+ let mut wall = board(json!([]));+ wall["polygons"] = json!([{"net": "GND", "layer": "F.Cu", "points": [[8.0, 0.0], [12.0, 0.0], [12.0, 10.0], [8.0, 10.0]]}, {"net": "GND", "layer": "B.Cu", "points": [[8.0, 0.0], [12.0, 0.0], [12.0, 10.0], [8.0, 10.0]]}]);+ assert_eq!(plan_route(&json!({"board": wall, "args": {"net": "SIG", "from": "U1.1", "to": "J1.1", "avoidPours": true}}))["found"], json!(false));+ assert_eq!(plan_route(&json!({"board": wall, "args": {"net": "SIG", "from": "U1.1", "to": "J1.1", "pourCost": 2.0}}))["found"], json!(true));+ // a pour that holds the route's own end pad cannot be kept out of: it is exempt and named (fusion-lane #21) let mut all = board(json!([]));- all["polygons"] = json!([{"net": "GND", "layer": "F.Cu", "points": [[0.0, 0.0], [20.0, 0.0], [20.0, 10.0], [0.0, 10.0]]}, {"net": "GND", "layer": "B.Cu", "points": [[0.0, 0.0], [20.0, 0.0], [20.0, 10.0], [0.0, 10.0]]}]);- assert_eq!(plan_route(&json!({"board": all, "args": {"net": "SIG", "from": "U1.1", "to": "J1.1", "avoidPours": true}}))["found"], json!(false));- assert_eq!(plan_route(&json!({"board": all, "args": {"net": "SIG", "from": "U1.1", "to": "J1.1", "pourCost": 2.0}}))["found"], json!(true));+ all["polygons"] = json!([{"net": "GND", "layer": "F.Cu", "points": [[0.0, 0.0], [20.0, 0.0], [20.0, 10.0], [0.0, 10.0]]}]);+ let held = plan_route(&json!({"board": all, "args": {"net": "SIG", "from": "U1.1", "to": "J1.1", "avoidPours": ["GND"]}}));+ assert_eq!(held["found"], json!(true), "{held}");+ assert_eq!(held["planner"]["avoidExempt"][0]["net"], "GND");+ assert_eq!(held["planner"]["pourCost"], json!(0.0));+ // a pour that touches U1.1 without holding it walls the pad in: the no-path reply says so, with its planner block+ let mut touch = board(json!([]));+ touch["polygons"] = json!([{"net": "GND", "layer": "F.Cu", "points": [[2.6, 0.0], [12.0, 0.0], [12.0, 10.0], [2.6, 10.0]]}, {"net": "GND", "layer": "B.Cu", "points": [[2.6, 0.0], [12.0, 0.0], [12.0, 10.0], [2.6, 10.0]]}]);+ let walled = plan_route(&json!({"board": touch, "args": {"net": "SIG", "from": "U1.1", "to": "J1.1", "avoidPours": ["GND"]}}));+ assert_eq!(walled["found"], json!(false), "{walled}");+ assert_eq!(walled["ends"][0]["avoidedPoursHere"][0], json!({"net": "GND", "layer": "F.Cu", "exempt": false}), "{walled}");+ assert!(walled["reason"].as_str().unwrap().contains("avoidedPoursHere"));+ assert_eq!(walled["planner"]["avoidPours"], json!(["GND"]));+ // a wall it never touches: the reply says a path exists through the pours+ let wall_only = plan_route(&json!({"board": wall, "args": {"net": "SIG", "from": "U1.1", "to": "J1.1", "avoidPours": true}}));+ assert_eq!(wall_only["withoutAvoid"]["found"], json!(true), "{wall_only}");+ assert!(wall_only["reason"].as_str().unwrap().contains("every way between the pads crosses one")); // and with the cost a short way round a narrow pour beats crossing it let mut strip = board(json!([])); strip["polygons"] = json!([{"net": "GND", "layer": "F.Cu", "points": [[9.0, 2.0], [11.0, 2.0], [11.0, 10.0], [9.0, 10.0]]}]); let soft = plan_route(&json!({"board": strip, "args": {"net": "SIG", "from": "U1.1", "to": "J1.1", "pourCost": 10.0, "allowVias": false}})); assert_eq!(soft["crossesPours"], json!([]), "{soft}"); }+ #[test]+ fn a_staircase_becomes_one_45_degree_segment() {+ // U1.1 at (2, 5) to a pad at (8, 9): the grid path is a staircase of corners; smoothed, the plan is straight and+ // 45-degree runs only, the diagonal clear of everything+ let mut b = board(json!([]));+ b["pads"][1]["x"] = json!(8.0); b["pads"][1]["y"] = json!(9.0);+ let r = plan_route(&json!({"board": b, "args": {"net": "SIG", "from": "U1.1", "to": "J1.1"}}));+ let way = r["routeNet"]["paths"][0].as_array().unwrap().clone();+ let mut pts = vec![(2.0, 5.0)];+ pts.extend(way[1..way.len() - 1].iter().map(|w| (f(&w["x"]), f(&w["y"]))));+ pts.push((8.0, 9.0));+ assert!(pts.len() <= 3, "at most one corner: {r}");+ for w in pts.windows(2) {+ let (dx, dy) = ((w[1].0 - w[0].0).abs(), (w[1].1 - w[0].1).abs());+ assert!(dx < 1e-9 || dy < 1e-9 || (dx - dy).abs() < 1e-9, "{w:?}");+ }+ assert!(pts.windows(2).any(|w| (w[1].0 - w[0].0).abs() > 1e-9 && (w[1].1 - w[0].1).abs() > 1e-9), "one diagonal: {r}");+ // shorter than the 10 mm staircase: 4 * sqrt(2) + 2+ assert!((f(&r["lengthMm"]) - (4.0 * 2f64.sqrt() + 2.0)).abs() < 1e-3, "{r}");+ let grid = plan_route(&json!({"board": b, "args": {"net": "SIG", "from": "U1.1", "to": "J1.1", "smooth": false}}));+ assert!((f(&grid["lengthMm"]) - 10.0).abs() < 1e-9);+ } }
bridge-rs/vendor/adom-eda-checks/src/schreview.rsadded+252@@ -0,0 +1,252 @@+//! A schematic review before the board is updated: every placed pin from the sheets (with its electrical type) against+//! the compiled netlist, and the symbols' pins against the footprints' pads. From the Altium bridge's schreview.rs. Unconnected pins (power pins as errors), nets with one pin, outputs driving each+//! other, inputs nothing drives, and IC power pins with no decoupling capacitor to ground.+use serde_json::{json, Map, Value};+use std::collections::{BTreeMap, BTreeSet};++/// Altium's pin electrical types (the ELECTRICAL field).+pub fn electrical(n: i64) -> &'static str {+ match n { 0 => "input", 1 => "io", 2 => "output", 3 => "open_collector", 4 => "passive", 5 => "hiz", 6 => "open_emitter", 7 => "power", _ => "unknown" }+}++/// A pin's type from the sheet model: Altium's code, or the name the standard uses (Fusion also sends `supply`, a+/// supply symbol's pin that drives its net, and `not_connected`).+pub fn pin_type(v: &Value) -> String {+ match v {+ Value::Number(n) => electrical(n.as_i64().unwrap_or(-1)).to_string(),+ Value::String(t) => match t.to_ascii_lowercase().replace(['-', ' '], "_").as_str() {+ "bidirectional" | "bidi" | "i/o" => "io".into(),+ "pwr" => "power".into(),+ "sup" => "supply".into(),+ "nc" => "not_connected".into(),+ "oc" | "opencollector" => "open_collector".into(),+ "pas" => "passive".into(),+ "tri" | "tristate" | "3state" => "hiz".into(),+ "in" => "input".into(),+ "out" => "output".into(),+ o => o.to_string(),+ },+ _ => "unknown".into(),+ }+}++pub fn is_ground(net: &str) -> bool {+ let n = net.to_ascii_uppercase();+ n == "GND" || n == "0V" || n == "VSS" || n == "AGND" || n == "DGND" || n == "PGND" || n == "GNDA" || n == "GNDD" || n.starts_with("GND_") || n.ends_with("_GND")+}++fn prefix(des: &str) -> String { des.chars().take_while(|c| c.is_ascii_alphabetic()).collect::<String>().to_ascii_uppercase() }++/// The review, from the parts (read_sheet_file components: designator, pins with number/name/electrical) and the nets+/// ({net: ["U1.8", ...]}). Pure.+pub fn review(parts: &[Value], nets: &Map<String, Value>) -> Value {+ // pin -> net+ let mut net_of: BTreeMap<String, String> = BTreeMap::new();+ for (n, ps) in nets { for p in ps.as_array().cloned().unwrap_or_default() { if let Some(s) = p.as_str() { net_of.insert(s.to_ascii_uppercase(), n.clone()); } } }+ // every placed pin, once (a multi-part chip appears once per part on the sheets)+ let mut pins: BTreeMap<String, (String, String, String, String)> = BTreeMap::new(); // key -> (designator, number, name, type)+ for c in parts {+ let des = c["designator"].as_str().unwrap_or("").to_string();+ if des.is_empty() || des.contains('?') { continue; }+ // a supply symbol with no package (Fusion's SUPPLY1..) joins its net by pin name and has no pin numbers: it is+ // no part on the board (fusion-lane)+ if c["pins"].as_array().map(|a| !a.is_empty() && a.iter().all(|p| p["number"].as_str().map(|n| n.trim().is_empty()).unwrap_or(true))).unwrap_or(false) { continue; }+ for p in c["pins"].as_array().cloned().unwrap_or_default() {+ let num = p["number"].as_str().unwrap_or("").to_string();+ pins.entry(format!("{des}.{num}").to_ascii_uppercase()).or_insert((des.clone(), num, p["name"].as_str().unwrap_or("").to_string(), pin_type(&p["electrical"])));+ }+ }+ let nc = |name: &str| { let n = name.to_ascii_uppercase(); n == "NC" || n == "N/C" || n == "DNC" || n.starts_with("NC_") || n == "NO CONNECT" };+ let mut errors = Vec::new();+ let mut warnings = Vec::new();+ for (key, (des, num, name, ty)) in &pins {+ if net_of.contains_key(key) || nc(name) || ty == "not_connected" { continue; }+ let f = json!({"check": "unconnected_pin", "pin": format!("{des}.{num}"), "name": name, "type": ty});+ if ty == "power" { errors.push(f) } else { warnings.push(f) }+ }+ for (n, ps) in nets {+ let members = ps.as_array().map(|a| a.len()).unwrap_or(0);+ if members == 1 { warnings.push(json!({"check": "single_pin_net", "net": n, "pin": ps[0]})); }+ let kinds: Vec<&str> = ps.as_array().cloned().unwrap_or_default().iter().filter_map(|p| p.as_str()).filter_map(|p| pins.get(&p.to_ascii_uppercase())).map(|t| t.3.as_str()).collect();+ let outs = kinds.iter().filter(|k| **k == "output").count();+ if outs >= 2 { errors.push(json!({"check": "outputs_together", "net": n, "outputs": outs})); }+ let driven = kinds.iter().any(|k| matches!(*k, "output" | "io" | "power" | "supply" | "passive" | "open_collector" | "open_emitter" | "hiz" | "unknown"));+ if !kinds.is_empty() && kinds.iter().all(|k| *k == "input") && !driven && members > 0 {+ warnings.push(json!({"check": "undriven_input", "net": n, "inputs": kinds.len()}));+ }+ }+ // decoupling: each IC power pin on a supply net (not ground) wants a capacitor between that net and a ground+ let caps_between: BTreeMap<String, Vec<String>> = {+ let mut m: BTreeMap<String, Vec<String>> = BTreeMap::new();+ let mut cap_nets: BTreeMap<String, BTreeSet<String>> = BTreeMap::new();+ for (key, (des, ..)) in &pins {+ if prefix(des) == "C" { if let Some(n) = net_of.get(key) { cap_nets.entry(des.clone()).or_default().insert(n.clone()); } }+ }+ for (c, ns) in cap_nets {+ if ns.iter().any(|n| is_ground(n)) { for n in ns.iter().filter(|n| !is_ground(n)) { m.entry(n.clone()).or_default().push(c.clone()); } }+ }+ m+ };+ let mut supplies: BTreeMap<String, BTreeSet<String>> = BTreeMap::new();+ for (key, (des, _, _, ty)) in &pins {+ if ty != "power" || !matches!(prefix(des).as_str(), "U" | "IC") { continue; }+ if let Some(n) = net_of.get(key).filter(|n| !is_ground(n)) { supplies.entry(n.clone()).or_default().insert(des.clone()); }+ }+ let mut decoupling = Vec::new();+ for (net, ics) in &supplies {+ let caps = caps_between.get(net).cloned().unwrap_or_default();+ // an inductor on a 'supply' pin's net makes it a switch node (a regulator's SW/LX pin): no capacitor belongs+ // there (the Bluetooth Sentinel's SMPS_LX read as missing decoupling)+ let switch = nets.get(net).and_then(|p| p.as_array()).map(|a| a.iter().filter_map(|p| p.as_str()).any(|p| prefix(p.split('.').next().unwrap_or("")) == "L")).unwrap_or(false);+ let row = json!({"net": net, "ics": ics, "capacitors": caps, "ok": !caps.is_empty() || switch, "switchNode": switch});+ if caps.is_empty() && !switch { warnings.push(json!({"check": "no_decoupling", "net": net, "ics": ics})); }+ decoupling.push(row);+ }+ json!({"pins": pins.len(), "nets": nets.len(), "errors": errors, "warnings": warnings, "decoupling": decoupling, "ok": errors.is_empty()})+}++/// Symbol pins against footprint pads, part by part: pins with no pad (a net that can never reach copper), pads with no+/// pin (copper no net reaches: fine for mounting and mechanical pads), and parts on only one side. Pure.+pub fn pin_pad(parts: &[Value], pads: &[Value], board_refs: &[String]) -> Value {+ let mut pins: BTreeMap<String, BTreeSet<String>> = BTreeMap::new();+ for c in parts {+ let des = c["designator"].as_str().unwrap_or("").to_string();+ if des.is_empty() || des.contains('?') { continue; }+ // a supply symbol with no package (Fusion's SUPPLY1..) joins its net by pin name and has no pin numbers: it is+ // no part on the board (fusion-lane)+ if c["pins"].as_array().map(|a| !a.is_empty() && a.iter().all(|p| p["number"].as_str().map(|n| n.trim().is_empty()).unwrap_or(true))).unwrap_or(false) { continue; }+ let e = pins.entry(des).or_default();+ for p in c["pins"].as_array().cloned().unwrap_or_default() { if let Some(n) = p["number"].as_str() { e.insert(n.to_ascii_uppercase()); } }+ }+ let mut padset: BTreeMap<String, BTreeSet<String>> = BTreeMap::new();+ for p in pads {+ let (Some(r), Some(n)) = (p["ref"].as_str().filter(|r| !r.is_empty()), p["name"].as_str()) else { continue };+ padset.entry(r.to_string()).or_default().insert(n.to_ascii_uppercase());+ }+ let mut mismatches = Vec::new();+ let mut ok = 0;+ for (des, ps) in &pins {+ let Some(pd) = padset.get(des) else { continue };+ let no_pad: Vec<&String> = ps.iter().filter(|n| !pd.contains(*n)).collect();+ // unnamed or '0' pads and mounting pads (MH*, EP*, SH*, MP*) carry no pin by design+ let no_pin: Vec<&String> = pd.iter().filter(|n| !ps.contains(*n) && !n.is_empty() && *n != "0" && !["MH", "MP", "SH", "EP", "PAD", "TAB"].iter().any(|m| n.starts_with(m))).collect();+ if no_pad.is_empty() && no_pin.is_empty() { ok += 1; continue; }+ mismatches.push(json!({"ref": des, "pinsWithoutPad": no_pad, "padsWithoutPin": no_pin, "pins": ps.len(), "pads": pd.len()}));+ }+ let on_board: BTreeSet<String> = board_refs.iter().cloned().collect();+ let sheet_only: Vec<&String> = pins.keys().filter(|d| !on_board.contains(*d) && !padset.contains_key(*d)).collect();+ let board_only: Vec<&String> = on_board.iter().filter(|d| !pins.contains_key(*d)).collect();+ json!({"partsChecked": ok + mismatches.len(), "matching": ok, "mismatches": mismatches, "onSheetsOnly": sheet_only, "onBoardOnly": board_only,+ "ok": mismatches.iter().all(|m| m["pinsWithoutPad"].as_array().map(|a| a.is_empty()).unwrap_or(true))})+}++/// The sheet parts companion (read_sheet_file's components, each with its pins): a list, or a reply with `components`.+fn sheet_parts(input: &Value) -> Option<Vec<Value>> {+ let p = crate::input::part(input, "sheetParts")?;+ p.get("components").or(Some(&p)).and_then(|x| x.as_array()).cloned()+}++/// schematic_review: input {sheetParts, netlist}. The netlist companion is {nets: {net: ["U1.8", ...]}} (or the map).+pub fn schematic_review(input: &Value) -> Value {+ let Some(parts) = sheet_parts(input) else { return crate::input::refuse("bad_args", "pass the sheets' parts (read_sheet_file with pins, every sheet) as sheetParts") };+ let Some(n) = crate::input::part(input, "netlist") else { return crate::input::refuse("bad_args", "pass the compiled netlist ({nets: {net: [\"U1.8\", ...]}}) as netlist") };+ let nets = n.get("nets").or(Some(&n)).and_then(|x| x.as_object()).cloned().unwrap_or_default();+ let mut out = review(&parts, &nets);+ out["success"] = json!(true);+ out["_hint"] = json!("errors stop a board (a power pin on no net, two outputs on one net); warnings deserve a look (pins on no net, one-pin nets, inputs nothing drives, an IC supply with no capacitor to ground). Pin types come from the symbols: a passive pin is never 'undriven'. Fix on the sheets (sch_connect, sch_place_part), then update_pcb.");+ out+}++/// pin_pad_check: input {board, sheetParts}. The symbols' pins against the placed footprints' pads.+pub fn pin_pad_check(input: &Value) -> Value {+ let st = match crate::input::board(input) { Ok(b) => b, Err(e) => return e };+ let Some(parts) = sheet_parts(input) else { return crate::input::refuse("bad_args", "pass the sheets' parts (read_sheet_file with pins, every sheet) as sheetParts") };+ let refs: Vec<String> = st["components"].as_array().cloned().unwrap_or_default().iter().filter_map(|c| c["ref"].as_str().map(String::from)).collect();+ let mut out = pin_pad(&parts, st["pads"].as_array().map(|a| a.as_slice()).unwrap_or(&[]), &refs);+ out["success"] = json!(true);+ out["_hint"] = json!("pinsWithoutPad is a part whose footprint cannot carry every pin's net (a wrong footprint, or pin numbers that do not match): fix the footprint or the symbol (swap_footprint, build_footprint) before routing. padsWithoutPin is copper no net reaches. onSheetsOnly / onBoardOnly differ until update_pcb.");+ out+}++#[cfg(test)]+mod tests {+ use super::*;++ fn part(des: &str, pins: &[(&str, &str, i64)]) -> Value {+ json!({"designator": des, "pins": pins.iter().map(|(n, nm, e)| json!({"number": n, "name": nm, "electrical": e})).collect::<Vec<_>>()})+ }++ #[test]+ fn pin_types_come_as_codes_or_names() {+ assert_eq!(pin_type(&json!(7)), "power");+ assert_eq!(pin_type(&json!("Bidirectional")), "io");+ assert_eq!(pin_type(&json!("sup")), "supply");+ let parts = vec![json!({"designator": "U1", "pins": [+ {"number": "1", "name": "IN", "electrical": "input"}, {"number": "2", "name": "X", "electrical": "not_connected"}]}),+ json!({"designator": "P1", "pins": [{"number": "1", "name": "VCC", "electrical": "supply"}]})];+ let nets = json!({"VCC": ["U1.1", "P1.1"]});+ let r = review(&parts, nets.as_object().unwrap());+ assert!(r["warnings"].as_array().unwrap().is_empty(), "{r}");+ }++ #[test]+ fn the_review_finds_each_kind_of_problem() {+ let parts = vec![+ part("U1", &[("1", "VCC", 7), ("2", "GND", 7), ("3", "OUT", 2), ("4", "NC", 0), ("5", "EN", 0)]),+ part("U2", &[("1", "VDD", 7), ("2", "GND", 7), ("3", "OUT", 2), ("4", "IN", 0)]),+ part("C1", &[("1", "", 4), ("2", "", 4)]),+ part("R1", &[("1", "", 4), ("2", "", 4)]),+ part("U3", &[("1", "SW", 7)]), part("L1", &[("1", "", 4), ("2", "", 4)]),+ ];+ let nets = json!({"3V3": ["U1.1", "C1.1"], "VDD": ["U2.1"], "LX": ["U3.1", "L1.1"], "GND": ["U1.2", "U2.2", "C1.2"], "BUS": ["U1.3", "U2.3"], "SENSE": ["U2.4"], "R": ["R1.1", "R1.2"]});+ let r = review(&parts, nets.as_object().unwrap());+ let checks = |k: &str| r[k].as_array().unwrap().iter().map(|f| f["check"].as_str().unwrap().to_string()).collect::<Vec<_>>();+ // U1.5 EN floats (input, warning); NC is skipped; two outputs share BUS (error)+ assert!(checks("errors").contains(&"outputs_together".to_string()));+ assert!(checks("warnings").contains(&"unconnected_pin".to_string()));+ assert!(!r["warnings"].as_array().unwrap().iter().any(|f| f["pin"] == "U1.4"));+ // VDD has one pin and no capacitor; SENSE is an input nothing drives+ assert!(checks("warnings").contains(&"single_pin_net".to_string()));+ assert!(checks("warnings").contains(&"no_decoupling".to_string()));+ assert!(checks("warnings").contains(&"undriven_input".to_string()));+ let dec = r["decoupling"].as_array().unwrap();+ assert!(dec.iter().any(|d| d["net"] == "3V3" && d["ok"] == json!(true)));+ assert!(dec.iter().any(|d| d["net"] == "VDD" && d["ok"] == json!(false)));+ // a regulator's switch pin on an inductor is not a missing capacitor+ assert!(dec.iter().any(|d| d["net"] == "LX" && d["switchNode"] == json!(true) && d["ok"] == json!(true)));+ }+ #[test]+ fn pin_pad_finds_footprints_that_do_not_fit_their_symbols() {+ let parts = vec![part("U1", &[("1", "A", 0), ("2", "B", 0), ("3", "C", 0)]), part("R1", &[("1", "", 4), ("2", "", 4)]), part("C9", &[("1", "", 4), ("2", "", 4)])];+ let pad = |r: &str, n: &str| json!({"ref": r, "name": n});+ let pads = vec![pad("U1", "1"), pad("U1", "2"), pad("U1", "4"), pad("U1", "EP"), pad("R1", "1"), pad("R1", "2"), pad("J9", "1")];+ let r = pin_pad(&parts, &pads, &["U1".into(), "R1".into(), "J9".into()]);+ assert_eq!(r["matching"], 1);+ let m = &r["mismatches"][0];+ assert_eq!(m["ref"], "U1");+ assert_eq!(m["pinsWithoutPad"], json!(["3"]));+ assert_eq!(m["padsWithoutPin"], json!(["4"]));+ assert_eq!(r["onSheetsOnly"], json!(["C9"]));+ assert_eq!(r["onBoardOnly"], json!(["J9"]));+ assert_eq!(r["ok"], json!(false));+ }++ #[test]+ fn the_verbs_take_the_companions_bare_or_in_a_reply() {+ let parts = json!({"success": true, "components": [part("U1", &[("1", "VCC", 7), ("2", "GND", 7)]), part("C1", &[("1", "", 4), ("2", "", 4)])]});+ let r = schematic_review(&json!({"sheetParts": parts, "netlist": {"nets": {"3V3": ["U1.1", "C1.1"], "GND": ["U1.2", "C1.2"]}}}));+ assert_eq!((r["success"].clone(), r["ok"].clone(), r["pins"].clone()), (json!(true), json!(true), json!(4)), "{r}");+ assert_eq!(schematic_review(&json!({"netlist": {}}))["errorCode"], "bad_args");+ let b = json!({"components": [{"ref": "U1"}, {"ref": "C1"}], "pads": [{"ref": "U1", "name": "1"}, {"ref": "U1", "name": "2"}, {"ref": "C1", "name": "1"}, {"ref": "C1", "name": "2"}]});+ let p = pin_pad_check(&json!({"board": b, "sheetParts": parts}));+ assert_eq!((p["matching"].clone(), p["ok"].clone()), (json!(2), json!(true)), "{p}");+ }++ #[test]+ fn a_supply_symbol_without_pin_numbers_is_no_part() {+ let parts = vec![part("U1", &[("1", "VCC", 7)]), json!({"designator": "SUPPLY1", "pins": [{"number": "", "name": "VCC", "electrical": "supply"}]})];+ let r = review(&parts, json!({"VCC": ["U1.1"]}).as_object().unwrap());+ assert_eq!(r["pins"], json!(1), "{r}");+ assert!(r["errors"].as_array().unwrap().is_empty());+ }+}
bridge-rs/vendor/adom-eda-checks/src/silkplace.rsadded+220@@ -0,0 +1,220 @@+//! Reference designators placed the way assembly houses want them: one size for all, upright, beside their own part,+//! clear of every pad (JLCPCB: silkscreen 0.15 mm from pads), every other part's body and every designator already+//! placed, and inside the board. From the Altium bridge's silkplace.rs: a plan here, which the bridge applies with+//! apply_silkscreen and checks against the tool's own text boxes after.+use serde_json::{json, Value};++fn f(v: &Value) -> f64 { v.as_f64().unwrap_or(0.0) }+fn r3(v: f64) -> f64 { (v * 1000.0).round() / 1000.0 }++type Rect = (f64, f64, f64, f64);++fn rect_of(v: &Value) -> Option<Rect> {+ let a = v.as_array()?;+ if a.len() != 4 { return None; }+ let n: Vec<f64> = a.iter().map(f).collect();+ Some((n[0].min(n[2]), n[1].min(n[3]), n[0].max(n[2]), n[1].max(n[3])))+}+fn grow(r: Rect, d: f64) -> Rect { (r.0 - d, r.1 - d, r.2 + d, r.3 + d) }+fn hit(a: Rect, b: Rect) -> bool { a.0 < b.2 && b.0 < a.2 && a.1 < b.3 && b.1 < a.3 }+fn union(a: Rect, b: Rect) -> Rect { (a.0.min(b.0), a.1.min(b.1), a.2.max(b.2), a.3.max(b.3)) }++/// A pad's copper as a rectangle (its rotated extent).+fn pad_rect(p: &Value) -> Rect {+ let (c, s) = (f(&p["rotation"]).to_radians().cos().abs(), f(&p["rotation"]).to_radians().sin().abs());+ let (sx, sy) = (f(&p["sizeX"]), f(&p["sizeY"]));+ let (hx, hy) = ((sx * c + sy * s) / 2.0, (sx * s + sy * c) / 2.0);+ (f(&p["x"]) - hx, f(&p["y"]) - hy, f(&p["x"]) + hx, f(&p["y"]) + hy)+}++fn on_side(layer: &Value, bottom: bool) -> bool {+ match layer.as_str() { Some("*.Cu") => true, Some("B.Cu") => bottom, Some("F.Cu") => !bottom, _ => false }+}++/// Where each designator goes: [{ref, x, y, size, rotation, side, at}] (x, y the text's lower-left, its right on the+/// bottom side where Altium mirrors it) and the parts with no clear spot. Pure: silk_state's components, the board's+/// pads and outline bounding box, and the boxes of labels that stay put.+pub fn plan(comps: &[Value], pads: &[Value], board: Rect, size: f64, min_size: f64, gap: f64, pad_clear: f64, fixed: &[(bool, Rect)]) -> (Vec<Value>, Vec<Value>) {+ // labels that stay where they are (parts left out, or with no spot) are obstacles like the ones placed+ let mut placed: Vec<(bool, Rect)> = fixed.to_vec();+ let (mut out, mut unplaced) = (Vec::new(), Vec::new());+ // the part's own outline: its body box and its own pads+ let own = |c: &Value| -> Option<Rect> {+ let r = c["ref"].as_str().unwrap_or("");+ let mut b = rect_of(&c["body"]);+ for p in pads.iter().filter(|p| p["ref"].as_str() == Some(r)) { b = Some(b.map(|x| union(x, pad_rect(p))).unwrap_or(pad_rect(p))); }+ b+ };+ let bodies: Vec<(String, bool, Rect)> = comps.iter().filter_map(|c| own(c).map(|b| (c["ref"].as_str().unwrap_or("").to_string(), c["side"] == "bottom", b))).collect();+ // big parts first: they have the fewest places to put a label and the small ones fit round them+ let mut order: Vec<&Value> = comps.iter().filter(|c| c["name"]["shown"].as_bool() != Some(false)).collect();+ order.sort_by(|a, b| {+ let area = |c: &Value| own(c).map(|r| (r.2 - r.0) * (r.3 - r.1)).unwrap_or(0.0);+ area(b).partial_cmp(&area(a)).unwrap()+ });+ let inside = grow(board, -0.2);+ for c in order {+ let rf = c["ref"].as_str().unwrap_or("").to_string();+ let bottom = c["side"] == "bottom";+ let Some(b) = own(c) else { unplaced.push(json!({"ref": rf, "why": "no body or pads to place it by"})); continue };+ if b.2 < board.0 || b.0 > board.2 || b.3 < board.1 || b.1 > board.3 {+ unplaced.push(json!({"ref": rf, "why": "the part is off the board: place it first (move_parts)"}));+ continue;+ }+ // the label's size at the new height, from Altium's own box at the old one+ // Altium's box is the text plus half its stroke all round (a 1.0 mm designator measures 1.285 mm tall on the+ // Bluetooth Sentinel example): plan the text, check the box+ let old = f(&c["name"]["size"]);+ let turned = (f(&c["name"]["rotation"]).rem_euclid(180.0) - 90.0).abs() < 1.0;+ let (m, w) = match rect_of(&c["name"]["box"]) {+ Some(r) if old > 0.0 && r.2 > r.0 => {+ let (bw, bh) = if turned { (r.3 - r.1, r.2 - r.0) } else { (r.2 - r.0, r.3 - r.1) };+ let m = ((bh - old) / 2.0).clamp(0.0, 0.3);+ (m, (bw - 2.0 * m).max(old * 0.5) * size / old)+ }+ _ => (0.15, rf.len() as f64 * size * 0.8),+ };+ let free = |text: Rect| -> bool {+ let r = grow(text, m);+ r.0 >= inside.0 && r.1 >= inside.1 && r.2 <= inside.2 && r.3 <= inside.3+ && !pads.iter().any(|p| on_side(&p["layer"], bottom) && hit(r, grow(pad_rect(p), pad_clear)))+ && !bodies.iter().any(|(o, side, ob)| *o != rf && *side == bottom && hit(r, *ob))+ && !placed.iter().any(|(side, pr)| *side == bottom && hit(r, grow(*pr, 0.1)))+ };+ // the sizes to try: `size`, then down in 0.1 mm steps to `min_size`+ let mut found = None;+ let mut s = size;+ while found.is_none() && s >= min_size - 1e-9 {+ found = spots(b, w * s / size, s, gap, bottom).into_iter().find(|(r, _, _)| free(*r)).map(|(r, rot, at)| (r, rot, at, s));+ s -= 0.1;+ }+ match found {+ Some((r, rot, at, s)) => {+ placed.push((bottom, grow(r, m)));+ // the text's anchor: lower left upright; turned 90 its letters lie left of the anchor (lower right of the+ // box); mirrored on the bottom it is the text's right end+ let (ax, ay) = if rot == 90 { (r.2, r.1) } else if bottom { (r.2, r.1) } else { (r.0, r.1) };+ out.push(json!({"ref": rf, "x": r3(ax), "y": r3(ay), "size": r3(s), "rotation": rot, "side": if bottom { "bottom" } else { "top" }, "at": at}));+ }+ None => unplaced.push(json!({"ref": rf, "why": "no clear spot beside the part", "triedSizes": [size, min_size]})),+ }+ }+ (out, unplaced)+}++/// Places a w x h label could go round the part box b, nearest first: centred on each side, then slid along it, at+/// `gap` and then 3 x `gap`; turned 90 degrees beside the left and right sides (top side only: Altium mirrors bottom+/// text). Each is (box, rotation, where).+fn spots(b: Rect, w: f64, h: f64, gap: f64, bottom: bool) -> Vec<(Rect, i64, String)> {+ let mut v = Vec::new();+ let (cx, cy) = ((b.0 + b.2) / 2.0, (b.1 + b.3) / 2.0);+ for g in [gap, 3.0 * gap] {+ // slide offsets along a side: centre first, then outwards both ways in 0.5 mm steps+ let slide = |len: f64| -> Vec<f64> {+ let mut o = vec![0.0];+ let mut k = 0.5;+ while k <= len / 2.0 + 0.5 { o.push(-k); o.push(k); k += 0.5; }+ o+ };+ for d in slide(b.2 - b.0) {+ v.push(((cx - w / 2.0 + d, b.3 + g, cx + w / 2.0 + d, b.3 + g + h), 0, "above".to_string()));+ v.push(((cx - w / 2.0 + d, b.1 - g - h, cx + w / 2.0 + d, b.1 - g), 0, "below".to_string()));+ }+ for d in slide(b.3 - b.1) {+ v.push(((b.2 + g, cy - h / 2.0 + d, b.2 + g + w, cy + h / 2.0 + d), 0, "right".to_string()));+ v.push(((b.0 - g - w, cy - h / 2.0 + d, b.0 - g, cy + h / 2.0 + d), 0, "left".to_string()));+ if !bottom {+ v.push(((b.2 + g, cy - w / 2.0 + d, b.2 + g + h, cy + w / 2.0 + d), 90, "right, turned".to_string()));+ v.push(((b.0 - g - h, cy - w / 2.0 + d, b.0 - g, cy + w / 2.0 + d), 90, "left, turned".to_string()));+ }+ }+ }+ v+}++/// Designators whose box (Altium's own) still touches a pad, closer than `pad_clear`. Pure.+pub fn on_pads(comps: &[Value], pads: &[Value], pad_clear: f64) -> Vec<Value> {+ comps.iter().filter(|c| c["name"]["shown"].as_bool() != Some(false)).filter_map(|c| {+ let r = rect_of(&c["name"]["box"])?;+ let bottom = c["side"] == "bottom";+ let p = pads.iter().find(|p| on_side(&p["layer"], bottom) && hit(r, grow(pad_rect(p), pad_clear - 0.01)))?;+ Some(json!({"ref": c["ref"], "pad": format!("{}.{}", p["ref"].as_str().unwrap_or(""), p["name"].as_str().unwrap_or(""))}))+ }).collect()+}++/// silk_designators: input {board, silk, args: {size?, minSize?, gap?, padClearance?, refs?}}. The plan: `planned`,+/// and `applyArgs` ready for apply_silkscreen (x, y the text's lower-left; its right end on the bottom side, where the+/// text is mirrored), the parts with no clear spot, and the labels on pads before.+pub fn silk_designators(input: &Value) -> Value {+ let st = match crate::input::board(input) { Ok(b) => b, Err(e) => return e };+ let args = &input["args"];+ let num = |k: &str, d: f64| args.get(k).and_then(|v| v.as_f64()).unwrap_or(d);+ let (size, gap, clear) = (num("size", 1.0), num("gap", 0.2), num("padClearance", 0.15));+ if size < 0.5 { return crate::input::refuse("bad_args", "size is the text height in mm, 0.5 or more (JLCPCB reads 1.0 mm and up reliably)"); }+ let Some(bb) = crate::geom::outline_bbox(&st) else { return crate::input::refuse("no_outline", "the board has no outline") };+ let Some(silk) = crate::input::part(input, "silk") else { return crate::input::refuse("bad_args", "pass silk_state as silk: each part's body box and designator") };+ let all = silk["components"].as_array().cloned().unwrap_or_default();+ let mut comps = all.clone();+ if let Some(want) = args.get("refs").and_then(|v| v.as_array()) {+ let w: Vec<&str> = want.iter().filter_map(|v| v.as_str()).collect();+ comps.retain(|c| c["ref"].as_str().map(|r| w.iter().any(|x| x.eq_ignore_ascii_case(r))).unwrap_or(false));+ }+ let pads = st["pads"].as_array().cloned().unwrap_or_default();+ let before = on_pads(&comps, &pads, clear);+ let min_size = num("minSize", size).min(size);+ // the labels of parts left out stay put; so do the labels of parts with no spot, so plan again round those+ let label = |c: &Value| -> Option<(bool, Rect)> { if c["name"]["shown"].as_bool() == Some(false) { None } else { rect_of(&c["name"]["box"]).map(|r| (c["side"] == "bottom", r)) } };+ let mut fixed: Vec<(bool, Rect)> = all.iter().filter(|c| !comps.iter().any(|k| k["ref"] == c["ref"])).filter_map(label).collect();+ let mut moving = comps.clone();+ let (mut names, mut unplaced) = (Vec::new(), Vec::new());+ // every round pins at least one more label, so this ends; the last round leaves nothing unpinned+ for _ in 0..=comps.len() {+ let (n, u) = plan(&moving, &pads, bb, size, min_size, gap, clear, &fixed);+ names = n;+ if u.is_empty() { break; }+ let stuck: Vec<Value> = u.iter().map(|x| x["ref"].clone()).collect();+ fixed.extend(moving.iter().filter(|c| stuck.contains(&c["ref"])).filter_map(label));+ moving.retain(|c| !stuck.contains(&c["ref"]));+ unplaced.extend(u);+ }+ let apply: Vec<Value> = names.iter().map(|n| json!({"ref": n["ref"], "x": n["x"], "y": n["y"], "size": n["size"], "rotation": n["rotation"]})).collect();+ json!({"success": true, "planned": names, "unplaced": unplaced, "onPadsBefore": before, "sizeMm": size, "applyArgs": {"names": apply},+ "_hint": "A plan: every label upright (or turned 90 beside the part), one size, beside its own part, clear of pads by padClearance and of other bodies and labels. Send applyArgs to apply_silkscreen, then read silk_state back and check no label touches a pad with the tool's own text boxes. unplaced parts had no clear spot: try minSize for them (refs), move the part, or place the label by hand."})+}++#[cfg(test)]+mod tests {+ use super::*;++ fn comp(r: &str, body: [f64; 4]) -> Value {+ json!({"ref": r, "side": "top", "body": body, "name": {"text": r, "size": 1.0, "shown": true, "box": [0.0, 0.0, 2.0, 1.0]}})+ }++ #[test]+ fn labels_go_beside_their_part_clear_of_pads_and_each_other() {+ // C1 sits just above U1, where U1's label would go+ let comps = vec![comp("U1", [10.0, 10.0, 16.0, 16.0]), comp("C1", [12.0, 16.4, 14.0, 17.4])];+ let pads = vec![json!({"ref": "C1", "name": "1", "x": 12.5, "y": 16.9, "sizeX": 0.8, "sizeY": 0.8, "rotation": 0, "layer": "F.Cu"}),+ json!({"ref": "C1", "name": "2", "x": 13.5, "y": 16.9, "sizeX": 0.8, "sizeY": 0.8, "rotation": 0, "layer": "F.Cu"})];+ let (out, un) = plan(&comps, &pads, (0.0, 0.0, 40.0, 40.0), 1.0, 1.0, 0.2, 0.15, &[]);+ assert!(un.is_empty());+ // U1 above would land on C1's body and pads: it goes below+ assert_eq!(out[0]["ref"], "U1");+ assert_eq!(out[0]["at"], "below");+ assert_eq!(out[1]["ref"], "C1");+ assert_eq!(out[1]["at"], "above");+ assert_eq!(out[1]["y"], 17.6);+ assert_eq!(out[0]["y"], 8.8);+ }++ #[test]+ fn a_part_boxed_in_is_reported_not_forced() {+ let comps = vec![comp("R1", [1.0, 1.0, 3.0, 2.0])];+ let (out, un) = plan(&comps, &[], (0.0, 0.0, 4.0, 3.0), 1.0, 1.0, 0.2, 0.15, &[]);+ assert!(out.is_empty());+ assert_eq!(un[0]["ref"], "R1");+ let on = on_pads(&[json!({"ref": "R1", "side": "top", "name": {"shown": true, "box": [0.0, 0.0, 2.0, 1.0]}})],+ &[json!({"ref": "R1", "name": "1", "x": 1.0, "y": 0.5, "sizeX": 0.5, "sizeY": 0.5, "rotation": 0, "layer": "F.Cu"})], 0.15);+ assert_eq!(on.len(), 1);+ }+}
bridge-rs/vendor/adom-eda-checks/src/space.rsadded+239@@ -0,0 +1,239 @@+//! Room on the board: free spots for a part near another (clear of every other part on that side, of that side's+//! copper, and inside the outline), and two-pad parts a quarter turn would shorten the airlines of. From the Altium+//! bridge's design.rs; a part is the box of its pads and, with the bodies companion, of its 3D body.+use serde_json::{json, Value};+use std::collections::{BTreeMap, HashMap};++fn f(v: &Value) -> f64 { v.as_f64().unwrap_or(0.0) }+fn r3(v: f64) -> f64 { (v * 1000.0).round() / 1000.0 }+type Rect = (f64, f64, f64, f64);+fn grow(r: Rect, g: f64) -> Rect { (r.0 - g, r.1 - g, r.2 + g, r.3 + g) }+fn hits(a: Rect, b: Rect) -> bool { a.0 < b.2 && b.0 < a.2 && a.1 < b.3 && b.1 < a.3 }+fn dist(a: (f64, f64), b: (f64, f64)) -> f64 { ((a.0 - b.0).powi(2) + (a.1 - b.1).powi(2)).sqrt() }++/// The parts' boxes and sides, with their bodies when the companion came.+fn part_boxes(st: &Value, input: &Value) -> BTreeMap<String, (bool, Rect)> {+ let mut bodies: BTreeMap<String, Rect> = BTreeMap::new();+ for b in crate::bodies::input_boxes(input).unwrap_or_default() {+ let e = bodies.entry(b.part.clone()).or_insert((b.x0, b.y0, b.x1, b.y1));+ *e = (e.0.min(b.x0), e.1.min(b.y0), e.2.max(b.x1), e.3.max(b.y1));+ }+ crate::placement::part_boxes(st, &bodies)+}++/// find_space: input {board, bodies?, args: {near? | at?: {x, y}, part? | sizeMm?: [w, h], side?, clearanceMm?, edgeMm?,+/// count?, radiusMm?, copper?, check?}}. Free spots nearest first, as where the part's origin goes; with check: true,+/// the parts that already overlap or leave the outline.+pub fn find_space(input: &Value) -> Value {+ let st = match crate::input::board(input) { Ok(b) => b, Err(e) => return e };+ let args = &input["args"];+ let s = |k: &str| args[k].as_str().map(String::from);+ let ring = crate::coppermap::outline_ring(&st);+ let boxes = part_boxes(&st, input);+ let parts: Vec<(String, Rect, bool)> = boxes.iter().map(|(r, (b, x))| (r.clone(), *x, *b)).collect();+ let clr = args["clearanceMm"].as_f64().unwrap_or(0.25);+ let edge = args["edgeMm"].as_f64().unwrap_or(0.3);+ let seg = |p: (f64, f64), a: (f64, f64), b: (f64, f64)| {+ let (dx, dy) = (b.0 - a.0, b.1 - a.1);+ let l2 = dx * dx + dy * dy;+ let t = if l2 == 0.0 { 0.0 } else { (((p.0 - a.0) * dx + (p.1 - a.1) * dy) / l2).clamp(0.0, 1.0) };+ dist(p, (a.0 + t * dx, a.1 + t * dy))+ };+ let in_outline = |r: Rect| -> bool {+ if ring.len() < 3 { return true; }+ [(r.0, r.1), (r.2, r.1), (r.2, r.3), (r.0, r.3)].iter().all(|&c| crate::route::inside(c, &ring) && (0..ring.len()).all(|i| seg(c, ring[i], ring[(i + 1) % ring.len()]) >= edge))+ };+ if args["check"].as_bool() == Some(true) {+ // the same tests placement_check makes (fusion-lane): a part under a raised one (an Adom molecule on pins) whose+ // pads stay apart and whose bodies do not meet in 3D is stacked, not overlapping; a part is off the outline by+ // its pads' centres, not its box (a round board's edge cuts a box corner off a part well inside it)+ let pads = st["pads"].as_array().cloned().unwrap_or_default();+ let bodies = crate::bodies::input_boxes(input);+ let (mut overlaps, mut stacked) = (Vec::new(), Vec::new());+ for i in 0..parts.len() { for j in i + 1..parts.len() {+ if parts[i].2 != parts[j].2 || !hits(parts[i].1, parts[j].1) { continue; }+ let pair = json!([parts[i].0, parts[j].0]);+ match &bodies { Some(bs) if crate::placement::is_stacked(&pads, bs, &parts[i].0, &parts[j].0, 0.0) => stacked.push(pair), _ => overlaps.push(pair) }+ } }+ let outside: Vec<&String> = parts.iter().filter(|p| {+ let own: Vec<&Value> = pads.iter().filter(|q| q["ref"].as_str() == Some(p.0.as_str())).collect();+ ring.len() >= 3 && !own.is_empty() && own.iter().any(|q| !crate::route::inside((f(&q["x"]), f(&q["y"])), &ring))+ }).map(|p| &p.0).collect();+ return json!({"success": true, "overlaps": overlaps, "stacked": stacked, "outsideOutline": outside, "parts": parts.len(), "bodiesUsed": bodies.is_some(),+ "_hint": "Overlaps compare part boxes (pads, and 3D bodies when given) on the same side; placement_check adds margins, stacked parts and mounting holes. find_space {near, part} finds a free spot; move_parts moves it."});+ }+ let comp = |d: &str| st["components"].as_array().and_then(|a| a.iter().find(|c| c["ref"].as_str().map(|r| r.eq_ignore_ascii_case(d)).unwrap_or(false)).cloned());+ // what to place: an existing part (its extent and origin) or a size+ let me = s("part").and_then(|p| parts.iter().find(|x| x.0.eq_ignore_ascii_case(&p)).cloned());+ let (w, h, off, my_bottom) = match (&me, args["sizeMm"].as_array()) {+ (Some((d, r, b)), _) => {+ let c = comp(d).unwrap_or(Value::Null);+ let (ox, oy) = (c["x"].as_f64().unwrap_or((r.0 + r.2) / 2.0), c["y"].as_f64().unwrap_or((r.1 + r.3) / 2.0));+ (r.2 - r.0, r.3 - r.1, (ox - (r.0 + r.2) / 2.0, oy - (r.1 + r.3) / 2.0), *b)+ }+ (None, Some(sz)) if sz.len() == 2 => (f(&sz[0]).max(0.01), f(&sz[1]).max(0.01), (0.0, 0.0), false),+ _ => return crate::input::refuse("bad_args", "part (a designator on the board) or sizeMm [w, h] is required"),+ };+ let bottom = match s("side").as_deref() { Some("bottom") => true, Some("top") => false, _ => my_bottom };+ let (cx, cy) = if let Some(n) = s("near") {+ match parts.iter().find(|x| x.0.eq_ignore_ascii_case(&n)) { Some((_, r, _)) => ((r.0 + r.2) / 2.0, (r.1 + r.3) / 2.0), None => return crate::input::refuse("no_such_part", &format!("{n} is not on the board")) }+ } else if args["at"].is_object() {+ (f(&args["at"]["x"]), f(&args["at"]["y"]))+ } else { return crate::input::refuse("bad_args", "near (a designator) or at {x, y} is required") };+ let mine = me.as_ref().map(|m| m.0.clone()).unwrap_or_default();+ let mut blocks: Vec<Rect> = parts.iter().filter(|p| p.2 == bottom && !p.0.eq_ignore_ascii_case(&mine)).map(|p| grow(p.1, clr)).collect();+ if args["copper"].as_bool() != Some(false) {+ let layer = if bottom { "B.Cu" } else { "F.Cu" };+ // net-less tracks are a hatched pour's pieces, which re-pour round a new part (6473 of them on the Bluetooth+ // Sentinel left no spot anywhere)+ for t in st["tracks"].as_array().into_iter().flatten().filter(|t| t["layer"] == layer && t["net"].as_str().map(|n| !n.is_empty()).unwrap_or(false)) {+ let (a, b, hw) = ((f(&t["start"]["x"]), f(&t["start"]["y"])), (f(&t["end"]["x"]), f(&t["end"]["y"])), f(&t["width"]) / 2.0);+ blocks.push(grow((a.0.min(b.0), a.1.min(b.1), a.0.max(b.0), a.1.max(b.1)), hw + clr));+ }+ for v in st["vias"].as_array().into_iter().flatten() {+ let (x, y, r) = (f(&v["position"]["x"]), f(&v["position"]["y"]), f(&v["size"]) / 2.0);+ blocks.push(grow((x - r, y - r, x + r, y + r), clr));+ }+ }+ let count = args["count"].as_u64().unwrap_or(5) as usize;+ let radius = args["radiusMm"].as_f64().unwrap_or(10.0);+ let step = 0.25;+ let n = (radius / step).ceil() as i64;+ let mut cands: Vec<(f64, f64, f64)> = Vec::new();+ for i in -n..=n { for j in -n..=n {+ let (x, y) = (cx + i as f64 * step, cy + j as f64 * step);+ let d = dist((x, y), (cx, cy));+ if d <= radius { cands.push((d, x, y)); }+ } }+ cands.sort_by(|a, b| a.0.partial_cmp(&b.0).unwrap());+ let (mut spots, mut taken): (Vec<Value>, Vec<Rect>) = (Vec::new(), Vec::new());+ for (d, x, y) in cands {+ let r = (x - w / 2.0, y - h / 2.0, x + w / 2.0, y + h / 2.0);+ if blocks.iter().any(|b| hits(r, *b)) || taken.iter().any(|t| hits(r, *t)) || !in_outline(r) { continue; }+ spots.push(json!({"x": r3(x + off.0), "y": r3(y + off.1), "distanceMm": r3(d), "extent": [r3(r.0), r3(r.1), r3(r.2), r3(r.3)]}));+ taken.push(grow(r, clr));+ if spots.len() >= count { break; }+ }+ if spots.is_empty() { return json!({"success": false, "errorCode": "no_space", "error": format!("no free {} x {} mm spot within {radius} mm", r3(w), r3(h)), "spots": []}); }+ json!({"success": true, "spots": spots, "part": if mine.is_empty() { Value::Null } else { json!(mine) }, "sizeMm": [r3(w), r3(h)], "side": if bottom { "bottom" } else { "top" },+ "_hint": "spots[].x/y are where the part's origin goes: move_parts {parts:[{ref, x, y, rotation}]}, then repour (pours are not avoided: they clear round the new pads). Each spot keeps clearanceMm from other part boxes on that side, from that side's tracks and vias, and edgeMm from the outline; nearest first. find_space {check: true} lists parts that already overlap."})+}++/// Minimum spanning tree length of points (Prim's, O(n^2): nets are small).+fn mst(pts: &[(f64, f64)]) -> f64 {+ if pts.len() < 2 { return 0.0; }+ let (mut inside, mut best) = (vec![false; pts.len()], vec![f64::MAX; pts.len()]);+ best[0] = 0.0;+ let mut total = 0.0;+ for _ in 0..pts.len() {+ let mut u = usize::MAX;+ for i in 0..pts.len() { if !inside[i] && (u == usize::MAX || best[i] < best[u]) { u = i; } }+ inside[u] = true;+ total += best[u];+ for v in 0..pts.len() { if !inside[v] { let d = dist(pts[u], pts[v]); if d < best[v] { best[v] = d; } } }+ }+ total+}++/// check_orientation: input {board, args: {parts?, minImprovementMm?, planeNetPads?}}. Advisory: each two-pad part's+/// quarter turns scored in place, a routable net by its airline (MST) length with the pad there, a plane-like net+/// (more than planeNetPads pads, GND) by the distance to its nearest same-net pad. Turns that save minImprovementMm or+/// more are reported; nothing moves.+pub fn check_orientation(input: &Value) -> Value {+ let st = match crate::input::board(input) { Ok(b) => b, Err(e) => return e };+ let args = &input["args"];+ let min_gain = args["minImprovementMm"].as_f64().unwrap_or(0.6);+ let plane_pads = args["planeNetPads"].as_u64().unwrap_or(12) as usize;+ let want: Vec<String> = args["parts"].as_array().map(|a| a.iter().filter_map(|x| x.as_str().map(|s| s.to_ascii_uppercase())).collect()).unwrap_or_default();+ let pads = st["pads"].as_array().cloned().unwrap_or_default();+ let mut net_pads: HashMap<String, Vec<(String, (f64, f64))>> = HashMap::new();+ for p in &pads {+ let n = p["net"].as_str().unwrap_or("");+ if !n.is_empty() { net_pads.entry(n.to_string()).or_default().push((p["ref"].as_str().unwrap_or("").to_string(), (f(&p["x"]), f(&p["y"])))); }+ }+ let (mut findings, mut checked) = (Vec::new(), 0);+ for c in st["components"].as_array().into_iter().flatten() {+ let r = c["ref"].as_str().unwrap_or("").to_string();+ if !want.is_empty() && !want.contains(&r.to_ascii_uppercase()) { continue; }+ let mine: Vec<&Value> = pads.iter().filter(|p| p["ref"].as_str() == Some(&r)).collect();+ if mine.len() != 2 { continue; }+ checked += 1;+ let (cx, cy, rot) = (f(&c["x"]), f(&c["y"]), f(&c["rotation"]));+ // the airlines with the part turned by delta degrees (counterclockwise, y up)+ let score = |delta: f64| -> f64 {+ let a = delta.to_radians();+ let mut total = 0.0;+ for p in &mine {+ let net = p["net"].as_str().unwrap_or("");+ if net.is_empty() { continue; }+ let (px, py) = (f(&p["x"]) - cx, f(&p["y"]) - cy);+ let at = (cx + px * a.cos() - py * a.sin(), cy + px * a.sin() + py * a.cos());+ let others: Vec<(f64, f64)> = net_pads.get(net).map(|v| v.iter().filter(|(o, _)| o != &r).map(|(_, q)| *q).collect()).unwrap_or_default();+ if others.is_empty() { continue; }+ total += if others.len() + 1 > plane_pads { others.iter().map(|q| dist(at, *q)).fold(f64::MAX, f64::min) } else { let mut pts = others.clone(); pts.push(at); mst(&pts) };+ }+ total+ };+ let now = score(0.0);+ let mut best = (0.0, now);+ for d in [90.0, 180.0, 270.0] { let sc = score(d); if sc < best.1 - 1e-9 { best = (d, sc); } }+ if now - best.1 >= min_gain {+ findings.push(json!({"ref": r, "rotation": rot, "suggested": (rot + best.0).rem_euclid(360.0), "airlineNowMm": r3(now), "airlineThenMm": r3(best.1), "savesMm": r3(now - best.1)}));+ }+ }+ findings.sort_by(|a, b| f(&b["savesMm"]).partial_cmp(&f(&a["savesMm"])).unwrap_or(std::cmp::Ordering::Equal));+ json!({"success": true, "checked": checked, "suggestions": findings,+ "_hint": "Advisory only: each two-pad part's quarter turns scored by airline length (MST of a routable net with the pad there; distance to the nearest pad of a plane-like net such as GND). Turn with move_parts {parts:[{ref, rotation}]} (position kept), then reroute those nets. Routed copper is not considered: on a routed board, treat these as hints."})+}++#[cfg(test)]+mod tests {+ use super::*;++ fn pad(r: &str, n: &str, x: f64, y: f64, net: &str) -> Value {+ json!({"ref": r, "name": n, "x": x, "y": y, "sizeX": 0.6, "sizeY": 0.6, "rotation": 0, "layer": "F.Cu", "drill": 0, "net": net, "shape": "rect"})+ }++ fn board() -> Value {+ // R1 lies along x, but its nets go up and down: a quarter turn shortens both airlines+ json!({"outline": [[0, 0], [20, 0], [20, 20], [0, 20]],+ "components": [{"ref": "R1", "x": 10.0, "y": 10.0, "rotation": 0.0, "side": "top"}, {"ref": "U1", "x": 10.0, "y": 15.0, "rotation": 0.0, "side": "top"}, {"ref": "U2", "x": 10.0, "y": 5.0, "rotation": 0.0, "side": "top"}],+ "pads": [pad("R1", "1", 9.0, 10.0, "A"), pad("R1", "2", 11.0, 10.0, "B"), pad("U1", "1", 10.0, 15.0, "A"), pad("U1", "2", 11.0, 15.0, "X"), pad("U2", "1", 10.0, 5.0, "B"), pad("U2", "2", 11.0, 5.0, "Y")]})+ }++ #[test]+ fn a_quarter_turn_that_shortens_the_airlines_is_suggested() {+ let r = check_orientation(&json!({"board": board(), "args": {}}));+ // U1 and U2 have two pads too, but turning them about the pad at their origin gains nothing+ assert_eq!((r["checked"].clone(), r["suggestions"].as_array().unwrap().len()), (json!(3), 1), "{r}");+ let s = &r["suggestions"][0];+ // pad 1 (net A) has to come up to U1: a quarter turn clockwise, 270 counterclockwise+ assert_eq!((s["ref"].as_str(), s["suggested"].as_f64()), (Some("R1"), Some(270.0)), "{r}");+ assert!(f(&s["savesMm"]) > 0.6);+ }++ #[test]+ fn free_spots_avoid_parts_copper_and_the_edge() {+ let mut b = board();+ b["tracks"] = json!([{"layer": "F.Cu", "net": "A", "width": 0.25, "start": {"x": 12.0, "y": 0.0}, "end": {"x": 12.0, "y": 20.0}}]);+ let r = find_space(&json!({"board": b, "args": {"near": "R1", "sizeMm": [2.0, 1.0], "count": 3}}));+ assert_eq!(r["success"], json!(true), "{r}");+ for s in r["spots"].as_array().unwrap() {+ let e: Vec<f64> = s["extent"].as_array().unwrap().iter().map(f).collect();+ // clear of R1's box (8.7..11.3 x 9.7..10.3) by 0.25, of the track at x 12 by 0.125 + 0.25+ assert!(e[2] <= 8.7 - 0.25 + 1e-9 || e[0] >= 11.3 + 0.25 - 1e-9 || e[3] <= 9.7 - 0.25 + 1e-9 || e[1] >= 10.3 + 0.25 - 1e-9, "{s}");+ assert!(e[2] <= 12.0 - 0.375 + 1e-9 || e[0] >= 12.0 + 0.375 - 1e-9, "{s}");+ }+ let chk = find_space(&json!({"board": board(), "args": {"check": true}}));+ assert_eq!((chk["overlaps"].as_array().unwrap().len(), chk["outsideOutline"].as_array().unwrap().len()), (0, 0));+ // a part under a raised molecule: pads apart, bodies apart in height, so stacked, not an overlap (fusion-lane)+ let mut m = board();+ m["components"].as_array_mut().unwrap().push(json!({"ref": "M1", "x": 10.0, "y": 10.0, "rotation": 0.0, "side": "top"}));+ m["pads"].as_array_mut().unwrap().extend([pad("M1", "1", 6.0, 10.0, "P"), pad("M1", "2", 14.0, 10.0, "Q")]);+ let bodies = json!({"bodies": [{"ref": "M1", "side": "top", "x0": 5.5, "y0": 8.0, "x1": 14.5, "y1": 12.0, "z0": 3.0, "z1": 4.0},+ {"ref": "R1", "side": "top", "x0": 8.7, "y0": 9.7, "x1": 11.3, "y1": 10.3, "z0": 0.0, "z1": 0.5}]});+ let s = find_space(&json!({"board": m, "bodies": bodies, "args": {"check": true}}));+ assert_eq!((s["overlaps"].as_array().unwrap().len(), s["stacked"].clone(), s["bodiesUsed"].clone()), (0, json!([["M1", "R1"]]), json!(true)), "{s}");+ assert_eq!(find_space(&json!({"board": board(), "args": {"near": "Q9", "sizeMm": [1, 1]}}))["errorCode"], "no_such_part");+ }+}
bridge-rs/vendor/adom-eda-checks/src/writers/ipc2581.rsadded+398@@ -0,0 +1,398 @@+//! IPC-2581 revision C (mm) for assembly and test, from the board model: the layers and stack-up, the outline, one+//! package per footprint (pins in the footprint's own frame), the components and BOM, the nets with their pins, and on+//! each copper layer the pads (with their pin), traces, arcs, vias and, with pour_state, the poured copper island by+//! island, plus the drills. From the Fusion bridge's routing_script.py `ipc2581_xml`, which validates against the+//! IPC-2581C schema; the element order follows it.+use super::dxf::f;+use serde_json::{json, Value};++/// A number as IPC-2581 wants it: up to 4 decimals, no trailing zeros.+fn n(v: f64) -> String {+ let s = format!("{:.4}", if v.abs() < 5e-5 { 0.0 } else { v });+ let s = s.trim_end_matches('0').trim_end_matches('.');+ if s.is_empty() || s == "-" { "0".into() } else { s.to_string() }+}++/// Fab formats are read by ASCII tools: the usual unit signs by name (10kΩ -> 10kohm), '?' for the rest.+fn ascii(t: &str) -> String {+ t.chars().map(|c| match c {+ c if (c as u32) < 128 => c.to_string(),+ '\u{03A9}' | '\u{2126}' => "ohm".into(), '\u{00B5}' | '\u{03BC}' => "u".into(), '\u{00B1}' => "+/-".into(), '\u{00B0}' => "deg".into(), '\u{2013}' | '\u{2014}' => "-".into(),+ _ => "?".into(),+ }).collect()+}++/// An attribute value: ASCII, XML-escaped.+fn a(t: &str) -> String { ascii(t).replace('&', "&").replace('<', "<").replace('>', ">").replace('"', """) }++/// The pad primitives used, by id, in the order first used.+#[derive(Default)]+struct Dict { ids: Vec<(String, String)> }++impl Dict {+ /// A pad's primitive: a circle, an oval (a stadium) or a centred rectangle.+ fn pad(&mut self, shape: &str, w: f64, h: f64) -> String {+ let round = matches!(shape, "round" | "circle");+ let (id, el) = if round && (w - h).abs() < 1e-6 {+ (format!("CIRCLE_{}", n(w)), format!("<Circle diameter=\"{}\"/>", n(w)))+ } else if round {+ (format!("OVAL_{}x{}", n(w), n(h)), format!("<Oval width=\"{}\" height=\"{}\"/>", n(w), n(h)))+ } else {+ (format!("RECT_{}x{}", n(w), n(h)), format!("<RectCenter width=\"{}\" height=\"{}\"/>", n(w), n(h)))+ };+ let id = id.replace('.', "_").replace('-', "m");+ if !self.ids.iter().any(|(i, _)| *i == id) { self.ids.push((id.clone(), el)); }+ id+ }+ fn xml(&self) -> String {+ let mut o = String::from(" <DictionaryStandard units=\"MILLIMETER\">\n");+ for (id, el) in &self.ids { o += &format!(" <EntryStandard id=\"{id}\">{el}</EntryStandard>\n"); }+ o + " </DictionaryStandard>\n"+ }+}++/// A closed outline from the board model's outline edges (lines and arcs), or its point list.+fn profile_polygon(st: &Value) -> String {+ let edges = st["outlineEdges"].as_array().cloned().unwrap_or_default();+ let pt = |v: &Value| (f(&v[0]), f(&v[1]));+ let mut o = String::from(" <Polygon>\n");+ if !edges.is_empty() {+ let first = pt(&edges[0]["start"]);+ o += &format!(" <PolyBegin x=\"{}\" y=\"{}\"/>\n", n(first.0), n(first.1));+ for (i, e) in edges.iter().enumerate() {+ // an edge ends where the next begins (the last closes the ring)+ let end = if e["end"].is_array() { pt(&e["end"]) } else { pt(&edges[(i + 1) % edges.len()]["start"]) };+ if e["kind"] == "arc" {+ let cw = super::dxf::bulge(e) < 0.0;+ o += &format!(" <PolyStepCurve x=\"{}\" y=\"{}\" centerX=\"{}\" centerY=\"{}\" clockwise=\"{cw}\"/>\n", n(end.0), n(end.1), n(f(&e["center"][0])), n(f(&e["center"][1])));+ } else {+ o += &format!(" <PolyStepSegment x=\"{}\" y=\"{}\"/>\n", n(end.0), n(end.1));+ }+ }+ } else {+ let ring: Vec<(f64, f64)> = st["outline"].as_array().cloned().unwrap_or_default().iter().map(pt).collect();+ if let Some(first) = ring.first() {+ o += &format!(" <PolyBegin x=\"{}\" y=\"{}\"/>\n", n(first.0), n(first.1));+ for p in ring.iter().skip(1).chain(std::iter::once(first)) { o += &format!(" <PolyStepSegment x=\"{}\" y=\"{}\"/>\n", n(p.0), n(p.1)); }+ }+ }+ o + " </Polygon>\n"+}++/// A ring of [x, y] as an IPC-2581 Polygon or Cutout (closed).+fn ring_xml(tag: &str, ring: &[(f64, f64)], ind: &str) -> String {+ let mut o = format!("{ind}<{tag}>\n{ind} <PolyBegin x=\"{}\" y=\"{}\"/>\n", n(ring[0].0), n(ring[0].1));+ for p in ring.iter().skip(1).chain(std::iter::once(&ring[0])) { o += &format!("{ind} <PolyStepSegment x=\"{}\" y=\"{}\"/>\n", n(p.0), n(p.1)); }+ o + &format!("{ind}</{tag}>\n")+}++/// The board as IPC-2581C text and what it holds.+pub fn ipc2581_text(st: &Value, input: &Value, title: &str, date: &str) -> (String, Value) {+ let arr = |v: &Value, k: &str| v[k].as_array().cloned().unwrap_or_default();+ let name = { let s: String = ascii(title).chars().map(|c| if c.is_ascii_alphanumeric() || "_.-".contains(c) { c } else { '_' }).collect(); if s.is_empty() { "board".into() } else { s } };+ let copper = crate::placetools::copper_layers(st, input);+ let lname = |i: usize| if i == 0 { "TOP".to_string() } else if i + 1 == copper.len() { "BOTTOM".to_string() } else { format!("INNER{i}") };+ let idx = |l: &str| copper.iter().position(|c| c == l);+ let mut dict = Dict::default();+ let comps = arr(st, "components");+ let pads = arr(st, "pads");+ let vias = arr(st, "vias");+ let stack = crate::input::stack(input);++ // the BOM: one item per pattern (and value, when the model carries one)+ let mut groups: Vec<((String, String), Vec<&Value>)> = Vec::new();+ for c in &comps {+ if !pads.iter().any(|p| p["ref"] == c["ref"]) { continue; }+ let k = (c["pattern"].as_str().unwrap_or("").to_string(), c["value"].as_str().unwrap_or("").to_string());+ match groups.iter_mut().find(|g| g.0 == k) { Some(g) => g.1.push(c), None => groups.push((k, vec![c])) }+ }+ groups.sort_by(|x, y| x.0.cmp(&y.0));+ let part_id = |p: &str, v: &str| { let s = a(&format!("{p}_{v}")); let s = s.trim_matches('_').to_string(); if s.is_empty() { "PART".to_string() } else { s } };+ let mut bom = format!(" <Bom name=\"{name}_BOM\">\n <BomHeader assembly=\"{name}\" revision=\"1\">\n <StepRef name=\"{name}\"/>\n </BomHeader>\n");+ for ((pat, val), cs) in &groups {+ bom += &format!(" <BomItem OEMDesignNumberRef=\"{}\" quantity=\"{}\" category=\"ELECTRICAL\" description=\"{}\">\n", part_id(pat, val), cs.len(), a(val));+ for c in cs {+ bom += &format!(" <RefDes name=\"{}\" packageRef=\"{}\" populate=\"true\" layerRef=\"{}\"/>\n", a(c["ref"].as_str().unwrap_or("")), a(pat), if c["side"] == "bottom" { "BOTTOM" } else { "TOP" });+ }+ bom += " <Characteristics category=\"ELECTRICAL\">\n";+ if !val.is_empty() { bom += &format!(" <Textual definitionSource=\"board model\" textualCharacteristicName=\"Value\" textualCharacteristicValue=\"{}\"/>\n", a(val)); }+ bom += " </Characteristics>\n </BomItem>\n";+ }+ bom += " </Bom>\n";++ // layers and the stack-up+ let mut cad = String::from(" <CadData>\n");+ for (i, _) in copper.iter().enumerate() {+ let side = if i == 0 { "TOP" } else if i + 1 == copper.len() { "BOTTOM" } else { "INTERNAL" };+ cad += &format!(" <Layer name=\"{}\" layerFunction=\"SIGNAL\" side=\"{side}\" polarity=\"POSITIVE\"/>\n", lname(i));+ }+ cad += " <Layer name=\"DRILL_TOP_BOTTOM\" layerFunction=\"DRILL\" side=\"ALL\" polarity=\"POSITIVE\"/>\n";+ let total = stack.as_ref().and_then(|s| s["totalUm"].as_f64()).filter(|t| *t > 0.0).unwrap_or(1600.0) / 1000.0;+ let cu: Vec<f64> = stack.as_ref().map(|s| arr(s, "layers").iter().map(|l| f(&l["copperUm"])).filter(|c| *c > 0.0).collect()).unwrap_or_default();+ cad += &format!(" <Stackup name=\"PRIMARY\" overallThickness=\"{}\" tolPlus=\"0\" tolMinus=\"0\" whereMeasured=\"METAL\" stackupStatus=\"PROPOSED\">\n <StackupGroup name=\"PRIMARY\" thickness=\"{}\" tolPlus=\"0\" tolMinus=\"0\">\n", n(total), n(total));+ for i in 0..copper.len() {+ cad += &format!(" <StackupLayer layerOrGroupRef=\"{}\" thickness=\"{}\" tolPlus=\"0\" tolMinus=\"0\" sequence=\"{}\"/>\n", lname(i), n(cu.get(i).copied().unwrap_or(35.0) / 1000.0), i + 1);+ }+ cad += " </StackupGroup>\n </Stackup>\n";+ let mut step = format!(" <Step name=\"{name}\">\n");++ // via padstacks, one per size and drill+ let mut vstacks: Vec<((String, String), String)> = Vec::new();+ for v in &vias {+ let key = (n(f(&v["size"])), n(f(&v["drill"])));+ if vstacks.iter().any(|x| x.0 == key) { continue; }+ let vn = format!("VIA_{}_{}", key.0, key.1).replace('.', "_");+ let prim = dict.pad("round", f(&v["size"]), f(&v["size"]));+ step += &format!(" <PadStackDef name=\"{vn}\">\n <PadstackHoleDef name=\"H{vn}\" diameter=\"{}\" platingStatus=\"VIA\" plusTol=\"0\" minusTol=\"0\" x=\"0\" y=\"0\"/>\n", key.1);+ for i in 0..copper.len() {+ step += &format!(" <PadstackPadDef layerRef=\"{}\" padUse=\"REGULAR\">\n <Location x=\"0\" y=\"0\"/>\n <StandardPrimitiveRef id=\"{prim}\"/>\n </PadstackPadDef>\n", lname(i));+ }+ step += " </PadStackDef>\n";+ vstacks.push((key, vn));+ }+ step += " <Datum x=\"0\" y=\"0\"/>\n <Profile>\n";+ step += &profile_polygon(st).replace(" <Polygon>", " <Polygon>").replace("\n <Poly", "\n <Poly").replace(" </Polygon>", " </Polygon>");+ step += " </Profile>\n";++ // packages: one per pattern, pins in the footprint's own frame (mirrored back for a bottom part)+ let mut made: Vec<(String, bool)> = Vec::new();+ let mut pkg_xml = String::new();+ for c in &comps {+ let rf = c["ref"].as_str().unwrap_or("");+ let own: Vec<&Value> = pads.iter().filter(|p| p["ref"].as_str() == Some(rf)).collect();+ let pat = { let p = c["pattern"].as_str().unwrap_or(""); if p.is_empty() { format!("PKG_{rf}") } else { p.to_string() } };+ if own.is_empty() || made.iter().any(|m| m.0 == pat) { continue; }+ let (cx, cy, th) = (f(&c["x"]), f(&c["y"]), f(&c["rotation"]).to_radians());+ let bottom = c["side"] == "bottom";+ let th_part = own.iter().any(|p| f(&p["drill"]) > 0.0);+ let mut pins = String::new();+ let mut bb = (f64::MAX, f64::MAX, f64::MIN, f64::MIN);+ for p in &own {+ let (dx, dy) = (f(&p["x"]) - cx, f(&p["y"]) - cy);+ let (mut lx, ly) = (dx * th.cos() + dy * th.sin(), -dx * th.sin() + dy * th.cos());+ if bottom { lx = -lx; }+ let mut rot = (f(&p["rotation"]) - f(&c["rotation"])).rem_euclid(360.0);+ if bottom { rot = (360.0 - rot).rem_euclid(360.0); }+ let (w, h) = (f(&p["sizeX"]), f(&p["sizeY"]));+ let half = w.max(h).max(f(&p["drill"])) / 2.0;+ bb = (bb.0.min(lx - half), bb.1.min(ly - half), bb.2.max(lx + half), bb.3.max(ly + half));+ let prim = dict.pad(p["shape"].as_str().unwrap_or("rect"), w, h);+ pins += &format!(" <Pin number=\"{}\" type=\"{}\">\n", a(p["name"].as_str().unwrap_or("")), if f(&p["drill"]) > 0.0 { "THRU" } else { "SURFACE" });+ if rot.abs() > 1e-6 && (rot - 360.0).abs() > 1e-6 { pins += &format!(" <Xform rotation=\"{}\"/>\n", n(rot)); }+ pins += &format!(" <Location x=\"{}\" y=\"{}\"/>\n <StandardPrimitiveRef id=\"{prim}\"/>\n </Pin>\n", n(lx), n(ly));+ }+ pkg_xml += &format!(" <Package name=\"{}\" type=\"OTHER\" pinOneOrientation=\"OTHER\">\n <Outline>\n{} <LineDesc lineEnd=\"ROUND\" lineWidth=\"0.1\"/>\n </Outline>\n{pins} </Package>\n",+ a(&pat), ring_xml("Polygon", &[(bb.0, bb.1), (bb.2, bb.1), (bb.2, bb.3), (bb.0, bb.3)], " "));+ made.push((pat, th_part));+ }+ step += &pkg_xml;+ for c in &comps {+ let rf = c["ref"].as_str().unwrap_or("");+ let pat = { let p = c["pattern"].as_str().unwrap_or(""); if p.is_empty() { format!("PKG_{rf}") } else { p.to_string() } };+ let Some((_, th_part)) = made.iter().find(|m| m.0 == pat) else { continue };+ if !pads.iter().any(|p| p["ref"].as_str() == Some(rf)) { continue; }+ let bottom = c["side"] == "bottom";+ step += &format!(" <Component refDes=\"{}\" packageRef=\"{}\" part=\"{}\" layerRef=\"{}\" mountType=\"{}\">\n", a(rf), a(&pat),+ part_id(c["pattern"].as_str().unwrap_or(""), c["value"].as_str().unwrap_or("")), if bottom { "BOTTOM" } else { "TOP" }, if *th_part { "THMT" } else { "SMT" });+ let rot = f(&c["rotation"]).rem_euclid(360.0);+ let has_rot = rot.abs() > 1e-6 && (rot - 360.0).abs() > 1e-6;+ if has_rot || bottom {+ step += &format!(" <Xform{}{}/>\n", if has_rot { format!(" rotation=\"{}\"", n(rot)) } else { String::new() }, if bottom { " mirror=\"true\"" } else { "" });+ }+ step += &format!(" <Location x=\"{}\" y=\"{}\"/>\n </Component>\n", n(f(&c["x"])), n(f(&c["y"])));+ }+ // nets with their pins+ let mut nets: Vec<(String, Vec<&Value>)> = Vec::new();+ for p in &pads {+ let (Some(net), Some(r)) = (p["net"].as_str().filter(|s| !s.is_empty()), p["ref"].as_str().filter(|s| !s.is_empty())) else { continue };+ let _ = r;+ match nets.iter_mut().find(|x| x.0 == net) { Some(x) => x.1.push(p), None => nets.push((net.to_string(), vec![p])) }+ }+ nets.sort_by(|x, y| x.0.cmp(&y.0));+ for (net, ps) in &nets {+ step += &format!(" <LogicalNet name=\"{}\">\n", a(net));+ for p in ps { step += &format!(" <PinRef componentRef=\"{}\" pin=\"{}\"/>\n", a(p["ref"].as_str().unwrap_or("")), a(p["name"].as_str().unwrap_or(""))); }+ step += " </LogicalNet>\n";+ }++ // copper, layer by layer: sets of features by net and use+ let zones = crate::input::pours(input);+ let (mut n_pads, mut n_traces, mut n_arcs, mut n_vias, mut n_islands) = (0, 0, 0, 0, 0);+ for (li, layer) in copper.iter().enumerate() {+ let mut sets: Vec<((String, &str), String)> = Vec::new();+ let mut put = |net: &str, kind: &'static str, body: String| {+ match sets.iter_mut().find(|s| s.0 .0 == net && s.0 .1 == kind) { Some(s) => s.1 += &body, None => sets.push(((net.to_string(), kind), body)) }+ };+ for p in &pads {+ let on = p["layer"].as_str() == Some(layer.as_str()) || p["layer"] == "*.Cu" || f(&p["drill"]) > 0.0;+ if !on { continue; }+ let rot = f(&p["rotation"]).rem_euclid(360.0);+ let prim = dict.pad(p["shape"].as_str().unwrap_or("rect"), f(&p["sizeX"]), f(&p["sizeY"]));+ let mut b = String::from(" <Pad>\n");+ if rot.abs() > 1e-6 && (rot - 360.0).abs() > 1e-6 { b += &format!(" <Xform rotation=\"{}\"/>\n", n(rot)); }+ b += &format!(" <Location x=\"{}\" y=\"{}\"/>\n <StandardPrimitiveRef id=\"{prim}\"/>\n", n(f(&p["x"])), n(f(&p["y"])));+ if let Some(r) = p["ref"].as_str().filter(|s| !s.is_empty()) { b += &format!(" <PinRef componentRef=\"{}\" pin=\"{}\"/>\n", a(r), a(p["name"].as_str().unwrap_or(""))); }+ b += " </Pad>\n";+ put(p["net"].as_str().unwrap_or(""), "pad", b);+ n_pads += 1;+ }+ for v in &vias {+ let ls: Vec<usize> = v["layers"].as_array().map(|x| x.iter().filter_map(|l| l.as_str().and_then(idx)).collect()).unwrap_or_default();+ let (lo, hi) = if ls.len() == 2 { (ls[0].min(ls[1]), ls[0].max(ls[1])) } else { (0, copper.len() - 1) };+ if li < lo || li > hi { continue; }+ let key = (n(f(&v["size"])), n(f(&v["drill"])));+ let vn = &vstacks.iter().find(|x| x.0 == key).unwrap().1;+ let prim = dict.pad("round", f(&v["size"]), f(&v["size"]));+ put(v["net"].as_str().unwrap_or(""), "via", format!(" <Pad padstackDefRef=\"{vn}\">\n <Location x=\"{}\" y=\"{}\"/>\n <StandardPrimitiveRef id=\"{prim}\"/>\n </Pad>\n", n(f(&v["position"]["x"])), n(f(&v["position"]["y"]))));+ n_vias += 1;+ }+ for t in arr(st, "tracks").iter().filter(|t| t["layer"].as_str() == Some(layer.as_str())) {+ put(t["net"].as_str().unwrap_or(""), "trace", format!(" <Features>\n <Line startX=\"{}\" startY=\"{}\" endX=\"{}\" endY=\"{}\">\n <LineDesc lineEnd=\"ROUND\" lineWidth=\"{}\"/>\n </Line>\n </Features>\n",+ n(f(&t["start"]["x"])), n(f(&t["start"]["y"])), n(f(&t["end"]["x"])), n(f(&t["end"]["y"])), n(f(&t["width"]))));+ n_traces += 1;+ }+ for r in arr(st, "arcs").iter().filter(|r| r["layer"].as_str() == Some(layer.as_str())) {+ let (cx, cy, rad) = (f(&r["center"]["x"]), f(&r["center"]["y"]), f(&r["radius"]));+ let (s0, s1) = (f(&r["startAngle"]).to_radians(), f(&r["endAngle"]).to_radians());+ put(r["net"].as_str().unwrap_or(""), "trace", format!(" <Features>\n <Arc startX=\"{}\" startY=\"{}\" endX=\"{}\" endY=\"{}\" centerX=\"{}\" centerY=\"{}\" clockwise=\"false\">\n <LineDesc lineEnd=\"ROUND\" lineWidth=\"{}\"/>\n </Arc>\n </Features>\n",+ n(cx + rad * s0.cos()), n(cy + rad * s0.sin()), n(cx + rad * s1.cos()), n(cy + rad * s1.sin()), n(cx), n(cy), n(f(&r["width"]))));+ n_arcs += 1;+ }+ for z in zones.iter().filter(|z| z["layer"].as_str() == Some(layer.as_str())) {+ for fill in arr(z, "fills") {+ let ring = |v: &Value| -> Vec<(f64, f64)> { v.as_array().cloned().unwrap_or_default().iter().map(|q| (f(&q[0]), f(&q[1]))).collect() };+ let outer = ring(&fill["outline"]);+ if outer.len() < 3 { continue; }+ let mut b = String::from(" <Features>\n <Contour>\n");+ b += &ring_xml("Polygon", &outer, " ");+ for h in arr(&fill, "holes") { let h = ring(&h); if h.len() >= 3 { b += &ring_xml("Cutout", &h, " "); } }+ b += " </Contour>\n </Features>\n";+ put(z["net"].as_str().unwrap_or(""), "pour", b);+ n_islands += 1;+ }+ }+ step += &format!(" <LayerFeature layerRef=\"{}\">\n", lname(li));+ for ((net, kind), body) in &sets {+ let mut attrs = if net.is_empty() { String::new() } else { format!(" net=\"{}\"", a(net)) };+ if *kind == "pad" { attrs += " padUsage=\"TERMINATION\""; } else if *kind == "via" { attrs += " padUsage=\"VIA\""; }+ step += &format!(" <Set{attrs}>\n{body} </Set>\n");+ }+ step += " </LayerFeature>\n";+ }+ // the drills: plated pad holes (a hole with no copper ring round it is non-plated), vias+ let mut holes: Vec<(String, f64, f64, f64, &str)> = pads.iter().filter(|p| f(&p["drill"]) > 0.0)+ .map(|p| (p["net"].as_str().unwrap_or("").to_string(), f(&p["x"]), f(&p["y"]), f(&p["drill"]), if f(&p["sizeX"]).min(f(&p["sizeY"])) <= f(&p["drill"]) + 1e-6 { "NONPLATED" } else { "PLATED" })).collect();+ holes.extend(vias.iter().map(|v| (v["net"].as_str().unwrap_or("").to_string(), f(&v["position"]["x"]), f(&v["position"]["y"]), f(&v["drill"]), "VIA")));+ step += " <LayerFeature layerRef=\"DRILL_TOP_BOTTOM\">\n";+ let mut hnets: Vec<&String> = holes.iter().map(|h| &h.0).collect();+ hnets.sort();+ hnets.dedup();+ let mut k = 0;+ for net in hnets {+ step += &format!(" <Set{}>\n", if net.is_empty() { String::new() } else { format!(" net=\"{}\"", a(net)) });+ for h in holes.iter().filter(|h| &h.0 == net) {+ k += 1;+ step += &format!(" <Hole name=\"H{k}\" diameter=\"{}\" platingStatus=\"{}\" plusTol=\"0\" minusTol=\"0\" x=\"{}\" y=\"{}\"/>\n", n(h.3), h.4, n(h.1), n(h.2));+ }+ step += " </Set>\n";+ }+ step += " </LayerFeature>\n </Step>\n";+ cad += &step;+ cad += " </CadData>\n";++ let soft = format!("adom-eda-checks {}", env!("CARGO_PKG_VERSION"));+ let mut o = String::from("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<IPC-2581 revision=\"C\" xmlns=\"http://webstds.ipc.org/2581\">\n <Content roleRef=\"Owner\">\n <FunctionMode mode=\"ASSEMBLY\"/>\n");+ o += &format!(" <StepRef name=\"{name}\"/>\n");+ for i in 0..copper.len() { o += &format!(" <LayerRef name=\"{}\"/>\n", lname(i)); }+ o += " <LayerRef name=\"DRILL_TOP_BOTTOM\"/>\n";+ o += &format!(" <BomRef name=\"{name}_BOM\"/>\n");+ o += &dict.xml();+ o += " </Content>\n <LogisticHeader>\n <Role id=\"Owner\" roleFunction=\"SENDER\"/>\n <Enterprise id=\"Adom\" code=\"NONE\"/>\n <Person name=\"adom-eda-checks\" enterpriseRef=\"Adom\" roleRef=\"Owner\"/>\n </LogisticHeader>\n";+ o += &format!(" <HistoryRecord number=\"1\" origination=\"{date}\" software=\"{soft}\" lastChange=\"{date}\">\n <FileRevision fileRevisionId=\"1\" comment=\"from the board model\">\n <SoftwarePackage name=\"adom-eda-checks\" revision=\"{}\" vendor=\"Adom\">\n <Certification certificationStatus=\"SELFTEST\"/>\n </SoftwarePackage>\n </FileRevision>\n </HistoryRecord>\n", env!("CARGO_PKG_VERSION"));+ o += &bom;+ o += " <Ecad name=\"";+ o += &name;+ o += "\">\n <CadHeader units=\"MILLIMETER\"/>\n";+ o += &cad;+ o += " </Ecad>\n</IPC-2581>\n";+ let counts = json!({"layers": copper.len() + 1, "packages": made.len(), "components": comps.iter().filter(|c| pads.iter().any(|p| p["ref"] == c["ref"])).count(), "nets": nets.len(),+ "pads": n_pads, "traces": n_traces, "arcs": n_arcs, "vias": n_vias, "pourIslands": n_islands, "holes": k});+ (o, counts)+}++/// The current UTC time as an xsd:dateTime, for the history record when the caller gives no `date`.+pub(crate) fn now() -> String {+ let s = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map(|d| d.as_secs() as i64).unwrap_or(0);+ let (days, rem) = (s.div_euclid(86400), s.rem_euclid(86400));+ // civil from days (Howard Hinnant)+ let z = days + 719468;+ let era = z.div_euclid(146097);+ let doe = z - era * 146097;+ let yoe = (doe - doe / 1460 + doe / 36524 - doe / 146096) / 365;+ let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);+ let mp = (5 * doy + 2) / 153;+ let d = doy - (153 * mp + 2) / 5 + 1;+ let m = if mp < 10 { mp + 3 } else { mp - 9 };+ let y = yoe + era * 400 + if m <= 2 { 1 } else { 0 };+ format!("{y:04}-{m:02}-{d:02}T{:02}:{:02}:{:02}Z", rem / 3600, rem % 3600 / 60, rem % 60)+}++/// writers::ipc2581: `{board, stack?, pours?, args: {title?, date?}}` -> the IPC-2581C text and what it holds.+pub fn export_ipc2581(input: &Value) -> Value {+ let board = match crate::input::board(input) { Ok(b) => b, Err(e) => return e };+ let args = input.get("args").cloned().unwrap_or(json!({}));+ let title = args["title"].as_str().unwrap_or("board");+ let date = args["date"].as_str().map(String::from).unwrap_or_else(now);+ let (text, counts) = ipc2581_text(&board, input, title, &date);+ let poured = !crate::input::pours(input).is_empty();+ json!({"success": true, "text": text, "counts": counts, "format": "IPC-2581 revision C", "mode": "ASSEMBLY", "units": "mm", "writtenFrom": "board model",+ "_hint": if poured { "IPC-2581C written from the board model (valid against the IPC-2581C schema): layers and stack-up, outline, packages and components, BOM, nets, and on each copper layer the pads, traces, arcs, vias and the poured copper island by island, plus the drills. Solder mask, paste and silkscreen are not in it: a fab order goes through the tool's Gerbers or ODB++." }+ else { "IPC-2581C written from the board model, without pours: pass pour_state as pours to add the poured copper island by island. Solder mask, paste and silkscreen are not in it: a fab order goes through the tool's Gerbers or ODB++." }})+}++#[cfg(test)]+mod tests {+ use super::*;++ fn board() -> Value {+ json!({"outlineEdges": [{"kind": "line", "start": [0.0, 0.0]}, {"kind": "line", "start": [30.0, 0.0]}, {"kind": "arc", "start": [30.0, 20.0], "end": [0.0, 20.0], "center": [15.0, 20.0], "radius": 15.0, "angle1": 0.0, "angle2": 180.0}, {"kind": "line", "start": [0.0, 20.0]}],+ "components": [{"ref": "U1", "x": 10.0, "y": 10.0, "rotation": 90.0, "side": "top", "pattern": "SOT23", "value": "LDO 3.3V"}, {"ref": "R1", "x": 20.0, "y": 5.0, "rotation": 0.0, "side": "bottom", "pattern": "0603", "value": "10kΩ"},+ {"ref": "LOGO", "x": 2.0, "y": 2.0, "rotation": 0.0, "side": "top", "pattern": "LOGO"}],+ "pads": [{"ref": "U1", "name": "1", "x": 9.05, "y": 8.9, "sizeX": 0.6, "sizeY": 0.7, "rotation": 90.0, "shape": "rect", "layer": "F.Cu", "drill": 0.0, "net": "VIN"},+ {"ref": "U1", "name": "2", "x": 10.95, "y": 8.9, "sizeX": 0.6, "sizeY": 0.7, "rotation": 90.0, "shape": "rect", "layer": "F.Cu", "drill": 0.0, "net": "GND"},+ {"ref": "U1", "name": "3", "x": 10.0, "y": 11.1, "sizeX": 0.6, "sizeY": 0.7, "rotation": 90.0, "shape": "rect", "layer": "F.Cu", "drill": 0.0, "net": "VOUT"},+ {"ref": "R1", "name": "1", "x": 19.2, "y": 5.0, "sizeX": 0.8, "sizeY": 0.9, "rotation": 0.0, "shape": "rect", "layer": "B.Cu", "drill": 0.0, "net": "VOUT"},+ {"ref": "R1", "name": "2", "x": 20.8, "y": 5.0, "sizeX": 0.8, "sizeY": 0.9, "rotation": 0.0, "shape": "rect", "layer": "B.Cu", "drill": 0.0, "net": "GND"},+ {"ref": "", "name": "", "x": 3.0, "y": 17.0, "sizeX": 3.2, "sizeY": 3.2, "rotation": 0.0, "shape": "round", "layer": "*.Cu", "drill": 3.2, "net": ""}],+ "tracks": [{"layer": "F.Cu", "width": 0.25, "net": "VOUT", "start": {"x": 10.0, "y": 11.1}, "end": {"x": 15.0, "y": 11.1}}],+ "arcs": [{"layer": "B.Cu", "width": 0.25, "net": "VOUT", "center": {"x": 17.0, "y": 8.0}, "radius": 2.0, "startAngle": 0.0, "endAngle": 90.0}],+ "vias": [{"position": {"x": 15.0, "y": 11.1}, "size": 0.6, "drill": 0.3, "layers": ["F.Cu", "B.Cu"], "net": "VOUT"}]})+ }++ #[test]+ fn the_board_comes_out_as_ipc_2581c() {+ let pours = json!({"zones": [{"net": "GND", "layer": "B.Cu", "fills": [{"outline": [[1.0, 1.0], [29.0, 1.0], [29.0, 9.0], [1.0, 9.0]], "holes": [[[18.5, 4.0], [21.5, 4.0], [21.5, 6.0], [18.5, 6.0]]]}]}]});+ let r = export_ipc2581(&json!({"board": board(), "pours": pours, "args": {"title": "Test Board", "date": "2026-10-29T00:00:00Z"}}));+ let t = r["text"].as_str().unwrap();+ assert!(t.starts_with("<?xml") && t.contains("<IPC-2581 revision=\"C\""));+ assert_eq!(r["counts"], json!({"layers": 3, "packages": 2, "components": 2, "nets": 3, "pads": 7, "traces": 1, "arcs": 1, "vias": 2, "pourIslands": 1, "holes": 2}), "{}", r["counts"]);+ // U1's pin 1 back in the footprint's frame: (9.05, 8.9) less (10, 10), turned back 90 degrees -> (-1.1, 0.95)+ assert!(t.contains("<Pin number=\"1\" type=\"SURFACE\">\n <Location x=\"-1.1\" y=\"0.95\"/>"), "{t}");+ // the bottom resistor is mirrored, the mounting hole has no ring so it is non-plated, the ohm sign is spelled out+ assert!(t.contains("refDes=\"R1\" packageRef=\"0603\" part=\"0603_10kohm\" layerRef=\"BOTTOM\" mountType=\"SMT\">\n <Xform mirror=\"true\"/>"));+ assert!(t.contains("platingStatus=\"NONPLATED\"") && t.contains("platingStatus=\"VIA\""));+ assert!(t.contains("<PolyStepCurve x=\"0\" y=\"20\" centerX=\"15\" centerY=\"20\" clockwise=\"false\"/>"), "{t}");+ assert!(t.contains("<Cutout>") && t.contains("<Oval") == false && t.contains("<Circle diameter=\"3.2\"/>"));+ assert!(!t.contains("LOGO"), "a component with no pads is no part");+ assert_eq!(n(0.10000001), "0.1");+ assert_eq!(n(-0.00001), "0");+ assert_eq!(ascii("10kΩ ±5%"), "10kohm +/-5%");+ }++ #[test]+ fn the_history_date_is_an_xsd_date_time() {+ let d = now();+ assert_eq!(d.len(), 20);+ assert!(d.starts_with("20") && d.ends_with('Z') && &d[10..11] == "T", "{d}");+ }+}
bridge-rs/vendor/adom-eda-checks/src/writers/mod.rs+5−3@@ -1,5 +1,5 @@-//! Board-file writers for a bridge whose tool has no native exporter (EDA Bridge Standard #16): GenCAD and DXF from the-//! board model, SVG artwork as regions for a layer, and a part's 3D body as STEP from its package dimensions (#20). Like the checks, no I/O and no tool: each returns the file text+//! Board-file writers for a bridge whose tool has no native exporter (EDA Bridge Standard #16): GenCAD, DXF and IPC-2581C+//! from the board model, SVG artwork as regions for a layer, and a part's 3D body as STEP from its package dimensions (#20). Like the checks, no I/O and no tool: each returns the file text //! or the regions as JSON, says it was written from the board model (`writtenFrom`), and the bridge writes the files or //! places the regions. A bridge whose tool has a native exporter keeps it. use serde_json::Value;@@ -7,10 +7,11 @@ use serde_json::Value; pub mod body3d; pub mod dxf; pub mod gencad;+pub mod ipc2581; pub mod svgart; /// The verbs these writers answer, by standard name.-pub const WRITERS: &[&str] = &["export_dxf", "export_gencad", "generate_body", "import_svg"];+pub const WRITERS: &[&str] = &["export_dxf", "export_gencad", "export_ipc2581", "generate_body", "import_svg"]; pub use dxf::dxf_layers; pub use gencad::gencad;@@ -21,6 +22,7 @@ pub fn run(verb: &str, input: &Value) -> Option<Value> { Some(match verb { "export_dxf" => dxf_layers(input), "export_gencad" => gencad(input),+ "export_ipc2581" => ipc2581::export_ipc2581(input), "generate_body" => body3d::generate_body(input), "import_svg" => svg_to_regions(input), _ => return None,
bridge-rs/vendor/adom-eda-checks/tests/fixtures.rs+7@@ -64,3 +64,10 @@ fn height_check_matches_altium() { fn placement_check_matches_altium() { same("placement_check", &["ok", "parts", "courtyardOverlaps", "offOrOverEdge", "onMountingHoles", "nearEdge", "marginMm", "edgeMm"]); }++#[test]+fn assembly_check_matches_altium() {+ // board.parts: the engine counts only components with pads (a logo is no part, fusion-lane #24), Altium all of them+ same("assembly_check", &["service", "fab", "board.bottomSideParts", "board.finestPitch", "board.smallestChip", "board.tinyFootprints", "board.fiducials", "board.throughHoleParts", "economic.ok", "standard.ok", "economic.rules.0.ok", "economic.rules.1.ok", "economic.rules.2.ok",+ "economic.rules.3.ok", "economic.rules.4.ok", "economic.rules.5.ok", "standard.rules.0.ok", "standard.rules.3.ok"]);+}