@rulecad/pcb 0.5.4 → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -3,6 +3,54 @@
3
3
  What changed in each release, for someone upgrading a workspace. A **drilled size** here is a dimension the fab
4
4
  makes (a hole's diameter in the drill file). Each release says whether any drilled or printed size moved, and why.
5
5
 
6
+ ## 0.6.0: diodes are wired the right way round, with pad 1 as the cathode; routeStore keeps the autorouter's results where its caller says; pcb ships tscircuit's notice for the code it follows
7
+
8
+ ### Fixed
9
+
10
+ - A net or track joined to a diode's `cathode` now reaches the diode's cathode. The board engine used to name a diode's two ports by the order of its pads, the first one the anode, whatever the pads said they were. On a DO-35 diode (`do35()`) the first pad is the square cathode pad, so every net joined to `D.cathode` went to the round anode pad instead, against the band printed on the board. A pad named `cathode` or `anode` (or `K`, `A`) is now that end; a diode whose pads are only numbered has pad 1 as its cathode, as KiCad and assemblers number a diode's pads.
11
+ - A diode's cathode is now its pin 1 in every file the board makes: the KiCad board and schematic, and the placement file. The keyboard's SOD-123 diodes (`keyboard()`) are turned half round on the back so that pad 1, the cathode, is on the row's side. Their copper and the bar printed by each one do not move; the KiCad files and the placement file change (each diode is placed at 180° rather than 0°).
12
+ - A diode with other than two pads, or with both pads at the same end, is refused with a message saying how to name them.
13
+
14
+ ### Changed
15
+
16
+ - A diode's ports are `pin1` (also `cathode`, `neg`, `K`, `1`) and `pin2` (also `anode`, `pos`, `A`, `2`). The names `left` and `right`, which meant the first and second pad, are gone: use `cathode` and `anode`.
17
+
18
+ ### Boards made before this change
19
+
20
+ - **thin-picro macropads** (`examples/thin-picro`, `macropad:front` and `macropad:rear`), and any other board with `do35()` diodes: every diode was wired backwards. Fitted by the band on the board, no key reads with COL2ROW firmware. To tell: on the old board, the row's track (the one running along to the next diode in the row) goes to the round pad. A board already made works if each diode is fitted with its band at the round pad, the opposite of the band printed on the board, or with firmware set to ROW2COL.
21
+ - **Keyboards made with `keyboard()`**, hand-soldered by the printed bar: these were right, and still are. Assembled by a fab from the old placement file, or drawn from the old KiCad files, every diode may be reversed, because those files gave the anode as pad 1. To tell: in the old KiCad board, each diode's pad 1 is on its switch's net. Check an assembled board's diodes: the band (cathode) should be on the side of the row track; if it is on the switch's side, set the firmware to ROW2COL.
22
+ - Build the boards again to get new Gerbers, KiCad files and placement files. The macropads' tracks to their diodes move; no printed size moves.
23
+
24
+ ### Added
25
+
26
+ - `routeStore({ get, put })` sets where the autorouter's results are kept, in place of the `RULECAD_ROUTE_CACHE` folder: `get(key)` gives a route's JSON text or nothing, `put(key, text)` keeps one, each key the 64 hex digits of a SHA-256 of the router's input and version, as the folder's file names are. `routeStore(null)` goes back to the folder. cad uses it to run board designs in its sandbox, which can't write files: the routes found there go back to cad, which writes them.
27
+ - Upgrading: nothing to do; without a store the folder is used as before. No printed size changes.
28
+
29
+ - A note, THIRD-PARTY.md, shipped with the package and linked from a new Licence section in the README: `fixedTraces` in circuit.mjs follows `withFixedTraces` in tscircuit's core, which is under the MIT licence, and the note carries that licence's copyright notice and text, as the licence asks. It also says that `@tscircuit/copper-pour-solver`, one of pcb's dependencies, is published without a licence although its repository is MIT. The code is unchanged: no board, and no printed size, changes.
30
+
31
+ ## 0.5.5: tracks finished for the fab, a route cache, a footprint for MX or Choc switches
32
+
33
+ ### Added
34
+
35
+ - `hybridSwitch(name, x, y, mx, choc)`: one footprint that takes a Cherry MX or a Kailh Choc v1 switch, soldered.
36
+ Both switches' pins keep their own holes, a pair per pin (pin1: MX's pin 1 and Choc's pin 1; pin2 likewise), joined
37
+ by a track. The centre hole is MX's 4.0 mm (a Choc post fits it); each side's two pegs, 0.42 mm apart, share one
38
+ hole round both (2.12 mm).
39
+ - A switch or diode with more than one pad on a pin draws as one symbol in the schematic, as chips already did.
40
+ - `finish: true` on a board: once routed, every track leaves its surface-mount pads square to the pad's edge, and
41
+ every acute corner between tracks of a net is filled (`@rulecad/smooth` 0.2's `finishCircuit`), kept tracks too. A
42
+ new check reports any left: it fails a board that asks for finishing, and tells any other board. The kept-routing
43
+ check counts a source's track redrawn to leave its pad square (the same ends) as the source's.
44
+ - A route cache: with `RULECAD_ROUTE_CACHE` set to a folder (cad sets its workspace's `.cache/routes`), the autorouter's
45
+ result for an input it has routed before is read back, not searched again: a board changed only after routing
46
+ (its finish, repairs, checks, or the library) builds in seconds, not minutes.
47
+ - Checks: a board whose keys are wired straight to GPIO (`matrix.direct`, `{ K1: 'GP20', ... }`) is checked for no
48
+ GPIO used twice, in place of the row and column check.
49
+
50
+ ### Drilled and printed sizes that moved
51
+
52
+ None: existing footprints are unchanged. A board with `finish: true` gets new copper (square exits, corner fills).
53
+
6
54
  ## 0.5.4: a board's mounting holes named by thread (Fixings 3)
7
55
 
8
56
  ### What reads fixings now
package/README.md CHANGED
@@ -89,6 +89,13 @@ export function main(v) {
89
89
  `neck` (mm, the fab's smallest track), a track still a little too close to another is straightened where the router
90
90
  doubled back, moved in where it hugs the board's edge, or narrowed where they pass. Existing vias reach the router at
91
91
  their real size. `effort` asks the router to search harder, at more time.
92
+ - **Finishing:** with `finish: true`, once routed (and smoothed), every track leaves a surface-mount pad square to the
93
+ pad's edge, and every acute corner between tracks of a net is filled ([@rulecad/smooth](../smooth)'s
94
+ `finishCircuit`), kept tracks too: a fab's engineer flags both (a small part can tombstone when its tracks pull off
95
+ its pads at an angle; an acute corner traps etchant). If the design checks then find a new error, the board goes
96
+ back as it was. A check lists anything left, and fails the board if it asked for finishing.
97
+ - **Route cache:** set `RULECAD_ROUTE_CACHE` to a folder (cad sets `.cache/routes`) and a route the router has found
98
+ for an identical input is read back instead of searched again.
92
99
  - **Smoothing:** with `smooth: true`, the router's tracks are pulled tight once routed
93
100
  ([@rulecad/smooth](../smooth)): wiggles, detours and doubling-backs straightened wherever the straight run keeps
94
101
  `clearance`, sharp bends cut across. Only the router's tracks move, and drawn tracks never do. A clone's kept
@@ -134,7 +141,9 @@ export function main(v) {
134
141
  `{ rect: { w, h, offset } }` is an oval (a rounded rectangle) round its hole, which can sit off-centre.
135
142
  - **Any board shape:** give `outline: [{ x, y }, ...]` in place of a centre and size. `shape.rounded(w, h, r)`,
136
143
  `shape.bevelled(w, h, b)`, `shape.circle(d)` and `shape.rect(w, h)` make common ones. The router keeps tracks
137
- inside the outline, and a check finds any pad outside it.
144
+ inside the outline, and a check finds any pad outside it. Every hole, on a board of any shape, is checked as a circle
145
+ against the edge: one that breaks through it fails, named, with how far it breaks out (`mounting hole 2 (3.4 mm)
146
+ breaks through the board's edge by 1.2 mm at (14.5, 0)`), so that the fab doesn't mill a notch where a screw goes.
138
147
  - **Copper of any shape:** a pad `{ pin, smd: true, x, y, points: [[x, y], ...] }` (x, y: where tracks join it), such
139
148
  as a ring from `shape.ring(r0, r1)` (a rotary contact, a touch pad). The router sees it as strips that follow its shape.
140
149
  - **Nets:** each net's pins are joined by the shortest set of links between them, at `board.track` (or the net's own
@@ -183,3 +192,8 @@ npx cad export macropad/board # <name>-fab.zip for JLCPCB, KiCad files, the
183
192
  the newest, and since its 0.0.3032 that has pulled in an old circuit-json that the design checks can't load
184
193
  (tscircuit/circuit-json-to-gerber#200).
185
194
  - Ordering is your click: `cad export` makes the fab zip and never places an order.
195
+
196
+ ## Licence
197
+
198
+ MIT (see [LICENSE](LICENSE)). `fixedTraces` in circuit.mjs follows tscircuit's MIT-licensed `withFixedTraces`: its
199
+ copyright notice is in [THIRD-PARTY.md](THIRD-PARTY.md), which goes with any copy of the package.
package/THIRD-PARTY.md ADDED
@@ -0,0 +1,42 @@
1
+ # Code in @rulecad/pcb that follows someone else's
2
+
3
+ Most of `@rulecad/pcb` is rulecad's own work, under the MIT licence in [LICENSE](LICENSE). One part is not.
4
+
5
+ ## `fixedTraces` in circuit.mjs
6
+
7
+ `fixedTraces`, in `circuit.mjs`, turns the tracks already drawn on a board into obstacles the autorouter keeps clear
8
+ of: each piece of track a box a track wide, each via a square. It follows the function `withFixedTraces` in tscircuit's
9
+ core (https://github.com/tscircuit/core), so that a board is routed around its drawn tracks in the same way there. That
10
+ code is under the MIT licence, whose notice follows. It asks only that the notice goes with any copy.
11
+
12
+ ```
13
+ MIT License
14
+
15
+ Copyright (c) 2024 tscircuit Inc.
16
+
17
+ Permission is hereby granted, free of charge, to any person obtaining a copy
18
+ of this software and associated documentation files (the "Software"), to deal
19
+ in the Software without restriction, including without limitation the rights
20
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
21
+ copies of the Software, and to permit persons to whom the Software is
22
+ furnished to do so, subject to the following conditions:
23
+
24
+ The above copyright notice and this permission notice shall be included in all
25
+ copies or substantial portions of the Software.
26
+
27
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
28
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
29
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
30
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
31
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
32
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
33
+ SOFTWARE.
34
+ ```
35
+
36
+ ## The packages pcb installs
37
+
38
+ pcb uses many of tscircuit's packages, installed from npm with their own licences; they are not copied into pcb. One
39
+ of them, `@tscircuit/copper-pour-solver`, is published without a licence field or file, though its repository
40
+ (https://github.com/tscircuit/copper-pour-solver) is under the MIT licence. The repository's test
41
+ `test/notices.test.mjs` lists every installed package's licence that is not one of the usual permissive ones, with the
42
+ reason it is accepted.
package/circuit.mjs CHANGED
@@ -15,6 +15,8 @@
15
15
  // holes: [{ x, y, d }], courtyard: { w, h } | null,
16
16
  // footprint: 'sod123' | 'jst4_sh' | 'pinrow4' ... (a footprinter string, SMD or through-hole, instead of pads),
17
17
  // sch: { x, y, symbol?, pinLabels? } }
18
+ // a diode's two ports are its 'cathode' (pin 1, also 'K') and 'anode' (pin 2, also 'A'): a pad whose pin is
19
+ // 'cathode' or 'anode' is that end, else pad 1 is the cathode, as KiCad and assemblers number a diode's pads
18
20
  // trace { from: [part, port], to: [part, port], width, path: [{ x, y }] (absolute, between the two ports), layer }; a trace
19
21
  // without a path is left to the autorouter when board.autoroute is set
20
22
  // nets { GND: ['U1.GND', 'J1.1', 'J2.1'] } or { GND: { pins: [...], width } }: each net's pins are joined by the
@@ -155,7 +157,7 @@ export async function circuitJson(board, { route = defaultRouter } = {}) {
155
157
  subcircuit_id: SUB, rulecad_model: { ...m, source: path, x: part.x, y: part.y, rotation: part.rotation ?? 0, layer: part.layer } }); }
156
158
  }
157
159
  // (the vias the router may make: the board's sizes, else ones with the ring a fab recommends, 0.3 in 0.8)
158
- add('pcb_board', { source_board_id: sourceBoard.source_board_id, subcircuit_id: SUB, center: board.center, thickness: board.thickness, num_layers: copper.length,
160
+ add('pcb_board', { source_board_id: sourceBoard.source_board_id, subcircuit_id: SUB, center: board.center, thickness: board.thickness, num_layers: copper.length, ...(board.finish ? { rulecad_finish: true } : {}),
159
161
  width: board.width, height: board.height, ...(board.outline ? { outline: board.outline.map(({ x, y }) => ({ x, y })) } : {}), material: 'fr4', ...FAB_MINIMUMS,
160
162
  ...(board.fab ? { min_trace_width: board.fab.track_min, min_trace_to_pad_edge_clearance: board.fab.gap_min, min_pad_edge_to_pad_edge_clearance: board.fab.gap_min, min_via_hole_edge_to_via_hole_edge_clearance: board.fab.gap_min } : {}), // (the fab's own, when the board names its rules)
161
163
  min_via_hole_diameter: board.route_via?.hole ?? board.via_hole ?? 0.3, min_via_pad_diameter: board.route_via?.pad ?? board.via_pad ?? 0.8 });
@@ -289,6 +291,7 @@ export async function circuitJson(board, { route = defaultRouter } = {}) {
289
291
  if (board.smooth) await smoothRouted(out, board);
290
292
  if (board.via_hole_gap) await viaHoleRepair(out, board.via_hole_gap, board.neck);
291
293
  if (board.track_gap && board.neck) await gapRepair(out, board.track_gap, board.neck);
294
+ if (board.finish) await finishTracks(out, board);
292
295
  }
293
296
  if (planeNets) await pours(out, add, board, planeNets, netOf);
294
297
  if (board.silk?.length) clearSilkAfter(out, add, board);
@@ -303,6 +306,37 @@ export async function circuitJson(board, { route = defaultRouter } = {}) {
303
306
  // from the pin). Each cut is recorded (rulecad_trimmed on the track, rulecad_shortened on a shortened stub segment) and
304
307
  // the checks name it. A track the design checks then find in a new error goes back as it was; if a cut is in one, the
305
308
  // board is smoothed again without cuts
309
+ // The tracks finished as a fab's engineer asks (@rulecad/smooth's finishCircuit): every track leaving a surface-mount pad
310
+ // square to its edge, and every acute corner between tracks of a net filled. Kept tracks are finished too (a redrawn
311
+ // one carries rulecad_squared: its first shape, which the checks know as the source's). If the design checks then find
312
+ // a new error, the board goes back as it was before finishing
313
+ export async function finishTracks(out, board) {
314
+ const { finishCircuit } = await import('@rulecad/smooth');
315
+ const { runAllChecks } = await import('@tscircuit/checks');
316
+ // each error by its kind and the elements in it, as smoothRouted keys them
317
+ const errors = async (json) => (await runAllChecks(structuredClone(json))).filter((e) => /_error$/.test(e.type))
318
+ .map((e) => JSON.stringify([e.type, ...[...new Set(JSON.stringify(e).match(/pcb_[a-z_]+?_\d+/g) || [])].sort()]));
319
+ const before = new Set(await errors(out)), was = new Map(out.filter((e) => e.type === 'pcb_trace').map((e) => [e.pcb_trace_id, e]));
320
+ let { json } = finishCircuit(out, { ...(board.clearance ? { clearance: board.clearance } : {}) });
321
+ // A change the design checks then find in a new error is undone (a pair redrawn together, both), the rest kept
322
+ for (let round = 0; round < 6; round++) {
323
+ const fresh = (await errors(json)).filter((e) => !before.has(e));
324
+ if (!fresh.length) return void out.splice(0, out.length, ...json);
325
+ const named = new Set(fresh.flatMap((e) => JSON.parse(e).slice(1)));
326
+ const pairs = new Set(json.filter((e) => e.type === 'pcb_trace' && named.has(e.pcb_trace_id) && e.rulecad_pair).map((e) => e.rulecad_pair));
327
+ const undo = (e) => e.type === 'pcb_trace' && (named.has(e.pcb_trace_id) || (e.rulecad_pair && pairs.has(e.rulecad_pair)));
328
+ let undone = 0;
329
+ json = json.flatMap((e) => {
330
+ if (!undo(e)) return [e];
331
+ if (e.rulecad_fill) { undone++; return []; } // a fill: taken away
332
+ const o = was.get(e.pcb_trace_id);
333
+ if (o && o !== e) { undone++; return [o]; } // a redrawn track: as it was
334
+ return [e];
335
+ });
336
+ if (!undone) break; // (a new error in nothing the finish changed: leave the board as it was)
337
+ }
338
+ }
339
+
306
340
  export async function smoothRouted(out, board) {
307
341
  const { smoothCircuit } = await import('@rulecad/smooth');
308
342
  const { runAllChecks } = await import('@tscircuit/checks');
@@ -770,15 +804,31 @@ async function pours(out, add, board, nets, netOf) {
770
804
  }
771
805
  }
772
806
 
773
- // A part's port names, in pad order: a switch's pin1 and pin2, a diode's anode and cathode, a chip's pins by label
807
+ // A part's port names, in pad order: a switch's pin1 and pin2, a diode's cathode and anode by its pads (diodePorts), a chip's pins by label
774
808
  function portNames(part, pads) {
775
- if (part.ftype === 'simple_diode') return [{ name: 'pin1', n: 1, hints: ['pin1', 'pos', 'anode', 'left', '1'] }, { name: 'pin2', n: 2, hints: ['pin2', 'neg', 'cathode', 'right', '2'] }];
809
+ if (part.ftype === 'simple_diode') return diodePorts(part, pads);
776
810
  return (part.pads || pads).map((p) => {
777
811
  const n = Number(p.pin.replace(/\D/g, '')), label = part.sch?.pinLabels?.[p.pin];
778
812
  return { name: label || p.pin, n, hints: label ? [label, p.pin, String(n)] : [p.pin, String(n)] };
779
813
  });
780
814
  }
781
815
 
816
+ // A diode's two ports, each named for the end of the diode its pad is. A pad that says which end it is (do35's
817
+ // 'cathode' and 'anode') is that end; otherwise pad 1 is the cathode (K) and pad 2 the anode (A), as KiCad's diode
818
+ // footprints and assemblers number them. The cathode is port 1 and the anode port 2, whatever order the pads come in,
819
+ // so a KiCad export and a placement file give pad 1 as the cathode, and the band goes at that end.
820
+ function diodePorts(part, pads) {
821
+ if (pads.length !== 2) throw new Error(`${part.name}: a diode has two pads, one for each end, and this one has ${pads.length}`);
822
+ const said = pads.map((p) => (/^(anode|a)$/i.test(p.pin) ? 'anode' : /^(cathode|k)$/i.test(p.pin) ? 'cathode' : null));
823
+ const other = (end) => (end === 'anode' ? 'cathode' : 'anode');
824
+ const byNumber = (p) => (Number(String(p.hint ?? p.pin).replace(/\D/g, '')) === 1 ? 'cathode' : 'anode');
825
+ const ends = said.map((s, i) => s ?? (said[1 - i] ? other(said[1 - i]) : byNumber(pads[i])));
826
+ if (ends[0] === ends[1]) throw new Error(`${part.name}: both of the diode's pads are its ${ends[0]}. Name one pad 'cathode' and the other 'anode', or number them 1 (cathode) and 2 (anode)`);
827
+ return ends.map((end) => end === 'cathode'
828
+ ? { name: 'pin1', n: 1, end, hints: ['pin1', 'cathode', 'neg', 'K', '1'] }
829
+ : { name: 'pin2', n: 2, end, hints: ['pin2', 'anode', 'pos', 'A', '2'] });
830
+ }
831
+
782
832
  // A net's connections: its pins joined by the shortest set of straight links between them (Prim's minimum spanning
783
833
  // tree, ties to the earlier pin), so the router gets short, sensible connections to route rather than a long chain
784
834
  function netTraces(board, port, joined = new Map()) {
@@ -841,11 +891,16 @@ function schematic(out, add, placed, board, port, netOf = new Map()) {
841
891
  const symbol = symbols[part.ftype === 'simple_diode' ? 'diode_down' : 'spst_switch_right'];
842
892
  const c = add('schematic_component', { center: { x: s.x, y: s.y }, rotation: 0, size: symbol.size, source_component_id: comp.source_component_id,
843
893
  is_box_with_pins: true, symbol_name: part.ftype === 'simple_diode' ? 'diode_down' : 'spst_switch_right', schematic_group_id: 'schematic_group_0' });
844
- sourcePorts.forEach((sp, i) => {
845
- const q = symbol.ports[i], center = { x: s.x + q.x - symbol.center.x, y: s.y + q.y - symbol.center.y };
894
+ // one symbol pin per pin: a pin with more than one pad (a hybrid switch's) draws its other pads as that one
895
+ const firsts = sourcePorts.filter((sp, i) => sourcePorts.findIndex((o) => o.name === sp.name) === i);
896
+ firsts.forEach((sp, i) => {
897
+ // (the diode symbol's first port is its anode, at the top: each diode port goes to its own end of the symbol)
898
+ const k = part.ftype === 'simple_diode' ? (sp.port_hints.includes('anode') ? 0 : 1) : i;
899
+ const q = symbol.ports[k], center = { x: s.x + q.x - symbol.center.x, y: s.y + q.y - symbol.center.y };
846
900
  sch.set(sp.source_port_id, add('schematic_port', { schematic_component_id: c.schematic_component_id, center, source_port_id: sp.source_port_id,
847
- facing_direction: part.ftype === 'simple_diode' ? (i ? 'down' : 'up') : (i ? 'right' : 'left'), distance_from_component_edge: 0.4 }));
901
+ facing_direction: part.ftype === 'simple_diode' ? (k ? 'down' : 'up') : (k ? 'right' : 'left'), distance_from_component_edge: 0.4 }));
848
902
  });
903
+ for (const sp of sourcePorts) if (!sch.has(sp.source_port_id)) sch.set(sp.source_port_id, sch.get(firsts.find((o) => o.name === sp.name).source_port_id));
849
904
  }
850
905
  // A wire between two parts' pins (L-shaped), or for a connection to the chip, a label at each end naming the pin
851
906
  const labelled = new Set(placed.filter((p) => p.at).map((p) => p.part.name));
@@ -932,7 +987,7 @@ export async function routeInput(json, toRoute, board = {}) {
932
987
 
933
988
  // The drawn tracks become fixed obstacles for the router: each segment a box a track wide (a diagonal one, a run of
934
989
  // boxes about a track-width long), each via a square. Ported from tscircuit core's withFixedTraces (MIT licence,
935
- // github.com/tscircuit/core), so a board is routed around them as it is there.
990
+ // github.com/tscircuit/core), so a board is routed around them as it is there: its notice is in THIRD-PARTY.md.
936
991
  function fixedTraces(input) {
937
992
  const obstacles = [];
938
993
  for (const trace of input.traces) {
@@ -1078,6 +1133,38 @@ export async function neckDown(json, traces, neck) {
1078
1133
  // The autorouter's pipelines, tried in order until one routes the board: its own, then its others, each a different search
1079
1134
  const PIPELINES = ['AutoroutingPipelineSolver', 'AutoroutingPipelineSolver4', 'AutoroutingPipelineSolver5', 'AutoroutingPipelineSolver6', 'AutoroutingPipelineSolver8'];
1080
1135
 
1136
+ // The route cache: a route per router input, keyed by the SHA-256 (64 hex digits) of the input and the router's
1137
+ // version. Kept in the store routeStore() was given, else as a file of that name in the folder RULECAD_ROUTE_CACHE
1138
+ // names; nothing (null) when neither is set. (cad's design sandbox can't write files: its runner sets a store that
1139
+ // reads the folder and hands what it routed back to the tool, which writes it.)
1140
+ let routes = null;
1141
+ /**
1142
+ * Where the autorouter's results are kept, in place of the RULECAD_ROUTE_CACHE folder: `get(key)` gives a route's
1143
+ * text (JSON) or undefined, `put(key, text)` keeps one; null goes back to the folder. Keys are 64 hex digits.
1144
+ * @param {{ get: (key: string) => string | undefined, put: (key: string, text: string) => void } | null} store
1145
+ */
1146
+ export function routeStore(store) { routes = store; }
1147
+ async function routeCache(input) {
1148
+ const dir = typeof process !== 'undefined' && process.env?.RULECAD_ROUTE_CACHE;
1149
+ if (!dir && !routes) return null;
1150
+ const [fs, path, crypto, { createRequire }] = await Promise.all([import('node:fs'), import('node:path'), import('node:crypto'), import('node:module')]);
1151
+ let version = '?';
1152
+ try { version = createRequire(import.meta.url)('@tscircuit/capacity-autorouter/package.json').version; } catch {}
1153
+ const key = crypto.createHash('sha256').update(JSON.stringify([version, input])).digest('hex');
1154
+ if (routes) {
1155
+ const store = routes;
1156
+ return {
1157
+ read: () => { try { const text = store.get(key); return text === undefined ? null : JSON.parse(text); } catch { return null; } },
1158
+ write: (traces) => { try { store.put(key, JSON.stringify(traces)); } catch {} },
1159
+ };
1160
+ }
1161
+ const file = path.join(dir, `${key}.json`);
1162
+ return {
1163
+ read: () => { try { return JSON.parse(fs.readFileSync(file, 'utf8')); } catch { return null; } },
1164
+ write: (traces) => { try { fs.mkdirSync(dir, { recursive: true }); fs.writeFileSync(file, JSON.stringify(traces)); } catch {} }, // (a cache that can't be written is only slower)
1165
+ };
1166
+ }
1167
+
1081
1168
  async function routeOnce(json, toRoute, board, limit = 0) {
1082
1169
  // The autorouter uses JavaScript features from Node 22 (iterator helpers): say so, rather than fail inside it
1083
1170
  if (Number(process.versions.node.split('.')[0]) < 22) throw new Error(`routing a board's remaining connections needs Node 22 or newer (this is Node ${process.versions.node}); boards drawn wholly by rule build on Node 20`);
@@ -1087,6 +1174,12 @@ async function routeOnce(json, toRoute, board, limit = 0) {
1087
1174
  // two-sided board: "a layer transition without a via"), or what it hands back fails here (a pad left without a
1088
1175
  // track, a track through a part), the next one: a different search from the start
1089
1176
  const pipelines = [...new Set([board.pipeline || PIPELINES[0], ...PIPELINES])], tried = [];
1177
+ // A route already found for this very input (RULECAD_ROUTE_CACHE: a folder; cad sets its workspace's .cache/routes):
1178
+ // its tracks as the router handed them back, so a board whose routing is unchanged builds in seconds, not the
1179
+ // router's minutes, while what comes after routing (repairs, smoothing, the finish) can still change
1180
+ const cache = await routeCache([srj, pipelines, board.effort ?? null, limit ? 'repair' : 'route']);
1181
+ const hit = cache?.read();
1182
+ if (hit) try { return routedTraces({ getOutputSimplifiedPcbTraces: () => structuredClone(hit) }, srj, json); } catch {} // (a stale one: route again)
1090
1183
  for (const name of pipelines) {
1091
1184
  if (!router[name]) continue;
1092
1185
  const solver = new router[name](srj, { cacheProvider: null, ...(board.effort ? { effort: board.effort } : {}) }); // effort: how hard it searches (1, the router's own)
@@ -1094,7 +1187,7 @@ async function routeOnce(json, toRoute, board, limit = 0) {
1094
1187
  try { while (!solver.solved && !solver.failed) { solver.step(); if (limit && Date.now() > limit) throw Object.assign(new Error('a repair took too long'), { late: true }); } }
1095
1188
  catch (e) { if (e.late) throw e; solver.failed = true; solver.error = solver.error || e.message; }
1096
1189
  if (solver.failed) { tried.push(`${name}: ${solver.error || 'no reason given'}`); continue; }
1097
- try { return routedTraces(solver, srj, json); } catch (e) { tried.push(`${name}: ${e.message}`); }
1190
+ try { const done = routedTraces(solver, srj, json); cache?.write(solver.getOutputSimplifiedPcbTraces()); return done; } catch (e) { tried.push(`${name}: ${e.message}`); }
1098
1191
  }
1099
1192
  throw new Error(tried.length > 1 ? `the autorouter couldn't route every connection, with any of its pipelines (${tried.join('; ')})` : tried[0]?.replace(/^\w+: /, '') || 'the autorouter has none of its pipelines');
1100
1193
  }
package/package.json CHANGED
@@ -1,16 +1,16 @@
1
1
  {
2
2
  "name": "@rulecad/pcb",
3
- "version": "0.5.4",
3
+ "version": "0.6.0",
4
4
  "description": "Circuit boards from rules: parts from rule sets or any standard footprint, quarter-turn rotation, nets and autorouting; keyboards with every matrix track drawn by rule. Gerbers, KiCad files and a JLCPCB BOM. Circuit JSON written directly: no React.",
5
5
  "type": "module",
6
6
  "exports": "./pcb.mjs",
7
7
  "files": [
8
- "pcb.mjs",
9
- "circuit.mjs",
10
- "kicad.mjs",
8
+ "*.mjs",
11
9
  "README.md",
12
10
  "CHANGELOG.md",
13
- "LICENSE"
11
+ "LICENSE",
12
+ "THIRD-PARTY.md",
13
+ "!test.mjs"
14
14
  ],
15
15
  "license": "MIT",
16
16
  "keywords": [
@@ -38,10 +38,10 @@
38
38
  "dependencies": {
39
39
  "@flatten-js/core": "1.6.14",
40
40
  "@jscad/modeling": "^2.12.0",
41
- "@rulecad/fixings": "^0.1.3",
42
- "@rulecad/rules": "^0.3.7",
41
+ "@rulecad/fixings": "^0.1.9",
42
+ "@rulecad/rules": "^0.3.31",
43
43
  "@resvg/resvg-js": "2.6.2",
44
- "@rulecad/smooth": "^0.1.2",
44
+ "@rulecad/smooth": "^0.2.0",
45
45
  "@tscircuit/capacity-autorouter": "0.0.982",
46
46
  "@tscircuit/checks": "0.0.264",
47
47
  "@tscircuit/circuit-json-util": "0.0.122",
package/pcb.mjs CHANGED
@@ -6,15 +6,15 @@
6
6
  // draws every track by rule, from the switch's footprint (mx rules) and our margins (the board's track and clear):
7
7
  // columns on the front copper: down each column from pin 2 to pin 2, jogging between the centre post and the left
8
8
  // peg; then below the keys, right, and up a lane beside the Pico to its pin
9
- // diodes SOD-123s on the back, under each switch below the centre post; pin 1 runs to the anode up a lane right
10
- // of the right peg
9
+ // diodes SOD-123s on the back, under each switch below the centre post, turned half round so that pad 1, the
10
+ // cathode, is on the row's side; the switch's pin 1 runs to the anode (pad 2) up a lane right of the right peg
11
11
  // rows on the back copper: cathode to cathode under each row of switches, then right and up or down a lane
12
12
  // beside the Pico to its pin
13
13
  // Diodes point from the switch to the row (COL2ROW in QMK's terms).
14
14
  import fs from 'node:fs';
15
15
  import path from 'node:path';
16
- import { circuitJson, bounds, smtBounds, slideClear, viaHoleGaps } from './circuit.mjs';
17
- export { bounds };
16
+ import { circuitJson, bounds, smtBounds, slideClear, viaHoleGaps, routeStore } from './circuit.mjs';
17
+ export { bounds, routeStore }; // (routeStore: where the autorouter's results are kept, circuit.mjs)
18
18
  import { createRequire } from 'node:module';
19
19
  // The published rule sets a footprint's pins come from (a Pico's GPIO, a XIAO's labels): read from @rulecad/rules as
20
20
  // published, not through @rulecad/cad, which pcb would then depend on (and cad names pcb: a loop), and which copies a
@@ -124,6 +124,43 @@ export const part = (name, footprint, x, y, o = {}) => chip(name, x, y, o, { foo
124
124
  * A pin header from rules (r: pitch, drill, pad; row_spacing for two rows): o.pins pins per row, o.rows 1 or 2.
125
125
  * Two rows are numbered as a DIP: 1 to n down the left, n + 1 to 2n up the right.
126
126
  */
127
+ // A footprint that takes either switch: a Cherry MX (m: the mx rules) or a Kailh Choc v1 (c: the choc rules), soldered.
128
+ // The centre hole is the wider of the two (MX's: a Choc's post sits in it); each side's two locating pegs, 0.42 mm
129
+ // apart, share one hole round both of theirs. Each switch's two pins keep their own holes: pin1 is MX's pin 1 and
130
+ // Choc's pin 1 (2.7 mm apart, behind the centre), pin2 MX's pin 2 and Choc's pin 2, each pair one pin, joined by a track
131
+ export function hybridSwitch(name, x, y, m, c, sch = {}) {
132
+ const pegX = (m.pcb_peg_x + c.pcb_peg_x) / 2, pegD = Math.abs(m.pcb_peg_x - c.pcb_peg_x) + Math.max(m.pcb_peg_hole, c.pcb_peg_hole); // round both pegs' holes
133
+ return { name, ftype: 'simple_switch', mpn: 'Cherry MX or Kailh Choc v1 (PCB mount)', package: 'Cherry MX / Kailh Choc v1 hybrid, PCB mount', x, y, layer: 'top', sch,
134
+ pads: [pad('pin1', m.pcb_pin1_x, m.pcb_pin1_y, m.pcb_pin_drill, m.pcb_pin_pad), pad('pin1', c.pcb_pin1_x, c.pcb_pin1_y, c.pcb_pin_drill, c.pcb_pin_pad),
135
+ pad('pin2', m.pcb_pin2_x, m.pcb_pin2_y, m.pcb_pin_drill, m.pcb_pin_pad), pad('pin2', c.pcb_pin2_x, c.pcb_pin2_y, c.pcb_pin_drill, c.pcb_pin_pad)],
136
+ holes: [hole(0, 0, Math.max(m.pcb_centre_hole, c.pcb_centre_hole)), hole(-pegX, 0, pegD), hole(pegX, 0, pegD)],
137
+ courtyard: { w: Math.max(m.pcb_body, c.pcb_body), h: Math.max(m.pcb_body, c.pcb_body) } };
138
+ }
139
+ // A DO-35 axial diode (a 1N4148: d, the do35 rules) lying flat between its two leads, bent down 0.3 in apart: cathode
140
+ // on the left (a square pad, and the band on its body), anode on the right, turned by rotation. Its 3D model is the body
141
+ // and the leads, through the board (thickness) and trimmed below it
142
+ export function do35(name, x, y, d, { rotation = 0, thickness = 1.6, sch = {}, mpn = '1N4148', layer = 'top' } = {}) {
143
+ const h = d.pitch / 2, bl = d.body_length / 2, r = d.body_d / 2, l = d.lead_d / 2, axis = r; // the body's axis, a radius up
144
+ return { name, ftype: 'simple_diode', mpn, package: 'DO-35, axial, 0.3 in', x, y, layer, rotation, sch, bom: false, place: false,
145
+ pads: [{ pin: 'cathode', x: -h, y: 0, hole: d.drill, outer: d.pad, rect: { w: d.pad, h: d.pad, offset: [0, 0] } }, pad('anode', h, 0, d.drill, d.pad)],
146
+ courtyard: null,
147
+ model: { boxes: [
148
+ { min: [-bl, -r, 0], max: [bl, r, 2 * r] }, // the glass body (a box round it)
149
+ ...[-1, 1].flatMap((s) => [
150
+ { min: [Math.min(s * bl, s * h) - (s > 0 ? 0 : l), -l, axis - l], max: [Math.max(s * bl, s * h) + (s > 0 ? l : 0), l, axis + l] }, // out along the axis
151
+ { min: [s * h - l, -l, -thickness - d.lead_out], max: [s * h + l, l, axis + l] }]) ] } }; // bent down through the board
152
+ }
153
+
154
+ // A single-row 0.1 in strip's 3D model, for header() parts (its pins along the part's y, as header() lays them):
155
+ // kind 'socket', a female socket's body (height tall) on the board; 'pins', a male header's spacer on the board and its
156
+ // pins above it (pin_above past the spacer) and through it
157
+ export function stripModel(n, { pitch = 2.54, kind = 'socket', height = 8.5, spacer = 2.5, pin = 0.64, pin_above = 6, thickness = 1.6, below = 3 } = {}) {
158
+ const half = (n * pitch) / 2, ys = Array.from({ length: n }, (_, i) => ((n - 1) / 2 - i) * pitch);
159
+ if (kind === 'socket') return { boxes: [{ min: [-pitch / 2, -half, 0], max: [pitch / 2, half, height] },
160
+ ...ys.map((y) => ({ min: [-pin / 2, y - pin / 2, -thickness - below], max: [pin / 2, y + pin / 2, 0] }))] };
161
+ return { boxes: [{ min: [-pitch / 2, -half, 0], max: [pitch / 2, half, spacer] }, ...ys.map((y) => ({ min: [-pin / 2, y - pin / 2, -thickness - below], max: [pin / 2, y + pin / 2, spacer + pin_above] }))] };
162
+ }
163
+
127
164
  export function header(name, x, y, r, o = {}) {
128
165
  const n = o.pins, two = (o.rows ?? 1) === 2, pads = [];
129
166
  for (let i = 0; i < n; i++) {
@@ -211,7 +248,9 @@ export function keyboard(v, keys) {
211
248
  // Around each switch (from its centre): the diode on the back below the post, its anode lane right of the right peg,
212
249
  // the row line below the diodes; the column lane on the front between the post and the left peg
213
250
  const anodeX = m.pcb_peg_x + m.pcb_peg_hole / 2 + v.clear + v.track / 2;
214
- const diode = { x: anodeX - d.pad_x, y: -(m.pcb_centre_hole / 2 + v.clear + d.pad_h / 2) }; // on the back, the anode is at +pad_x
251
+ // On the back, turned half round, the diode's pad 1 (its cathode, as KiCad and assemblers number it) is at -pad_x
252
+ // and its anode at +pad_x: the anode by its switch's pin, the cathode on the row line's side
253
+ const diode = { x: anodeX - d.pad_x, y: -(m.pcb_centre_hole / 2 + v.clear + d.pad_h / 2) };
215
254
  const cathodeX = anodeX - 2 * d.pad_x, lineY = diode.y - d.pad_h / 2 - v.clear - v.track / 2;
216
255
  const jogX = -(m.pcb_centre_hole / 2 + (m.pcb_peg_x - m.pcb_peg_hole / 2 - m.pcb_centre_hole / 2) / 2), slant = Math.abs(m.pcb_pin2_x) - Math.abs(jogX);
217
256
  const pegEdge = m.pcb_peg_x + m.pcb_peg_hole / 2 + v.clear + v.track / 2; // a track this far from a key's centre clears its pegs
@@ -262,7 +301,7 @@ export function keyboard(v, keys) {
262
301
  const pts = (list) => list.map(([x, y]) => ({ x, y })); // a track's corners between its two pads, on the board
263
302
  for (const k of keys) {
264
303
  parts.push(mx(`K${k.n}`, k.x, k.y, m, { x: k.c * SX, y: -k.r * SY }),
265
- { name: `D${k.n}`, ftype: 'simple_diode', footprint: 'sod123', package: 'SOD-123', mpn: '1N4148W', x: k.x + diode.x, y: k.y + diode.y, layer: 'bottom', sch: { x: k.c * SX + 1, y: -k.r * SY - 0.8 } });
304
+ { name: `D${k.n}`, ftype: 'simple_diode', footprint: 'sod123', package: 'SOD-123', mpn: '1N4148W', x: k.x + diode.x, y: k.y + diode.y, layer: 'bottom', rotation: 180, sch: { x: k.c * SX + 1, y: -k.r * SY - 0.8 } });
266
305
  traces.push({ from: [`D${k.n}`, 'anode'], to: [`K${k.n}`, 'pin1'], width: v.track, path: pts([[k.x + anodeX, k.y + m.pcb_pin1_y]]) });
267
306
  }
268
307
 
@@ -1090,6 +1129,16 @@ export function inside(points, x, y) {
1090
1129
  }
1091
1130
  return hit;
1092
1131
  }
1132
+ // How far the point is from the nearest side of the outline (a closed list of points), in mm
1133
+ function toEdge(points, x, y) {
1134
+ let d = Infinity;
1135
+ for (let i = 0; i < points.length; i++) {
1136
+ const a = points[i], b = points[(i + 1) % points.length], dx = b.x - a.x, dy = b.y - a.y, l = dx * dx + dy * dy;
1137
+ const t = l ? Math.max(0, Math.min(1, ((x - a.x) * dx + (y - a.y) * dy) / l)) : 0;
1138
+ d = Math.min(d, Math.hypot(x - a.x - t * dx, y - a.y - t * dy));
1139
+ }
1140
+ return d;
1141
+ }
1093
1142
 
1094
1143
  // ---------- building ----------
1095
1144
  // render(board) -> Circuit JSON (circuit.mjs)
@@ -1113,7 +1162,8 @@ export function solids(json, { thickness, smooth = 16, models }) { // models: {
1113
1162
  // size, mm, in the layout's frame) and, with the Pico under it, the Pico's centre
1114
1163
  export function outputs(json, matrix) {
1115
1164
  const b = json.find((e) => e.type === 'pcb_board');
1116
- return { board_x: b.center.x, board_y: b.center.y, board_w: b.width, board_d: b.height, ...(b.outline ? { board_outline: b.outline } : {}), ...(matrix?.pico ? { pico_x: matrix.pico.x, pico_y: matrix.pico.y } : {}) };
1165
+ return { board_x: b.center.x, board_y: b.center.y, board_w: b.width, board_d: b.height, ...(b.outline ? { board_outline: b.outline } : {}), ...(matrix?.pico ? { pico_x: matrix.pico.x, pico_y: matrix.pico.y } : {}),
1166
+ ...Object.fromEntries(Object.entries(matrix?.place || {}).filter(([, n]) => typeof n === 'number')) }; // (where a board puts what an assembly mounts on it: matrix.place, numbers by name)
1117
1167
  }
1118
1168
 
1119
1169
  /**
@@ -1215,10 +1265,13 @@ export async function checks(json, v, matrix, source) { // source: a clone's { c
1215
1265
  const theirs = (layer, width, a, b) => tracksAt.has(seg(layer, width, a, b));
1216
1266
  const laid = traces.filter((t) => t.rulecad_kept), isVia = (t) => t.route[1]?.route_type === 'via';
1217
1267
  const along = (o, p) => { const dx = o.b.x - o.a.x, dy = o.b.y - o.a.y, l = Math.hypot(dx, dy); return Math.abs((p.x - o.a.x) * dy - (p.y - o.a.y) * dx) / l < 1e-4 && ((p.x - o.a.x) * dx + (p.y - o.a.y) * dy) / l > -1e-4 && ((p.x - o.a.x) * dx + (p.y - o.a.y) * dy) / l < l + 1e-4; };
1268
+ let squared = 0;
1218
1269
  const cutBy = [], moved = laid.filter((t) => {
1219
1270
  if (isVia(t)) return !viasAt.has(key(t.route[0].x, t.route[0].y));
1220
1271
  const [p, q] = t.route, w = p.width, layer = p.layer;
1221
1272
  if (t.route.length === 2 && theirs(layer, w, p, q)) return false;
1273
+ const sq = t.rulecad_squared; // the source's segment, redrawn to leave its pad square: the same ends
1274
+ if (sq && theirs(sq.a.layer ?? layer, sq.a.width ?? w, sq.a, sq.b)) { squared++; return false; } // (its pad end left square, or joined to the next square, by the finish)
1222
1275
  const o = t.rulecad_shortened; // a piece of the source's segment, from one of its ends
1223
1276
  if (o && t.route.length === 2 && theirs(layer, w, o.a, o.b) && along(o, p) && along(o, q) && [p, q].some((r) => [o.a, o.b].some((e) => key(e.x, e.y) === key(r.x, r.y)))) {
1224
1277
  cutBy.push(Math.hypot(o.b.x - o.a.x, o.b.y - o.a.y) - Math.hypot(q.x - p.x, q.y - p.y)); return false;
@@ -1231,7 +1284,19 @@ export async function checks(json, v, matrix, source) { // source: a clone's { c
1231
1284
  const escapes = traces.reduce((n, t) => n + (t.rulecad_cut || 0), 0);
1232
1285
  const vias = laid.filter(isVia).length, short = laid.filter((t) => t.rulecad_shortened).length, total = cutBy.reduce((n, d) => n + d, 0);
1233
1286
  out.push(moved.length || strays.length ? { level: 'fail', text: `${moved.length + strays.length} of the source's own tracks and vias aren't where the source has them` }
1234
- : { level: 'pass', text: `the source's own routing as it was: ${laid.length - vias - short} tracks and ${vias} vias exactly where the source has them${cutBy.length ? `, but for ${escapes} escapes cut back where a routed track turned straight back on them (${gone.length} segments gone, ${short} shortened: ${mm(total)} mm of track in all)` : ''} (only the router's tracks are tidied)` });
1287
+ : { level: 'pass', text: `the source's own routing as it was: ${laid.length - vias - short} tracks and ${vias} vias exactly where the source has them${cutBy.length ? `, but for ${escapes} escapes cut back where a routed track turned straight back on them (${gone.length} segments gone, ${short} shortened: ${mm(total)} mm of track in all)` : ''} ${squared ? `; ${squared} of them redrawn by the finish (to leave a pad square, or rejoined)` : ''} (only the router's tracks are tidied)` });
1288
+ }
1289
+ // What a fab's engineer flags in tracks: one leaving a surface-mount pad at an angle (a small part can tombstone, drawn
1290
+ // up on one end as its solder melts) and acute corners between tracks of a net (acid traps). A board that asks for
1291
+ // finishing (finish: true) fails on any left; others are told
1292
+ {
1293
+ const { unfinished } = await import('@rulecad/smooth');
1294
+ const u = unfinished(json), asked = !!json.find((e) => e.type === 'pcb_board')?.rulecad_finish, at = (l) => l.slice(0, 4).map((x) => `${mm(x.at.x)}, ${mm(x.at.y)}`).join('; ');
1295
+ const ours = { exits: u.exits.filter((l) => !l.kept), acute: u.acute.filter((l) => !l.kept) }, theirs = { exits: u.exits.filter((l) => l.kept), acute: u.acute.filter((l) => l.kept) };
1296
+ const say = (x) => [x.exits.length && `${x.exits.length} tracks leave an SMD pad at an angle (${at(x.exits)})`, x.acute.length && `${x.acute.length} acute corners between tracks (${at(x.acute)})`].filter(Boolean).join('; ');
1297
+ out.push(!ours.exits.length && !ours.acute.length ? { level: 'pass', text: `finish: every track leaves its SMD pad square to the pad's edge, and no tracks meet at an acute angle${theirs.exits.length || theirs.acute.length ? ', but where the source\'s own routing has them' : ''}` }
1298
+ : { level: asked ? 'fail' : 'warn', text: `finish: ${say(ours)}${asked ? '' : ' (finish: true on the board squares and fills them)'}` });
1299
+ if (theirs.exits.length || theirs.acute.length) out.push({ level: 'warn', text: `finish, as the source's own routing has them (no room to change without moving other copper): ${say(theirs)}` });
1235
1300
  }
1236
1301
  // Tracks and the gaps between them, measured from the board as drawn (not the design's variables): the narrowest
1237
1302
  // track, and the nearest two tracks of different connections come on one layer, edge to edge
@@ -1263,8 +1328,24 @@ export async function checks(json, v, matrix, source) { // source: a clone's { c
1263
1328
  : { level: 'pass', text: `tracks ${mm(narrow)} mm or wider${tight ? `, ${mm(tight.d)} mm or more apart` : ''}, measured on the board: over JLCPCB's ${j.track_min} / ${j.gap_min} mm` });
1264
1329
  // A board that can't be made: no size, a hole through its edge, two parts of one name, a pin in two nets
1265
1330
  const named = json.filter((e) => e.type === 'source_component').map((e) => e.name), twice = named.filter((n, i) => named.indexOf(n) !== i);
1266
- const edgeHoles = b.outline ? [] : json.filter((e) => (e.type === 'pcb_hole' || e.type === 'pcb_plated_hole') && !halves.has(e.pcb_plated_hole_id)).filter((e) => { const r = (e.outer_diameter ?? e.hole_diameter ?? e.hole_width ?? 0) / 2; return Math.abs(e.x - b.center.x) + r > b.width / 2 + 1e-6 || Math.abs(e.y - b.center.y) + r > b.height / 2 + 1e-6; });
1267
- const broken = [!(b.width > 0 && b.height > 0) && `the board is ${mm(b.width)} × ${mm(b.height)} mm`, edgeHoles.length && `${edgeHoles.length} holes break through the board's edge`, twice.length && `two parts named ${[...new Set(twice)].join(', ')}`].filter(Boolean); // (a pin in two nets is refused as the board is built)
1331
+ // A hole through the edge: every hole, and the copper round a round plated one, tested as a circle against the board's
1332
+ // outline (a rectangular board's is its four corners), so a shaped board and a rectangular one are held to one test:
1333
+ // its centre inside, and as far from the nearest side as its radius. Half holes and parts that reach past the edge as
1334
+ // a clone's source has them are on the edge by design (checked above and below)
1335
+ const reaching = same && b.outline ? same.reaching : new Set(); // (on a shaped board only, as before: a rectangle has no notch to reach into)
1336
+ const edge = b.outline || [[-1, -1], [1, -1], [1, 1], [-1, 1]].map(([sx, sy]) => ({ x: b.center.x + (sx * b.width) / 2, y: b.center.y + (sy * b.height) / 2 }));
1337
+ const refOf = new Map(json.filter((e) => e.type === 'pcb_component').map((e) => [e.pcb_component_id, json.find((c) => c.type === 'source_component' && c.source_component_id === e.source_component_id)?.name]));
1338
+ const boardHoles = json.filter((e) => e.type === 'pcb_hole' && !e.pcb_component_id);
1339
+ const holeName = (e) => (e.type === 'pcb_plated_hole' ? `${refOf.get(e.pcb_component_id) ?? 'a part'}.${e.port_hints?.[1] ?? 'pin'}'s hole`
1340
+ : e.pcb_component_id ? `${refOf.get(e.pcb_component_id) ?? 'a part'}'s hole` : `mounting hole ${boardHoles.indexOf(e) + 1}`);
1341
+ const edgeHoles = json.filter((e) => (e.type === 'pcb_hole' || e.type === 'pcb_plated_hole') && !halves.has(e.pcb_plated_hole_id) && !reaching.has(e.pcb_component_id)).map((e) => {
1342
+ const copper = e.shape === 'circle' && e.outer_diameter != null, r = (copper ? e.outer_diameter : e.hole_diameter ?? e.hole_width ?? 0) / 2;
1343
+ const x = e.x + (copper ? 0 : e.hole_offset_x ?? 0), y = e.y + (copper ? 0 : e.hole_offset_y ?? 0), d = toEdge(edge, x, y), from = inside(edge, x, y) ? d : -d; // from: to the edge, inward
1344
+ return { e, r, x, y, copper, past: r - from }; // past: how far it reaches beyond the edge
1345
+ }).filter((h) => h.past > 1e-6);
1346
+ const holeText = (h) => `${holeName(h.e)} (${mm(2 * h.r)} mm${h.copper ? ' across its copper' : ''}) ${h.past >= 2 * h.r - 1e-6 ? 'is outside the board\'s edge' : `breaks through the board's edge by ${mm(h.past)} mm`} at (${mm(h.x)}, ${mm(h.y)})`;
1347
+ const broken = [!(b.width > 0 && b.height > 0) && `the board is ${mm(b.width)} × ${mm(b.height)} mm`,
1348
+ edgeHoles.length && (edgeHoles.length === 1 ? holeText(edgeHoles[0]) : `${edgeHoles.length} holes break through the board's edge: ${edgeHoles.slice(0, 3).map(holeText).join(', ')}${edgeHoles.length > 3 ? ', …' : ''}`), twice.length && `two parts named ${[...new Set(twice)].join(', ')}`].filter(Boolean); // (a pin in two nets is refused as the board is built)
1268
1349
  if (broken.length) out.push({ level: 'fail', text: `the board can't be made as drawn: ${broken.join('; ')}` });
1269
1350
  // Vias and plated holes against the fab's sizes, each measured from the board: the hole, the pad, and the ring
1270
1351
  // between them (under the recommended ring a warning, under the least a failure). A via's ring and a plated hole's
@@ -1305,10 +1386,12 @@ export async function checks(json, v, matrix, source) { // source: a clone's { c
1305
1386
  const drills = json.filter((e) => e.type === 'pcb_hole' || e.type === 'pcb_plated_hole' || e.type === 'pcb_via').map((e) => e.hole_diameter ?? e.hole_width);
1306
1387
  if (drills.length) out.push(Math.min(...drills) < j.drill_min ? { level: 'fail', text: `a hole under JLCPCB's ${j.drill_min} mm` } : { level: 'pass', text: `${drills.length} holes, smallest ${Math.min(...drills)} mm (JLCPCB: ${j.drill_min} mm)` });
1307
1388
  const size = `${b.width.toFixed(1)} × ${b.height.toFixed(1)} mm`;
1308
- if (b.outline) { // a shaped board: every pad and hole inside it
1309
- const reaching = same ? same.reaching : new Set();
1310
- const pads = json.filter((e) => ['pcb_smtpad', 'pcb_plated_hole', 'pcb_hole'].includes(e.type) && !halves.has(e.pcb_plated_hole_id) && !reaching.has(e.pcb_component_id)), out_ = pads.filter((e) => (e.points || [e]).some((q) => !inside(b.outline, q.x, q.y)));
1311
- out.push(out_.length ? { level: 'fail', text: `${out_.length} pads or holes outside the board's outline (first at ${mm(out_[0].x)}, ${mm(out_[0].y)} mm)` } : { level: 'pass', text: `shaped board (${b.outline.length} points): all ${pads.length} pads and holes inside it` });
1389
+ if (b.outline) { // a shaped board: every pad and hole inside it (its holes and round plated pads tested above, as circles)
1390
+ const pads = json.filter((e) => ['pcb_smtpad', 'pcb_plated_hole', 'pcb_hole'].includes(e.type) && !halves.has(e.pcb_plated_hole_id) && !reaching.has(e.pcb_component_id));
1391
+ const circles = new Set(json.filter((e) => e.type === 'pcb_hole' || (e.type === 'pcb_plated_hole' && e.shape === 'circle' && e.outer_diameter != null))); // (said above when they cross)
1392
+ const out_ = pads.filter((e) => !circles.has(e) && (e.type === 'pcb_smtpad' && e.shape === 'circle' ? !inside(b.outline, e.x, e.y) || toEdge(b.outline, e.x, e.y) < e.radius - 1e-6 // a round pad: as a circle
1393
+ : (e.points || [e]).some((q) => !inside(b.outline, q.x, q.y)))); // a polygon pad by its corners; any other by its centre
1394
+ out.push(out_.length ? { level: 'fail', text: `${out_.length} pads or holes outside the board's outline (first at ${mm(out_[0].x ?? out_[0].points[0].x)}, ${mm(out_[0].y ?? out_[0].points[0].y)} mm)` } : edgeHoles.length ? { level: 'info', text: `shaped board (${b.outline.length} points): its pads are inside it, but not its holes (above)` } : { level: 'pass', text: `shaped board (${b.outline.length} points): all ${pads.length} pads and holes inside it` });
1312
1395
  }
1313
1396
  if (castellated.length) { // JLCPCB's rules for half holes: big enough, far enough apart
1314
1397
  const small = castellated.filter((e) => e.hole_diameter < (j.castellated_drill_min ?? 0.6));
@@ -1319,7 +1402,12 @@ export async function checks(json, v, matrix, source) { // source: a clone's { c
1319
1402
  : { level: 'pass', text: `${castellated.length} castellated holes on the edge, ${mm(Math.min(...castellated.map((e) => e.hole_diameter)))} mm or more, ${mm(gap)} mm apart (JLCPCB: ${j.castellated_drill_min ?? 0.6} / ${j.castellated_gap_min ?? 0.6} mm). Order with castellated holes` });
1320
1403
  }
1321
1404
  out.push(Math.max(b.width, b.height) <= j.cheap_size ? { level: 'pass', text: `${size}: within JLCPCB's lowest price (${j.cheap_size} × ${j.cheap_size} mm)` } : { level: 'info', text: `${size}: over ${j.cheap_size} × ${j.cheap_size} mm, priced by quote` });
1322
- if (matrix) {
1405
+ if (matrix?.direct) { // keys wired straight to a GPIO each, no matrix: every key its own pin
1406
+ const gpio = Object.values(matrix.direct);
1407
+ out.push(new Set(gpio).size === gpio.length
1408
+ ? { level: 'pass', text: `direct wiring: ${gpio.length} keys, each on a GPIO of its own (${Object.entries(matrix.direct).map(([k, g]) => `${k} ${g}`).join(', ')})` }
1409
+ : { level: 'fail', text: 'direct wiring: two keys share a GPIO' });
1410
+ } else if (matrix) {
1323
1411
  const cells = new Set(matrix.keys.map((k) => `${k.row},${k.col}`)), gpio = [...Object.values(matrix.rows), ...Object.values(matrix.cols)];
1324
1412
  out.push(cells.size === matrix.keys.length && new Set(gpio).size === gpio.length
1325
1413
  ? { level: 'pass', text: `matrix: ${matrix.keys.length} keys on ${Object.keys(matrix.rows).length} rows × ${Object.keys(matrix.cols).length} columns, ${gpio.length} GPIO (rows ${Object.values(matrix.rows).join(' ')}; columns ${Object.values(matrix.cols).join(' ')})` }
@@ -1350,7 +1438,6 @@ export async function checks(json, v, matrix, source) { // source: a clone's { c
1350
1438
  // a part that reaches past the outline there too, and the source's own vias, kept, where they touch its pads. Returns a test for a design-rule error, with .reaching:
1351
1439
  // the board's components that reach past it as on the source.
1352
1440
  function asSource(json, circuit, kept) {
1353
- const toEdge = (pts, x, y) => { let d = Infinity; for (let i = 0; i < pts.length; i++) { const a = pts[i], b = pts[(i + 1) % pts.length], dx = b.x - a.x, dy = b.y - a.y, l = dx * dx + dy * dy, t = l ? Math.max(0, Math.min(1, ((x - a.x) * dx + (y - a.y) * dy) / l)) : 0; d = Math.min(d, Math.hypot(x - a.x - t * dx, y - a.y - t * dy)); } return d; };
1354
1441
  const src = new Map(), past = new Set(), so = circuit.outline;
1355
1442
  if (!so) return null;
1356
1443
  for (const p of circuit.parts) {