diff options
Diffstat (limited to 'knowledge/tooling')
| -rw-r--r-- | knowledge/tooling/compose-board.md | 48 | ||||
| -rw-r--r-- | knowledge/tooling/connector-tab.md | 40 | ||||
| -rw-r--r-- | knowledge/tooling/height-check.md | 22 | ||||
| -rw-r--r-- | knowledge/tooling/housing-inputs.md | 17 | ||||
| -rw-r--r-- | knowledge/tooling/kicad.md | 74 | ||||
| -rw-r--r-- | knowledge/tooling/konnect.md | 69 | ||||
| -rw-r--r-- | knowledge/tooling/model-check.md | 21 | ||||
| -rw-r--r-- | knowledge/tooling/placement-check.md | 58 | ||||
| -rw-r--r-- | knowledge/tooling/placer.md | 124 | ||||
| -rw-r--r-- | knowledge/tooling/pnr.md | 120 | ||||
| -rw-r--r-- | knowledge/tooling/router.md | 95 | ||||
| -rw-r--r-- | knowledge/tooling/rust-router.md | 151 | ||||
| -rw-r--r-- | knowledge/tooling/schgen.md | 33 | ||||
| -rw-r--r-- | knowledge/tooling/thermal-vias.md | 25 | ||||
| -rw-r--r-- | knowledge/tooling/threemf-group.md | 11 |
15 files changed, 908 insertions, 0 deletions
diff --git a/knowledge/tooling/compose-board.md b/knowledge/tooling/compose-board.md new file mode 100644 index 0000000..41c8b25 --- /dev/null +++ b/knowledge/tooling/compose-board.md @@ -0,0 +1,48 @@ +# Compose board tool (compose_board.py) + +`tools/compose_board.py` builds a base board from routed module boards. It copies each module's footprints, tracks, vias, pours and drawings onto the base board as one tile (a KiCad group named after the sheet). It turns the tile 0 or 180° and moves it, and renames references and nets to the base board's schematic. The modules stay the source: rebuild to pick up a changed module. + +## Use + +``` sh +. tools/kicad_env.sh +cp libraries/templates/DIN_6TE/DIN_6TE.kicad_pcb myboard/myboard.kicad_pcb # start from an empty template +$KPY tools/compose_board.py myboard/compose.json +$KPY tools/sync_board.py myboard/out/myboard.net myboard/myboard.kicad_pcb # paths, values, fields +$KPY tools/silk_refs.py myboard/myboard.kicad_pcb +``` + +Close the board in KiCad first. The `.kicad_pro` is restored after SaveBoard. + +## Requirements on the schematic + +- **References offset per sheet:** the base schematic uses the modules' block sheets with references offset per sheet (`U1` → `U601` with offset 600). A block used twice is one sheet file with two instance paths. +- **Nets through the pads:** nets come from the base netlist through the pads. A module net takes the base net of its pads (`/Iso/GND_ISO` → `/Iso 1/GND_ISO`, `/Iso/TXD` → `/MB1_TXD`). All pads of a module net must agree, or the script stops and lists them. +- **`repin`:** a pad whose net the root sheet changed, such as an address strap that is GND in the module and +3V3 on the base board. Its module copper is left out from the pad up to the first via or junction. A pad that loses its only link shows in DRC as unconnected. + +## Spec (JSON) + +- `board`, `netlist`; +- `modules`: per module + - `board`, `sheet`, `offset`; + - `block`: the module's block rectangle in its own coordinates (pours, not the test outline); + - `rot` (0 or 180); + - `at`: top-left corner of the turned block on the base board; + - `skip`: e.g. the module's housing post, which the base template already has; + - `repin`; +- `parts`: base-sheet parts (pull-ups) placed from the netlist's footprint; +- `tabs`: `bottom` / `top` connector lists for [connector_tab.add_tabs](connector-tab.md). + - `tab_merge` (mm, default 3): bodies closer than this share one tab. + - The template outline is a `gr_rect`. Compose turns it into segments first, so `add_tabs` can split them. + +## What it handles and what not + +- Each tile's pours get priority `module priority + index`. Butting tiles' GND pours touch, which DRC reports as `zones_intersect` at equal priority. +- Copies keep the module's routing exactly. Base-board nets between tiles stay unrouted; route them afterwards, e.g. with the [Rust router](rust-router.md) and the whole board as `[[fixed]]` copper. +- Rotations other than 0/180° are not tested. +- KiCad API notes: + - `FOOTPRINT.Duplicate(addToParentGroup)` takes an argument; the other items' `Duplicate()` takes none. + - Cast copies with `Cast_to_FOOTPRINT`, `Cast_to_ZONE` and `.Cast()`. + - Pads keep the source board's net objects until `SetNet` is called with the base board's. + +Related: [KiCad notes (sync_board)](kicad.md), [Placer](placer.md), [DIN-rail board format](../topics/din-rail-format.md). diff --git a/knowledge/tooling/connector-tab.md b/knowledge/tooling/connector-tab.md new file mode 100644 index 0000000..de6a9fb --- /dev/null +++ b/knowledge/tooling/connector-tab.md @@ -0,0 +1,40 @@ +# Connector tab tool (connector_tab.py) + +`tools/connector_tab.py` puts a board's edge connectors onto a board tab. Where a connector sits at an edge, the PCB runs out as a tab (default 2.0 mm) into the housing's wall notch. The tab is as wide as the connector bodies, and the mating face or wire entry ends flush with the tab edge ([DIN-rail board format](../topics/din-rail-format.md)). + +## Two uses + +- **From a board generator script** (new boards): + 1. Draw the plain rectangular outline. + 2. Place the connector so its face ends `TAB` past the block edge: pin row = edge − pin-to-face distance + `TAB`. + 3. Call `add_tabs(board, ["J1", ...], TAB)` before saving. + + The block (pours, group bboxes, the router's `area = "pours"`) keeps the old edge; only Edge.Cuts grows. +- **On a routed board** (keeps the routing): + +``` sh +. tools/kicad_env.sh +$KPY tools/connector_tab.py board.kicad_pcb J1 J2 --dy 2.0 [--tab 2.0] [--merge 3.0] +``` + +The second use does this: + +- moves the footprints by `--dy` (positive = outward); +- gives every track that ended on one of their pads a straight stub along the move (same layer and width); +- splits the straight edge into the tab; +- refills the zones and restores the `.kicad_pro`. + +Close the board in KiCad first and checkpoint it. Afterwards, run DRC with parity. + +`add_tabs(..., side="top")` splits the top edge instead, with the tab going up. + +## How the tab is sized + +- **Width:** the union of the connector bodies, taken from their F.Fab outline (the bounding box minus half the line width, i.e. the body edge itself). Bodies closer than `--merge` (3 mm) share one tab, so the printed shell gets one notch instead of thin wall webs. +- **Which edge:** only the lowest straight Edge.Cuts segment under the bodies is split. Rounded corners stay. + +## What DRC catches afterwards + +Tracks that ran between the old pin row and the edge end up under the moved pads. Reroute them by hand on the tab, under the connector body. A connector that already sticks out (e.g. an RJ45 jack) can keep its position with `--dy 0 --tab 2.5`. + +Related: [Thermal vias](thermal-vias.md) (another post-route board edit), [Placer](placer.md). diff --git a/knowledge/tooling/height-check.md b/knowledge/tooling/height-check.md new file mode 100644 index 0000000..f64fcff --- /dev/null +++ b/knowledge/tooling/height-check.md @@ -0,0 +1,22 @@ +# Height check + +`tools/height_check.py` checks every top-side part of a DIN-rail board against the height limits of the printed housing ([DIN-rail board format](../topics/din-rail-format.md)). + +``` sh +tools/router/.venv/bin/python tools/height_check.py myboard/myboard.kicad_pcb +``` + +- **Housing footprint:** the board must carry `HW:DIN_Housing_<k>TE` (from `tools/din_template.py`). Its position is the housing centre, and `k` selects the dimensions. The limits come from `dims()` in `tools/din_template.py`, so the check, the footprint notes and the templates share one source. +- **Limits:** + - inside the front-cap box: `h_tall` (45.8 mm); + - elsewhere: `h_low` (31.8 mm, the bottom of the front-cap lip); + - outside the step lines (|y| > 33): the 45° shoulder slope applies, 19 mm at the line, 1 mm less per mm outward, 9.5 mm at the PCB edge. +- **Method:** each 3D-model vertex is checked against the limit at its place, using the same model transform as [Model check](model-check.md) plus the footprint's position and rotation. +- **Edge connectors:** parts that reach past the PCB edge are listed with "needs a notch through the slope" and not judged; their notch is cut up through the slope. +- **Assembly STEP files:** these cannot be placed without their transforms. The F.CrtYd outline at the model's top height is used instead, flagged "approx". +- **Not checked:** parts without a STEP model are listed as not checked, and bottom-side parts are not checked yet. +- **Exit code** 1 when a part is too tall. + +The model paths resolve `${HW_LIB}` to `libraries/` in the repo and the KiCad stock models through [kicad_paths.py](../../tools/kicad_paths.py). + +For the openings and the spacer frame: [Housing inputs](housing-inputs.md). diff --git a/knowledge/tooling/housing-inputs.md b/knowledge/tooling/housing-inputs.md new file mode 100644 index 0000000..a0e38ae --- /dev/null +++ b/knowledge/tooling/housing-inputs.md @@ -0,0 +1,17 @@ +# Housing inputs + +`tools/housing_inputs.py` prints the numbers a board's DIN-rail housing needs: where each PCB tab is, what kind of opening each edge connector gets, and where the spacer frame must clear through-hole pins. + +``` sh +tools/router/.venv/bin/python tools/housing_inputs.py myboard/myboard.kicad_pcb +``` + +- **Housing coordinates:** origin at the `HW:DIN_Housing_<k>TE` footprint, X = board x − centre, Y = centre − board y (Y up), so the numbers go straight into CAD box features. +- **Tabs:** the Edge.Cuts segments at |y| = PCB edge + 2 mm, per side, with their X ranges. Notch X = tab ± `notch_clr`. Frame tongue X = tab ± (`notch_clr` − `fit`). +- **Edge connectors:** the parts whose 3D model reaches past the PCB edge, as in [Height check](height-check.md), with the back of the body (|y|) and the height. The kind of opening: + - `TerminalBlock` footprints: screw terminal, notch from 0.5 mm behind the body; + - a body that fits under the slope with 1 mm to spare (≤ 8 mm tall): side-entry window in the end wall only; + - anything else: notch from the riser, with the back wall above the body if the body reaches under the riser. +- **Pin cutouts:** per footprint, the through-hole pads that lie under the frame, as a rectangle ± 1.5 mm. Cutouts closer than 1 mm are flagged for merging. +- **Bottom-side footprints** are listed; the frame does not account for them. +- **Constants:** the ones at the top (`FRAME_Y0`, `PIN_CLR`, …) copy the housing model's parameters. Change both together. diff --git a/knowledge/tooling/kicad.md b/knowledge/tooling/kicad.md new file mode 100644 index 0000000..d81430e --- /dev/null +++ b/knowledge/tooling/kicad.md @@ -0,0 +1,74 @@ +# KiCad notes + +Setup the tools expect, and pcbnew Python quirks met while writing them. + +## Setup + +- **KiCad 10.** The tools find `kicad-cli` and KiCad's Python through [tools/kicad_env.sh](../../tools/kicad_env.sh) (shell) and the stock libraries through [tools/kicad_paths.py](../../tools/kicad_paths.py) (Python): + - macOS: `/Applications/KiCad/KiCad.app` is found automatically. `kicad-cli` is not on PATH there. + - Linux: the system Python has `pcbnew` when KiCad is installed from packages. + - Overrides: `KICAD_PYTHON`, `KICAD_CLI`, `KICAD_SHARE`, and KiCad's own `KICAD10_SYMBOL_DIR` / `KICAD10_FOOTPRINT_DIR` / `KICAD10_3DMODEL_DIR`. +- **The repo root** (`ROOT` in `kicad_paths.py`) is the directory with `libraries/`, found upward from the current directory. Set `HW_ROOT` to override. +- **Shared libraries:** set a KiCad path variable `HW_LIB` to `<repo>/libraries` (Preferences → Configure Paths). Add `HW` entries that use `${HW_LIB}` to the global `sym-lib-table`, `fp-lib-table` and `design-block-lib-table`: + - `${HW_LIB}/symbols/HW.kicad_sym` + - `${HW_LIB}/footprints/HW.pretty` + - `${HW_LIB}/blocks/HW.kicad_blocks` + + Footprints reference models as `${HW_LIB}/3dmodels/HW.3dshapes/<name>.step`. Never use absolute paths. +- **Project templates:** `libraries/templates/<name>/` (project files named after the folder, plus `meta/info.html`) appear under User Templates once symlinked into `~/Documents/KiCad/10.0/template/`. + +## Modules as design blocks + +Reusable circuits live as design blocks in `HW.kicad_blocks`. Each block has a test project in `modules/<block>/`, so that it can pass ERC and DRC on its own. A module is never built alone, so its test project has no breakout header: + +- the root sheet holds the block sheet, no-connect flags on its pins and PWR_FLAGs; +- the test board is the block's tile. + +## pcbnew Python quirks + +- **The wxApp assert** (`assert "traits" failed … create wxApp`) that KiCad's bundled Python prints is harmless. +- **Flipping:** `FOOTPRINT.SetLayerAndFlip()` and `Flip()` segfault on a footprint that is not on a board yet. Call `board.Add(fp)` first, then flip. +- **`pcbnew.NewBoard(path)` + `SaveBoard()`** also writes a default `.kicad_pro`, a `.kicad_prl` and a `~<project>.kicad_pro.lck` next to the board. Overwrite the `.kicad_pro` with the settings you want, and delete the other two. +- **`pcbnew.LoadBoard()` + `SaveBoard()` on an existing project board resets the `.kicad_pro`.** It comes back with only the Default net class, no patterns, and no track-width or via palette, and DRC still passes if nothing was routed against a class rule. Copy the project file before the save and write it back afterwards; every tool here does this. Before committing, diff the `.kicad_pro` against git and read the net classes back (`net_settings.classes`); DRC alone will not catch it. +- **`kicad-cli pcb render`** renders the 3D view to PNG (`--side`, `--rotate "-60,0,30"`, `--perspective`). It is handy for checking a 3D model's placement without the GUI. +- **Fields and schematic linkage:** `FOOTPRINT.SetField(name, value)` adds a user field (LCSC, MPN); hide it with `GetField(name).SetVisible(False)`. For schematic linkage, set: + - `SetPath(KIID_PATH("/<sheet uuid>/<symbol uuid>"))`; + - `SetSheetname` and `SetSheetfile`; + - the lib id via `SetFPID(LIB_ID(nick, name))`. + + DRC schematic parity then reports 0 issues without opening the GUI. +- **Use `BOARD.Delete(item)`, not `BOARD.Remove(footprint)`.** `Remove` breaks the board's lists: afterwards `GetTracks()`, `Zones()` and `GetDrawings()` raise `'SwigPyObject' object is not iterable` or segfault, and `FindFootprintByReference()` and `fp.Pads()` return untyped objects. +- **Footprint order:** KiCad orders footprints by UUID. A board regenerated from a script gets new UUIDs, so anything that iterates footprints or pads (a router dump, label placement) must sort them to give the same result twice. +- **Update PCB from Schematic without the GUI:** `tools/sync_board.py NETLIST BOARD [--at X,Y] [--strip-routing]` (KiCad's Python, board closed). It: + - deletes footprints no longer in the netlist; + - adds new ones from the library at `--at`; + - writes value, LCSC/MPN/Datasheet/Description, schematic path and pad nets on every footprint; + - only reports changed footprint ids; + - leaves board-only footprints (housing posts) alone. + + `--strip-routing` drops all tracks and vias, for a board that `tools/pnr.sh` will route again. +- **Dangling test:** `CONNECTIVITY_DATA.TestTrackEndpointDangling(track, False)` after `board.BuildConnectivity()` is DRC's own dangling test for tracks and vias. Zones count once they are filled. +- **Net class order:** KiCad sorts the net classes by name when it saves the `.kicad_pro`; their `priority` keeps the matching order. Compare classes by name, not by position. + +## Writing schematics as files + +- **`lib_symbols` must hold flattened copies.** A derived symbol (`extends`) gets the parent's units and its own properties. +- **Field angles are relative to the symbol.** On a symbol at 90°, a field with angle 90 reads horizontally. +- **Stacked pins** share one connection point; one label or power symbol connects all of them. +- **A label placed exactly on a pin end connects.** Check with the netlist, not only ERC. +- **PWR_FLAGs:** a PWR_FLAG wired only to a power symbol (nothing else on that sheet) gives `pin_not_connected`. Put the PWR_FLAG on a global label of the same name instead (`+5V`, `GND`). +- **Sheet pins:** no-connect flags on a sheet's pins are accepted; the nets inside keep the sheet's names (`/Sheet/SCLK`). Removing root-sheet labels renames the nets, so the board then needs Update from Schematic (or `tools/prune_copper.py --netlist`). + +## JLC production files without the GUI + +- **The JLC plugin** (bennymeg, `com_github_bennymeg_JLC-Plugin-for-KiCad`) has a CLI. Run it from `~/Documents/KiCad/10.0/3rdparty/plugins` with KiCad's Python: + + ``` sh + $KPY -m com_github_bennymeg_JLC-Plugin-for-KiCad.cli -p <abs board path> -t -f -nI -nB + ``` + + It writes `production/` next to the board: the gerber zip, `bom.csv`, `positions.csv`, `designators.csv` and `netlist.ipc`. It ends with a harmless wx assert, and still makes `production/backups/` despite `-nB`; delete that. +- **CPL rotations:** the plugin's `transformations.csv` defaults are per package, but JLC's library entries differ per part. + 1. Check every polarised part in JLC's placement preview (pink dot = JLC's pin 1). + 2. Set the symbol field `FT Rotation Offset` (degrees CCW, added after the default). + 3. `tools/sync_board.py` copies it to the footprint. diff --git a/knowledge/tooling/konnect.md b/knowledge/tooling/konnect.md new file mode 100644 index 0000000..e5b78f9 --- /dev/null +++ b/knowledge/tooling/konnect.md @@ -0,0 +1,69 @@ +# Konnect (KiCad MCP) + +[Konnect](https://github.com/mixelpixx/Konnect) is the MCP server that lets an AI agent read and edit KiCad projects through KiCad's IPC API. It is a Rust binary, also packaged as a KiCad plugin. This repo carries it as a git submodule at `tools/konnect`. It is AGPL-3.0, unlike the rest of this repo (MIT); see its own LICENSE. + +## Status of the projects + +- `mixelpixx/Konnect`: the open-source version (AGPL-3.0, Rust, KiCad IPC API). Archived upstream; v0.13.0 is its last release. +- `Orchis-ai-LLC/Konnect-EDA`: the successor, commercial and closed source. +- `mixelpixx/KiCAD-MCP-Server`: the older Python version (MIT), still maintained. It uses KiCad's SWIG Python bindings rather than the IPC API, and has fewer tools. + +The AGPL Konnect is the most complete open option and uses the IPC API, which is replacing SWIG. Since upstream is archived, keep your own fork if you change it. Point the submodule at it with `git config submodule.tools/konnect.url <your fork>`. + +## Build and connect + +You need the Rust toolchain pinned in `rust-toolchain.toml` (rustup installs it automatically) and `protoc` (`brew install protobuf`, or your distribution's `protobuf-compiler`). + +``` sh +git submodule update --init tools/konnect +cd tools/konnect +cargo build --release -p konnect # → target/release/konnect +``` + +Register the binary as an MCP server in your agent, e.g. for Claude Code: + +``` sh +claude mcp add konnect -- "$PWD/target/release/konnect" --config ~/Documents/KiCad/10.0/3rdparty/plugins/com_github_mixelpixx_konnect/settings.json +``` + +For Codex, add the same command and arguments to `~/.codex/config.toml`. The `settings.json` comes with the KiCad plugin install. + +- After rebuilding, reconnect the MCP server (`/mcp` in Claude Code) to load the new binary. `cargo clean` removes the binary and breaks the MCP entry until the next build. +- Per-project config: `<project>/.konnect/project.json` (design rules, overrides). Commit it. Visual baselines go in `<project>/.konnect/baselines/`. +- `tools/konnect/DEV.md` covers tests, the schematic viewer and PCM packaging. + +## Direct file edits + +Konnect's agent skills forbid editing KiCad files directly. In practice, scripted edits through KiCad's own Python (`pcbnew`) are often more reliable. Do them safely: + +1. save the editor state; +2. checkpoint the files; +3. keep a stale open editor from overwriting the change; +4. reload the exact document; +5. verify by reading back, plus ERC/DRC. + +The repo's [AGENTS.md](../../AGENTS.md) gives agents that permission. + +## Quirks seen + +- `add_schematic_text` writes `\n` literally when the text is passed with escaped newlines. Pass real line breaks. +- `update_pcb_from_schematic` needs the PCB editor open with the board. +- A local net label and a hierarchical label with the same name on one sheet do connect. +- Konnect's DSN export refuses Edge.Cuts arcs; KiCad's native export handles them. +- Typed footprint refresh refuses `net_tie_pad_groups`. KiCad's native Update Footprints from Library handles them. + +### Live track edits on an open board + +- `query_traces` (board path + full net name with sheet prefix) lists segments with their UUIDs. +- `delete_trace` takes one UUID. +- `route_trace` adds one straight segment; pass `width`, because it defaults to 0.25 mm. +- No tool deletes a via. Plan around existing vias, or edit the file with the board closed. +- `run_drc` with `sync_live_board = true, refill_zones = true` refills over IPC, saves the open board, then runs DRC on the saved file. + +A workflow that works: + +1. try the edit on a file copy with pcbnew and run DRC on it; +2. checkpoint the saved board; +3. check that the live net matches the file; +4. apply the same segments live; +5. sync, run DRC, and read back the saved file. diff --git a/knowledge/tooling/model-check.md b/knowledge/tooling/model-check.md new file mode 100644 index 0000000..a4ae99c --- /dev/null +++ b/knowledge/tooling/model-check.md @@ -0,0 +1,21 @@ +# Model check + +`tools/model_check.py` checks a footprint's 3D model placement against its pads, without opening KiCad. + +``` sh +tools/router/.venv/bin/python tools/model_check.py libraries/footprints/HW.pretty/<name>.kicad_mod [-D HW_LIB=...] +``` + +- **Transform:** it reads the footprint's `(model …)` offset, scale and rotation, loads the STEP file's vertices and applies KiCad's transform: scale, then rotate X, Y, Z (KiCad negates the angles), then offset. 3D Y points up, footprint Y points down. +- **Output:** the model's extent and height, and for every drilled pad (THT, NPTH) the distance to the nearest model feature below the board surface (pin tips, pegs, shell legs). + - Good: every hole within about 0.1 mm, body bottom at z ≈ 0. + - "Nothing below the board surface" means the model is upside down or floating. +- **When to run it:** on every new footprint with a model, especially ones converted with easyeda2kicad. Their offsets and rotations are often wrong; seen on a MagJack (2.2 mm off in y) and a USB-C receptacle (rotated 180° about X, standing on its mating face). +- **SMD-only parts:** it cannot match holes. Check those with `kicad-cli pcb render` ([KiCad notes](kicad.md)). +- **Assemblies** (manufacturer STEP files with coloured sub-parts, [3D models](../topics/3d-models.md)) are refused. Flatten a copy with FreeCAD, point a scratch copy of the footprint at it and check that. Keep the original in the library. freecadcmd treats arguments as files to open, so pass paths through the environment: + +``` sh +STEPFILE=in.stp OUT=flat.step freecadcmd -c "import os, Part; s=Part.read(os.environ['STEPFILE']); Part.Compound(s.Solids).exportStep(os.environ['OUT'])" +``` + +Related: [KiCad notes](kicad.md). diff --git a/knowledge/tooling/placement-check.md b/knowledge/tooling/placement-check.md new file mode 100644 index 0000000..bfe3897 --- /dev/null +++ b/knowledge/tooling/placement-check.md @@ -0,0 +1,58 @@ +# Placement check + +`tools/placement_check.py` rates a KiCad board's component placement before routing. Use it after every placement change. + +## Run + +Needs KiCad's Python (for `pcbnew`). It reads the saved file, so the board can stay open in KiCad; save first. + +``` sh +. tools/kicad_env.sh +$KPY tools/placement_check.py board.kicad_pcb --pair U2:J2 --svg /tmp/overlay.svg +rsvg-convert -w 1100 /tmp/overlay.svg -o /tmp/overlay.png # to look at it +``` + +Options: + +- `--ignore J3,...`: leave out parts whose long ratsnest lines would swamp the result, e.g. an off-board connector. +- `--pair A:B[:max]`: courtyard gap between two parts that must sit close together, e.g. an Ethernet IC and its jack. With a maximum it is scored. +- `--fill REGEX`: nets left out of the ratsnest. The default is GND-like names; nets with a copper zone are added automatically. +- `--svg`: overlay with: + - courtyards (grey front, purple back); + - pads (green = fill net); + - ratsnest (blue); + - crossings (red circles); + - flagged parts (orange). +- `--json`: all findings, for scripts. +- `--apply-rotations OUT`: writes a copy with the suggested rotations. Turns that would hit another courtyard are never suggested. + +## What it checks + +- **Crossings** of ratsnest lines (MST per net, fill nets left out). On two layers each one costs a via or a detour. +- **Length** of the ratsnest, total and per net class. +- **Decoupling.** For every cap with one pad on a fill net: + - Its other pad must be within 3 mm of the nearest IC pin (a part with at least 4 pads) on the same net. Bulk caps (≥ 4.7 µF) get 8 mm and may also sit at an inductor or ferrite. + - Its ground pad must be within that limit + 2 mm of a ground pin of the same IC, as a proxy for the loop area. + - Each IC pin on a decoupled net must have a cap within 3 mm. Crystal nets are excluded. +- **Rotation** of 2-pad parts: turns of 90/180/270° in place that cross less or shorten the ratsnest by more than 0.5 mm. +- **Courtyards:** front and back overlaps, and THT pads inside another footprint's back courtyard. With `HW:DIN_Post` or `HW:DIN_Housing_<k>TE` on the board, that covers parts on housing posts, ribs and spacers ([DIN-rail board format](../topics/din-rail-format.md)). + +Score: 100, minus a penalty per finding, down to a minimum of 0: + +| Finding | Penalty | +| ------------------- | ------------------------------------ | +| crossing | 1 | +| decoupling overshoot | 1 per mm, at most 5 per cap | +| uncovered pin | 1 | +| rotation suggestion | 2 | +| courtyard conflict | 10 | +| failed pair | 5 | + +## Reading the result + +- **Compare scores between variants of the same board;** the absolute number means little. Some crossings come from the pinout and no placement removes them, e.g. a swapped differential pair or a USB-C's two pad rows. +- **Look at the overlay, not just the number.** The ratsnest is straight lines between pads, so it cannot see routing channels. +- **Rotation suggestions cover only 2-pad parts.** For ICs and connectors, try the turns by hand. +- `tools/placement_slots.py board.kicad_pcb slots.json [--out moved.kicad_pcb]` hill-climbs which part sits in which of a set of fixed slots (and which way it faces) against this checker's penalties. See the script's docstring for the format. It does not replace setting decoupling caps by hand: it can swap two caps out of pin order, because the ratsnest does not care. + +Related: [Placer](placer.md), [Rust router](rust-router.md). diff --git a/knowledge/tooling/placer.md b/knowledge/tooling/placer.md new file mode 100644 index 0000000..3e3493d --- /dev/null +++ b/knowledge/tooling/placer.md @@ -0,0 +1,124 @@ +# Placer + +`tools/placer/` places a board's footprints automatically by simulated annealing (Rust). The cost terms were learned from hand placement, and the [Rust router](rust-router.md) is the final judge: route the best candidates and pick by the routed result. [Place and route your own board](pnr.md) runs the whole chain. + +## Run + +``` sh +. tools/kicad_env.sh # KPY, KC +cargo build --release --manifest-path tools/placer/Cargo.toml +$KC sch export netlist -o /tmp/b.net board.kicad_sch +$KPY tools/placer/export.py board.kicad_pcb /tmp/problem.json /tmp/b.net # pin types from the netlist +P=tools/placer/target/release/placer +$P score /tmp/problem.json placement.toml [placement.json] # cost terms and worst findings +$P run /tmp/problem.json placement.toml /tmp/out --runs 32 --inner 10 # rank_NN.json, runs.tsv +$P run ... --route board.json route.toml --route-top 32 # also route and rank them +$P selftest /tmp/problem.json placement.toml # incremental cost == full evaluation +$KPY tools/placer/apply.py board.kicad_pcb /tmp/out/rank_00.json placed.kicad_pcb +``` + +`apply.py` sets positions and rotations, deletes tracks and vias, and restores the `.kicad_pro` that `SaveBoard` would reset. `PLACER_TRACE=1` prints one line per temperature. + +`placer congest PROBLEM CONFIG [--cell MM] PLACEMENT...` prints RUDY overflow and a coarse global route per placement, for experiments. + +**Rank by routing**: with `--route`, the best K placements are routed in-process after annealing and ranked: + +1. legal placements first; +2. then split nets, failed connections and pour islands; +3. then the route.toml's `[rank]` score. + +The output is `routed.tsv`, `routes_NN.json` and `routed_best.json`. `placer route PROBLEM CONFIG board.json route.toml OUT placement...` does the same for existing placement files. + +## placement.toml + +Most labels are inferred. The file only adds what cannot be: + +- **Fixed:** locked footprints, board-only footprints and mounting holes are inferred. List more in `fixed = [...]`. A symbol field `Place_Fixed` works too. +- **Decoupling caps:** a C with one pad on a fill net (GND, or a net with a zone). Its pin is the nearest IC pin on the other net. Bulk caps (≥ 4.7 µF) may also sit at an L or FB. + - "Nearest" is measured at the start position. If all parts start in a heap beside the IC, attach each IC decap explicitly: `[[attach]] part = "C12", pin = "U2.21"`. +- **Pin directions:** + - 2-pad parts point along their axis. + - ICs and connectors point by the side of the pad envelope; elongated pads decide first. + - Centre and THT pads have none. +- **Fine-pitch fan-out band:** parts with at least 8 SMD pads closer than 0.7 mm get their pad envelope + 1 mm as a band that other parts' pads must stay out of. +- **Net weights:** by net class (`[class] Power = 0.5`), overridden by `[[net]] match = "glob", weight = x`. +- **Groups:** `[[group]] name, parts, bbox = [x0, y0, x1, y1]`. Members move together in group moves, and a bbox keeps them in a region. The symbol field `Place_Group` works too (`eth/xtal` is a subgroup of `eth`). The sidecar wins. +- **Links:** `[[link]] a = "NT1.2", b = "R11.2", max = 1.3` (`weight`, default 1). Two pads farther apart than `max` cost more, quadratically for the first 2 mm. Use it for a net tie on its Kelvin pad or an ESD diode at its pin. +- **Pulls:** `[[pull]] nets = ["*/SCLK", ...], side = "N"|"S"|"E"|"W"` (`weight`). Each pad on those nets costs per mm from that side of its group's bbox (else of the board). Use it for interface nets with a single pin on the block, which otherwise pull nowhere. +- **Replicated channels:** `[[replicate]] parts = [[CH1 parts], [CH2 parts], ...], pitch = [dx, dy]`. Channel k's part i follows channel 0's part i at k × pitch with the same rotation; same footprints are required. +- **Weights:** `[weights]` overrides the cost weights below. The defaults are in `src/model.rs`. + +Example: + +``` toml +fixed = ["U1", "J2"] + +[class] +Ethernet = 3.0 +Power = 0.5 +Default = 1.0 + +[[group]] +name = "eth" +parts = ["U3", "Y1", "C20", "C21"] +bbox = [112.0, 60.0, 130.0, 80.0] + +[[attach]] +part = "C5" +pin = "U1.19" + +[[pull]] +nets = ["*/SCLK", "*/MOSI", "*/MISO"] +side = "S" +``` + +## Cost + +| Term | What it stands for | +| ----------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------- | +| length | MST ratsnest length × net weight | +| crossing | crossings of ratsnest lines of different nets (a via each on 2 layers); each decap's line to its pin counts too, so caps keep pin order | +| block | ratsnest lines over another net's pads | +| escape | lines leaving a pin backwards | +| decap | distance cap → pin plus half ground pad → that IC's GND pin; beyond 3 mm (8 mm bulk) quadratic, then linear | +| cover | IC pins on a decoupled net farther than 3 mm from any cap on it | +| overlap / band / bounds | courtyard overlap (courtyards grown 0.03 mm), pads in a fan-out band, outside the board / pad edge clearance / keep-outs / group bbox | +| link, pull | `[[link]]` pads past their distance, `[[pull]]` pads' distance to their side | + +A move re-evaluates only what it touches: the nets of the moved parts, the ratsnest lines that changed, part pairs and part terms. `selftest` checks this against a full evaluation. + +**Calibrate before trusting it.** Damage a good hand placement on purpose: swap caps, turn a ferrite, put a pull-up into a fan-out. Every variant must cost more. That is how the crossing, block and escape terms got their current form. + +## Annealing + +- **Moves:** + - shift, turn, or shift + turn; + - swap with a same-footprint part; + - put a pad next to another pad of its net; + - move an IC with its satellites (2-pad parts on its nets within 3 mm); + - shift or turn a group; + - **push**: shift a part together with every part whose courtyard it would hit, up to 8 parts. + + The grid is 0.05 mm, and single moves are clamped to the board. +- **Schedule:** VPR, with N^(4/3) × `inner` moves per temperature. Cooling and move range follow the acceptance rate. +- **Legality:** the legality terms ramp from 1 % to full weight while the temperature falls 100×. The best state is only taken at full weight, and a final greedy quench runs at 10×. Legal results rank first. +- **Stop:** when the best improved less than 0.1 % over 15 temperatures and acceptance is below 5 %. + +What went wrong first, so it does not again: + +- Parts ended off the board: early moves span the board diagonal, and a flat "outside" penalty gives no gradient. Fixed by clamping and a distance term. +- T0 was huge because a scrambled start's overlaps dominate. Fixed by measuring T0 at the ramp start and a linear tail on the decap limit. +- An IC got stuck by its caps: a cluster of all 2-pad parts on its nets included everything on 3V3. Satellites are now only parts within 3 mm. +- DRC found touching courtyards, a cap in an antenna keep-out and a pad too close to the edge. Fixed with a courtyard margin, pad keep-outs from rule areas, and bounds from the outline polygon instead of the Edge.Cuts bounding box. + +## Experience + +- Speed: about 45k moves/s per core. Quality grows with run length, not run count: 32 runs at `--inner 10` (about 7 s each on a 50-part board) beat many short runs. +- On a dense ESP32 + Ethernet board the annealer found the hand layout's structure by itself: Ethernet IC central, termination toward the jack, crystal close, buck at the side. +- **Lower placer cost does not mean better routing.** Coarse group regions taken from a designer's layout routed better (23/32 vs 17/32 complete) than a free placement with lower cost. Keep regions until the cost knows about quiet planes and feed directions. +- **The push move** fixes a class of local minimum: several parts that must move together because any one alone hits a neighbour's courtyard. +- When shrinking a block, sweep the group bbox and compare the routed `[rank]` scores. Do not stop at the first size that still places. +- Not modelled, so check by hand: Kelvin taps, and references that `silk_refs.py` cannot fit (those go to F.Fab). +- Footprints with bottom-side pads (KiCad `_ThermalVias` variants) are refused. Use the plain footprint and [Thermal vias](thermal-vias.md) after routing. + +Related: [Placement check](placement-check.md), [Router (Python)](router.md), [Placement for routing](../topics/placement-for-routing.md). diff --git a/knowledge/tooling/pnr.md b/knowledge/tooling/pnr.md new file mode 100644 index 0000000..4d2489b --- /dev/null +++ b/knowledge/tooling/pnr.md @@ -0,0 +1,120 @@ +# Place and route your own board (pnr) + +`tools/pnr.sh` takes a KiCad board with its schematic and gives you routed candidates that KiCad's DRC has checked. It places the parts with the [Placer](placer.md) (simulated annealing, 32 runs), routes every candidate with the [Rust router](rust-router.md) (negotiated congestion), then runs apply → route → write → DRC on the best six and installs the one you choose. + +You can also run only the router on a board you placed yourself. See [Route a placed board](#route-a-placed-board). + +## Requirements + +- **KiCad 10**, with `kicad-cli` and a Python that can `import pcbnew`. + - On macOS both come from `KiCad.app` and are found automatically. + - On Linux, the distribution package puts `pcbnew` into the system Python. + - Override with `KICAD_PYTHON=...` and `KICAD_CLI=...` ([tools/kicad_env.sh](../../tools/kicad_env.sh)). +- **Rust** (stable, via rustup). `pnr.sh` builds the placer, and the router crate links into it. Build the router binary yourself once: `cargo build --release --manifest-path tools/router-rs/Cargo.toml`. +- `python3` (3.8+) for the small JSON summaries. +- Two-layer boards. The router uses F.Cu and B.Cu only. + +## The board directory + +``` +myboard/ + myboard.kicad_pro / .kicad_sch / .kicad_pcb name = directory name + placement.toml what the placer must know (can be almost empty) + route.toml how to route (see rust-router.md) +``` + +The board needs: + +- a closed Edge.Cuts outline; +- all footprints on the board, in any position (Update PCB from Schematic and leave them in a heap); +- the net classes set in the project, because the router takes widths and clearances from them; +- zones for the plane net (usually GND on B.Cu, and F.Cu too if you like). The router models their fill and checks that every pad reaches them. + +Lock the parts that must not move: connectors at the edge, a module with an antenna, mounting holes. Or list them in `placement.toml` under `fixed = [...]`. + +## Minimal configs + +`placement.toml`: + +``` toml +fixed = ["J1", "U1"] # besides locked footprints and mounting holes + +[class] # net-class weights for the ratsnest length +Power = 0.5 # wide supply tracks are routed last and go around signals +Default = 1.0 +``` + +`route.toml`: + +``` toml +plane_nets = ["GND"] + +[[step]] +do = "negotiate" +planes = true # the GND drops are negotiated with everything else +cost = "none" + +[[step]] +do = "repair" + +[[step]] +do = "cleanup" + +[[step]] +do = "pour" # check the GND pour for islands and join them with vias +``` + +That is enough for a first run. The [Placer](placer.md) and [Rust router](rust-router.md) pages list what else there is: groups and regions, decap pin assignments, links, pulls, replicated channels, bundles, escapes, cost zones and per-net settings. + +## Run + +``` sh +sh tools/pnr.sh run myboard # RUNS=32 JOBS=6 by default; TOP (6) is the 3rd argument +``` + +Output goes to `myboard/out/pnr/`: + +- `run/routed.tsv`: every candidate, ranked: legal placement first, then split nets, failed connections, pour islands, then the `[rank]` score (length, vias, necks); +- `eval/rank_NN/`: the best TOP candidates after apply → route → write → KiCad DRC (`routed.kicad_pcb`, `drc.json`, `route.log`); +- the summary line: `SUMMARY complete=<boards DRC calls fully connected>/<total> unconnected=... vias=... length=...`. + +Open a few `eval/rank_NN/routed.kicad_pcb` files in KiCad and pick one. Then: + +``` sh +sh tools/pnr.sh install myboard rank_00 +``` + +This checkpoints the board to `myboard/out/before-pnr-<date>/`, then: + +1. places references with `silk_refs.py`; +2. fills the pours and saves; +3. restores the `.kicad_pro`, which pcbnew's `SaveBoard` would otherwise reset; +4. runs DRC with schematic parity and ERC. + +Close the board in KiCad first. Both commands refuse while KiCad's lock file is there. + +## Route a placed board + +``` sh +. tools/kicad_env.sh +R=tools/router-rs/target/release/router +$KPY tools/router/dump_board.py myboard.kicad_pcb /tmp/board.json +$R route /tmp/board.json route.toml /tmp/routes.json +$KPY tools/router/write_board.py myboard.kicad_pcb /tmp/routes.json /tmp/routed.kicad_pcb --replace --prune-vias GND +cp myboard.kicad_pro /tmp/routed.kicad_pro +$KC pcb drc --refill-zones /tmp/routed.kicad_pcb +$KPY tools/router/plot_routes.py /tmp/board.json /tmp/routes.json /tmp/routes.png # needs the router venv +``` + +The last line of `route` reads `RESULT split=0 failed=0 islands=0 vias=… length=…`. Zeros mean complete. KiCad's DRC is the judge. + +## When it does not route + +Most failures come from the placement, not the router: + +- **A pin that never connects** on every candidate: something walls it in. Look at the plot, then give it a fan-out band, keep a corridor free, or raise the net's `priority` in `route.toml`. +- **Interface lines of a block** with one pad each: add `[[escape]]` lines (see the [Rust router](rust-router.md) page), or complete boards will wall them in. +- **Fine-pitch parts off the 0.05 mm grid**: put fixed parts' origins on multiples of 0.05 mm. +- **Placer cost does not predict routability.** Route more candidates (`RUNS=64`) rather than tuning the cost weights. + +See [Placement for routing](../topics/placement-for-routing.md) for the rules behind this. The [Rust router](rust-router.md) page has the lessons that came out of real boards. diff --git a/knowledge/tooling/router.md b/knowledge/tooling/router.md new file mode 100644 index 0000000..136f1e8 --- /dev/null +++ b/knowledge/tooling/router.md @@ -0,0 +1,95 @@ +# Router (Python) + +`tools/router/` is the scripted grid maze router that came before the [Rust router](rust-router.md). It routes one net at a time, in an order the board's own `route.py` script sets. New boards should use the Rust router, with a `route.toml` instead of a `route.py`. This router stays for existing scripts. Its board I/O (`dump_board.py`, `write_board.py`, `plot_routes.py`) is shared by both. + +## Setup + +``` sh +python3 -m venv tools/router/.venv +tools/router/.venv/bin/pip install -r tools/router/requirements.txt # numpy, shapely, scipy, matplotlib +``` + +The C core (`astar.c`) compiles itself with `cc` on first import. + +## How it works + +- **Grid:** 0.05 mm cells on F.Cu and B.Cu. + - Exact distance fields hold, for every cell, the distance to the nearest copper and to the nearest copper of another net. + - A track of width w fits where foreign copper is at least w/2 + 0.2 mm away. + - Near pads it may neck down (e.g. 0.5 mm power to 0.2 mm), so fine-pitch pins can be entered. +- **Search** (`astar.c`): 8-direction A* with costs for vias (default 40 cells), turns and B.Cu (`bmult`, default 3), plus optional cost maps per layer. No via lands in a pad. +- **Strategies** (`pipeline.py`): + - `route_plane_net("GND")`: each SMD ground pad gets its own via to the B.Cu plane; + - `connect(net)`: joins all copper of a net, nearest piece first; + - `route_pair(net, a, b)`: pad to pad; + - `connect_decaps(net)`: each decoupling cap to its own nearest IC pin, before the rest of the net; + - `tie(net, pad, xy)`: pad to a new via; + - `route_waypoints(...)`: a trunk through fixed points; + - `stitch("GND", pitch)`: stitching vias wherever they fit (finished boards only); + - `load_existing(dump)`: fixed copper, e.g. a planned bus, loaded before anything else; + - `route_net(...)` + `repair()`: rip-up and reroute. +- **Board I/O** (KiCad's Python): + - `dump_board.py` writes pads, net classes and widths, keep-outs, zones and existing copper to JSON. The output is sorted, so the same placement always gives the same dump. KiCad orders footprints by UUID, which a regenerated board draws anew, and the router's result depends on pad order. + - `write_board.py` writes tracks, vias and pours (`--replace`, `--diff`, `--zones`, `--prune-vias GND`). `--diff` changes only the items that differ, so untouched copper keeps its exact drill and width. Every mode restores the `.kicad_pro` that `SaveBoard` resets ([KiCad notes](kicad.md)). +- **Debugging:** `plot_routes.py board.json routes.json out.png [x0 y0 x1 y1]` draws each net in its own colour with its name, B.Cu dashed and failed pins crossed. KiCad's SVG export cannot show which net blocks which; this can. + +## Workflow + +``` sh +. tools/kicad_env.sh # KPY, KC +VPY=tools/router/.venv/bin/python +$KPY tools/router/dump_board.py board.kicad_pcb /tmp/board.json +$VPY my_board/route.py /tmp/board.json /tmp/routes.json # the board's own script +$VPY tools/router/plot_routes.py /tmp/board.json /tmp/routes.json /tmp/z.png 110 90 130 110 +$KPY tools/router/write_board.py board.kicad_pcb /tmp/routes.json board.kicad_pcb --replace --prune-vias GND +$KC pcb drc --refill-zones --schematic-parity board.kicad_pcb +$KPY tools/silk_refs.py board.kicad_pcb # references off pads and each other +``` + +`silk_refs.py` keeps each reference 0.5 mm inside the real board outline, clear of pads, vias and other silk. + +Close the board in KiCad and check for its `~*.lck` file before writing. Run with `PYTHONHASHSEED=0` so a rebuild gives the same board. + +To take parts off a routed board, use `tools/prune_copper.py board.kicad_pcb --remove J3 [--clip X0,Y0,X1,Y1] [--netlist board.net]`. It does four things: + +1. deletes the footprints; +2. optionally cuts the outline down, clipping zones and deleting copper outside; +3. renames nets to the schematic's names; +4. deletes whatever DRC would call dangling, repeating until nothing is left (KiCad's own `TestTrackEndpointDangling`). + +## Order that works (sequential routing) + +1. **Keep hand routing** of nets whose parts did not move (`load_existing`). Those nets are protected from rip-up. +2. **Ground:** fixed vias under a QFP without an exposed pad, its GND pins to those vias, then every other SMD ground pad to its own via. If signal lines will close in THT ground pads, tie them to their own via now. +3. **The fine-pitch IC's own pins first:** crystal, regulator caps, bias resistor. Join analog supply pins inside the pad ring, then the PHY pairs, then control and bus lines. +4. **Supplies after the signals:** decaps pad to pad, then the rest of each rail. Wide power trunks go around signals easily; signals cannot get past an early trunk. +5. **Other signals, shortest first.** +6. `repair()`, then pours, then DRC. + +**Buses between two ICs:** do not leave them to a one-net-at-a-time router; a six-line bus took 37 vias that way. Instead: + +1. Work out the crossings from the pin orders on both ends. +2. Give each layer an order that needs no crossings. +3. Write the geometry as fixed copper and route the rest around it. + +That took 8 vias. The Rust router's negotiation makes this mostly unnecessary. + +## Cost zones + +- **F.Cu under a module** with pads underneath, and **inside a QFP pad ring** (reserved for its ground vias): cost 200 per cell. That is effectively forbidden, but not a hard keep-out, so GND drops can still use it. +- **Block tile:** make the board outline the tile plus the copper-to-edge clearance on the sides that face other blocks. The router and DRC then keep all copper inside the tile. +- **Quiet zone on B.Cu** under a crystal, PHY or Ethernet IC: +10 per cell for signals, which keeps the ground plane whole where it matters. +- **A failure within 0.4 s** means a pin is enclosed, not that the search budget ran out. Test the net alone on the empty board, and after each phase, to find which phase encloses it. + +## Rip-up and reroute + +`route_net(name, cost=..., **kw)` records each connection's cost map and settings. `repair(rounds, protect=kept_nets)` works in four steps: + +1. finds nets still in several pieces; +2. removes the nets with copper within 1.2 mm of the unconnected pieces; +3. routes the failed net first; +4. routes the removed nets again with their recorded settings. + +It cannot fix placement. If a net fails alone on the empty board, or fails again after repair, change the placement ([Placement for routing](../topics/placement-for-routing.md)). + +Related: [Placement check](placement-check.md), [Net classes](../topics/netclasses.md). diff --git a/knowledge/tooling/rust-router.md b/knowledge/tooling/rust-router.md new file mode 100644 index 0000000..430fbd2 --- /dev/null +++ b/knowledge/tooling/rust-router.md @@ -0,0 +1,151 @@ +# Rust router + +`tools/router-rs/` routes 2-layer KiCad boards on a 0.05 mm grid with **negotiated congestion** (PathFinder): all nets at once, so there is no net order to get wrong. It reads a board dump from `tools/router/dump_board.py` and writes `routes.json` for `tools/router/write_board.py`. It is also a library: the [Placer](placer.md) links it to route its candidates in-process. KiCad's DRC stays the judge. + +For the end-to-end flow on your own board, start with [Place and route your own board](pnr.md). + +## Use + +``` sh +cargo build --release --manifest-path tools/router-rs/Cargo.toml +. tools/kicad_env.sh # KPY, KC +R=tools/router-rs/target/release/router +$KPY tools/router/dump_board.py board.kicad_pcb board.json +$R route board.json route.toml routes.json [--fixed NAME=FILE]... [--stop LABEL] +$R place board.json placement.json moved.json # move parts to a placer result, without KiCad +$KPY tools/router/write_board.py board.kicad_pcb routes.json out.kicad_pcb --replace [--zones zones.json] --prune-vias GND +$KC pcb drc --refill-zones out.kicad_pcb +``` + +The last line of `route` is: + +``` +RESULT split=<nets in pieces> failed=<connections> islands=<plane-net pad groups the pours leave apart> + vias= length= bcu= neck=<mm narrower than the net's width, outside pads> score=<[rank]> time= +``` + +`ROUTER_TIMES=1` prints each step's time. `ROUTER_TRACE=1` prints each search and the conflicts left after the last negotiation round. + +`write_board.py` options: + +- `--replace` deletes the board's tracks and vias first. +- `--diff` changes only what differs from the board. Use it when `routes.json` also holds the board's own copper, for example a `[[fixed]]` dump, so that untouched copper keeps its exact drill and width. +- `--prune-vias NET` removes that net's vias that connect nothing. +- `--zones` adds pours from a JSON file. + +All three restore the `.kicad_pro` that pcbnew's `SaveBoard` would reset. + +## route.toml + +The doc comment of `src/config.rs` is the full reference. In short: + +### Board-wide + +- `prefix`: a sheet path such as `"/My Sheet/"` that net names in the file may leave out. +- `plane_nets`: nets that reach their pads through pours and drop vias, usually `["GND"]`. With `area = "pours"`, give a sheet-local plane its full name (e.g. `/Iso/GND_ISO`). Zones are matched literally, and a missing pour silently shrinks the area. +- `area`: limits where copper may go. + - `"pours"` keeps all copper inside the plane nets' pours, e.g. a design block that will be pasted onto a larger board. + - `[[x, y], ...]` gives a polygon instead. + - `area_margin` (mm) keeps copper that far inside. +- `[[bundle]] nets = [...]`: pairs and buses that should run side by side. A step that does not hug a partner's copper costs `attract` more. Set `attract` on the negotiate step (0.5 works well); the cleanup step defaults to 0.5. It is soft attraction, not coupled routing. +- `[[fixed]]`: copper loaded before the steps. + - `name` + `--fixed NAME=FILE`, or `path` relative to the toml. + - A JSON of tracks and vias, or a board dump with `unmoved = true` (keep the copper of nets whose parts did not move). + - `done = true` marks its nets complete. `protect = true` protects it from rip-up. + - `exclude = [...]`, `optional = true`. +- `[costs.NAME]`: cost maps. + - `zones = [{ layer = "F"|"B", fp = "U1", rect = [x0, y0, x1, y1], cost = 200 }]`. Rectangles are relative to the footprint origin and do not turn with it. Without `fp` they are absolute. Zones add up. + - `rudy = { scale, max }`: RUDY congestion of the pads' MSTs. + - `none` is empty. A step's `cost` stays set for the following steps. +- `[nets.NAME]`: per-net settings. + - `w` (width) and `wneck` (neck width). + - `neck_zone`: how far from a pad a track may neck; default 1 mm. + - `root` (`"U1:19"`, where the net's tree grows from) and `decaps` (each decoupling cap to its pin first). + - `priority` (higher routes first), `cost`, `bmult` (B.Cu multiplier) and `via_cost`. + - `[[nets.NAME.join]]` pad pairs routed first: `{ a = "U1:4", b = "U1:8", w, wneck, cost, allow_via }`. +- `[[escape]]`: reserves a way out for nets that leave a block, such as a module's interface lines with one pad each. + - Keys: `nets = [...]`, `from = [x, y]`, `to = [x, y]`, `size` (default 0.25), `w`, `keep`. + - It adds one virtual pad per net, evenly spaced from `from` to `to` and snapped to the grid, and routes them in the same negotiation. + - Their copper is left out of `routes.json` unless `keep = true`. + - A board only counts as complete if every interface line can still reach the edge. +- `[rank]`: how routed boards compare (used by `placer --route` and `pnr.sh`). + - First: split nets, failed connections, pour islands. + - Then a score: Σ length × net weight (`nets = [{ match = "*/ETH_*", weight = 2 }]`, `*` globs) + `via_mm` (2) × vias + `neck_mm` (2) × necked mm + `bcu_mm` (0) × B.Cu mm. + +### Steps (`[[step]] do = ...`, in order) + +| Step | What it does | +| ----------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------ | +| `negotiate` | routes every net still in pieces at once. `planes = true` negotiates the plane nets' pad drops too, so they give way to signals. Also: `cost`, `rounds`, `pres`, `pres_mult`, `hist`, `margin` (search window around each connection, default 1.5 mm), `attract` | +| `repair` | rips up what lies around failures and routes again (`rounds`) | +| `cleanup` | reroutes each net once with the rest fixed: shorter, fewer vias, tighter octilinear shortcuts, necks widened (`neck`, default 4) | +| `pour` | models the plane net's pour fill, finds islands that leave pads apart and joins them with vias (`fix`, default true; `d` via size) | +| `via` | fixed vias, e.g. ground vias inside a QFP pad ring | +| `plane` | each SMD pad of a plane net drops to its own via before the negotiation (`only`, `skip`) | +| `connect`, `pair`, `decaps`, `rest`, `tie`, `stitch` | sequential steps: nets in a given order, pad to pad, caps to pins, everything left, pad to a new via, stitching vias (finished boards only) | + +`label = "x"` on a step and `--stop x` end the run after that step. + +Two typical recipes: + +- `negotiate` (with `planes = true`) → `repair` → `cleanup` → `pour`. +- `via` + `plane` for ground first, then `negotiate` → `repair` → `cleanup`. + +## How it works + +- **Grid**: 0.05 mm, origin snapped to a multiple of 0.05 mm (the edge clearance uses the true outline), so pads of parts on the placer's grid sit on cell centres. +- **Fields** (`board.rs`): + - Per cell and layer: the distance to and net of the nearest copper, and the distance to the nearest copper of another net. + - Board edge, NPTH and keep-outs are static no-net copper. + - Footprint copper that is not a pad (a net tie's bridge) is static too, sampled every 0.025 mm. + - A track of width w fits where foreign copper is at least w/2 + clearance away. It may neck to `wneck` only within `neck_zone` of the pads it joins. + - Separate fields keep vias out of SMD pads and drill edges 0.25 mm apart (KiCad's `min_hole_to_hole`). +- **Search** (`astar.rs`): 8-direction A* with turn cost (no turns over 90°), via cost, B.Cu multiplier (3) and cost maps. It uses a radix heap, which works because the octile heuristic is consistent. +- **Negotiation** (`router.rs`): + - Every net in pieces is a job. Tracks routed in negotiation are soft. + - A step onto other nets' soft copper costs (base + history) × (1 + present factor). + - After each round only the conflicting connections are rerouted. A net that stays in conflict for three rounds is rerouted whole with a wider window. + - Present factor 4, × 1.5 per round, up to 30 rounds. + - Whatever still conflicts is routed with soft copper made hard, trying every order of up to four such nets. Then all copper is hardened and dangling remnants are pruned. +- **Cleanup** (`cleanup.rs`): + - Each net is rerouted with the rest fixed. Steps that hug other copper are cheaper, so lines bundle. + - A reroute is kept if it is at most 2 % worse (length + 2 mm per via + 2 × necked mm) and splits nothing. + - Vias that are not needed go. + - Same-layer chains are pulled tight to octilinear shortcuts, and necked tracks widen wherever clearance allows. +- **Pours** (`pour.rs`): + - A plane net's pours fill where foreign copper is at least clearance + half the minimum fill width away. + - The net's copper joins an island where tracks and vias touch it, and where pads are within thermal-gap + spoke distance. + - Pad groups left apart get a via or a short track to the main island. Whatever stays apart is reported as `islands`. +- **Placer link**: + - `placer run ... --route board.json route.toml --route-top K` routes the best K placements in parallel and ranks them. + - `placer route PROBLEM CONFIG board.json route.toml OUT PLACEMENT...` does the same for existing placement files. + - Memory: about 160 MB per board routed at once. + +## Lessons from real boards + +- **Net order was the limit, and negotiation removes it.** With the same grid, costs and A*, a one-net-at-a-time router completed 5 of 32 placer candidates on a dense ESP32 + Ethernet board. Negotiation completed 20, and later 26 with bundle attraction. +- **PathFinder's multiplicative form matters.** With additive costs (step + present + history), the present factor swamps history, and two nets keep trading the same crossing. (base + history) × (1 + present) converged in about 12 rounds. +- **Hard pre-routes can box in pins** that negotiation cannot free later. Prefer `planes = true` over `plane` steps when ground drops wall in signal pins. +- **Interface escapes in a block.** Without `[[escape]]`, "complete" boards walled in an MCU's interface pins with supply and crystal tracks. + - Don't put cost zones on the escape channels. They price the layer for the escape lines too, which then drop to B.Cu with a via at each fine-pitch pin. + - Space escape pads at least 0.5 mm apart for 0.2 mm lines. Lines need 0.415 mm, and at 0.45 mm the slack is less than one grid step. + - Choose `from`/`to` so that the pitch is a multiple of 0.05 mm. + - Keep the escape corridor free of parts. Covering the whole pin side with a footprint rule area works. +- **Fine-pitch parts must sit on the 0.05 mm grid.** A QFN 0.01 mm off the cells failed random pins on every placement. Put fixed parts' origins on multiples of 0.05 mm. The placer keeps its own parts on the grid. +- **0.4 mm QFN vs 0.5 mm LQFP**: two 0.2 mm tracks cannot leave neighbouring 0.4 mm-pitch pins side by side. If nearly every pin is used, all lines must neck (`wneck = 0.15`, `neck_zone = 2`). When a fine-pitch MCU has many consecutive pins in use, compare packages before tuning the router: the LQFP routed every time, the QFN never. +- **Routing a base board between fixed blocks**: + - Load the whole board dump as `[[fixed]] unmoved = true, protect = true` and route only what is still apart. + - Raise `margin` on the negotiate step (e.g. 20). Otherwise the 1.5 mm window never reaches the free channel between blocks, and lines cut through them. + - Write the result with `write_board.py --diff`. +- **Rerouting a few nets on a finished board**: strip those nets' copper from a copy, dump it, and load the dump as `[[fixed]] unmoved = true` **without** `done = true`. With `done = true` the stripped nets count as done too, and negotiate gets no jobs. +- **Starved thermal spokes**: the router does not model thermal-relief spokes. Through-hole plane pads next to signal pins can end with one spoke (KiCad DRC `starved_thermal`). On small pours, solid zone connections for those pads fix it. +- **Bundle attraction only works in the negotiation.** In the cleanup the space beside a partner is already taken. With `attract = 0.5` on negotiate, pair coupling went from about 2–9 % to about 30 %, with fewer vias. Too strong (2) pulls nets off their short paths. +- **Placement measures do not predict routability.** Spearman |ρ| ≤ 0.3 between unconnected pins and placer cost, crossings, RUDY or a coarse global route. Rank by routing instead (`--route`). +- A weighted A* heuristic (1.5–2) made negotiation slower and worse. Search windows and partial reroutes were what helped. + +## Limits + +- Two layers only. Footprints with bottom-side pads are refused: use the plain exposed-pad footprint, then [Thermal vias](thermal-vias.md) after routing. +- Differential pairs are routed as single nets; bundles only attract. +- No thermal-spoke check in the pour model. +- Negotiated boards take 4–15 s each on a 50-part board, single-threaded per board. diff --git a/knowledge/tooling/schgen.md b/knowledge/tooling/schgen.md new file mode 100644 index 0000000..c7cdff0 --- /dev/null +++ b/knowledge/tooling/schgen.md @@ -0,0 +1,33 @@ +# Schematic generator (schgen) + +`tools/schgen.py` writes KiCad 10 schematics from Python. Describe a circuit in a small script (e.g. `modules/<name>/tools/gen_sch.py`) and regenerate the schematic whenever it changes. + +## Use + +``` python +import sys; sys.path.insert(0, "tools") +from schgen import Sheet, G +s = Sheet(project, "block.kicad_sch", root_uuid, sheet_uuid, "Sheet Name", paper="A3") +u = s.add("Amplifier_Operational:LM324", "U2", x, y, rot=0, unit=1, value="LM324BIPWR", # dnp=True, in_bom=False for unfitted parts + fp="Package_SO:TSSOP-14_4.4x5mm_P0.65mm", fields={"LCSC": "...", "MPN": "..."}) +s.net(u, "3", "DAC1") # 2.54 mm stub + local label, text runs away from the pin +s.power(u, "11", "GND") # stub + power symbol turned to face away from the pin +s.hlabel(u, "1", "OUT", "output") +s.nc(u, "14"); s.text("note", x, y); s.write(path) +root = Sheet(project, "root.kicad_sch", root_uuid) +pins = root.sheet("Sheet Name", "block.kicad_sch", x, y, w, h, [("SDA", "bidirectional")], sheet_uuid, page="2") +``` + +- Symbols come from KiCad's stock libraries (found by [kicad_paths.py](../../tools/kicad_paths.py)) or the repo's `HW` library (`libraries/symbols/HW.kicad_sym`). They are flattened into `lib_symbols`: `extends` is resolved and sub-units are renamed. +- Pin positions: library Y points up, sheet Y points down, and rotation is counter-clockwise on screen. Mirroring is not supported. +- UUIDs are uuid5 of project, sheet path, reference and unit, so regenerating writes the same file and the board keeps its links. +- Check every result with `kicad-cli sch erc` and `sch export netlist`, and look at `kicad-cli sch export svg`. + +## Pitfalls met + +- **A power symbol on a sideways pin** first got a stub that turned down. It landed on the next pin's stub end and shorted three pins to GND; only the netlist showed it, ERC gave just a warning. `power()` now puts the symbol straight out from the pin and turns the symbol instead. +- **`#PWR`/`#FLG` references must be unique across all sheets.** Start the root sheet's flags high, e.g. `#FLG51`. Duplicates make `kicad-cli` warn "schematic has annotation errors". +- **Page numbers:** a root with several sheets needs a distinct `page` for each. +- **Layout units:** layout is in grid units (`G` = 2.54 mm), and A3 is 165 × 117 grid units. Keep text off the border. + +More schematic-as-file lessons: [KiCad notes](kicad.md#writing-schematics-as-files). diff --git a/knowledge/tooling/thermal-vias.md b/knowledge/tooling/thermal-vias.md new file mode 100644 index 0000000..ecd9390 --- /dev/null +++ b/knowledge/tooling/thermal-vias.md @@ -0,0 +1,25 @@ +# Thermal vias (tools/thermal_vias.py) + +The [Placer](placer.md) and the [Rust router](rust-router.md) refuse footprints with bottom-side pads ("U1 has a bottom-side pad; flipped footprints are not supported"). KiCad's `_ThermalVias` footprint variants carry a B.Cu copy of the exposed pad, so they are refused too. Instead: + +1. Use the plain exposed-pad footprint in the schematic. +2. Keep B.Cu free under the pad with a cost zone in `route.toml`, e.g. `{ layer = "B", fp = "U3", rect = [-2.5, -2.5, 2.5, 2.5], cost = 100 }`. Zone rects do not turn with the part, so use a square that both orientations share. +3. After routing (`tools/pnr.sh install`), add the vias: + +``` sh +. tools/kicad_env.sh +$KPY tools/thermal_vias.py board.kicad_pcb U2 U3 U4 [--pitch 1.2 --via 0.6 --drill 0.3] +``` + +The script: + +- takes each footprint's largest SMD pad and lays a centred grid of vias on it (1.2 mm pitch, inset by radius + 0.1 mm); +- gives each via the pad's net; +- skips positions within clearance (0.2 mm) of another net's B.Cu copper, or closer than 0.25 mm hole to hole; +- refills the zones, saves and restores the `.kicad_pro`. + +Run DRC afterwards. + +- **Plane net only.** Use it only for pads on the ground plane's net; an exposed pad on another net would cut islands into the B.Cu pour. +- **Via-in-pad.** Vias inside the mask opening are open via-in-pad and can wick solder; vias under the mask are tented. At 0.3 mm drill that is fine for typical assembly; ask the fab for plugged vias if voiding matters. +- **Re-run** after every `pnr.sh install`, which replaces the board. diff --git a/knowledge/tooling/threemf-group.md b/knowledge/tooling/threemf-group.md new file mode 100644 index 0000000..565048c --- /dev/null +++ b/knowledge/tooling/threemf-group.md @@ -0,0 +1,11 @@ +# 3MF group + +`tools/threemf_group.py` turns a 3MF with several objects into one object with parts, for multi-colour prints such as label inlays in a housing. + +``` sh +python3 tools/threemf_group.py in.3mf out.3mf [name] +``` + +- **Why:** many CAD 3MF exports write one object per body, and a slicer loads separate objects as separate objects. A shell and its label glyphs must be one object, so that each part can get its own filament. +- **What it does:** it adds a parent object (named from the argument, else the first object's name) whose `<components>` reference every build item. Build transforms move onto the components, and only the parent is built. It writes core 3MF only, with no slicer-specific metadata; Orca, Bambu and Prusa load the result as one object with parts. +- **In place:** using the same path for in and out is fine; the whole file is read first. |
