@rulecad/pcb 0.5.1 → 0.5.4

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 ADDED
@@ -0,0 +1,31 @@
1
+ # Changelog: @rulecad/pcb
2
+
3
+ What changed in each release, for someone upgrading a workspace. A **drilled size** here is a dimension the fab
4
+ makes (a hole's diameter in the drill file). Each release says whether any drilled or printed size moved, and why.
5
+
6
+ ## 0.5.4: a board's mounting holes named by thread (Fixings 3)
7
+
8
+ ### What reads fixings now
9
+
10
+ - `mount(thread, x, y, { fit, d, keepout, set, sets })` sizes a board's own mounting hole from the thread's rule set
11
+ through `@rulecad/fixings`: `mount('M2', x, y)` is `m2.clearance`, 2.4 mm, the normal clearance hole of ISO 273. The
12
+ fab drills it, so no printer's compensation is added. `{ fit: 'close' }` and `{ fit: 'loose' }` take ISO 273's other
13
+ two holes.
14
+ - `{ d }` keeps a hole the board's maker gives (a Raspberry Pi Pico's 2.1 mm), and refuses one no wider than the thread.
15
+ - `mount` refuses a non-thread, a whole screw's name, a hole the screw would not pass, an unknown option or fit.
16
+ - The keyboard recipe's corner holes (`mount_holes: 1`) are now `mount('M2', ...)`.
17
+ - New dependency: `@rulecad/fixings`.
18
+
19
+ ### Drilled and printed sizes that moved
20
+
21
+ None. The keyboard recipe's corner holes stay 2.4 mm (`m2.clearance`, as before). The thin-picro module in the
22
+ repository keeps the Pico's 2.1 mm holes through `{ d: 2.1 }`, so it fits cases made for a Pico; its fab files are
23
+ unchanged.
24
+
25
+ ### What a workspace should change
26
+
27
+ - A board that typed its mounting hole's diameter can name the thread instead: `holes: [mount('M2', 10, 5)]`. Typed
28
+ holes keep working.
29
+ - In cad, a case under a board can read the board's holes (`v.pcb.board_holes`), draw an insert's boss under each
30
+ with `v.fixings.insertBoss('M2', ...)`, and the assembly can screw the board down with a `fasten` through the
31
+ board's own holes (`"holes": "pcb.board"`). cad's EXAMPLES, chapter 6, does this end to end.
package/README.md CHANGED
@@ -36,6 +36,15 @@ export function main(v) {
36
36
  - **Parts:** `xiao`, `qwiic`, `jstph` and `header` take their sizes and pinouts from rule sets in @rulecad/rules (each
37
37
  value with its source); `part(name, footprint, x, y)` takes any footprinter name: `soic8`, `0603`, `sot23`,
38
38
  `jst4_sh`, `pinrow4` (SMD or through-hole). Options: `rotation` (0, 90, 180, 270), `layer`, `mpn`, `labels`.
39
+ - **Mounting holes, by thread:** `mount('M2', x, y)` is a board's own hole for an M2 screw, sized from the thread's
40
+ rule set through @rulecad/fixings: `m2.clearance`, 2.4 mm (ISO 273's normal clearance hole). The fab drills it, so
41
+ nothing is added for a printer. `{ fit: 'close' }` or `{ fit: 'loose' }` take ISO 273's other two holes; `{ d: 2.1 }`
42
+ takes a hole the board's maker gives (a Pico's), refused where it is no wider than the thread; `{ keepout: 1.5 }` keeps
43
+ the router's tracks that far from the hole's centre. Put the result in the board's `holes`: `holes: [mount('M2', 10,
44
+ 5)]`. In a cad design, `v.pcb.mount` reads the workspace's own thread set (`rules/m2.json`) before the kit's. The
45
+ keyboard recipe's corner holes (`mount_holes: 1`) are `mount('M2')`. A case reads them (`board_holes`) and puts an
46
+ insert's boss under each (`v.fixings.insertBoss('M2', ...)`); an assembly then screws the board down with `fasten`
47
+ and `"holes": "<item>.board"` (cad's EXAMPLES, chapter 6).
39
48
  - **Parts from KiCad:** `fromKicad(text)` turns a KiCad footprint (`.kicad_mod`) into pad data (y up) and its
40
49
  courtyard. Keep the result in a rule set's `"footprints"` with its source and pin names (`labels: { pin1: 'GND' }`),
41
50
  then place it with `footprint(name, data, x, y, o)`: a design reads rule sets, never files or the network.
@@ -88,6 +97,22 @@ export function main(v) {
88
97
  track the design checks then find in a new error goes back as it was, and a board where a cut causes one is smoothed
89
98
  again without cuts. For a clone that keeps its source's routing, the checks confirm every kept track and via is still
90
99
  exactly where the source has it, and name each escape cut back and how much track went.
100
+ - **A pin with pads apart:** a part whose footprint gives one pin two pads apart from each other (a USB-C socket's two
101
+ VBUS pads, both its A4) gets a track between them, as its net joins the first. Pads that touch (a half hole in its
102
+ header pad) are one copper already, and a plane net's pads each reach the plane.
103
+ - **Fab checks for vias:** a via's ring is measured against JLCPCB's figures for vias (`via_annular_min`, `via_annular`:
104
+ its pad 0.1 mm wider than its hole, 0.15 preferred), a plated hole's against those for holes. Each via's hole is
105
+ measured edge to edge to the nearest track of another net (`via_hole_track`, 0.2 mm): JLCPCB measures from the hole,
106
+ so a small via's thin ring leaves less room than the copper clearance suggests.
107
+ - **Fab files, plotted by KiCad where they must be:** the Gerber writer plots a rounded pad square, so beside a copper
108
+ plane its corners would short to it, and it can't drill a slot. For a board with either, `fabFiles` has KiCad plot the
109
+ Gerbers and drill files from the very board its design-rule check has just passed, and refuses if the check finds an
110
+ error or the drill files aren't the design's holes, slots included. Without KiCad such a board's fab files aren't
111
+ made. The plots share the design's origin with the placement file. A source's slotted holes are kept as slots.
112
+ - **KiCad, as a second opinion:** `kicadFiles` writes the board as KiCad reads it (kicad.mjs: every pad, track and via
113
+ on its named net, a hole set off-centre in its pad where KiCad drills it, castellated pins marked, rounded pads round,
114
+ and a `.kicad_pro` and `.kicad_dru` with the board's rules). Where KiCad is installed, `checks` also runs its
115
+ design-rule check (`kicad-cli`, `KICAD_CLI` to name another), KiCad pouring the planes itself.
91
116
  - **Labels clear of copper:** `clearLabels(silk, circuit)` slides each silkscreen label across its reading direction to
92
117
  the nearest place clear of every pad and of the labels before it (the fab trims silkscreen off copper, so a label
93
118
  on a pad loses letters). A label for a pin hemmed in by its neighbours (`to`: where the pin is) goes to the nearest
package/circuit.mjs CHANGED
@@ -22,9 +22,15 @@
22
22
  // width or board.track; pins are named part.pin, by the pin's label, its name or its number
23
23
  // silk { rect: { x, y, w, h }, layer } | { text, x, y, size, layer, rotation } (rotation: degrees, counter-clockwise)
24
24
  // effort how hard the autorouter searches (default its own, 1): more for a crowded board, at more time
25
+ // pipeline the autorouter's pipeline to try first (a class it exports, e.g. 'AutoroutingPipelineSolver4'); unset, its
26
+ // own. If one fails, the next in PIPELINES is tried
25
27
  // holes [{ x, y, d, keepout }] in the board (mounting holes; keepout: a radius the router keeps tracks out of, for a screw head)
26
28
  // layers 2 (default), 4 or 6 copper layers: tracks on the outer two, planes inside
27
29
  // clearance (mm) the router keeps from everything in its way (a clone: the source's); unset, the router's own
30
+ // route_via { pad, hole } (mm): the vias the router makes, when not via_pad and via_hole (the planes' vias)
31
+ // join_pads false: a pin's pads apart aren't joined by a track (see samePin)
32
+ // track_gap (mm) routed tracks closer than this (a fab's least gap) are necked to neck where they pass
33
+ // via_hole_gap (mm) a routed track closer to a via's hole than this is bowed out round it (JLCPCB: 0.2)
28
34
  // smooth true: routed tracks pulled tight once routed (@rulecad/smooth), where the straight run keeps clearance
29
35
  // neck (mm) a routed track still too close to another after repair is narrowed to this where they pass (the fab's smallest)
30
36
  // planes { GND: { layer: 'inner1', pins: ['U1.GND', ...] } }: nets joined by copper filling an inner layer. Each SMD pad
@@ -32,7 +38,8 @@
32
38
  // either is routed to the nearest pad of its net that reaches the plane. via_pad, via_hole, plane_clearance
33
39
  // (mm, defaults 0.6, 0.3, 0.2) size them
34
40
  // copper { tracks: [{ a, b, width, layer, island }], vias: [{ x, y, pad, hole, island }], islands: [{ id, net, pins, via }] }:
35
- // a source's own routing, kept (moveGroup's keep): laid as it is; its pins count as joined
41
+ // a source's own routing, kept (moveGroup's keep): laid as it is; its pins count as joined. An island marked
42
+ // after: true is laid once the rest is routed, unseen by the router
36
43
  // pads may be castellated ({ castellated: true }: a half hole on the edge, joined at its inner edge) or a rounded
37
44
  // rectangle round their hole ({ rect: { w, h, offset: [x, y] } }: an oval pad, a hole off-centre)
38
45
  // All positions are in mm, in the board's own frame. A part on the bottom is seen from above: mirrored in x.
@@ -110,6 +117,7 @@ export async function circuitJson(board, { route = defaultRouter } = {}) {
110
117
  // ---- parts: source records, then their footprints on the board ----
111
118
  const copper = copperLayers(board.layers ?? 2); // a hole or a via goes through all of them
112
119
  const ports = new Map(); // `${part}.${port name or hint}` -> { source, pcb, x, y, layers }
120
+ const pinPads = new Map(); // `${part}.${pin name}` -> each of its pads: { key (in ports), x, y, reach (its copper's half size) }
113
121
  const placed = [];
114
122
  for (const part of board.parts) {
115
123
  const comp = add('source_component', { ftype: part.ftype, name: part.name, manufacturer_part_number: part.mpn,
@@ -150,7 +158,7 @@ export async function circuitJson(board, { route = defaultRouter } = {}) {
150
158
  add('pcb_board', { source_board_id: sourceBoard.source_board_id, subcircuit_id: SUB, center: board.center, thickness: board.thickness, num_layers: copper.length,
151
159
  width: board.width, height: board.height, ...(board.outline ? { outline: board.outline.map(({ x, y }) => ({ x, y })) } : {}), material: 'fr4', ...FAB_MINIMUMS,
152
160
  ...(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)
153
- min_via_hole_diameter: board.via_hole ?? 0.3, min_via_pad_diameter: board.via_pad ?? 0.8 });
161
+ 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 });
154
162
 
155
163
  for (const { part, comp, pads, sourcePorts, fpEls, at, mirror, size } of placed) {
156
164
  // The component sits at the middle of its pads and holes (as tscircuit places it: pick-and-place reads this)
@@ -171,7 +179,8 @@ export async function circuitJson(board, { route = defaultRouter } = {}) {
171
179
  add('pcb_solder_paste', { layer: part.layer, shape: 'rect', width: p.w * PASTE, height: p.h * PASTE, x: p.x, y: p.y, pcb_component_id: pc.pcb_component_id, pcb_smtpad_id: pad.pcb_smtpad_id, subcircuit_id: SUB });
172
180
  } else if (p.rect) { // an oval pad or a hole off-centre: a rounded rectangle, its hole offset turned with the part
173
181
  const sz = size(p.rect.w, p.rect.h), o0 = at(0, 0), o1 = at(p.rect.offset[0], p.rect.offset[1]);
174
- add('pcb_plated_hole', { ...own, pcb_port_id: port.pcb_port_id, shape: 'circular_hole_with_rect_pad', hole_shape: 'circle', pad_shape: 'rect', hole_diameter: p.hole,
182
+ const slot = p.rect.slot && size(p.rect.slot[0], p.rect.slot[1]); // (a slotted hole, as a USB-C socket's shell legs need)
183
+ add('pcb_plated_hole', { ...own, pcb_port_id: port.pcb_port_id, ...(slot ? { shape: 'pill_hole_with_rect_pad', hole_shape: 'pill', hole_width: slot.w, hole_height: slot.h } : { shape: 'circular_hole_with_rect_pad', hole_shape: 'circle', hole_diameter: p.hole }), pad_shape: 'rect',
175
184
  rect_pad_width: sz.w, rect_pad_height: sz.h, rect_border_radius: Math.min(sz.w, sz.h) / 2, hole_offset_x: Math.round((o1.x - o0.x) * 1e6) / 1e6, hole_offset_y: Math.round((o1.y - o0.y) * 1e6) / 1e6,
176
185
  port_hints: [`unnamed_platedhole${i + 1}`, p.pin], x: p.x, y: p.y, layers, is_covered_with_solder_mask: false });
177
186
  } else {
@@ -184,6 +193,11 @@ export async function circuitJson(board, { route = defaultRouter } = {}) {
184
193
  const join = p.castellated ? inward(board, p.x, p.y, (p.outer + (p.hole ?? p.outer)) / 4) : { x: p.x, y: p.y };
185
194
  if (p.castellated) Object.assign(port, join);
186
195
  for (const key of [sourcePorts[i].name, ...sourcePorts[i].port_hints]) ports.set(`${part.name}.${key}`, { source: sourcePorts[i], pcb: port, x: join.x, y: join.y, layers });
196
+ // one pin: one name and one number (a module's GND pins share a name, each its own number, and join inside it)
197
+ const pin = `${part.name}.${sourcePorts[i].name}#${sourcePorts[i].pin_number}`, list = pinPads.get(pin) || [];
198
+ ports.set(`${pin}#${list.length}`, { source: sourcePorts[i], pcb: port, x: join.x, y: join.y, layers }); // each pad of a pin by itself
199
+ list.push({ key: `${sourcePorts[i].name}#${sourcePorts[i].pin_number}#${list.length}`, names: [sourcePorts[i].name, ...sourcePorts[i].port_hints].map((n) => `${part.name}.${n}`),
200
+ x: p.x, y: p.y, reach: Math.max(p.w ?? 0, p.h ?? 0, p.outer ?? 0, p.rect?.w ?? 0, p.rect?.h ?? 0) / 2 }); pinPads.set(pin, list);
187
201
  });
188
202
  for (const h of part.holes || []) { const q = at(h.x, h.y); add('pcb_hole', { ...own, hole_shape: 'circle', hole_diameter: h.d, x: q.x, y: q.y, is_covered_with_solder_mask: false }); }
189
203
  if (part.courtyard) { const c = size(part.courtyard.w, part.courtyard.h); add('pcb_courtyard_rect', { ...own, layer: part.layer, center: { x: part.x, y: part.y }, width: c.w, height: c.h }); }
@@ -225,11 +239,21 @@ export async function circuitJson(board, { route = defaultRouter } = {}) {
225
239
  add('pcb_via', { pcb_trace_id: tr.pcb_trace_id, x: v.x, y: v.y, hole_diameter: v.hole, outer_diameter: v.pad, layers: copper, from_layer: 'top', to_layer: 'bottom', subcircuit_id: SUB });
226
240
  }
227
241
  };
228
- const toRoute = [], traces = [...(board.traces || []), ...netTraces(board, port, joined), ...links];
242
+ // A pin with pads apart from each other (a USB-C socket's two VBUS pads, both its A4): joined by a track, as its net
243
+ // joins the pin's first pad. Pads that touch (a half hole in its header pad) are one copper already, and a plane net's
244
+ // pads each reach the plane
245
+ const netNamed = (names) => Object.entries(board.nets || {}).find(([, spec]) => (Array.isArray(spec) ? spec : spec.pins).some((p) => names.includes(p)))?.[0];
246
+ const samePin = [...pinPads].flatMap(([pin, pads]) => {
247
+ const net = pads.length > 1 && netNamed(pads[0].names), part = pin.slice(0, pin.indexOf('.'));
248
+ if (pads.length < 2 || !net || board.planes?.[net] || board.join_pads === false || pads[0].names.some((n) => joined.has(n))) return []; // (or the source's kept copper joins them)
249
+ return pads.slice(1).filter((q, i) => Math.hypot(q.x - pads[i].x, q.y - pads[i].y) > q.reach + pads[i].reach)
250
+ .map((q) => ({ from: [part, pads[0].key], to: [part, q.key], width: board.track, net }));
251
+ });
252
+ const toRoute = [], traces = [...(board.traces || []), ...netTraces(board, port, joined), ...links, ...samePin];
229
253
  for (const t of traces) {
230
254
  const a = port(...t.from), b = port(...t.to);
231
255
  const st = add('source_trace', { connected_source_port_ids: [a.source.source_port_id, b.source.source_port_id], connected_source_net_ids: [], subcircuit_id: SUB,
232
- display_name: `.${t.from.join(' > .')} to .${t.to.join(' > .')}`, min_trace_thickness: t.width });
256
+ display_name: `.${t.from.join(' > .')} to .${t.to.join(' > .')}`, min_trace_thickness: t.width, ...(t.net ? { rulecad_net: t.net } : {}) }); // (the net's name: KiCad's files carry it)
233
257
  if (!t.path) { // a kept escape (stub) from either pin: laid as part of this connection, which is routed from its end
234
258
  const ends = [a, b].map((q, i) => { const stub = stubOf.get([t.from, t.to][i].join('.')); if (!stub) return q; stubOf.delete([t.from, t.to][i].join('.'));
235
259
  layStub(stub, st.source_trace_id); return { ...q, x: stub.end.x, y: stub.end.y, layers: [stub.end.layer] }; });
@@ -259,7 +283,12 @@ export async function circuitJson(board, { route = defaultRouter } = {}) {
259
283
  const t = add('pcb_trace', { route: r.route, source_trace_id: r.source_trace_id, subcircuit_id: SUB, rulecad_routed: true });
260
284
  for (const v of r.vias) add('pcb_via', { pcb_trace_id: t.pcb_trace_id, ...v, layers: copper, subcircuit_id: SUB }); // whose via it is: the checks need it
261
285
  }
286
+ // kept copper laid once routed (an island marked after): unseen by the router, so the rest routes as it would
287
+ // without it; smoothing and the checks see it
288
+ if (board.copper?.islands.some((k) => k.after)) keptCopper(out, add, board, copper, planeNets || {}, true);
262
289
  if (board.smooth) await smoothRouted(out, board);
290
+ if (board.via_hole_gap) await viaHoleRepair(out, board.via_hole_gap, board.neck);
291
+ if (board.track_gap && board.neck) await gapRepair(out, board.track_gap, board.neck);
263
292
  }
264
293
  if (planeNets) await pours(out, add, board, planeNets, netOf);
265
294
  if (board.silk?.length) clearSilkAfter(out, add, board);
@@ -320,6 +349,133 @@ export async function smoothRouted(out, board) {
320
349
  }
321
350
  }
322
351
 
352
+ // Each via's hole against the tracks of other nets near it: { via, gap (hole edge to track edge, mm), at, kept (the
353
+ // via and the track both a source's own copper), trace, seg (the segment's index) }: the nearest track for each via,
354
+ // or (all) every track segment closer than under
355
+ export function viaHoleGaps(json, { all = false, under = Infinity } = {}) {
356
+ const up = new Map(), find = (a) => { while (up.get(a) !== a) { up.set(a, up.get(up.get(a))); a = up.get(a); } return a; };
357
+ const join = (a, b) => { for (const x of [a, b]) if (!up.has(x)) up.set(x, x); up.set(find(a), find(b)); };
358
+ for (const e of json) if (e.type === 'source_trace') { join(e.source_trace_id, e.source_trace_id); for (const id of [...(e.connected_source_port_ids || []), ...(e.connected_source_net_ids || [])]) join(e.source_trace_id, id); }
359
+ const traceOf = new Map(json.filter((e) => e.type === 'pcb_trace').map((t) => [t.pcb_trace_id, t]));
360
+ const netOf = (t) => (t?.source_trace_id && up.has(t.source_trace_id) ? find(t.source_trace_id) : null);
361
+ const segs = json.filter((e) => e.type === 'pcb_trace').flatMap((t) => t.route.slice(1).map((q, i) => [t.route[i], q, t, i]).filter(([p, q]) => p.route_type === 'wire' && q.route_type === 'wire' && p.layer === q.layer));
362
+ const toSeg = (c, a, b) => { const dx = b.x - a.x, dy = b.y - a.y, l = dx * dx + dy * dy, t = l ? Math.max(0, Math.min(1, ((c.x - a.x) * dx + (c.y - a.y) * dy) / l)) : 0; return { d: Math.hypot(c.x - a.x - t * dx, c.y - a.y - t * dy), p: { x: a.x + t * dx, y: a.y + t * dy } }; };
363
+ const out = [];
364
+ for (const v of json.filter((e) => e.type === 'pcb_via')) {
365
+ const vt = traceOf.get(v.pcb_trace_id), net = netOf(vt);
366
+ let best = null;
367
+ for (const [a, b, t, i] of segs) {
368
+ if (t === vt || (net != null && netOf(t) === net)) continue;
369
+ if (Math.min(a.x, b.x) - 2 > v.x || Math.max(a.x, b.x) + 2 < v.x || Math.min(a.y, b.y) - 2 > v.y || Math.max(a.y, b.y) + 2 < v.y) continue;
370
+ const { d, p } = toSeg(v, a, b), gap = d - v.hole_diameter / 2 - Math.max(a.width ?? 0, b.width ?? 0) / 2;
371
+ const found = { via: v, gap, at: p, kept: !!(vt?.rulecad_kept && t.rulecad_kept), trace: t, seg: i };
372
+ if (all) { if (gap < under) out.push(found); } else if (!best || gap < best.gap) best = found;
373
+ }
374
+ if (best) out.push(best);
375
+ }
376
+ return out;
377
+ }
378
+
379
+ // A routed track closer to a via's hole than the fab allows (JLCPCB measures from the hole, so a small via's thin ring
380
+ // leaves less room than the copper clearance): necked down where it passes (to neck, the fab's smallest track) if
381
+ // that's room enough, else bowed out round the via by what it lacks, the segment's middle stretch moved off, its ends
382
+ // where they were; last, a via still a little close moved away by what it lacks. A change the design checks then find in
383
+ // a new error goes back
384
+ export async function viaHoleRepair(out, gapMin, neck = 0) {
385
+ const { runAllChecks } = await import('@tscircuit/checks');
386
+ const errors = async () => (await runAllChecks(structuredClone(out))).filter((e) => /_error$/.test(e.type))
387
+ .map((e) => JSON.stringify([e.type, ...[...new Set(JSON.stringify(e).match(/pcb_[a-z_]+?_\d+/g) || [])].sort()]));
388
+ const before = new Set(await errors()), tried = new Set();
389
+ const short = () => viaHoleGaps(out, { all: true, under: gapMin - 1e-6 }).filter((g) => g.trace.rulecad_routed);
390
+ const width = (g) => Math.max(g.trace.route[g.seg].width ?? 0, g.trace.route[g.seg + 1].width ?? 0);
391
+ const necked = (r, i) => r.map((q, k) => (k === i || k === i + 1 ? { ...q, width: Math.min(q.width ?? neck, neck) } : q));
392
+ // First, necked down where they pass (nothing moves, so nothing new comes close): every segment that's then far enough
393
+ if (neck) for (const g of short()) if (width(g) > neck && g.gap + (width(g) - neck) / 2 >= gapMin) g.trace.route = necked(g.trace.route, g.seg);
394
+ // Then the rest bowed out round the via (and necked, so the bow is smaller), one per track a round, each checked
395
+ for (let round = 0; round < 6; round++) {
396
+ const was = new Map(), done = new Set();
397
+ for (const g of short().sort((x, y) => x.gap - y.gap)) {
398
+ const t = g.trace, key = `${t.pcb_trace_id}:${g.via.pcb_via_id}`;
399
+ if (done.has(t.pcb_trace_id) || tried.has(key)) continue; // (one bow a track a round: its segments' places change)
400
+ let r = t.route;
401
+ const w = width(g), thin = neck && w > neck ? neck : w, a = r[g.seg], b = r[g.seg + 1], len = Math.hypot(b.x - a.x, b.y - a.y);
402
+ if (len < 1e-6) continue;
403
+ if (thin < w) r = necked(r, g.seg);
404
+ const u = { x: (b.x - a.x) / len, y: (b.y - a.y) / len }, off = { x: g.at.x - g.via.x, y: g.at.y - g.via.y }, d = Math.hypot(off.x, off.y);
405
+ const n = d > 1e-9 ? { x: off.x / d, y: off.y / d } : { x: -u.y, y: u.x }, need = gapMin - g.gap - (w - thin) / 2 + 0.01;
406
+ const along = (g.at.x - a.x) * u.x + (g.at.y - a.y) * u.y, half = g.via.outer_diameter / 2 + need + 0.15; // the stretch beside the via
407
+ const s0 = Math.max(0, along - half), s1 = Math.min(len, along + half), ramp = Math.min(need * 2, s0, len - s1);
408
+ const pt = (s, k) => { const { start_pcb_port_id, end_pcb_port_id, ...q } = { ...r[g.seg], width: thin, x: a.x + u.x * s + n.x * k, y: a.y + u.y * s + n.y * k }; return q; };
409
+ const bow = [ramp > 0 ? pt(s0 - ramp, 0) : null, pt(s0, need), pt(s1, need), ramp > 0 ? pt(s1 + ramp, 0) : null].filter(Boolean)
410
+ .filter((q) => Math.hypot(q.x - a.x, q.y - a.y) > 1e-6 && Math.hypot(q.x - b.x, q.y - b.y) > 1e-6);
411
+ was.set(t.pcb_trace_id, { route: t.route, key });
412
+ t.route = [...r.slice(0, g.seg + 1), ...bow, ...r.slice(g.seg + 1)];
413
+ done.add(t.pcb_trace_id);
414
+ }
415
+ if (!was.size) break;
416
+ // a bow in a new error: the track as it was before it, and that bow not tried again
417
+ for (const e of (await errors()).filter((x) => !before.has(x))) for (const [id, w] of was) if (e.includes(`"${id}"`)) {
418
+ out.find((x) => x.type === 'pcb_trace' && x.pcb_trace_id === id).route = w.route; tried.add(w.key); was.delete(id);
419
+ }
420
+ }
421
+ // Last, a router's via still a little close (its track can't bow: no room): the via nudged (with its own track's ends
422
+ // there) a few hundredths of a millimetre, the first way round that clears every track near it, each move checked
423
+ const vias = new Map(out.filter((e) => e.type === 'pcb_via').map((v) => [v.pcb_via_id, v]));
424
+ for (const g of short()) {
425
+ const v = vias.get(g.via.pcb_via_id), own = out.find((e) => e.type === 'pcb_trace' && e.pcb_trace_id === v.pcb_trace_id);
426
+ if (!own?.rulecad_routed || tried.has(`via:${v.pcb_via_id}`)) continue;
427
+ tried.add(`via:${v.pcb_via_id}`);
428
+ const was_ = { x: v.x, y: v.y, route: own.route }, at = (q) => Math.hypot(q.x - was_.x, q.y - was_.y) < 1e-6;
429
+ const place = (x, y) => { v.x = x; v.y = y; own.route = was_.route.map((q) => (at(q) ? { ...q, x, y } : q)); };
430
+ const worst = () => Math.min(gapMin, ...viaHoleGaps(out, { all: true, under: gapMin }).filter((h) => h.via === v).map((h) => h.gap));
431
+ let fixed = false;
432
+ for (const step of [0.01, 0.02, 0.03, 0.05]) {
433
+ for (let k = 0; k < 16 && !fixed; k++) {
434
+ const t = (k / 16) * 2 * Math.PI;
435
+ place(was_.x + Math.cos(t) * step, was_.y + Math.sin(t) * step);
436
+ if (worst() >= gapMin - 1e-6 && !(await errors()).some((x) => !before.has(x))) fixed = true;
437
+ }
438
+ if (fixed) break;
439
+ }
440
+ if (!fixed) place(was_.x, was_.y);
441
+ }
442
+ }
443
+
444
+ // Routed tracks of different nets a hair closer than the fab's least gap (the design checks allow a little; a fab's
445
+ // rule doesn't): each routed segment of the pair necked down where they pass (to neck), which opens the gap by half the
446
+ // width it loses, each change checked
447
+ export async function gapRepair(out, gapMin, neck) {
448
+ const { runAllChecks } = await import('@tscircuit/checks');
449
+ const errors = async () => (await runAllChecks(structuredClone(out))).filter((e) => /_error$/.test(e.type))
450
+ .map((e) => JSON.stringify([e.type, ...[...new Set(JSON.stringify(e).match(/pcb_[a-z_]+?_\d+/g) || [])].sort()]));
451
+ const parent = new Map(), root = (x) => { while (parent.get(x) !== x) x = parent.get(x); return x; };
452
+ for (const t of out.filter((e) => e.type === 'source_trace')) {
453
+ const ends = [t.source_trace_id, ...(t.connected_source_port_ids || []), ...(t.connected_source_net_ids || [])];
454
+ for (const e of ends) if (!parent.has(e)) parent.set(e, e);
455
+ for (const e of ends.slice(1)) parent.set(root(e), root(ends[0]));
456
+ }
457
+ const netOf = (t) => (parent.has(t.source_trace_id) ? root(t.source_trace_id) : t.pcb_trace_id);
458
+ const ps = (p, o) => { const dx = o.b.x - o.a.x, dy = o.b.y - o.a.y, l = dx * dx + dy * dy, t = l ? Math.max(0, Math.min(1, ((p.x - o.a.x) * dx + (p.y - o.a.y) * dy) / l)) : 0; return Math.hypot(p.x - o.a.x - t * dx, p.y - o.a.y - t * dy); };
459
+ const segs = out.filter((e) => e.type === 'pcb_trace').flatMap((t) => t.route.slice(1).map((q, i) => ({ t, i, a: t.route[i], b: q }))
460
+ .filter((g) => g.a.route_type === 'wire' && g.b.route_type === 'wire' && g.a.layer === g.b.layer));
461
+ const w = (g) => Math.max(g.a.width ?? 0, g.b.width ?? 0), before = new Set(await errors()), was = new Map();
462
+ for (let x = 0; x < segs.length; x++) for (let y = x + 1; y < segs.length; y++) {
463
+ const g = segs[x], h = segs[y];
464
+ if (g.t === h.t || g.a.layer !== h.a.layer || netOf(g.t) === netOf(h.t)) continue;
465
+ if (Math.min(g.a.x, g.b.x) > Math.max(h.a.x, h.b.x) + 1 || Math.min(h.a.x, h.b.x) > Math.max(g.a.x, g.b.x) + 1) continue;
466
+ const d = Math.min(ps(g.a, h), ps(g.b, h), ps(h.a, g), ps(h.b, g)) - w(g) / 2 - w(h) / 2;
467
+ if (d <= 1e-6 || d >= gapMin - 1e-9) continue;
468
+ for (const s of [g, h]) if (s.t.rulecad_routed && w(s) > neck) {
469
+ if (!was.has(s.t.pcb_trace_id)) was.set(s.t.pcb_trace_id, s.t.route);
470
+ s.t.route = s.t.route.map((q, k) => (k === s.i || k === s.i + 1 ? { ...q, width: Math.min(q.width ?? neck, neck) } : q));
471
+ s.a = s.t.route[s.i]; s.b = s.t.route[s.i + 1];
472
+ }
473
+ }
474
+ for (const e of (await errors()).filter((x) => !before.has(x))) for (const [id, route] of was) if (e.includes(`"${id}"`)) {
475
+ out.find((x) => x.type === 'pcb_trace' && x.pcb_trace_id === id).route = route; was.delete(id);
476
+ }
477
+ }
478
+
323
479
  // Each routed track's kept escape at either end: the stub of the source's track it carries on from (its end not on a
324
480
  // pad), followed back from the joint segment by segment while it's a single line on one layer, stopping at a via or a
325
481
  // branch. -> Map(pcb_trace_id -> { start, end }), each { lead: points from the stub's root to the joint, segs: the stub's
@@ -359,13 +515,13 @@ export const holeSize = (e) => (e.outer_diameter != null ? { w: e.outer_diameter
359
515
 
360
516
  // The source's copper kept with a block of parts (moveGroup's keep): its tracks and vias as they were, each island a
361
517
  // source trace joining its pins (and its plane, if its via reaches one), so nothing routes them again
362
- function keptCopper(out, add, board, copper, planeNets) {
518
+ function keptCopper(out, add, board, copper, planeNets, later = false) {
363
519
  const pins = padsByPin(out);
364
- for (const k of board.copper.islands) { // (stubs are laid with the connection they start: see the traces below)
520
+ for (const k of board.copper.islands.filter((x) => !!x.after === later)) { // (stubs are laid with the connection they start: see the traces below)
365
521
  const ports = [...new Set(k.pins.flatMap((p) => (pins.get(p) || []).map((f) => f.sp.source_port_id)))];
366
522
  const plane = k.via && planeNets[k.net];
367
523
  if (!ports.length || (ports.length < 2 && !plane)) continue; // nothing left to join
368
- const st = add('source_trace', { connected_source_port_ids: ports, connected_source_net_ids: plane ? [plane.id] : [], subcircuit_id: SUB, display_name: `${k.pins.join(', ')}: the source's own copper` });
524
+ const st = add('source_trace', { connected_source_port_ids: ports, connected_source_net_ids: plane ? [plane.id] : [], subcircuit_id: SUB, display_name: `${k.pins.join(', ')}: the source's own copper`, ...(k.net ? { rulecad_net: k.net } : {}) });
369
525
  for (const g of board.copper.tracks.filter((t) => t.island === k.id))
370
526
  add('pcb_trace', { route: [{ route_type: 'wire', x: g.a.x, y: g.a.y, width: g.width, layer: g.layer }, { route_type: 'wire', x: g.b.x, y: g.b.y, width: g.width, layer: g.layer }], source_trace_id: st.source_trace_id, subcircuit_id: SUB, rulecad_kept: true });
371
527
  for (const v of board.copper.vias.filter((x) => x.island === k.id)) {
@@ -488,8 +644,9 @@ function planeVias(out, add, board, copper) {
488
644
  ...out.filter((e) => e.type === 'pcb_hole').map((e) => ({ id: e.pcb_hole_id, x: e.x, y: e.y, r: e.hole_diameter / 2 }))];
489
645
  const segs = [], sameNet = Object.fromEntries(Object.keys(board.planes).map((n) => [n, []])); // plane tracks drawn so far; each net's vias
490
646
  const kept = board.copper || { tracks: [], vias: [], islands: [] }; // the source's copper, kept: in the way, and some pads already reach their plane by it
491
- for (const g of kept.tracks) if (g.layer === 'top' || g.layer === 'bottom') segs.push({ a: g.a, b: g.b, layer: g.layer, w: g.width });
492
- for (const v of kept.vias) circles.push({ id: `kept${circles.length}`, x: v.x, y: v.y, r: v.pad / 2 });
647
+ const laterIds = new Set((kept.islands || []).filter((k) => k.after).map((k) => k.id)); // (laid once routed: not in the router's way)
648
+ for (const g of kept.tracks) if ((g.layer === 'top' || g.layer === 'bottom') && !laterIds.has(g.island)) segs.push({ a: g.a, b: g.b, layer: g.layer, w: g.width });
649
+ for (const v of kept.vias) if (!laterIds.has(v.island)) circles.push({ id: `kept${circles.length}`, x: v.x, y: v.y, r: v.pad / 2 });
493
650
  const reachedBy = new Set(kept.islands.filter((k) => k.via && board.planes[k.net]).flatMap((k) => k.pins));
494
651
  const toRect = (x, y, q) => Math.hypot(Math.max(Math.abs(x - q.x) - q.w / 2, 0), Math.max(Math.abs(y - q.y) - q.h / 2, 0));
495
652
  const toSeg = (x, y, a, c) => { const dx = c.x - a.x, dy = c.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; return Math.hypot(x - a.x - t * dx, y - a.y - t * dy); };
@@ -810,14 +967,14 @@ export function layerChanges(route, holes) {
810
967
  const pieces = [[]];
811
968
  for (const p of route) {
812
969
  if (p.route_type !== 'through_obstacle') { pieces.at(-1).push(p); continue; }
813
- const at = p.start, inHole = holes.some((h) => {
814
- const r = Math.max(holeSize(h).w, holeSize(h).h) / 2;
815
- return Math.hypot(at.x - h.x, at.y - h.y) <= r + 1e-6 && Math.hypot(p.end.x - h.x, p.end.y - h.y) <= r + 1e-6;
816
- });
817
- if (!inHole) throw new Error(`the autorouter ran a track through a part at (${at.x.toFixed(2)}, ${at.y.toFixed(2)}) mm: move the parts apart or give it more room`);
970
+ // The router sees a hole or via as a square round its copper, so it may mark the change anywhere in that square,
971
+ // corners included: in it counts, and the track is taken on to the hole's centre on each side, so it joins its copper
972
+ const at = p.start, inSquare = (q, h, r) => Math.abs(q.x - h.x) <= r + 1e-6 && Math.abs(q.y - h.y) <= r + 1e-6;
973
+ const hole = holes.find((h) => { const r = Math.max(holeSize(h).w, holeSize(h).h) / 2; return inSquare(at, h, r) && inSquare(p.end, h, r); });
974
+ if (!hole) throw new Error(`the autorouter ran a track through a part at (${at.x.toFixed(2)}, ${at.y.toFixed(2)}) mm: move the parts apart or give it more room`);
818
975
  const width = p.width ?? pieces.at(-1).at(-1)?.width;
819
- pieces.at(-1).push({ route_type: 'wire', x: at.x, y: at.y, width, layer: p.from_layer });
820
- pieces.push([{ route_type: 'wire', x: p.end.x, y: p.end.y, width, layer: p.to_layer }]);
976
+ pieces.at(-1).push({ route_type: 'wire', x: at.x, y: at.y, width, layer: p.from_layer }, { route_type: 'wire', x: hole.x, y: hole.y, width, layer: p.from_layer });
977
+ pieces.push([{ route_type: 'wire', x: hole.x, y: hole.y, width, layer: p.to_layer }, { route_type: 'wire', x: p.end.x, y: p.end.y, width, layer: p.to_layer }]);
821
978
  }
822
979
  return pieces.filter((q) => q.length > 1);
823
980
  }
@@ -918,15 +1075,33 @@ export async function neckDown(json, traces, neck) {
918
1075
  return out;
919
1076
  }
920
1077
 
1078
+ // The autorouter's pipelines, tried in order until one routes the board: its own, then its others, each a different search
1079
+ const PIPELINES = ['AutoroutingPipelineSolver', 'AutoroutingPipelineSolver4', 'AutoroutingPipelineSolver5', 'AutoroutingPipelineSolver6', 'AutoroutingPipelineSolver8'];
1080
+
921
1081
  async function routeOnce(json, toRoute, board, limit = 0) {
922
1082
  // The autorouter uses JavaScript features from Node 22 (iterator helpers): say so, rather than fail inside it
923
1083
  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`);
924
- const { AutoroutingPipelineSolver } = await import('@tscircuit/capacity-autorouter');
1084
+ const router = await import('@tscircuit/capacity-autorouter');
925
1085
  const srj = await routeInput(json, toRoute, board);
926
- const solver = new AutoroutingPipelineSolver(srj, { cacheProvider: null, ...(board.effort ? { effort: board.effort } : {}) }); // effort: how hard it searches (1, the router's own)
927
- // stepped by hand, so a repair can be given a time limit (a first route has none)
928
- while (!solver.solved && !solver.failed) { solver.step(); if (limit && Date.now() > limit) throw new Error('a repair took too long'); }
929
- if (solver.failed) throw new Error(`the autorouter couldn't route every connection: ${solver.error || 'no reason given'}`);
1086
+ // The router's own pipeline first. If it gives up, one of its later stages throws (its via clean-up can, on a crowded
1087
+ // two-sided board: "a layer transition without a via"), or what it hands back fails here (a pad left without a
1088
+ // track, a track through a part), the next one: a different search from the start
1089
+ const pipelines = [...new Set([board.pipeline || PIPELINES[0], ...PIPELINES])], tried = [];
1090
+ for (const name of pipelines) {
1091
+ if (!router[name]) continue;
1092
+ const solver = new router[name](srj, { cacheProvider: null, ...(board.effort ? { effort: board.effort } : {}) }); // effort: how hard it searches (1, the router's own)
1093
+ // stepped by hand, so a repair can be given a time limit (a first route has none)
1094
+ 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
+ catch (e) { if (e.late) throw e; solver.failed = true; solver.error = solver.error || e.message; }
1096
+ 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}`); }
1098
+ }
1099
+ 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
+ }
1101
+
1102
+ // What a solved pipeline hands back, as tracks on the board: throws if a pad is left without a track or a track runs
1103
+ // through a part
1104
+ function routedTraces(solver, srj, json) {
930
1105
  // The routes for the connections asked for (the solver also hands back the fixed ones), each from its first pad to
931
1106
  // its second, as tscircuit records them
932
1107
  const traces = [], asked = new Map(srj.connections.map((c) => [c.name, c.pointsToConnect]));
package/kicad.mjs ADDED
@@ -0,0 +1,249 @@
1
+ // A board in KiCad's own files, as KiCad reads them: tscircuit's converter (circuit-json-to-kicad) writes the board,
2
+ // and this makes up what it leaves out or reads differently, so KiCad's design-rule check sees the board our checks see.
3
+ // - nets: the converter takes each pad's, track's and via's net from a connectivity key that tscircuit's own core
4
+ // writes and a board built here doesn't. kicadNets() works the nets out (the ports each source trace joins, and the
5
+ // copper laid for it) and names each: its source net's name (GND), the net the board gave the trace (/USB+), else
6
+ // after its first pad (Net-(R4-Pad1))
7
+ // - a hole set off-centre in its pad: KiCad puts the pad at its hole and moves its copper by the drill's offset;
8
+ // tscircuit puts the pad at its copper, the hole moved by hole_offset. The converter writes the copper's place, so
9
+ // the hole lands off by the offset: patchKicadPcb() moves each such pad to its hole
10
+ // - castellated pads (a half hole on the edge) marked as KiCad's castellated pads, which may cross the board's edge
11
+ // - a via laid twice at one place (a kept via and the track that names it) written once
12
+ // - the rules: kicadProject() writes the project file KiCad reads them from, with the board's own minimums (pcb_board's
13
+ // min_* values, which our checks use), and a custom rule file for exceptions the source has (pads by its edge)
14
+ // - kicadDrc(): KiCad's own design-rule check on all of that, when KiCad is installed
15
+ // - kicadFab(): the Gerber and drill files, plotted by KiCad from the board that check has just passed
16
+ import fs from 'node:fs';
17
+ import os from 'node:os';
18
+ import path from 'node:path';
19
+ import { execFileSync } from 'node:child_process';
20
+
21
+ const KICAD_CENTRE = 100; // where the converter puts the design's (0, 0) on KiCad's page (mm)
22
+
23
+ /**
24
+ * Circuit JSON with every source port, source trace, pcb trace and via keyed to its net, and a named source net for
25
+ * each, as circuit-json-to-kicad reads them. A copy; the input is unchanged.
26
+ * @param {object[]} json @returns {object[]}
27
+ */
28
+ export function kicadNets(json) {
29
+ const out = structuredClone(json);
30
+ const up = new Map(), find = (a) => { while (up.get(a) !== a) { up.set(a, up.get(up.get(a))); a = up.get(a); } return a; };
31
+ const join = (a, b) => { for (const x of [a, b]) if (!up.has(x)) up.set(x, x); up.set(find(a), find(b)); };
32
+ for (const e of out) if (e.type === 'source_trace') {
33
+ const ids = [...(e.connected_source_port_ids || []), ...(e.connected_source_net_ids || [])];
34
+ join(e.source_trace_id, e.source_trace_id);
35
+ for (const id of ids) join(e.source_trace_id, id);
36
+ }
37
+ for (const e of out) if (e.type === 'source_net' || e.type === 'source_port') join(e.source_net_id || e.source_port_id, e.source_net_id || e.source_port_id);
38
+ // a pin with more than one pad (a half hole and a header hole) has a port for each: one net. (Pins sharing only a name,
39
+ // as a module's GND pins do, are joined only where the board joins them)
40
+ const pin = new Map();
41
+ for (const e of out) if (e.type === 'source_port') { const k = `${e.source_component_id}:${e.name}:${e.pin_number}`; if (pin.has(k)) join(pin.get(k), e.source_port_id); else pin.set(k, e.source_port_id); }
42
+ const key = (id) => `net_${find(id)}`;
43
+ // each net's name: its source net's, the board's name for one of its traces, else after its first pad
44
+ const names = new Map();
45
+ for (const e of out) if (e.type === 'source_net') names.set(key(e.source_net_id), e.name);
46
+ for (const e of out) if (e.type === 'source_trace' && e.rulecad_net && !names.has(key(e.source_trace_id))) names.set(key(e.source_trace_id), e.rulecad_net);
47
+ const part = new Map(out.filter((e) => e.type === 'source_component').map((e) => [e.source_component_id, e.name]));
48
+ for (const e of out) if (e.type === 'source_port' && !names.has(key(e.source_port_id))) names.set(key(e.source_port_id), `Net-(${part.get(e.source_component_id) ?? '?'}-Pad${String(e.name ?? e.pin_number).replace(/^pin/, '')})`);
49
+ // one name, one net: KiCad joins nets that share a name (a USB-C socket's A5 and B5 are both its pin 5)
50
+ const taken = new Map();
51
+ for (const [k, n] of names) { const c = (taken.get(n) || 0) + 1; taken.set(n, c); if (c > 1) names.set(k, `${n}_${c}`); }
52
+ // a net no trace joins is a pin on its own: no KiCad net (net 0), as KiCad leaves an unconnected pad
53
+ const joined = new Set(out.filter((e) => e.type === 'source_trace').map((e) => key(e.source_trace_id)));
54
+ for (const k of pin.values()) if ([...pin.values()].filter((x) => key(x) === key(k)).length > 1 || out.some((e) => e.type === 'source_port' && e.source_port_id !== k && key(e.source_port_id) === key(k))) joined.add(key(k)); // (two pads of one pin: a net of their own)
55
+ const nets = new Map(out.filter((e) => e.type === 'source_net').map((e) => [key(e.source_net_id), e]));
56
+ for (const k of joined) if (!nets.has(k)) {
57
+ const n = { type: 'source_net', source_net_id: `rulecad_${k}`, name: names.get(k), member_source_group_ids: [], subcircuit_connectivity_map_key: k };
58
+ out.push(n); nets.set(k, n);
59
+ }
60
+ for (const [k, n] of nets) n.subcircuit_connectivity_map_key = k;
61
+ const traceKey = new Map();
62
+ for (const e of out) {
63
+ if (e.type === 'source_trace') { e.subcircuit_connectivity_map_key = key(e.source_trace_id); }
64
+ else if (e.type === 'source_port' && joined.has(key(e.source_port_id))) e.subcircuit_connectivity_map_key = key(e.source_port_id);
65
+ }
66
+ for (const e of out) if (e.type === 'pcb_trace' && e.source_trace_id && up.has(e.source_trace_id)) { e.subcircuit_connectivity_map_key = key(e.source_trace_id); traceKey.set(e.pcb_trace_id, e.subcircuit_connectivity_map_key); }
67
+ for (const e of out) if (e.type === 'pcb_via' && traceKey.has(e.pcb_trace_id)) e.subcircuit_connectivity_map_key = traceKey.get(e.pcb_trace_id);
68
+ return out;
69
+ }
70
+
71
+ /**
72
+ * The converter's .kicad_pcb made right for KiCad (see the top of this file): pads with an off-centre hole moved to
73
+ * their hole, castellated pads marked, a via laid twice written once.
74
+ * @param {string} text @param {object[]} json @returns {string}
75
+ */
76
+ export function patchKicadPcb(text, json) {
77
+ const r4 = (n) => Math.round(n * 1e4) / 1e4;
78
+ // a pad with a drill offset: at its hole (the copper keeps its place: the offset is now from the hole to it)
79
+ text = text.replace(/(\(pad "[^"]*" thru_hole \w+\s*\(at )(-?[\d.e-]+) (-?[\d.e-]+)((?: -?[\d.e-]+)?\)(?:(?!\(pad )[\s\S])*?\(drill [^()]*\(offset (-?[\d.e-]+) (-?[\d.e-]+)\))/g,
80
+ (all, head, x, y, rest, dx, dy) => `${head}${r4(Number(x) - Number(dx))} ${r4(Number(y) - Number(dy))}${rest}`);
81
+ // Pads found by where their footprint puts them (the hole, now), in footprint coordinates
82
+ const comp = new Map(json.filter((e) => e.type === 'pcb_component').map((e) => [e.pcb_component_id, e]));
83
+ const at = (e) => { const c = comp.get(e.pcb_component_id); return c && { x: e.x + (e.hole_offset_x ?? 0) - c.center.x, y: -(e.y + (e.hole_offset_y ?? 0) - c.center.y), e }; };
84
+ const holes = json.filter((e) => e.type === 'pcb_plated_hole').map(at).filter(Boolean);
85
+ const find = (x, y) => holes.find((p) => Math.abs(p.x - Number(x)) < 1e-3 && Math.abs(p.y - Number(y)) < 1e-3)?.e;
86
+ // castellated: the half hole and every other pad of its pin (a header pad joined to it reaches the edge with it), as
87
+ // KiCad's castellated pads, which may cross the board's edge
88
+ const edgePins = new Set(holes.filter((p) => p.e.port_hints?.includes('castellated')).map((p) => `${p.e.pcb_component_id}:${p.e.port_hints?.[1]}`));
89
+ // a rectangular pad with rounded corners (rect_border_radius): KiCad's rounded rectangle, which the converter leaves square
90
+ text = text.replace(/\(pad "[^"]*" thru_hole (\w+)\s*\(at (-?[\d.e-]+) (-?[\d.e-]+)[^)]*\)/g, (all, shape, x, y) => {
91
+ const e = find(x, y); if (!e) return all;
92
+ let out = all;
93
+ if (shape === 'rect' && e.rect_border_radius) out = out.replace(' thru_hole rect', ' thru_hole roundrect') + `\n (roundrect_rratio ${r4(e.rect_border_radius / Math.min(e.rect_pad_width, e.rect_pad_height))})`;
94
+ if (edgePins.has(`${e.pcb_component_id}:${e.port_hints?.[1]}`)) out += '\n (property pad_prop_castellated)';
95
+ return out;
96
+ });
97
+ // the drill and place origin at the design's own (0, 0), so plots and our placement file share one frame
98
+ text = text.replace(/\(setup\b/, `(setup\n\t\t(aux_axis_origin ${KICAD_CENTRE} ${KICAD_CENTRE})`);
99
+ // a via twice at one place, the same size, layers and net: once
100
+ const seen = new Set();
101
+ text = text.replace(/\n \(via\s*\(at (-?[\d.e-]+) (-?[\d.e-]+)\)\s*\(size ([\d.]+)\)\s*\(drill ([\d.]+)\)\s*\(layers ([^)]*)\)\s*(\(net \d+\))?[\s\S]*?\n \)/g, (all, x, y, size, drill, layers, net) => {
102
+ const k = [r4(Number(x)), r4(Number(y)), size, drill, layers, net].join(' ');
103
+ if (seen.has(k)) return '';
104
+ seen.add(k); return all;
105
+ });
106
+ return text;
107
+ }
108
+
109
+ /**
110
+ * KiCad's project file (.kicad_pro) with the board's own design rules, and a custom rules file (.kicad_dru):
111
+ * minimums from pcb_board's min_* values (what our checks use), the default net class at the board's clearance and
112
+ * track. edgeExempt: parts whose pads may come as close to the board's edge as the source has them ({ ref, edge }).
113
+ * @param {object[]} json @param {{ clearance?: number, track?: number, edgeExempt?: { ref: string, edge: number }[] }} [o]
114
+ * @returns {{ pro: string, dru: string }}
115
+ */
116
+ export function kicadProject(json, { clearance, track, edgeExempt = [] } = {}) {
117
+ const b = json.find((e) => e.type === 'pcb_board') || {};
118
+ const via = json.find((e) => e.type === 'pcb_via');
119
+ const vias = json.filter((e) => e.type === 'pcb_via'), holes = json.filter((e) => e.type === 'pcb_plated_hole' || e.type === 'pcb_hole' || e.type === 'pcb_via').map((e) => e.hole_diameter ?? e.hole_width).filter(Boolean);
120
+ const viaPad = Math.min(b.min_via_pad_diameter ?? 0.3, ...vias.map((v) => v.outer_diameter)), viaHole = Math.min(b.min_via_hole_diameter ?? 0.2, ...vias.map((v) => v.hole_diameter));
121
+ const gap = clearance ?? b.min_trace_to_pad_edge_clearance ?? 0.1;
122
+ const rules = {
123
+ min_clearance: gap, min_track_width: Math.min(b.min_trace_width ?? 0.1, ...json.filter((e) => e.type === 'pcb_trace').flatMap((t) => t.route.map((p) => p.width ?? Infinity))),
124
+ min_via_diameter: viaPad, min_through_hole_diameter: Math.min(viaHole, ...holes), min_via_annular_width: Math.min(...vias.map((v) => (v.outer_diameter - v.hole_diameter) / 2), (viaPad - viaHole) / 2),
125
+ min_copper_edge_clearance: b.min_board_edge_clearance ?? 0.2, min_hole_clearance: b.min_trace_to_hole_edge_clearance ?? 0.2,
126
+ min_hole_to_hole: b.min_via_hole_edge_to_via_hole_edge_clearance ?? 0.1, min_silk_clearance: 0, min_microvia_diameter: 0.2, min_microvia_drill: 0.1,
127
+ allow_blind_buried_vias: false, allow_microvias: false, max_error: 0.005, use_height_for_length_calcs: true };
128
+ const pro = { board: { design_settings: { defaults: {}, rules, track_widths: [0], via_dimensions: [{ diameter: 0, drill: 0 }], rule_severities: {} } },
129
+ meta: { filename: 'board.kicad_pro', version: 3 },
130
+ net_settings: { classes: [{ name: 'Default', clearance: gap, track_width: track ?? 0.15, via_diameter: via?.outer_diameter ?? viaPad, via_drill: via?.hole_diameter ?? viaHole,
131
+ microvia_diameter: 0.2, microvia_drill: 0.1, diff_pair_gap: 0.2, diff_pair_width: 0.2, diff_pair_via_gap: 0.25, wire_width: 6, bus_width: 12, line_style: 0, pcb_color: 'rgba(0, 0, 0, 0.000)', schematic_color: 'rgba(0, 0, 0, 0.000)', priority: 2147483647 }], meta: { version: 3 } } };
132
+ const dru = ['(version 1)', ...edgeExempt.map((x) => `(rule "${x.ref}: its pads by the edge, as the source has them"\n (condition "A.Parent == '${x.ref}' && A.Type == 'Pad'")\n (constraint edge_clearance (min ${x.edge}mm)))`)].join('\n') + '\n';
133
+ return { pro: JSON.stringify(pro, null, 2) + '\n', dru };
134
+ }
135
+
136
+ // kicad-cli, where KiCad installs it (KICAD_CLI names another), or null when KiCad isn't installed
137
+ export function kicadCli(env = process.env) {
138
+ const candidates = [env.KICAD_CLI, '/Applications/KiCad/KiCad.app/Contents/MacOS/kicad-cli', '/usr/bin/kicad-cli', '/usr/local/bin/kicad-cli', 'C:\\Program Files\\KiCad\\bin\\kicad-cli.exe'].filter(Boolean);
139
+ return candidates.find((p) => fs.existsSync(p)) ?? null;
140
+ }
141
+
142
+ // The board written where KiCad reads it, for fn({ cli, dir, board }); gone afterwards
143
+ async function onKicadBoard(json, o, fn) {
144
+ const cli = kicadCli();
145
+ if (!cli) return null;
146
+ const { CircuitJsonToKicadPcbConverter } = await import('circuit-json-to-kicad');
147
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'rulecad-kicad-'));
148
+ try {
149
+ const netted = kicadNets(json), pcb = new CircuitJsonToKicadPcbConverter(netted); pcb.runUntilFinished();
150
+ const { pro, dru } = kicadProject(netted, o), board = path.join(dir, 'board.kicad_pcb');
151
+ fs.writeFileSync(board, patchKicadPcb(pcb.getOutputString(), netted));
152
+ fs.writeFileSync(path.join(dir, 'board.kicad_pro'), pro); fs.writeFileSync(path.join(dir, 'board.kicad_dru'), dru);
153
+ return await fn({ cli, dir, board });
154
+ } finally { fs.rmSync(dir, { recursive: true, force: true }); }
155
+ }
156
+
157
+ // kicad-cli's design-rule check, KiCad pouring the planes (extra: more arguments, as --save-board)
158
+ function runDrc(cli, dir, board, extra = []) {
159
+ const version = execFileSync(cli, ['version'], { encoding: 'utf8' }).trim();
160
+ execFileSync(cli, ['pcb', 'drc', '--refill-zones', ...extra, '--format', 'json', '--severity-all', '-o', path.join(dir, 'drc.json'), board], { stdio: 'pipe' });
161
+ const d = JSON.parse(fs.readFileSync(path.join(dir, 'drc.json'), 'utf8'));
162
+ const all = [...d.violations, ...d.unconnected_items].filter((x) => x.type !== 'lib_footprint_issues'); // (KiCad's library has no "tscircuit" footprints: nothing about the board)
163
+ return { version, errors: all.filter((x) => x.severity === 'error'), warnings: all.filter((x) => x.severity !== 'error') };
164
+ }
165
+
166
+ /**
167
+ * KiCad's own design-rule check on the board, as a second opinion: its files written as kicadFiles() writes them
168
+ * (KiCad pours the planes itself, by its rules), checked by kicad-cli. -> { version, errors: [{ type, description,
169
+ * items }], warnings } or null when KiCad isn't installed.
170
+ * @param {object[]} json @param {{ clearance?: number, track?: number, edgeExempt?: { ref: string, edge: number }[] }} [o]
171
+ */
172
+ export async function kicadDrc(json, o = {}) {
173
+ return onKicadBoard(json, o, ({ cli, dir, board }) => runDrc(cli, dir, board));
174
+ }
175
+
176
+ /**
177
+ * Whether a board's fab files must come from KiCad: slotted holes (the Gerber writer can't drill one), or rounded pads
178
+ * beside a copper plane (it plots them square, so their corners reach into a plane cut round the true shape).
179
+ * @param {object[]} json @returns {boolean}
180
+ */
181
+ export function needsKicadFab(json) {
182
+ const plated = json.filter((e) => e.type === 'pcb_plated_hole');
183
+ return plated.some((e) => e.hole_width != null && e.hole_height != null && e.hole_width !== e.hole_height) || (plated.some((e) => e.rect_border_radius) && json.some((e) => e.type === 'pcb_copper_pour'));
184
+ }
185
+
186
+ /**
187
+ * Every hole the board's design has, found in KiCad's drill files: its place, its size, and a slot's length. Excellon text
188
+ * in mm with its zero at the design's. -> what's wrong, in words ([] when they agree).
189
+ * @param {object[]} json @param {string} pth @param {string} npth @returns {string[]}
190
+ */
191
+ export function drillMismatches(json, pth, npth) {
192
+ const read = (text) => {
193
+ const tools = new Map(), out = []; let size = null;
194
+ for (const raw of text.split(/\r?\n/)) {
195
+ const line = raw.trim(), tool = line.match(/^T(\d+)(?:[A-Z]\S*?)?C([\d.]+)/), pick = line.match(/^T(\d+)$/), at = line.match(/^X(-?[\d.]+)Y(-?[\d.]+)(?:G85X(-?[\d.]+)Y(-?[\d.]+))?/);
196
+ if (tool) tools.set(tool[1], Number(tool[2])); else if (pick) size = tools.get(pick[1]);
197
+ else if (at) out.push({ x: (Number(at[1]) + (at[3] != null ? Number(at[3]) : Number(at[1]))) / 2, y: (Number(at[2]) + (at[4] != null ? Number(at[4]) : Number(at[2]))) / 2, d: size, run: at[3] != null ? Math.hypot(Number(at[3]) - Number(at[1]), Number(at[4]) - Number(at[2])) : 0, used: false });
198
+ }
199
+ return out;
200
+ };
201
+ const near = 0.011, wrong = [];
202
+ const compare = (text, all, kind) => {
203
+ const found = read(text), seen = new Set(), wanted = all.filter((h) => { const k = [h.x.toFixed(3), h.y.toFixed(3), h.d, h.run].join(); return !seen.has(k) && seen.add(k); }); // (a via laid twice is drilled once)
204
+ for (const h of wanted) {
205
+ const f = found.find((q) => !q.used && Math.hypot(q.x - h.x, q.y - h.y) < near);
206
+ if (!f) { wrong.push(`no ${kind} hole at (${h.x.toFixed(3)}, ${h.y.toFixed(3)})`); continue; }
207
+ f.used = true;
208
+ if (Math.abs(f.d - h.d) > near || Math.abs(f.run - h.run) > near) wrong.push(`${kind} hole at (${h.x.toFixed(3)}, ${h.y.toFixed(3)}): ${f.d} mm${f.run ? ' slot' : ''} in the file, ${h.d} mm${h.run ? ` slot running ${h.run.toFixed(3)} mm` : ''} in the design`);
209
+ }
210
+ for (const f of found.filter((q) => !q.used)) wrong.push(`a ${kind} hole at (${f.x.toFixed(3)}, ${f.y.toFixed(3)}) the design doesn't have`);
211
+ };
212
+ const hole = (e) => { const w = e.hole_width, h = e.hole_height, slot = e.hole_diameter == null && w != null && h != null; return { x: e.x + (e.hole_offset_x ?? 0), y: e.y + (e.hole_offset_y ?? 0), d: slot ? Math.min(w, h) : e.hole_diameter ?? w, run: slot ? Math.abs(w - h) : 0 }; };
213
+ compare(pth, json.filter((e) => e.type === 'pcb_plated_hole' || e.type === 'pcb_via').map(hole), 'plated');
214
+ compare(npth, json.filter((e) => e.type === 'pcb_hole').map(hole), 'unplated');
215
+ return wrong;
216
+ }
217
+
218
+ /**
219
+ * The Gerber and drill files, plotted by KiCad from the very board its design-rule check has just passed, planes poured,
220
+ * named as a fab expects: { 'name.GTL': text, ..., 'name-PTH.DRL': text, 'name-NPTH.DRL': text }. Throws if the check
221
+ * finds an error (allow(finding): one that's accepted, the source's own) or the drill files aren't the design's holes;
222
+ * null when KiCad isn't installed.
223
+ * @param {object[]} json @param {string} name @param {{ clearance?: number, track?: number, edgeExempt?: object[], allow?: (x: any) => boolean }} [o]
224
+ */
225
+ export async function kicadFab(json, name, o = {}) {
226
+ return onKicadBoard(json, o, ({ cli, dir, board }) => {
227
+ const drc = runDrc(cli, dir, board, ['--save-board']), errors = drc.errors.filter((x) => !o.allow?.(x));
228
+ if (errors.length) throw new Error(`no fab files: KiCad's design-rule check found ${errors.length} errors on the board it would plot (first: ${errors[0].description})`);
229
+ const copper = json.find((e) => e.type === 'pcb_board')?.num_layers ?? 2, inner = Array.from({ length: copper - 2 }, (_, i) => `In${i + 1}.Cu`);
230
+ const layers = ['F.Cu', ...inner, 'B.Cu', 'F.Paste', 'B.Paste', 'F.SilkS', 'B.SilkS', 'F.Mask', 'B.Mask', 'Edge.Cuts'];
231
+ const plots = path.join(dir, 'plots'), drills = path.join(dir, 'drills');
232
+ fs.mkdirSync(plots); fs.mkdirSync(drills);
233
+ execFileSync(cli, ['pcb', 'export', 'gerbers', '--layers', layers.join(','), '--use-drill-file-origin', '--no-x2', '--no-netlist', '-o', `${plots}/`, board], { stdio: 'pipe' });
234
+ execFileSync(cli, ['pcb', 'export', 'drill', '--format', 'excellon', '--excellon-separate-th', '--excellon-units', 'mm', '--excellon-zeros-format', 'decimal', '--excellon-oval-format', 'alternate', '--drill-origin', 'plot', '-o', `${drills}/`, board], { stdio: 'pipe' });
235
+ const ext = { F_Cu: 'GTL', B_Cu: 'GBL', F_Paste: 'GTP', B_Paste: 'GBP', F_Silkscreen: 'GTO', B_Silkscreen: 'GBO', F_Mask: 'GTS', B_Mask: 'GBS', Edge_Cuts: 'GKO' };
236
+ const out = {};
237
+ for (const f of fs.readdirSync(plots)) {
238
+ if (f.endsWith('.gbrjob')) continue;
239
+ const layer = f.replace(/^board-/, '').replace(/\.[^.]+$/, ''), inn = layer.match(/^In(\d+)_Cu$/), e = inn ? `G${inn[1]}` : ext[layer];
240
+ if (!e) throw new Error(`no fab files: KiCad plotted a layer we can't name (${f})`);
241
+ out[`${name}.${e}`] = fs.readFileSync(path.join(plots, f), 'utf8');
242
+ }
243
+ if (Object.keys(out).length !== layers.length) throw new Error(`no fab files: KiCad plotted ${Object.keys(out).length} of ${layers.length} layers`);
244
+ const pth = fs.readFileSync(path.join(drills, 'board-PTH.drl'), 'utf8'), npth = fs.readFileSync(path.join(drills, 'board-NPTH.drl'), 'utf8');
245
+ const wrong = drillMismatches(json, pth, npth);
246
+ if (wrong.length) throw new Error(`no fab files: KiCad's drill files aren't the design's holes (${wrong.length}; first: ${wrong[0]})`);
247
+ return { ...out, [`${name}-PTH.DRL`]: pth, [`${name}-NPTH.DRL`]: npth };
248
+ });
249
+ }
package/package.json CHANGED
@@ -1,13 +1,15 @@
1
1
  {
2
2
  "name": "@rulecad/pcb",
3
- "version": "0.5.1",
3
+ "version": "0.5.4",
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
8
  "pcb.mjs",
9
9
  "circuit.mjs",
10
+ "kicad.mjs",
10
11
  "README.md",
12
+ "CHANGELOG.md",
11
13
  "LICENSE"
12
14
  ],
13
15
  "license": "MIT",
@@ -36,9 +38,10 @@
36
38
  "dependencies": {
37
39
  "@flatten-js/core": "1.6.14",
38
40
  "@jscad/modeling": "^2.12.0",
39
- "@rulecad/rules": "^0.3.4",
41
+ "@rulecad/fixings": "^0.1.3",
42
+ "@rulecad/rules": "^0.3.7",
40
43
  "@resvg/resvg-js": "2.6.2",
41
- "@rulecad/smooth": "^0.1.0",
44
+ "@rulecad/smooth": "^0.1.2",
42
45
  "@tscircuit/capacity-autorouter": "0.0.982",
43
46
  "@tscircuit/checks": "0.0.264",
44
47
  "@tscircuit/circuit-json-util": "0.0.122",
package/pcb.mjs CHANGED
@@ -13,7 +13,7 @@
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 } from './circuit.mjs';
16
+ import { circuitJson, bounds, smtBounds, slideClear, viaHoleGaps } from './circuit.mjs';
17
17
  export { bounds };
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
@@ -21,6 +21,7 @@ import { createRequire } from 'node:module';
21
21
  // set into the current folder when it reads one
22
22
  const loadRuleSet = (name) => createRequire(import.meta.url)(`@rulecad/rules/${name}.json`);
23
23
  import jscad from '@jscad/modeling';
24
+ import { fixingModel } from '@rulecad/fixings';
24
25
 
25
26
  // A rows × cols grid of keys at the key pitch, centred on the origin: [{ r, c, x, y, n }], n counting from 1, row 0
26
27
  // at the back (+y)
@@ -34,6 +35,51 @@ export function grid(rows, cols, pitch) {
34
35
  const pad = (pin, x, y, hole, outer) => ({ pin, x, y, hole, outer }); // plated, round, relative to the part
35
36
  const hole = (x, y, d) => ({ x, y, d });
36
37
 
38
+ // ---------- mounting holes, by thread ----------
39
+ // Which figure of a thread's rule set each fit of hole is: ISO 273's close, normal and loose clearance holes
40
+ const MOUNT_FITS = { clearance: 'clearance', close: 'clearance_close', loose: 'clearance_loose' };
41
+ const shown = (x) => (x === undefined ? 'nothing' : JSON.stringify(x) ?? String(x));
42
+
43
+ /**
44
+ * A board's mounting hole, named by its screw's thread and sized from the thread's rule set (@rulecad/fixings reads
45
+ * it): { x, y, d, keepout?, thread, fit } as a board's `holes` take them. The fab drills it, so the hole is the figure
46
+ * as it stands, with nothing added for a printer: mount('M2', x, y) is m2.clearance, 2.4 mm.
47
+ * @param {string} thread the screw's thread: 'M2', 'M2.5', 'M3', '4-40'
48
+ * @param {number} x @param {number} y where, in mm, in the board's frame
49
+ * @param {{ fit?: 'clearance' | 'close' | 'loose', d?: number, keepout?: number, set?: object, sets?: object }} [o]
50
+ * fit: the clearance hole's fit (default the normal one); d: a hole the board's maker gives instead (a Pico's 2.1 mm),
51
+ * held to pass the thread; keepout: a radius from the hole's centre the router keeps tracks out of (a screw head's
52
+ * room); set: the thread's figures as a design reads them (v.m2), used first; sets: a workspace's rule sets by name,
53
+ * whose set for this thread is read before the kit's (cad binds them for v.pcb.mount)
54
+ * @returns {{ x: number, y: number, d: number, keepout?: number, thread: string, fit: string }}
55
+ */
56
+ export function mount(thread, x, y, o = {}) {
57
+ const what = 'mount', example = "mount('M2', 10, 5) or mount('M2', 10, 5, { fit: 'close' })";
58
+ if (o == null || typeof o !== 'object' || Array.isArray(o)) throw new Error(`${what}: the options are an object ({ fit, d, keepout }), not ${shown(o)}: ${example}`);
59
+ const known = ['fit', 'd', 'keepout', 'set', 'sets'], odd = Object.keys(o).filter((k) => !known.includes(k));
60
+ if (odd.length) throw new Error(`${what}: no option ${odd.map((k) => `"${k}"`).join(', ')} (there are ${known.join(', ')}): ${example}`);
61
+ for (const [k, n] of [['x', x], ['y', y]]) if (typeof n !== 'number' || !Number.isFinite(n)) throw new Error(`${what}: ${k} is a number, in mm in the board's frame (got ${shown(n)}): ${example}`);
62
+ const fit = o.fit ?? 'clearance';
63
+ if (!(fit in MOUNT_FITS)) throw new Error(`${what}: fit is ${Object.keys(MOUNT_FITS).join(', ')} (got ${shown(fit)})`);
64
+ if (o.keepout != null && !(typeof o.keepout === 'number' && o.keepout > 0)) throw new Error(`${what}: keepout is a radius above 0, in mm from the hole's centre (got ${shown(o.keepout)})`);
65
+ if (o.set != null && (typeof o.set !== 'object' || Array.isArray(o.set))) throw new Error(`${what}: set is the thread's figures as a design reads them (v.m2), not ${shown(o.set)}`);
66
+ let m;
67
+ try { m = fixingModel(thread, {}, { sets: o.sets }); } catch (e) { throw new Error(`${what}: ${String(e.message).replace(/^fixingModel: /, '')}`); } // (a name that is no thread, a thread with no rule set)
68
+ if (m.item !== 'thread') throw new Error(`${what}: name the thread alone ('${m.thread}'), not ${shown(thread)}: the hole is for any screw on it`);
69
+ if (o.set?.thread != null && String(o.set.thread) !== m.thread) throw new Error(`${what}: set is ${shown(o.set.thread)}'s figures, and the hole is for ${m.thread}`);
70
+ const figure = MOUNT_FITS[fit], own = o.set?.[figure], ruled = m.figures[figure]?.value;
71
+ let d;
72
+ if (o.d != null) {
73
+ if (!(typeof o.d === 'number' && o.d > 0)) throw new Error(`${what}: d is the hole's diameter, in mm, above 0 (got ${shown(o.d)})`);
74
+ if (o.d <= m.major) throw new Error(`${what}: a ${o.d} mm hole is no wider than ${m.thread}'s ${m.major} mm thread (${m.set}.major_diameter): the screw would not pass. ${m.thread}'s clearance hole is ${ruled ?? 'not in its rule set'}${ruled != null ? ' mm' : ''}`);
75
+ d = o.d;
76
+ } else {
77
+ d = typeof own === 'number' ? own : ruled;
78
+ if (typeof d !== 'number') throw new Error(`${what}: ${m.thread} has no ${figure} in its rule set (${m.set}): give the hole as d`);
79
+ }
80
+ return { ...hole(x, y, d), ...(o.keepout != null ? { keepout: o.keepout } : {}), thread: m.thread, fit: o.d != null ? 'given' : fit };
81
+ }
82
+
37
83
  // An MX switch, PCB mount: two pins, the centre post and the two fixing pegs
38
84
  export function mx(name, x, y, m, sch = {}) {
39
85
  return { name, ftype: 'simple_switch', mpn: 'Cherry MX (PCB mount)', package: 'Cherry MX, PCB mount', x, y, layer: 'top', sch,
@@ -59,9 +105,10 @@ export const picoGpio = (side) => Object.entries(loadRuleSet('pico').rules[`gpio
59
105
  // ---------- any board ----------
60
106
  // Parts for any board, not only keyboards. Each returns a part as circuit.mjs describes it: put them in board.parts, join
61
107
  // their pins with board.nets, and set board.autoroute. o (all optional): { rotation: 0 | 90 | 180 | 270, layer,
62
- // mpn, labels: { pin1: 'GND', ... }, sch: { x, y } }. Pin labels name the pins in nets ('U1.GND') and on the schematic.
108
+ // mpn, labels: { pin1: 'GND', ... }, sch: { x, y }, model: { boxes: [{ min, max }] } (its 3D body in its own frame, z up
109
+ // from the board's face, mm) }. Pin labels name the pins in nets ('U1.GND') and on the schematic.
63
110
  const chip = (name, x, y, o, more) => ({ name, ftype: 'simple_chip', x, y, layer: o.layer ?? 'top', rotation: o.rotation ?? 0, mpn: o.mpn, ...(o.package ? { package: o.package } : {}),
64
- courtyard: o.courtyard ?? null, sch: { x: o.sch?.x ?? x / 2, y: o.sch?.y ?? y / 2, pinLabels: o.labels ?? {} }, ...more });
111
+ courtyard: o.courtyard ?? null, sch: { x: o.sch?.x ?? x / 2, y: o.sch?.y ?? y / 2, pinLabels: o.labels ?? {} }, ...(o.model ? { model: o.model } : {}), ...more });
65
112
  const pinNo = (p) => Number(p.pin.replace(/\D/g, ''));
66
113
  // A rule set's pin map ({ "1": "GND", ... }) as pin labels ({ pin1: 'GND', ... })
67
114
  const labelsFrom = (set, rule) => Object.fromEntries(Object.entries(loadRuleSet(set).rules[rule].pins).map(([n, l]) => [`pin${n}`, l]));
@@ -140,7 +187,7 @@ export function fromLayout(list, pitch) {
140
187
  // under: the Pico on header pins under the board, components down, turned so its two rows of pins
141
188
  // lie in the gaps either side of key row mcu_row + 1, its USB out the mcu_side edge; the matrix is
142
189
  // drawn by rule and the connections to the Pico autorouted
143
- // mcu_gap, mcu_side, mcu_row, mount_holes (1: an M2 hole in each corner), thickness
190
+ // mcu_gap, mcu_side, mcu_row, mount_holes (1: an M2 hole in each corner, mount('M2'): m2.clearance), thickness
144
191
  // matrix: each key's row and column and the GPIO each row and column uses, for checks and firmware.
145
192
  // Lanes beside the Pico, nearest first: each runs from `from` to `to` (its pin's height) and then in to its pin,
146
193
  // across every lane nearer than it, so a lane may be given a nearer place only if its run covers none of the other
@@ -344,7 +391,7 @@ export function keyboard(v, keys) {
344
391
  ...(v.margin >= text * 2 ? [{ text: 'rulecad: diodes point to the rows', x: (keyBox.left + keyBox.right) / 2, y: bottom + v.margin / 2, size: text, layer: 'bottom' }] : [])];
345
392
  const board = { center: { x: cx, y: cy }, width: right - left, height: top - bottom, thickness: v.thickness, autoroute: under,
346
393
  silk_line: v.jlcpcb.silk_line, silk_text: v.jlcpcb.silk_text, via_hole: 0.3, via_pad: 0.3 + 2 * v.jlcpcb.annular, fab: v.jlcpcb, // (vias with the ring the fab recommends; the fab's minimums for the router)
347
- parts, traces, silk: marks, holes: corners.map(([x, y]) => hole(x, y, v.m2.clearance)) };
394
+ parts, traces, silk: marks, holes: corners.map(([x, y]) => mount('M2', x, y, { set: v.m2 })) }; // (the m2 rules' clearance hole, as the fab drills it)
348
395
  const matrix = {
349
396
  keys: keys.map((k) => ({ key: `K${k.n}`, ...(k.label ? { label: k.label } : {}), row: k.r, col: k.c })),
350
397
  rows: Object.fromEntries(rows.map((r) => [r, rowPin[r].gpio])), cols: Object.fromEntries(cols.map((c) => [c, colPin[c].gpio])),
@@ -517,6 +564,7 @@ export function fromKicadPcb(text) {
517
564
  const pad = { pin: name, x: r4(bottom ? -px : px), y: r4(-py), w: num(sz[1]), h: num(sz[2]), angle, smd: kind === 'smd', shape, net: kidOf(p, 'net')?.[2] || null };
518
565
  const ratio = kidOf(p, 'roundrect_rratio'); // rounded corners, as a share of the shorter side
519
566
  if (shape === 'roundrect' && ratio) pad.corner = r4(num(ratio[1]) * Math.min(pad.w, pad.h));
567
+ if (shape === 'oval' && pad.w !== pad.h) pad.corner = r4(Math.min(pad.w, pad.h) / 2); // an oval: round ends, a rectangle's corners rounded all the way
520
568
  if (drill) {
521
569
  const d = drill.slice(1), oval = d[0] === 'oval', ds = d.filter((x) => !Array.isArray(x) && x !== 'oval').map(num), off = kidOf(drill, 'offset');
522
570
  pad.hole = Math.min(...ds);
@@ -580,7 +628,7 @@ export function fromKicadPcb(text) {
580
628
  export function clone(circuit, o = {}) {
581
629
  const inner = (l) => /^In\d+\.Cu$/.test(l), layers = o.layers ?? circuit.layers ?? 2;
582
630
  const planes = o.planes ?? Object.entries(circuit.planes || {}).filter(([, ls]) => ls.some(inner)).map(([n]) => n);
583
- const notes = [], castellated = new Set(), oval = new Set();
631
+ const notes = [], castellated = new Set();
584
632
  const parts = circuit.parts.map((p) => {
585
633
  const quarterTurn = p.rotation % 90 === 0, t = (p.rotation * Math.PI) / 180, c = Math.cos(t), s = Math.sin(t);
586
634
  const pads = p.pads.map((q) => {
@@ -588,11 +636,10 @@ export function clone(circuit, o = {}) {
588
636
  if (!q.smd) {
589
637
  const at = quarterTurn ? { x: q.x, y: q.y } : { x: q.x * c - q.y * s, y: q.x * s + q.y * c };
590
638
  if (q.castellated) { castellated.add(p.ref); return { pin, hint: q.pin, ...at, hole: q.hole, outer: Math.min(q.w, q.h), castellated: true }; }
591
- if (q.hole_size) oval.add(p.ref); // a slot: drilled round, at its narrow width
592
639
  if (q.w === q.h && !q.hole_offset) return { pin, hint: q.pin, ...at, hole: q.hole, outer: q.w };
593
640
  // an oval pad, or a hole off its centre: a rounded rectangle round the hole, turned with the part (quarter turns)
594
641
  const sw = (q.angle + (quarterTurn ? 0 : p.rotation)) % 180 === 90, w = sw ? q.h : q.w, h = sw ? q.w : q.h;
595
- return { pin, hint: q.pin, ...at, hole: q.hole, outer: Math.min(w, h), rect: { w, h, offset: q.hole_offset || [0, 0] } };
642
+ return { pin, hint: q.pin, ...at, hole: q.hole, outer: Math.min(w, h), rect: { w, h, offset: q.hole_offset || [0, 0], ...(q.hole_size ? { slot: sw ? [q.hole_size[1], q.hole_size[0]] : q.hole_size } : {}) } }; // (slot: a slotted hole's width and height)
596
643
  }
597
644
  const turn = q.angle + (quarterTurn ? 0 : p.rotation);
598
645
  if (turn % 90 === 0) { // a rectangle, its sides swapped by a quarter turn of its own
@@ -624,7 +671,6 @@ export function clone(circuit, o = {}) {
624
671
  if (layers >= 4 && Object.keys(onPlanes).length) notes.push(`planes on inner layers: ${Object.entries(onPlanes).map(([n, q]) => `${n} on ${q.layer} (${q.pins.length} pads)`).join(', ')}`);
625
672
  else if (planes.length) notes.push(`left to planes, not routed: ${planes.map((n) => `${n} (${circuit.nets[n]?.length ?? 0} pads)`).join(', ')}. On 2 layers these nets need a pour joined to every pad: build the board with 4 layers ({ layers: 4 }) to give them planes`);
626
673
  if (castellated.size) notes.push(`castellated pads on ${plural(castellated, 'part', 'parts')}: half holes on the board's edge, which the fab cuts through (an option when ordering)`);
627
- if (oval.size) notes.push(`slots drilled round, at their narrow width, on ${plural(oval, 'part', 'parts')}`);
628
674
  if (dropped.size) notes.push(`${dropped.size} pins with no pad left on this board are out of their nets: ${[...dropped].slice(0, 5).join(', ')}`);
629
675
  const src = circuit.source || {}; // the source's via and clearance, which its layout was made to
630
676
  const sizes = { ...(src.via ? { via_pad: src.via.pad, via_hole: src.via.hole } : {}), ...(src.clearance ? { plane_clearance: src.clearance } : {}) };
@@ -1089,6 +1135,37 @@ export const holes = (json) => json.filter((e) => e.type === 'pcb_hole' && !e.pc
1089
1135
  const mm = (x) => String(Number(x.toFixed(3))); // 0.30000000000000004 reads as 0.3
1090
1136
  // checks(json, v, matrix, source) -> findings ({ level, text }): tscircuit's own design checks, the fab's limits, the
1091
1137
  // matrix, and for a clone (source: { circuit, arranged }) the source's circuit and placement
1138
+ export { viaHoleGaps }; // (in circuit.mjs, which repairs by it)
1139
+
1140
+ // A source board's nearest track to its edge, copper to edge (mm): what its own layout allows there
1141
+ export function sourceEdgeGap(circuit) {
1142
+ const edges = [circuit.outline, ...(circuit.cutouts || [])].filter((o) => o?.length).flatMap((o) => o.map((p, i) => [p, o[(i + 1) % o.length]]));
1143
+ const ps = (p, a, b) => { const dx = b.x - a.x, dy = b.y - a.y, l = dx * dx + dy * dy, t = l ? Math.max(0, Math.min(1, ((p.x - a.x) * dx + (p.y - a.y) * dy) / l)) : 0; return Math.hypot(p.x - a.x - t * dx, p.y - a.y - t * dy); };
1144
+ const gaps = (circuit.routing?.tracks || []).map((g) => Math.min(...edges.map(([a, b]) => Math.min(ps(g.a, a, b), ps(g.b, a, b), ps(a, g.a, g.b), ps(b, g.a, g.b)))) - g.width / 2);
1145
+ return gaps.length && edges.length ? Math.min(...gaps) : null;
1146
+ }
1147
+
1148
+ // The rules KiCad checks a board by: its own clearance, and a clone's pads by the edge where the source has them
1149
+ // (inherited: the design-rule errors already said to be the source's)
1150
+ function kicadRules(json, inherited) {
1151
+ const edgeExempt = [...new Set(inherited.map((e) => e.message?.match(/^SMT pad (\w+)\./)?.[1]).filter(Boolean))].map((ref) => ({ ref, edge: 0 }));
1152
+ return { clearance: json.find((e) => e.type === 'pcb_board')?.min_trace_to_pad_edge_clearance, edgeExempt };
1153
+ }
1154
+ // A KiCad finding that is the source's own: a kept track by the edge no nearer than the source's nearest (KiCad's place
1155
+ // is 100 mm in, y down)
1156
+ function kicadSourceEdge(json, source) {
1157
+ const srcEdge = source?.circuit ? sourceEdgeGap(source.circuit) : null;
1158
+ const keptSegs = json.filter((e) => e.type === 'pcb_trace' && e.rulecad_kept).flatMap((t) => t.route.slice(1).map((q, i) => [t.route[i], q]));
1159
+ const onKept = (pos) => keptSegs.some(([a, b]) => { const p = { x: pos.x - 100, y: 100 - pos.y }, dx = b.x - a.x, dy = b.y - a.y, l = dx * dx + dy * dy, t = l ? Math.max(0, Math.min(1, ((p.x - a.x) * dx + (p.y - a.y) * dy) / l)) : 0; return Math.hypot(p.x - a.x - t * dx, p.y - a.y - t * dy) < 0.02; });
1160
+ return (x) => x.type === 'copper_edge_clearance' && srcEdge != null && x.items.some((i) => /^Track /.test(i.description) && onKept(i.pos)) && Number(x.description.match(/actual ([\d.]+) mm/)?.[1]) >= srcEdge - 1e-3;
1161
+ }
1162
+ // The design-rule errors a clone has where its source has them, for kicadRules
1163
+ async function sourceErrors(json, source) {
1164
+ if (!source?.circuit) return [];
1165
+ const { runAllChecks } = await import('@tscircuit/checks'), same = asSource(json, source.circuit, source.arranged?.kept);
1166
+ return (await runAllChecks(structuredClone(json))).filter((e) => same(e));
1167
+ }
1168
+
1092
1169
  export async function checks(json, v, matrix, source) { // source: a clone's { circuit, arranged } (its own checks join these)
1093
1170
  const { runAllChecks } = await import('@tscircuit/checks');
1094
1171
  const out = [], j = v.jlcpcb;
@@ -1106,8 +1183,15 @@ export async function checks(json, v, matrix, source) { // source: a clone's { c
1106
1183
  // A clone's pads as close to the edge as the source has them, and parts that reach past it as they do there, are the
1107
1184
  // source's design (a mid-mount socket in its notch): said, not failed. Anything else near the edge fails as usual
1108
1185
  const inherited = [], same = source?.circuit ? asSource(json, source.circuit, source.arranged?.kept) : null, planeNames = new Set(json.filter((e) => e.type === 'source_net').map((e) => e.name));
1186
+ // A clone's own kept tracks as near the edge as the source's own come (its tracks by its USB-C notch): the source's
1187
+ // nearest track to its edge, copper to edge, measured on the source
1188
+ const srcEdge = source?.circuit ? sourceEdgeGap(source.circuit) : null, keptIds = new Set(json.filter((e) => e.type === 'pcb_trace' && e.rulecad_kept).map((e) => e.pcb_trace_id));
1189
+ const keptByEdge = (e) => { const m = e.message?.match(/^Trace too close to board edge \(([\d.]+)mm/), id = JSON.stringify(e).match(/pcb_trace_\d+/)?.[0];
1190
+ if (!m || srcEdge == null || !keptIds.has(id)) return false;
1191
+ const t = json.find((x) => x.pcb_trace_id === id), w = Math.max(...t.route.map((q) => q.width ?? 0));
1192
+ return Number(m[1]) - w / 2 >= srcEdge - 1e-3; };
1109
1193
  const drc = (await runAllChecks(json)).filter((e) => !(e.type === 'pcb_component_outside_board_error' && fits(e.pcb_component_id)) && !onEdge(e))
1110
- .filter((e) => !(same?.(e) && inherited.push(e)))
1194
+ .filter((e) => !((same?.(e) || keptByEdge(e)) && inherited.push(e)))
1111
1195
  .filter((e) => !(planeNames.has(e.message?.match(/is not connected to net \[(.+)\] by a PCB trace/)?.[1]))); // planes join these: checked below, pad by pad
1112
1196
  const problems = [...json, ...drc].filter((e) => /_error$/.test(e.type));
1113
1197
  const seen = new Set(), errors = problems.filter((e) => !seen.has(e.message) && seen.add(e.message));
@@ -1183,17 +1267,32 @@ export async function checks(json, v, matrix, source) { // source: a clone's { c
1183
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)
1184
1268
  if (broken.length) out.push({ level: 'fail', text: `the board can't be made as drawn: ${broken.join('; ')}` });
1185
1269
  // Vias and plated holes against the fab's sizes, each measured from the board: the hole, the pad, and the ring
1186
- // between them (under the recommended ring a warning, under the least a failure). A clone's vias as its source
1270
+ // between them (under the recommended ring a warning, under the least a failure). A via's ring and a plated hole's
1271
+ // have their own figures (JLCPCB asks a via's pad only 0.1 mm wider than its hole). A clone's vias as its source
1187
1272
  // has them are the source's design: said, not failed
1188
1273
  const srcVia = source?.circuit?.via, asSrc = (e) => srcVia && Math.abs(e.hole_diameter - srcVia.hole) < 1e-6 && Math.abs(e.outer_diameter - srcVia.pad) < 1e-6;
1189
- const rings = json.filter((e) => e.type === 'pcb_via' || (e.type === 'pcb_plated_hole' && e.outer_diameter != null && e.hole_diameter != null)).map((e) => ({ e, ring: (e.outer_diameter - e.hole_diameter) / 2, via: e.type === 'pcb_via' }));
1190
- const least = j.annular_min ?? 0.18, badVias = rings.filter((r) => r.via && !asSrc(r.e) && (r.e.hole_diameter < j.via_hole || r.e.outer_diameter < j.via_pad)), thinRings = rings.filter((r) => !asSrc(r.e) && r.ring < least), smallRings = rings.filter((r) => !asSrc(r.e) && r.ring >= least && r.ring < j.annular);
1191
- const inherited_ = rings.filter((r) => asSrc(r.e) && r.ring < j.annular).length;
1274
+ // (a plated hole sharing its pin with a surface pad of its part is a via in that pad, such as a chip's thermal vias
1275
+ // under its exposed pad: a via's figures)
1276
+ const padPins = new Set(json.filter((e) => e.type === 'pcb_smtpad').map((e) => `${e.pcb_component_id}:${e.port_hints?.[0]}`));
1277
+ const inPad = (e) => e.type === 'pcb_plated_hole' && e.port_hints?.slice(1).some((h) => padPins.has(`${e.pcb_component_id}:${String(h).replace(/^pin/, '')}`));
1278
+ const rings = json.filter((e) => e.type === 'pcb_via' || (e.type === 'pcb_plated_hole' && e.outer_diameter != null && e.hole_diameter != null)).map((e) => ({ e, ring: (e.outer_diameter - e.hole_diameter) / 2, via: e.type === 'pcb_via' || inPad(e) }));
1279
+ const leastOf = (r) => (r.via ? j.via_annular_min ?? j.annular_min ?? 0.18 : j.annular_min ?? 0.18), wantOf = (r) => (r.via ? j.via_annular ?? j.annular : j.annular);
1280
+ const badVias = rings.filter((r) => r.via && !asSrc(r.e) && (r.e.hole_diameter < j.via_hole || r.e.outer_diameter < j.via_pad)), thinRings = rings.filter((r) => !asSrc(r.e) && r.ring < leastOf(r) - 1e-9), smallRings = rings.filter((r) => !asSrc(r.e) && r.ring >= leastOf(r) - 1e-9 && r.ring < wantOf(r) - 1e-9);
1281
+ const inherited_ = rings.filter((r) => asSrc(r.e) && r.ring < wantOf(r)).length, kind = (list) => (list.every((r) => r.via) ? 'vias' : list.every((r) => !r.via) ? 'plated holes' : 'vias and plated holes');
1282
+ const least = (list) => mm(Math.min(...list.map((r) => r.ring))), figures = (list) => [...new Set(list.map((r) => (r.via ? 'vias' : 'plated holes')))].map((k) => k === 'vias' ? `${j.via_annular_min ?? j.annular_min} mm for vias` : `${j.annular_min} mm for plated holes`).join(', ');
1192
1283
  if (rings.length) {
1193
1284
  out.push(badVias.length ? { level: 'fail', text: `${badVias.length} vias under JLCPCB's ${j.via_hole} mm hole in a ${j.via_pad} mm pad (${mm(badVias[0].e.hole_diameter)} in ${mm(badVias[0].e.outer_diameter)})` }
1194
- : thinRings.length ? { level: 'fail', text: `${thinRings.length} ${thinRings[0].via ? 'vias' : 'plated holes'} with a ${mm(Math.min(...thinRings.map((r) => r.ring)))} mm ring, under JLCPCB's least of ${least} mm` }
1195
- : smallRings.length ? { level: 'warn', text: `${smallRings.length} ${smallRings.every((r) => r.via) ? 'vias' : 'plated holes'} with a ${mm(Math.min(...smallRings.map((r) => r.ring)))} mm ring: above JLCPCB's least of ${least} mm, under the ${j.annular} mm it recommends` }
1196
- : { level: 'pass', text: `${rings.filter((r) => r.via).length} vias and ${rings.filter((r) => !r.via).length} plated holes, rings ${mm(Math.min(...rings.map((r) => r.ring)))} mm or more (JLCPCB recommends ${j.annular})${inherited_ ? `; ${inherited_} as the source has them` : ''}` });
1285
+ : thinRings.length ? { level: 'fail', text: `${thinRings.length} ${kind(thinRings)} with a ${least(thinRings)} mm ring, under JLCPCB's least (${figures(thinRings)})` }
1286
+ : smallRings.length ? { level: 'warn', text: `${smallRings.length} ${kind(smallRings)} with a ${least(smallRings)} mm ring: above JLCPCB's least, under what it recommends (${[...new Set(smallRings.map((r) => (r.via ? `${j.via_annular ?? j.annular} mm for vias` : `${j.annular} mm for plated holes`)))].join(', ')})` }
1287
+ : { level: 'pass', text: `${rings.filter((r) => r.via).length} vias (rings ${rings.some((r) => r.via) ? least(rings.filter((r) => r.via)) : '-'} mm or more) and ${rings.filter((r) => !r.via).length} plated holes (${rings.some((r) => !r.via) ? least(rings.filter((r) => !r.via)) : '-'} mm or more): JLCPCB recommends ${j.via_annular ?? j.annular} and ${j.annular}${inherited_ ? `; ${inherited_} as the source has them` : ''}` });
1288
+ }
1289
+ // A via's hole to a track of another net (JLCPCB measures it from the hole's edge, not the via's pad: a small via's
1290
+ // thin ring leaves less room than the copper clearance suggests)
1291
+ if (j.via_hole_track && json.some((e) => e.type === 'pcb_via')) {
1292
+ const close = viaHoleGaps(json).filter((g) => g.gap < j.via_hole_track - 1e-6);
1293
+ const own = close.filter((g) => !(g.kept && asSrc(g.via)));
1294
+ out.push(own.length ? { level: 'fail', text: `${own.length} tracks closer than JLCPCB's ${j.via_hole_track} mm to a via's hole (${mm(Math.min(...own.map((g) => g.gap)))} mm at ${mm(own[0].at.x)}, ${mm(own[0].at.y)})` }
1295
+ : { level: 'pass', text: `every via's hole ${j.via_hole_track} mm or more from tracks of other nets${close.length ? `, but ${close.length} as the source has them` : ''}` });
1197
1296
  }
1198
1297
  // Silkscreen the fab can print: lines no thinner than silk_line, text no smaller than silk_text
1199
1298
  const silkLines = json.filter((e) => (e.type === 'pcb_silkscreen_path' || e.type === 'pcb_silkscreen_rect' || e.type === 'pcb_silkscreen_line' || e.type === 'pcb_silkscreen_circle') && e.stroke_width != null && e.stroke_width < j.silk_line);
@@ -1226,6 +1325,20 @@ export async function checks(json, v, matrix, source) { // source: a clone's { c
1226
1325
  ? { 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(' ')})` }
1227
1326
  : { level: 'fail', text: 'matrix: two keys share a row and column, or a GPIO is used twice' });
1228
1327
  }
1328
+ // KiCad's own design-rule check, when KiCad is installed: the board as KiCad reads it, its planes poured by KiCad. A
1329
+ // clone's pads by the edge where the source has them are allowed there, as in our checks
1330
+ const { kicadDrc } = await import('./kicad.mjs');
1331
+ const kicad = await kicadDrc(json, kicadRules(json, inherited)).catch((e) => ({ failed: e }));
1332
+ if (!kicad) out.push({ level: 'info', text: 'KiCad isn\'t installed: its design-rule check, a second opinion, skipped' });
1333
+ else if (kicad.failed) out.push({ level: 'warn', text: `KiCad's design-rule check didn't run: ${String(kicad.failed.message || kicad.failed).split('\n')[0]}` });
1334
+ else {
1335
+ const asSrcEdge = kicadSourceEdge(json, source), srcEdgeHits = kicad.errors.filter(asSrcEdge);
1336
+ kicad.errors = kicad.errors.filter((x) => !asSrcEdge(x));
1337
+ if (srcEdgeHits.length) inherited.push(...srcEdgeHits.map((x) => ({ message: `KiCad: ${x.description}` })));
1338
+ const by = (list) => Object.entries(list.reduce((m, x) => ((m[x.type.replace(/_/g, ' ')] = (m[x.type.replace(/_/g, ' ')] || 0) + 1), m), {})).map(([t, n]) => `${n} ${t}`).join(', ');
1339
+ out.push(kicad.errors.length ? { level: 'fail', text: `KiCad ${kicad.version}'s design-rule check: ${kicad.errors.length} errors (${by(kicad.errors)}); first: ${kicad.errors[0].description}` }
1340
+ : { level: 'pass', text: `KiCad ${kicad.version}'s design-rule check, its own planes poured: no errors${kicad.warnings.length ? ` (warnings: ${by(kicad.warnings)})` : ''}` });
1341
+ }
1229
1342
  if (inherited.length) out.push({ level: 'info', text: `as the source has them, so not failed: ${[...new Set(inherited.map((e) => e.message.replace(/ \(.*$/, '').replace(/\. Try moving.*$/, '')))].slice(0, 4).join('; ')}${inherited.length > 4 ? ` (${inherited.length} in all)` : ''}` });
1230
1343
  if (source?.circuit) out.push(...sameCircuit(json, source.circuit, {}, source.arranged?.added || []), ...placementChecks(source.arranged || source.circuit, source.circuit.placement || learnPlacement(source.circuit)));
1231
1344
  const notes = new Set([...json, ...drc].filter((e) => /_warning$/.test(e.type)).map((e) => e.type.replace(/^(source|pcb)_|_warning$/g, '').replace(/_/g, ' ')));
@@ -1292,7 +1405,17 @@ function planeChecks(json) {
1292
1405
  // ---------- files ----------
1293
1406
  // The fab files: Gerbers (KiCad's Protel names, which JLCPCB reads), drill files, BOM and placement -> { name: text }
1294
1407
  const PROTEL = { F_Cu: 'GTL', B_Cu: 'GBL', F_Mask: 'GTS', B_Mask: 'GBS', F_SilkScreen: 'GTO', B_SilkScreen: 'GBO', F_Paste: 'GTP', B_Paste: 'GBP', Edge_Cuts: 'GKO' };
1295
- export async function fabFiles(json, name) {
1408
+ export async function fabFiles(json, name, { source } = {}) {
1409
+ // Rounded pads and slots are more than the Gerber writer draws: it plots a rounded pad square, so its corners reach
1410
+ // into a plane cut round the true shape, and it can't drill a slot. KiCad plots those boards, and checks the very copper
1411
+ // it plots first; without KiCad they aren't made at all
1412
+ const { kicadFab, needsKicadFab } = await import('./kicad.mjs');
1413
+ if (needsKicadFab(json)) {
1414
+ const made = await kicadFab(json, name, { ...kicadRules(json, await sourceErrors(json, source)), allow: kicadSourceEdge(json, source) });
1415
+ if (!made) throw new Error('this board has slotted holes, or rounded pads beside a copper plane: its fab files need KiCad (install it, or name kicad-cli in KICAD_CLI)');
1416
+ const { convertCircuitJsonToPickAndPlaceCsv } = await import('circuit-json-to-pnp-csv');
1417
+ return { ...made, [`${name}-bom.csv`]: bom(json), [`${name}-cpl.csv`]: convertCircuitJsonToPickAndPlaceCsv(json) };
1418
+ }
1296
1419
  const { convertSoupToGerberCommands, stringifyGerberCommandLayers, convertSoupToExcellonDrillCommands, stringifyExcellonDrill } = await import('circuit-json-to-gerber');
1297
1420
  const { convertCircuitJsonToPickAndPlaceCsv } = await import('circuit-json-to-pnp-csv');
1298
1421
  const out = {};
@@ -1320,11 +1443,15 @@ function bom(json) {
1320
1443
  }
1321
1444
 
1322
1445
  // KiCad's own files, to check with kicad-cli or finish by hand: { 'name.kicad_pcb': text, 'name.kicad_sch': text }
1323
- export async function kicadFiles(json, name) {
1446
+ export async function kicadFiles(json, name, { clearance, track, edgeExempt: exempt, source } = {}) {
1447
+ const edgeExempt = exempt ?? kicadRules(json, await sourceErrors(json, source)).edgeExempt;
1324
1448
  const { CircuitJsonToKicadPcbConverter, CircuitJsonToKicadSchConverter } = await import('circuit-json-to-kicad');
1325
- const pcb = new CircuitJsonToKicadPcbConverter(json); pcb.runUntilFinished();
1449
+ const { kicadNets, patchKicadPcb, kicadProject } = await import('./kicad.mjs');
1450
+ const netted = kicadNets(json); // (see kicad.mjs: what the converter leaves out, made up)
1451
+ const pcb = new CircuitJsonToKicadPcbConverter(netted); pcb.runUntilFinished();
1326
1452
  const sch = new CircuitJsonToKicadSchConverter(json); sch.runUntilFinished();
1327
- return { [`${name}.kicad_pcb`]: pcb.getOutputString(), [`${name}.kicad_sch`]: sch.getOutputString() };
1453
+ const { pro, dru } = kicadProject(netted, { clearance, track, edgeExempt });
1454
+ return { [`${name}.kicad_pcb`]: patchKicadPcb(pcb.getOutputString(), netted), [`${name}.kicad_sch`]: sch.getOutputString(), [`${name}.kicad_pro`]: pro, [`${name}.kicad_dru`]: dru };
1328
1455
  }
1329
1456
 
1330
1457
  // The 2D views for the model page, as SVG drawings: [[name, svg]]. "Group: view" names group into one tab with a