@rulecad/pcb 0.3.6 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (4) hide show
  1. package/README.md +78 -2
  2. package/circuit.mjs +627 -53
  3. package/package.json +3 -1
  4. package/pcb.mjs +812 -33
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 } from './circuit.mjs';
16
+ import { circuitJson, bounds, smtBounds, slideClear } from './circuit.mjs';
17
17
  export { bounds };
18
18
  import { loadRuleSet } from '@rulecad/cad/rules';
19
19
  import jscad from '@jscad/modeling';
@@ -138,6 +138,18 @@ export function fromLayout(list, pitch) {
138
138
  // drawn by rule and the connections to the Pico autorouted
139
139
  // mcu_gap, mcu_side, mcu_row, mount_holes (1: an M2 hole in each corner), thickness
140
140
  // matrix: each key's row and column and the GPIO each row and column uses, for checks and firmware.
141
+ // Lanes beside the Pico, nearest first: each runs from `from` to `to` (its pin's height) and then in to its pin,
142
+ // across every lane nearer than it, so a lane may be given a nearer place only if its run covers none of the other
143
+ // lanes' pins. { id: place }, 0 the nearest. (When no lane qualifies, the shortest run takes the place: the checks say)
144
+ export function laneOrder(lanes) {
145
+ const out = {}, left = [...lanes], covers = (l, y) => y > Math.min(l.from, l.to) - 1e-9 && y < Math.max(l.from, l.to) + 1e-9;
146
+ for (let place = 0; left.length; place++) {
147
+ const next = left.find((l) => left.every((o) => o === l || !covers(l, o.to))) ?? [...left].sort((a, b) => Math.abs(a.to - a.from) - Math.abs(b.to - b.from))[0];
148
+ out[next.id] = place; left.splice(left.indexOf(next), 1);
149
+ }
150
+ return out;
151
+ }
152
+
141
153
  export function keyboard(v, keys) {
142
154
  const m = v.mx, p = v.pico, d = v.sod123, lane = v.track + v.clear, half = m.pitch / 2, under = v.controller === 'under';
143
155
  const rows = [...new Set(keys.map((k) => k.r))].sort((a, b) => a - b), cols = [...new Set(keys.map((k) => k.c))].sort((a, b) => a - b);
@@ -183,7 +195,10 @@ export function keyboard(v, keys) {
183
195
  pinRows.push({ gap, y: ys, xs, keep });
184
196
  }
185
197
  } else {
186
- const cx = keyBox.right + v.mcu_gap + p.width / 2, cy = (keyBox.top + keyBox.bottom) / 2;
198
+ // Beside the keys, mcu_gap off them, or further out when the lanes to its pins (one a column on the front, one a
199
+ // row on the back, a lane apart) wouldn't fit between the keys and its pins
200
+ const lanesWide = Math.max(cols.length, rows.length) * lane, pinsIn = p.width / 2 + picoPin(1, p).x - p.pin_pad / 2 - v.clear - v.track / 2; // the left pins' near edge and clearance, in from the Pico's edge
201
+ const cx = keyBox.right + Math.max(v.mcu_gap, lanesWide + v.clear - pinsIn) + p.width / 2, cy = (keyBox.top + keyBox.bottom) / 2;
187
202
  pinAt = (n) => { const q = picoPin(n, p); return { x: cx + q.x, y: cy + q.y }; };
188
203
  pico0 = { x: cx, y: cy };
189
204
  right = cx + p.width / 2 + v.margin;
@@ -267,25 +282,40 @@ export function keyboard(v, keys) {
267
282
  traces.push({ from: near.sel, to: ['U1', `pin${best.g.pin}`], width: v.track }); // no path: the autorouter's
268
283
  }
269
284
  } else {
270
- // Beside: rows take the free left-edge pins nearest their row line, columns the lowest of the rest; every track
271
- // drawn: rows right then up or down a lane beside the Pico (back), columns below the keys and up a lane (front),
272
- // the leftmost column lowest and nearest the Pico, so no two cross
285
+ // Beside: rows take the free left-edge pins nearest their row lines, top row first and each below the last's
286
+ // (so none cross), columns the pins nearest the lanes' depth below the keys. Every track drawn: a row right along
287
+ // its line then up or down a lane beside the Pico (back copper) to its pin's height and in; a column down below
288
+ // the keys, right, and up or down a lane (front) to its pin's height and in. Each lane runs in to its pin across
289
+ // the lanes nearer the Pico, so those must end before it: lanes are given out nearest first to whichever would
290
+ // cross none of the rest (laneOrder), and the depths below the keys the same way
273
291
  const nearPins = pinAt(1).x - p.pin_pad / 2 - v.clear - v.track / 2, free = picoGpio('left'), take = (pin) => free.splice(free.findIndex((g) => g.pin === pin), 1)[0];
274
- for (const r of rows) {
275
- const y = rowY(r) + lineY, best = [...free].sort((a, b) => Math.abs(pinAt(a.pin).y - y) - Math.abs(pinAt(b.pin).y - y))[0];
292
+ let above = Infinity; // the last row's pin: the next row's is below it, leaving enough below for the rest
293
+ rows.forEach((r, i) => {
294
+ const y = rowY(r) + lineY, rest = rows.length - 1 - i;
295
+ const best = free.filter((g) => pinAt(g.pin).y < above && free.filter((o) => pinAt(o.pin).y < pinAt(g.pin).y).length >= rest).sort((a, b) => Math.abs(pinAt(a.pin).y - y) - Math.abs(pinAt(b.pin).y - y))[0];
276
296
  if (!best) throw new Error(`the Pico's left edge has no GPIO left for row ${r}`);
277
- rowPin[r] = take(best.pin);
278
- }
279
- const lowest = [...free].sort((a, b) => pinAt(a.pin).y - pinAt(b.pin).y);
280
- if (lowest.length < cols.length) throw new Error(`${cols.length} columns need ${cols.length} more GPIO on the Pico's left edge; ${lowest.length} are left`);
281
- cols.forEach((c, i) => { colPin[c] = lowest[i]; });
297
+ rowPin[r] = take(best.pin); above = pinAt(best.pin).y;
298
+ });
299
+ // The columns' pins: the nearest to the runs below the keys, all above them or all below (lanes up or lanes
300
+ // down, not both: their runs would cross each other's lanes), above when there are enough
301
+ const depthLine = keyBox.bottom - (cols.length + 1) / 2 * lane;
302
+ const byDepth = (list) => [...list].sort((a, b) => Math.abs(pinAt(a.pin).y - depthLine) - Math.abs(pinAt(b.pin).y - depthLine));
303
+ const over = free.filter((g) => pinAt(g.pin).y > depthLine), belowLine = free.filter((g) => pinAt(g.pin).y <= depthLine);
304
+ const nearDepth = byDepth(over.length >= cols.length ? over : belowLine.length >= cols.length ? belowLine : free);
305
+ if (nearDepth.length < cols.length) throw new Error(`${cols.length} columns need ${cols.length} more GPIO on the Pico's left edge; ${nearDepth.length} are left`);
306
+ cols.forEach((c, i) => { colPin[c] = nearDepth[i]; });
307
+ const rowLane = laneOrder(rows.map((r) => ({ id: r, from: rowY(r) + lineY, to: pinAt(rowPin[r].pin).y })));
282
308
  for (const r of rows) {
283
- const last = keys.filter((k) => k.r === r).sort((a, b) => a.x - b.x).at(-1), pinY = pinAt(rowPin[r].pin).y;
309
+ const last = keys.filter((k) => k.r === r).sort((a, b) => a.x - b.x).at(-1), pinY = pinAt(rowPin[r].pin).y, laneX = nearPins - rowLane[r] * lane;
284
310
  traces.push({ from: [`D${last.n}`, 'cathode'], to: ['U1', `pin${rowPin[r].pin}`], width: v.track,
285
- path: pts([[last.x + cathodeX, last.y + lineY], [nearPins - lane, last.y + lineY], [nearPins - lane, pinY]]) });
311
+ path: pts([[last.x + cathodeX, last.y + lineY], [laneX, last.y + lineY], [laneX, pinY]]) });
286
312
  }
287
- cols.forEach((c, i) => {
288
- const last = keys.filter((k) => k.c === c).sort((a, b) => b.r - a.r)[0], depth = keyBox.bottom - (cols.length - i) * lane, laneX = nearPins - i * lane;
313
+ // The depths: a lane's run below the keys crosses the lanes further out on its way in, so where their pins are
314
+ // above the runs the nearer lane runs deeper (and ends lower), where below, shallower
315
+ const pinsAbove = cols.filter((c) => pinAt(colPin[c].pin).y > depthLine).length >= cols.length / 2;
316
+ const colLane = laneOrder(cols.map((c) => ({ id: c, from: depthLine, to: pinAt(colPin[c].pin).y })));
317
+ cols.forEach((c) => {
318
+ const last = keys.filter((k) => k.c === c).sort((a, b) => b.r - a.r)[0], i = colLane[c], depth = keyBox.bottom - (pinsAbove ? cols.length - i : i + 1) * lane, laneX = nearPins - i * lane;
289
319
  traces.push({ from: [`K${last.n}`, 'pin2'], to: ['U1', `pin${colPin[c].pin}`], width: v.track,
290
320
  path: pts([[last.x + jogX, last.y + m.pcb_pin2_y - slant], [last.x + jogX, depth], [laneX, depth], [laneX, pinAt(colPin[c].pin).y]]) });
291
321
  });
@@ -309,6 +339,7 @@ export function keyboard(v, keys) {
309
339
  ...keys.map((k) => rect(k.x + cathodeX + d.pad_w / 2 + silk * 2, k.y + diode.y, silk, d.pad_h, 'bottom')),
310
340
  ...(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' }] : [])];
311
341
  const board = { center: { x: cx, y: cy }, width: right - left, height: top - bottom, thickness: v.thickness, autoroute: under,
342
+ silk_line: v.jlcpcb.silk_line, silk_text: v.jlcpcb.silk_text, via_hole: 0.3, via_pad: 0.3 + 2 * v.jlcpcb.annular, // (vias with the ring the fab recommends)
312
343
  parts, traces, silk: marks, holes: corners.map(([x, y]) => hole(x, y, v.m2.clearance)) };
313
344
  const matrix = {
314
345
  keys: keys.map((k) => ({ key: `K${k.n}`, ...(k.label ? { label: k.label } : {}), row: k.r, col: k.c })),
@@ -354,6 +385,616 @@ export function footprint(name, data, x, y, o = {}) {
354
385
  return chip(name, x, y, { courtyard: data.courtyard, mpn: data.mpn, labels: data.labels, ...o }, { pads });
355
386
  }
356
387
 
388
+ // ---------- whole boards from KiCad: clones ----------
389
+ // A published board (a .kicad_pcb, KiCad 6 or later) read as a circuit: its parts with their pads, its nets, its planes and
390
+ // its outline. Keep the result in a rule set's "circuit" (cad clone writes it, with the source and its licence), and
391
+ // build boards from it with clone(): the circuit stays the source's, and the layout is redrawn by rules. sameCircuit()
392
+ // checks that a board still joins exactly the pins the source joins.
393
+
394
+ // KiCad's files are S-expressions: (name value (child ...) ...) as nested arrays, strings unquoted
395
+ function sexpr(text) {
396
+ const stack = [[]];
397
+ for (const t of text.match(/"(?:[^"\\]|\\.)*"|\(|\)|[^\s()"]+/g) || []) {
398
+ if (t === '(') stack.push([]);
399
+ else if (t === ')') { const l = stack.pop(); if (!stack.length) throw new Error('not a KiCad file: a ")" closes nothing'); stack.at(-1).push(l); }
400
+ else stack.at(-1).push(t[0] === '"' ? t.slice(1, -1).replace(/\\(.)/g, '$1') : t);
401
+ }
402
+ if (stack.length !== 1) throw new Error('not a KiCad file: a "(" is never closed');
403
+ return stack[0][0];
404
+ }
405
+ const kidsOf = (l, name) => l.filter((c) => Array.isArray(c) && c[0] === name);
406
+ const kidOf = (l, name) => kidsOf(l, name)[0];
407
+ const r4 = (n) => Math.round(n * 1e4) / 1e4 || 0; // 0.1 mm to the micron, and never -0
408
+ const turnOf = (deg) => ((Math.round(deg * 1e3) / 1e3 % 360) + 360) % 360;
409
+
410
+ // Edge.Cuts pieces ({ a, b } lines, arcs already cut into lines) joined end to end into closed loops
411
+ function loops(pieces, tol = 0.005) {
412
+ const same = (p, q) => Math.abs(p.x - q.x) < tol && Math.abs(p.y - q.y) < tol, out = [], left = [...pieces];
413
+ while (left.length) {
414
+ const loop = [left[0].a, left[0].b]; left.shift();
415
+ for (let found = true; found && !same(loop[0], loop.at(-1));) {
416
+ found = false;
417
+ for (let i = 0; i < left.length; i++) {
418
+ const s = left[i], end = loop.at(-1);
419
+ if (same(s.a, end) || same(s.b, end)) { loop.push(same(s.a, end) ? s.b : s.a); left.splice(i, 1); found = true; break; }
420
+ }
421
+ }
422
+ if (same(loop[0], loop.at(-1)) && loop.length > 3) out.push(loop.slice(0, -1));
423
+ else return null; // an open edge: the outline isn't one closed shape
424
+ }
425
+ return out;
426
+ }
427
+ const area = (pts) => pts.reduce((s, p, i) => { const q = pts[(i + 1) % pts.length]; return s + p.x * q.y - q.x * p.y; }, 0) / 2;
428
+
429
+ // The source's own tracks and vias, with their nets, in the circuit's frame: { tracks: [{ a, b, width, layer, net }],
430
+ // vias: [{ x, y, pad, hole, net }] }. Layers as boards here name them (top, inner1, ..., bottom)
431
+ function sourceCopper(root, to) {
432
+ const names = new Map(kidsOf(root, 'net').map((n) => [n[1], n[2]])), layer = (l) => (l === 'F.Cu' ? 'top' : l === 'B.Cu' ? 'bottom' : `inner${l.match(/\d+/)[0]}`);
433
+ const pt = (l) => to({ x: Number(l[1]), y: Number(l[2]) }), netOf = (e) => { const n = kidOf(e, 'net'); return n ? (n[2] ?? names.get(n[1]) ?? null) : null; };
434
+ return {
435
+ tracks: kidsOf(root, 'segment').map((g) => ({ a: pt(kidOf(g, 'start')), b: pt(kidOf(g, 'end')), width: Number(kidOf(g, 'width')[1]), layer: layer(kidOf(g, 'layer')[1]), net: netOf(g) })),
436
+ vias: kidsOf(root, 'via').map((v) => ({ ...pt(kidOf(v, 'at')), pad: Number(kidOf(v, 'size')[1]), hole: Number(kidOf(v, 'drill')[1]), net: netOf(v) }))
437
+ };
438
+ }
439
+
440
+ // The sizes the source uses most: its vias ({ via: { pad, hole } }), its narrowest track, its zones' clearance
441
+ function commonest(root) {
442
+ const most = (list) => { const n = new Map(); for (const k of list) n.set(k, (n.get(k) || 0) + 1); return [...n].sort((a, b) => b[1] - a[1])[0]?.[0]; };
443
+ const via = most(kidsOf(root, 'via').map((v) => `${kidOf(v, 'size')?.[1]} ${kidOf(v, 'drill')?.[1]}`));
444
+ const widths = kidsOf(root, 'segment').map((g) => Number(kidOf(g, 'width')?.[1])).filter((w) => w > 0);
445
+ const clear = most(kidsOf(root, 'zone').map((z) => kidOf(kidOf(z, 'connect_pads') || [], 'clearance')?.[1]).filter(Boolean));
446
+ return { ...(via ? { via: { pad: Number(via.split(' ')[0]), hole: Number(via.split(' ')[1]) } } : {}), ...(widths.length ? { track: Math.min(...widths) } : {}), ...(clear ? { clearance: Number(clear) } : {}) };
447
+ }
448
+
449
+ /**
450
+ * A KiCad board (.kicad_pcb text, KiCad 6 or later) as a circuit, in mm, y up, centred on the outline's bounds:
451
+ * { layers, width, height, outline, parts, nets, planes, holes, source }. Each part keeps its place on the source
452
+ * board ({ ref, footprint, value, mpn, lcsc, x, y, rotation, layer }) and its pads in its own frame, as seen from
453
+ * the side it's on ({ pin, x, y, w, h, angle, smd, shape, net } and, for holes, hole, hole_offset, castellated), and its
454
+ * unplated holes (holes: [{ x, y, d }], a socket's locating pegs). The board's own holes (a mounting hole) are in holes.
455
+ * nets: { name: ['U1.3', 'C4.1'] }, part and pad, for nets joining two pads or more. planes: nets the source fills on
456
+ * whole layers ({ GND: ['In1.Cu', 'B.Cu'] }). routing: the source's own tracks and vias (for keeping its layout of an
457
+ * area: moveGroup with keep). source: what the file says beyond the circuit (counts, its commonest via and clearance).
458
+ * @param {string} text @returns {object}
459
+ */
460
+ export function fromKicadPcb(text) {
461
+ const root = sexpr(text);
462
+ if (root?.[0] !== 'kicad_pcb') throw new Error('not a KiCad board: a .kicad_pcb starts with (kicad_pcb');
463
+ if (!kidOf(root, 'footprint')) throw new Error('no footprints in this board: KiCad 6 or later is needed (older files call them "module": open and save it in KiCad 6+)');
464
+ const layers = kidOf(root, 'layers').slice(1).filter((l) => l[2] === 'signal').map((l) => l[1]);
465
+ const num = Number, pieces = [], holes = [], raw = [];
466
+ const edge = (l, place) => { // a line or an arc on Edge.Cuts, as straight pieces in the board's frame
467
+ if ((kidOf(l, 'layer')?.[1]) !== 'Edge.Cuts') return;
468
+ const pt = (k) => { const p = kidOf(l, k); return p && place(num(p[1]), num(p[2])); };
469
+ const a = pt('start'), b = pt('end'), m = pt('mid');
470
+ if (!a || !b) return;
471
+ if (!m) return pieces.push({ a, b });
472
+ const ax = b.x - a.x, ay = b.y - a.y, bx = m.x - a.x, by = m.y - a.y, d = 2 * (ax * by - ay * bx); // the circle through a, m, b
473
+ const cx = a.x + (by * (ax * ax + ay * ay) - ay * (bx * bx + by * by)) / d, cy = a.y + (ax * (bx * bx + by * by) - bx * (ax * ax + ay * ay)) / d;
474
+ const r = Math.hypot(a.x - cx, a.y - cy), at = (p) => Math.atan2(p.y - cy, p.x - cx), t0 = at(a);
475
+ let t1 = at(b), tm = at(m);
476
+ const norm = (t) => ((t - t0) % (2 * Math.PI) + 2 * Math.PI) % (2 * Math.PI);
477
+ t1 = norm(t1); tm = norm(tm); const sweep = tm < t1 ? t1 : t1 - 2 * Math.PI, n = Math.max(2, Math.ceil(Math.abs(sweep) / (Math.PI / 16)));
478
+ let prev = a;
479
+ for (let i = 1; i <= n; i++) { const t = t0 + (sweep * i) / n, q = i === n ? b : { x: cx + r * Math.cos(t), y: cy + r * Math.sin(t) }; pieces.push({ a: prev, b: q }); prev = q; }
480
+ };
481
+ for (const g of root) if (Array.isArray(g) && ['gr_line', 'gr_arc'].includes(g[0])) edge(g, (x, y) => ({ x, y }));
482
+ for (const g of kidsOf(root, 'gr_rect')) if (kidOf(g, 'layer')?.[1] === 'Edge.Cuts') {
483
+ const s = kidOf(g, 'start'), e = kidOf(g, 'end'), [x0, y0, x1, y1] = [s[1], s[2], e[1], e[2]].map(num);
484
+ pieces.push({ a: { x: x0, y: y0 }, b: { x: x1, y: y0 } }, { a: { x: x1, y: y0 }, b: { x: x1, y: y1 } }, { a: { x: x1, y: y1 }, b: { x: x0, y: y1 } }, { a: { x: x0, y: y1 }, b: { x: x0, y: y0 } });
485
+ }
486
+ for (const f of kidsOf(root, 'footprint')) {
487
+ const at = kidOf(f, 'at'), fx = num(at[1]), fy = num(at[2]), deg = num(at[3] || 0), t = (deg * Math.PI) / 180, c = Math.cos(t), s = Math.sin(t);
488
+ const bottom = (kidOf(f, 'layer')?.[1]) === 'B.Cu';
489
+ const place = (x, y) => ({ x: fx + x * c + y * s, y: fy - x * s + y * c }); // KiCad's frame: y down, angles counter-clockwise on screen
490
+ for (const l of [...kidsOf(f, 'fp_line'), ...kidsOf(f, 'fp_arc')]) edge(l, place);
491
+ const props = Object.fromEntries(kidsOf(f, 'property').map((p) => [String(p[1]).trim(), p[2]]));
492
+ const ref = props.Reference ?? kidsOf(f, 'fp_text').find((x) => x[1] === 'reference')?.[2];
493
+ const pads = [], own = []; // own: the part's unplated holes (a socket's locating pegs), in its frame
494
+ for (const p of kidsOf(f, 'pad')) {
495
+ const [, name, kind, shape] = p, pa = kidOf(p, 'at'), sz = kidOf(p, 'size'), drill = kidOf(p, 'drill');
496
+ if (kind === 'np_thru_hole') { own.push({ x: r4(bottom ? -num(pa[1]) : num(pa[1])), y: r4(-num(pa[2])), d: num(drill[1]), at: place(num(pa[1]), num(pa[2])) }); continue; }
497
+ if (!name) continue; // unnamed pads are mechanical: no net
498
+ // A pad's place in the part's frame, y up, seen from the side the part is on: (x, -y) on top; a part on the back
499
+ // is stored mirrored by KiCad, and turned the other way, so (-x, -y) with the turn negated (see rotation below)
500
+ const px = num(pa[1]), py = num(pa[2]), angle = turnOf((num(pa[3] || 0) - deg) * (bottom ? -1 : 1));
501
+ 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 };
502
+ const ratio = kidOf(p, 'roundrect_rratio'); // rounded corners, as a share of the shorter side
503
+ if (shape === 'roundrect' && ratio) pad.corner = r4(num(ratio[1]) * Math.min(pad.w, pad.h));
504
+ if (drill) {
505
+ const d = drill.slice(1), oval = d[0] === 'oval', ds = d.filter((x) => !Array.isArray(x) && x !== 'oval').map(num), off = kidOf(drill, 'offset');
506
+ pad.hole = Math.min(...ds);
507
+ if (oval && ds.length > 1 && ds[0] !== ds[1]) pad.hole_size = [ds[0], ds[1]];
508
+ if (off && (num(off[1]) || num(off[2]))) { // KiCad drills at the pad's position and moves its copper by the offset (turned with the pad)
509
+ const t = ((num(pa[3] || 0) - deg) * Math.PI) / 180, ox = num(off[1]), oy = -num(off[2]); // y up
510
+ const o = [(ox * Math.cos(t) - oy * Math.sin(t)) * (bottom ? -1 : 1), ox * Math.sin(t) + oy * Math.cos(t)];
511
+ pad.x = r4(pad.x + o[0]); pad.y = r4(pad.y + o[1]); pad.hole_offset = [r4(-o[0]), r4(-o[1])]; // the copper's centre, and the hole from it
512
+ }
513
+ }
514
+ if (p.some((x) => Array.isArray(x) && x[0] === 'property' && x[1] === 'pad_prop_castellated')) pad.castellated = true;
515
+ pads.push(pad);
516
+ }
517
+ if (!pads.length) { holes.push(...own.map((h) => ({ ...h.at, d: h.d }))); continue; } // a mounting hole (a board's), a logo: nothing to connect
518
+ const attr = kidOf(f, 'attr') || []; // parts the source keeps off its BOM and placement files (edge pads, test points)
519
+ const m3 = kidOf(f, 'model'), xyz = (k) => { const v = kidOf(kidOf(m3, k) || [], 'xyz'); return v ? v.slice(1).map(Number) : null; };
520
+ const model = m3 && { path: m3[1], offset: xyz('offset') || [0, 0, 0], scale: xyz('scale') || [1, 1, 1], rotate: xyz('rotate') || [0, 0, 0] }; // its 3D model, as KiCad finds it
521
+ raw.push({ ref, footprint: f[1], value: props.Value, mpn: props.MPN ?? props['Manufacturer Part Number'], lcsc: props.LCSC, x: fx, y: fy, rotation: turnOf(bottom ? -deg : deg), layer: bottom ? 'bottom' : 'top', pads,
522
+ ...(model ? { model } : {}), ...(attr.includes('exclude_from_bom') ? { bom: false } : {}), ...(attr.includes('exclude_from_pos_files') ? { place: false } : {}),
523
+ ...(own.length ? { holes: own.map(({ at, ...h }) => h) } : {}) });
524
+ }
525
+ // The outline: the loops on Edge.Cuts, the biggest outside (counter-clockwise, y up); without one closed loop, its bounds
526
+ const found = loops(pieces);
527
+ const all = pieces.flatMap((p) => [p.a, p.b]);
528
+ if (!all.length) throw new Error('no board outline: nothing is drawn on Edge.Cuts');
529
+ const xs = all.map((p) => p.x), ys = all.map((p) => p.y), cx = (Math.min(...xs) + Math.max(...xs)) / 2, cy = (Math.min(...ys) + Math.max(...ys)) / 2;
530
+ const to = (p) => ({ x: r4(p.x - cx), y: r4(cy - p.y) }); // into the circuit's frame: centred, y up
531
+ let outline = null, cutouts = [];
532
+ if (found) {
533
+ const shapes = found.map((l) => l.map(to)).map((l) => (area(l) < 0 ? l.reverse() : l)).sort((a, b) => area(b) - area(a));
534
+ [outline, ...cutouts] = shapes;
535
+ }
536
+ const parts = raw.map((p) => ({ ...p, ...to(p) }));
537
+ const nets = {};
538
+ for (const p of parts) for (const q of p.pads) if (q.net) (nets[q.net] ||= new Set()).add(`${p.ref}.${q.pin}`);
539
+ const planes = {};
540
+ for (const z of kidsOf(root, 'zone')) {
541
+ const net = kidOf(z, 'net_name')?.[1], on = [...(kidOf(z, 'layers')?.slice(1) || []), ...(kidOf(z, 'layer') ? [kidOf(z, 'layer')[1]] : [])];
542
+ if (net) planes[net] = [...new Set([...(planes[net] || []), ...on])];
543
+ }
544
+ return {
545
+ layers: layers.length, copper: layers, width: r4(Math.max(...xs) - Math.min(...xs)), height: r4(Math.max(...ys) - Math.min(...ys)),
546
+ thickness: num(kidOf(kidOf(root, 'general') || [], 'thickness')?.[1]) || null,
547
+ outline, cutouts, parts,
548
+ nets: Object.fromEntries(Object.entries(nets).filter(([, s]) => s.size > 1).map(([k, s]) => [k, [...s]])),
549
+ planes, holes: holes.map((h) => ({ ...to(h), d: h.d })),
550
+ routing: sourceCopper(root, to),
551
+ source: { generator: kidOf(root, 'generator')?.[1], version: kidOf(root, 'version')?.[1], tracks: kidsOf(root, 'segment').length + kidsOf(root, 'arc').length, vias: kidsOf(root, 'via').length,
552
+ ...commonest(root) }
553
+ };
554
+ }
555
+
556
+ /**
557
+ * A circuit's parts and nets (fromKicadPcb's, kept in a rule set) for a board, each part where the source put it: put
558
+ * them in board.parts and board.nets. o.planes: nets left out of the routing, for planes to join (default: the nets
559
+ * the source fills on inner layers, when it has them). o.layers: the board's copper layers (default the source's): on 4
560
+ * or more, those nets get planes on inner layers (board.planes). Returns { parts, nets, planes, holes, outline, layers,
561
+ * copper (the source's routing kept with moveGroup), via_pad, via_hole, plane_clearance (the source's), notes }: notes say what this board does with them, and what it can't carry yet (slots are drilled round).
562
+ * @param {object} circuit @param {{ planes?: string[], layers?: number }} [o]
563
+ */
564
+ export function clone(circuit, o = {}) {
565
+ const inner = (l) => /^In\d+\.Cu$/.test(l), layers = o.layers ?? circuit.layers ?? 2;
566
+ const planes = o.planes ?? Object.entries(circuit.planes || {}).filter(([, ls]) => ls.some(inner)).map(([n]) => n);
567
+ const notes = [], castellated = new Set(), oval = new Set();
568
+ const parts = circuit.parts.map((p) => {
569
+ const quarterTurn = p.rotation % 90 === 0, t = (p.rotation * Math.PI) / 180, c = Math.cos(t), s = Math.sin(t);
570
+ const pads = p.pads.map((q) => {
571
+ const pin = `pin${q.pin}`;
572
+ if (!q.smd) {
573
+ const at = quarterTurn ? { x: q.x, y: q.y } : { x: q.x * c - q.y * s, y: q.x * s + q.y * c };
574
+ 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 }; }
575
+ if (q.hole_size) oval.add(p.ref); // a slot: drilled round, at its narrow width
576
+ if (q.w === q.h && !q.hole_offset) return { pin, hint: q.pin, ...at, hole: q.hole, outer: q.w };
577
+ // an oval pad, or a hole off its centre: a rounded rectangle round the hole, turned with the part (quarter turns)
578
+ const sw = (q.angle + (quarterTurn ? 0 : p.rotation)) % 180 === 90, w = sw ? q.h : q.w, h = sw ? q.w : q.h;
579
+ return { pin, hint: q.pin, ...at, hole: q.hole, outer: Math.min(w, h), rect: { w, h, offset: q.hole_offset || [0, 0] } };
580
+ }
581
+ const turn = q.angle + (quarterTurn ? 0 : p.rotation);
582
+ if (turn % 90 === 0) { // a rectangle, its sides swapped by a quarter turn of its own
583
+ const sw = turn % 180 !== 0, at = quarterTurn ? { x: q.x, y: q.y } : { x: q.x * c - q.y * s, y: q.x * s + q.y * c };
584
+ return { pin, smd: true, hint: q.pin, ...at, w: sw ? q.h : q.w, h: sw ? q.w : q.h, ...(q.shape === 'circle' && q.w === q.h ? { circle: true } : {}), ...(q.corner ? { corner: q.corner } : {}) };
585
+ }
586
+ const a = (turn * Math.PI) / 180, ca = Math.cos(a), sa = Math.sin(a), at = quarterTurn ? { x: q.x, y: q.y } : { x: q.x * c - q.y * s, y: q.x * s + q.y * c };
587
+ const pts = [[-1, -1], [1, -1], [1, 1], [-1, 1]].map(([u, v]) => [r4(at.x + (u * q.w / 2) * ca - (v * q.h / 2) * sa), r4(at.y + (u * q.w / 2) * sa + (v * q.h / 2) * ca)]);
588
+ return { pin, smd: true, hint: q.pin, ...at, points: pts }; // corners relative to the part, as circuit.mjs takes them
589
+ });
590
+ const holes = (p.holes || []).map((h) => (quarterTurn ? h : { ...h, x: h.x * c - h.y * s, y: h.x * s + h.y * c }));
591
+ return { name: p.ref, ftype: 'simple_chip', x: p.x, y: p.y, layer: p.layer, rotation: quarterTurn ? p.rotation : 0, mpn: p.mpn, lcsc: p.lcsc, value: p.value, ...(p.bom === false ? { bom: false } : {}), ...(p.place === false ? { place: false } : {}), ...(holes.length ? { holes } : {}),
592
+ ...(p.model && circuit.models?.[p.model.path] ? { model: { ...p.model, ...circuit.models[p.model.path], turn: quarterTurn ? 0 : p.rotation } } : {}), courtyard: null, pads }; // no sch: laid out on the schematic in rows, each pin labelled with its net
593
+ }).filter((p) => p.pads.length);
594
+ const have = new Set(parts.flatMap((p) => p.pads.map((q) => `${p.name}.${q.pin}`))), dropped = new Set();
595
+ const nets = Object.fromEntries(Object.entries(circuit.nets).filter(([n]) => !planes.includes(n))
596
+ .map(([n, pins]) => [n, pins.map((x) => { const i = x.indexOf('.'); return `${x.slice(0, i)}.pin${x.slice(i + 1)}`; })
597
+ .filter((x) => have.has(x) || !dropped.add(x))]).filter(([, pins]) => pins.length > 1));
598
+ const plural = (set, one, many) => `${set.size} ${set.size === 1 ? one : many} (${[...set].join(', ')})`;
599
+ // On 4 layers or more, each plane net fills the inner layer the source gives it (the first, if several), or the next free one
600
+ const onPlanes = {}, free = Array.from({ length: Math.max(0, layers - 2) }, (_, i) => `inner${i + 1}`);
601
+ if (layers >= 4) for (const n of planes) {
602
+ const own = (circuit.planes?.[n] || []).find(inner), want = own ? `inner${own.match(/\d+/)[0]}` : null;
603
+ const layer = want && free.includes(want) ? want : free[0];
604
+ if (!layer) { notes.push(`${n}: no inner layer left for its plane`); continue; }
605
+ free.splice(free.indexOf(layer), 1);
606
+ onPlanes[n] = { layer, pins: (circuit.nets[n] || []).map((x) => { const i = x.indexOf('.'); return `${x.slice(0, i)}.pin${x.slice(i + 1)}`; }).filter((x) => have.has(x)) };
607
+ }
608
+ 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(', ')}`);
609
+ 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`);
610
+ 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)`);
611
+ if (oval.size) notes.push(`slots drilled round, at their narrow width, on ${plural(oval, 'part', 'parts')}`);
612
+ 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(', ')}`);
613
+ const src = circuit.source || {}; // the source's via and clearance, which its layout was made to
614
+ const sizes = { ...(src.via ? { via_pad: src.via.pad, via_hole: src.via.hole } : {}), ...(src.clearance ? { plane_clearance: src.clearance } : {}) };
615
+ // The source's own copper kept with a moved block, its pins named as the board names them
616
+ const named = (x) => { const i = x.indexOf('.'); return `${x.slice(0, i)}.pin${x.slice(i + 1)}`; };
617
+ const copper = circuit.kept?.islands.length ? { ...circuit.kept, islands: circuit.kept.islands.map((k) => ({ ...k, pins: k.pins.map(named) })),
618
+ stubs: (circuit.kept.stubs || []).map((b) => ({ ...b, pin: named(b.pin) })) } : null;
619
+ if (copper) notes.push(`the source's own routing kept: ${copper.tracks.length} tracks and ${copper.vias.length} vias in ${copper.islands.length} pieces, and ${copper.stubs.length} escapes routed on from where they leave`);
620
+ return { parts, nets, holes: circuit.holes, outline: circuit.outline, layers, ...(Object.keys(onPlanes).length ? { planes: onPlanes } : {}), ...(copper ? { copper } : {}), ...sizes, notes };
621
+ }
622
+
623
+ // A part's pads on the board (the circuit's frame), as render places them: turned, and mirrored in x on the back
624
+ export function padsOnBoard(part) {
625
+ const m = part.layer === 'bottom' ? -1 : 1, t = (part.rotation * Math.PI) / 180, c = Math.cos(t), s = Math.sin(t);
626
+ return part.pads.map((q) => ({ ...q, bx: r4(part.x + m * (c * q.x - s * q.y)), by: r4(part.y + (s * q.x + c * q.y)) }));
627
+ }
628
+
629
+ /**
630
+ * The circuit with one part on a new footprint: the same pins, so the same nets, with pads where you put them (each
631
+ * { pin, x, y, w, h, angle, smd, hole, ... } as fromKicadPcb gives them, in the part's frame). Every pin the part had must
632
+ * have a pad, and no other: its circuit can't change, only its shape. Returns a new circuit.
633
+ * @param {object} circuit @param {string} ref @param {object[]} pads
634
+ */
635
+ export function withFootprint(circuit, ref, pads) {
636
+ const part = circuit.parts.find((p) => p.ref === ref);
637
+ if (!part) throw new Error(`withFootprint: no part ${ref} in the circuit`);
638
+ const had = new Map(part.pads.map((q) => [q.pin, q.net])), given = new Set(pads.map((q) => q.pin));
639
+ const missing = [...had.keys()].filter((n) => !given.has(n)), extra = [...given].filter((n) => !had.has(n));
640
+ if (missing.length || extra.length) throw new Error(`withFootprint: ${ref}'s new pads must have the same pins as before${missing.length ? `; missing ${missing.join(', ')}` : ''}${extra.length ? `; not on ${ref}: ${extra.join(', ')}` : ''}`);
641
+ return { ...circuit, parts: circuit.parts.map((p) => (p.ref === ref ? { ...p, footprint: `${p.footprint} (reshaped)`, pads: pads.map((q) => ({ angle: 0, smd: false, shape: 'circle', ...q, net: had.get(q.pin) })) } : p)) };
642
+ }
643
+
644
+ /**
645
+ * New pins on a clone's part, declared: each pad { pin, net, ...pad } joins an existing net of the source (a reset line
646
+ * from a test point to the edge), or with `joins: ['U3.13']` a new net to pins the source leaves unconnected (a spare
647
+ * GPIO brought out). The circuit is then the source's plus these; `added` lists them, and sameCircuit (given them)
648
+ * checks the rest is unchanged and names each one. @param {object} circuit @param {string} ref @param {object[]} pads
649
+ */
650
+ export function addPins(circuit, ref, pads) {
651
+ const part = circuit.parts.find((p) => p.ref === ref);
652
+ if (!part) throw new Error(`addPins: no part ${ref} in the circuit`);
653
+ const have = new Set(part.pads.map((q) => q.pin)), nets = { ...circuit.nets }, added = [...(circuit.added || [])];
654
+ for (const q of pads) {
655
+ if (have.has(q.pin)) throw new Error(`addPins: ${ref} already has a pin ${q.pin}`);
656
+ if (!q.joins && !nets[q.net]) throw new Error(`addPins: no net ${q.net} in the source (give joins: [...] for a new net)`);
657
+ if (q.joins) for (const x of q.joins) { const owner = Object.entries(nets).find(([, n]) => n.includes(x)); if (owner) throw new Error(`addPins: ${x} is already on ${owner[0]}`); }
658
+ nets[q.net] = [...(nets[q.net] || q.joins), `${ref}.${q.pin}`];
659
+ added.push({ pin: `${ref}.${q.pin}`, net: q.net, ...(q.joins ? { joins: q.joins } : {}) });
660
+ }
661
+ const extra = pads.map(({ joins, ...q }) => ({ angle: 0, smd: false, shape: 'circle', ...q }));
662
+ return { ...circuit, nets, added, parts: circuit.parts.map((p) => (p.ref === ref ? { ...p, pads: [...p.pads, ...extra] } : p)) };
663
+ }
664
+
665
+ /**
666
+ * Silkscreen labels moved clear of copper and of each other: each slides across its reading direction (a level label up
667
+ * or down, a turned one left or right), a step at a time up to reach, to the nearest place clear of every pad by gap. A
668
+ * label with nowhere clear stays put, marked clash: true. The fab trims silkscreen off copper, so a label on a pad loses
669
+ * letters. A label with `to: { x, y }` (or a list of such, to choose from) points at it: it goes to the nearest place
670
+ * to where it's asked for (within `near` mm) that is clear of pads, of surface-mount parts' bodies and of other labels,
671
+ * inside `area` ({ minX, maxX, minY, maxY }), with a small triangle beside it pointing at the spot: for a pin with no
672
+ * room for its label beside it.
673
+ * o: { reach = 1.5, step = 0.1, gap = 0.15, char = 0.75 (a character's width over its height), area, near = 6 }.
674
+ * @param {object[]} silk { text, x, y, size, rotation, to } @param {object} circuit @param {object} [o]
675
+ */
676
+ export function clearLabels(silk, circuit, { reach = 1.5, step = 0.1, gap = 0.15, char = 0.75, area = null, near = 6 } = {}) {
677
+ const padBoxes = (p) => padsOnBoard(p).map((q) => { const t = turnOf(p.rotation + q.angle) % 180 === 90; return { x: q.bx, y: q.by, w: t ? q.h : q.w, h: t ? q.w : q.h }; });
678
+ const copper = circuit.parts.flatMap((p) => [...padBoxes(p),
679
+ ...padsOnBoard({ ...p, pads: (p.holes || []).map((h) => ({ ...h, w: h.d, h: h.d, angle: 0 })) }).map((h) => ({ x: h.bx, y: h.by, w: h.w, h: h.h }))]);
680
+ // A surface-mount part's body spans its pads: a label with an arrow keeps off it (the part would hide it)
681
+ const bodies = circuit.parts.filter((p) => p.pads.length > 1 && p.pads.every((q) => q.smd)).map((p) => {
682
+ const b = padBoxes(p), x0 = Math.min(...b.map((q) => q.x - q.w / 2)), x1 = Math.max(...b.map((q) => q.x + q.w / 2)), y0 = Math.min(...b.map((q) => q.y - q.h / 2)), y1 = Math.max(...b.map((q) => q.y + q.h / 2));
683
+ return { x: (x0 + x1) / 2, y: (y0 + y1) / 2, w: x1 - x0, h: y1 - y0 };
684
+ });
685
+ return slideClear(silk, copper, { reach, step, gap, char, bodies, area, near });
686
+ }
687
+
688
+ /**
689
+ * Placement rules learnt from the source: each small part (fewer than 4 pads: resistors, capacitors, LEDs) stays near
690
+ * the pad of a bigger part (an anchor: a chip, a connector, a crystal) on its most particular net (the one joining the
691
+ * fewest pins), the nearest such pad on the source board: a decoupling capacitor by its power pin, a crystal's capacitors by the crystal. Each rule:
692
+ * { part, anchor, pin, net, source (mm, pad centre to pad centre on the source), max (mm) }. max allows a quarter more,
693
+ * and at least 0.5 mm: edit it in the rule set to be stricter or freer. o.anchor: the fewest pads an anchor has (4).
694
+ * @param {object} circuit @param {{ anchor?: number }} [o] @returns {object[]}
695
+ */
696
+ export function learnPlacement(circuit, o = {}) {
697
+ const min = o.anchor ?? 4, anchors = circuit.parts.filter((p) => p.pads.length >= min), rules = [];
698
+ const anchorPads = anchors.flatMap((a) => padsOnBoard(a).filter((q) => q.net).map((q) => ({ ...q, ref: a.ref })));
699
+ for (const p of circuit.parts.filter((x) => x.pads.length < min)) {
700
+ let best = null; // on its most particular net (the fewest pins: a crystal's pin before GND), then the nearest pad
701
+ for (const q of padsOnBoard(p)) for (const a of anchorPads) {
702
+ if (!q.net || a.net !== q.net) continue;
703
+ const d = Math.hypot(a.bx - q.bx, a.by - q.by), n = circuit.nets[q.net]?.length ?? Infinity;
704
+ if (!best || n < best.n || (n === best.n && d < best.d)) best = { d, n, q, a };
705
+ }
706
+ if (best) rules.push({ part: p.ref, anchor: best.a.ref, pin: best.a.pin, net: best.q.net, source: r4(best.d), max: r4(Math.max(best.d * 1.25, best.d + 0.5)) });
707
+ }
708
+ return rules;
709
+ }
710
+
711
+ /**
712
+ * The circuit with some parts moved, each small part going with the anchor its placement rule names (turned with it,
713
+ * kept the same way round): moves { U3: { x, y, rotation } } (any of the three; rotation in quarter turns from above).
714
+ * Parts not moved, and not following a moved anchor, stay where the source put them. Returns a new circuit.
715
+ * @param {object} circuit @param {Record<string, { x?: number, y?: number, rotation?: number }>} moves @param {object[]} [rules]
716
+ */
717
+ export function arrange(circuit, moves, rules = circuit.placement || learnPlacement(circuit)) {
718
+ const byRef = new Map(circuit.parts.map((p) => [p.ref, p])), follow = new Map(rules.map((r) => [r.part, r.anchor]));
719
+ for (const ref of Object.keys(moves)) if (!byRef.has(ref)) throw new Error(`arrange: no part ${ref} in the circuit`);
720
+ const moved = (p) => {
721
+ const to = moves[p.ref];
722
+ if (to) { const dr = ((to.rotation ?? p.rotation) - p.rotation + 360) % 360; return { ...p, x: to.x ?? p.x, y: to.y ?? p.y, rotation: (to.rotation ?? p.rotation) % 360, dr }; }
723
+ const a = follow.has(p.ref) && !moves[p.ref] ? byRef.get(follow.get(p.ref)) : null, at = a && moves[a.ref];
724
+ if (!at) return p;
725
+ const turn = ((at.rotation ?? a.rotation) - a.rotation + 360) % 360, t = (turn * Math.PI) / 180, c = Math.cos(t), s = Math.sin(t);
726
+ const dx = p.x - a.x, dy = p.y - a.y, own = p.layer === a.layer ? turn : -turn; // a part on the other side turns the other way, seen from its side
727
+ return { ...p, x: r4((at.x ?? a.x) + c * dx - s * dy), y: r4((at.y ?? a.y) + s * dx + c * dy), rotation: turnOf(p.rotation + own) };
728
+ };
729
+ const parts = circuit.parts.map(moved).map(({ dr, ...p }) => p);
730
+ const shifted = new Set(parts.filter((p, i) => p.x !== circuit.parts[i].x || p.y !== circuit.parts[i].y || p.rotation !== circuit.parts[i].rotation).map((p) => p.ref)); // a kept island to a part that moved apart is left to routing
731
+ const kept = circuit.kept && { ...circuit.kept, islands: circuit.kept.islands.filter((k) => !k.pins.some((x) => shifted.has(x.split('.')[0]))) };
732
+ if (kept) {
733
+ kept.stubs = (kept.stubs || []).filter((b) => !shifted.has(b.pin.split('.')[0]));
734
+ const ids = new Set([...kept.islands.map((k) => k.id), ...kept.stubs.map((b) => b.id)]);
735
+ kept.tracks = kept.tracks.filter((g) => ids.has(g.island ?? g.stub)); kept.vias = kept.vias.filter((v) => ids.has(v.island ?? v.stub));
736
+ }
737
+ return { ...circuit, ...(kept ? { kept } : {}), parts };
738
+ }
739
+
740
+ /**
741
+ * The circuit with a group of parts moved as one block, every part keeping its place relative to the others: turned
742
+ * about the origin by turn (quarter turns, counter-clockwise from above), then moved by dx, dy. For keeping a source's
743
+ * proven layout of a whole area (a chip with all its small parts) while the board around it changes. With { keep: true }
744
+ * the source's tracks and vias that join only these parts' pads come too (circuit.kept, which clone() hands the board):
745
+ * that area's routing is the source's, proven, and only the connections leaving it are routed. Returns a new circuit.
746
+ * @param {object} circuit @param {string[]} refs @param {{ turn?: number, dx?: number, dy?: number }} move @param {{ keep?: boolean }} [o]
747
+ */
748
+ export function moveGroup(circuit, refs, { turn = 0, dx = 0, dy = 0 } = {}, { keep = false } = {}) {
749
+ const set = new Set(refs), missing = refs.filter((r) => !circuit.parts.some((p) => p.ref === r));
750
+ if (missing.length) throw new Error(`moveGroup: no part ${missing.join(', ')} in the circuit`);
751
+ if (turn % 90) throw new Error(`moveGroup: turn in quarter turns (0, 90, 180, 270), not ${turn}`);
752
+ const t = (turn * Math.PI) / 180, c = Math.round(Math.cos(t)), s = Math.round(Math.sin(t));
753
+ const at = ({ x, y }) => ({ x: r4(c * x - s * y + dx), y: r4(s * x + c * y + dy) });
754
+ let kept = circuit.kept;
755
+ if (keep) { // the source's copper wholly within the group, moved with it
756
+ if (!circuit.routing) throw new Error('moveGroup: keep needs the source\'s tracks (circuit.routing, from fromKicadPcb)');
757
+ const k = islands(circuit, set);
758
+ kept = { tracks: [...(kept?.tracks || []), ...k.tracks.map((g) => ({ ...g, a: at(g.a), b: at(g.b) }))],
759
+ vias: [...(kept?.vias || []), ...k.vias.map((v) => ({ ...v, ...at(v) }))], islands: [...(kept?.islands || []), ...k.islands],
760
+ stubs: [...(kept?.stubs || []), ...k.stubs.map((b) => ({ ...b, end: { ...b.end, ...at(b.end) } }))] };
761
+ }
762
+ return { ...circuit, ...(kept ? { kept } : {}), parts: circuit.parts.map((p) => (!set.has(p.ref) ? p : {
763
+ ...p, ...at(p), rotation: turnOf(p.rotation + (p.layer === 'bottom' ? -turn : turn))
764
+ })) };
765
+ }
766
+
767
+ // The source's copper in islands: tracks and vias joined end to end, through a via, or by touching a pad of their net.
768
+ // Returns the islands that touch only pads of the given parts (at least one): { tracks, vias, islands: [{ id, net,
769
+ // pins, via }] }, each track and via carrying its island's id. Islands touching any other part, or no pad, are left.
770
+ function islands(circuit, refs) {
771
+ const { tracks, vias } = circuit.routing, near = 0.01;
772
+ const pads = circuit.parts.flatMap((p) => padsOnBoard(p).map((q) => {
773
+ const turned = turnOf(p.rotation + q.angle) % 180 === 90;
774
+ return { ref: p.ref, pin: q.pin, net: q.net, x: q.bx, y: q.by, w: turned ? q.h : q.w, h: turned ? q.w : q.h, layer: q.smd ? p.layer : null };
775
+ }));
776
+ const onSeg = (pt, g) => { const dx = g.b.x - g.a.x, dy = g.b.y - g.a.y, l = dx * dx + dy * dy, u = l ? Math.max(0, Math.min(1, ((pt.x - g.a.x) * dx + (pt.y - g.a.y) * dy) / l)) : 0; return Math.hypot(pt.x - g.a.x - u * dx, pt.y - g.a.y - u * dy) <= near; };
777
+ // copper touching copper: a track's end within half its width of the pad (as KiCad joins them), a via within its radius
778
+ const inPad = (pt, q, layer, reach = 0) => (!q.layer || !layer || q.layer === layer) && Math.abs(pt.x - q.x) <= q.w / 2 + reach + near && Math.abs(pt.y - q.y) <= q.h / 2 + reach + near;
779
+ const nodes = [...tracks.map((g, i) => ({ kind: 't', i, g, net: g.net })), ...vias.map((v, i) => ({ kind: 'v', i, v, net: v.net }))];
780
+ const adj = nodes.map(() => []), up = nodes.map((_, i) => i), find = (i) => { while (up[i] !== i) i = up[i] = up[up[i]]; return i; }, join = (i, j) => { up[find(i)] = find(j); };
781
+ const byNet = new Map(); nodes.forEach((n, i) => byNet.set(n.net, [...(byNet.get(n.net) || []), i]));
782
+ for (const list of byNet.values()) for (let x = 0; x < list.length; x++) for (let y = x + 1; y < list.length; y++) {
783
+ const A = nodes[list[x]], B = nodes[list[y]];
784
+ const touch = A.kind === 't' && B.kind === 't' ? A.g.layer === B.g.layer && (onSeg(A.g.a, B.g) || onSeg(A.g.b, B.g) || onSeg(B.g.a, A.g) || onSeg(B.g.b, A.g))
785
+ : A.kind === 'v' && B.kind === 'v' ? Math.hypot(A.v.x - B.v.x, A.v.y - B.v.y) <= (A.v.pad + B.v.pad) / 2
786
+ : (() => { const [t, v] = A.kind === 't' ? [A.g, B.v] : [B.g, A.v]; return Math.hypot(t.a.x - v.x, t.a.y - v.y) <= v.pad / 2 + near || Math.hypot(t.b.x - v.x, t.b.y - v.y) <= v.pad / 2 + near; })();
787
+ if (touch) { join(list[x], list[y]); adj[list[x]].push(list[y]); adj[list[y]].push(list[x]); }
788
+ }
789
+ const touched = new Map(); // island root -> pads it touches
790
+ nodes.forEach((n, i) => {
791
+ const hit = pads.filter((q) => q.net === n.net && (n.kind === 't' ? inPad(n.g.a, q, n.g.layer, n.g.width / 2) || inPad(n.g.b, q, n.g.layer, n.g.width / 2) : inPad(n.v, q, null, n.v.pad / 2)));
792
+ const r = find(i); touched.set(r, [...(touched.get(r) || []), ...hit]);
793
+ });
794
+ const keep = new Map(); // root -> island
795
+ for (const [r, hit] of touched) if (hit.length && hit.every((q) => refs.has(q.ref)))
796
+ keep.set(r, { id: `island${keep.size + 1}`, net: nodes[r].net, pins: [...new Set(hit.map((q) => `${q.ref}.${q.pin}`))], via: false });
797
+ // A kept piece's dead ends (a branch that led somewhere left behind): trimmed, track by track
798
+ const dead = new Set(), ends = (i) => { const g = nodes[i].g; return [g.a, g.b]; };
799
+ for (let again = true; again;) {
800
+ again = false;
801
+ nodes.forEach((n, i) => {
802
+ if (n.kind !== 't' || dead.has(i) || !keep.has(find(i))) return;
803
+ const free = ends(i).some((pt) => !pads.some((q) => q.net === n.net && inPad(pt, q, n.g.layer, n.g.width / 2))
804
+ && !adj[i].some((j) => !dead.has(j) && (nodes[j].kind === 'v' ? Math.hypot(pt.x - nodes[j].v.x, pt.y - nodes[j].v.y) <= nodes[j].v.pad / 2 + near : onSeg(pt, nodes[j].g) || [nodes[j].g.a, nodes[j].g.b].some((e) => Math.hypot(e.x - pt.x, e.y - pt.y) <= near))));
805
+ if (free) { dead.add(i); again = true; }
806
+ });
807
+ }
808
+ // A track's end that stops just short of its pad (its copper overlapping it, as KiCad joins them) is moved onto the pad
809
+ const onto = (pt, net, layer, reach) => { const q = pads.find((d) => d.net === net && inPad(pt, d, layer, reach) && !inPad(pt, d, layer));
810
+ return q ? { x: r4(Math.min(Math.max(pt.x, q.x - q.w / 2 + 0.01), q.x + q.w / 2 - 0.01)), y: r4(Math.min(Math.max(pt.y, q.y - q.h / 2 + 0.01), q.y + q.h / 2 - 0.01)) } : pt; };
811
+ const snapped = (g) => ({ ...g, a: onto(g.a, g.net, g.layer, g.width / 2), b: onto(g.b, g.net, g.layer, g.width / 2) });
812
+ const out = { tracks: [], vias: [], islands: [], stubs: [] };
813
+ nodes.forEach((n, i) => { const k = keep.get(find(i)); if (!k || dead.has(i)) return; if (n.kind === 't') out.tracks.push({ ...snapped(n.g), island: k.id }); else { k.via = true; out.vias.push({ ...n.v, island: k.id }); } });
814
+ out.islands = [...keep.values()];
815
+ // Breakouts: an island from one of the block's pins out to other parts keeps its stretch within the block's bounds,
816
+ // from the pin to where it leaves (a fine-pitch chip's escape, proven); the rest is routed from the stub's end
817
+ const own = pads.filter((q) => refs.has(q.ref));
818
+ if (!own.length) return out;
819
+ const box = { x0: Math.min(...own.map((q) => q.x - q.w / 2)) - 0.3, x1: Math.max(...own.map((q) => q.x + q.w / 2)) + 0.3, y0: Math.min(...own.map((q) => q.y - q.h / 2)) - 0.3, y1: Math.max(...own.map((q) => q.y + q.h / 2)) + 0.3 };
820
+ const inBox = (pt) => pt.x >= box.x0 && pt.x <= box.x1 && pt.y >= box.y0 && pt.y <= box.y1;
821
+ const inside = (n) => (n.kind === 't' ? inBox(n.g.a) && inBox(n.g.b) : inBox(n.v));
822
+ for (const [r, hit] of touched) {
823
+ const mine = [...new Set(hit.filter((q) => refs.has(q.ref)).map((q) => `${q.ref}.${q.pin}`))];
824
+ if (keep.has(r) || mine.length !== 1 || hit.every((q) => refs.has(q.ref))) continue;
825
+ const pin = own.find((q) => `${q.ref}.${q.pin}` === mine[0]);
826
+ const touches = (n) => (n.kind === 't' ? inPad(n.g.a, pin, n.g.layer, n.g.width / 2) || inPad(n.g.b, pin, n.g.layer, n.g.width / 2) : inPad(n.v, pin, null, n.v.pad / 2));
827
+ const start = nodes.map((n, i) => i).filter((i) => find(i) === r && touches(nodes[i]));
828
+ // From the pin outward: whole pieces within the bounds, and the one track that crosses them cut where it does
829
+ const seen = new Set(), cut = [], queue = [];
830
+ const visit = (j, from) => {
831
+ if (seen.has(j)) return;
832
+ const n = nodes[j];
833
+ if (inside(n)) { seen.add(j); queue.push(j); return; }
834
+ if (n.kind !== 't') return cut.push(null); // a via outside: give up on a stub
835
+ const [p, q] = inBox(n.g.a) ? [n.g.a, n.g.b] : inBox(n.g.b) ? [n.g.b, n.g.a] : [null, null];
836
+ if (!p) return cut.push(null);
837
+ let t = 1; // where p -> q leaves the box
838
+ for (const [d, lo, hi, o] of [[q.x - p.x, box.x0, box.x1, p.x], [q.y - p.y, box.y0, box.y1, p.y]]) if (d) t = Math.min(t, ((d > 0 ? hi : lo) - o) / d);
839
+ cut.push({ g: { ...n.g, a: p, b: { x: r4(p.x + (q.x - p.x) * t), y: r4(p.y + (q.y - p.y) * t) } } });
840
+ };
841
+ for (const i of start) visit(i);
842
+ while (queue.length) { const i = queue.shift(); for (const j of adj[i]) visit(j, i); }
843
+ if (cut.length !== 1 || !cut[0]) continue; // no way out, more than one, or not a plain track: routed whole
844
+ const id = `stub${out.stubs.length + 1}`, g = cut[0].g;
845
+ out.stubs.push({ id, net: g.net, pin: mine[0], end: { x: g.b.x, y: g.b.y, layer: g.layer } });
846
+ out.tracks.push({ ...snapped(g), stub: id });
847
+ for (const i of seen) { const n = nodes[i]; if (n.kind === 't') out.tracks.push({ ...snapped(n.g), stub: id }); else out.vias.push({ ...n.v, stub: id }); }
848
+ }
849
+ return out;
850
+ }
851
+
852
+ /**
853
+ * Are the small parts still near their anchors? Findings ({ level, text }): one fail per broken rule, naming the part,
854
+ * the pin and the distances, or a pass.
855
+ * @param {object} circuit @param {object[]} [rules]
856
+ */
857
+ export function placementChecks(circuit, rules = circuit.placement || learnPlacement(circuit)) {
858
+ const byRef = new Map(circuit.parts.map((p) => [p.ref, p])), out = [];
859
+ for (const r of rules) {
860
+ const p = byRef.get(r.part), a = byRef.get(r.anchor);
861
+ if (!p || !a) { out.push({ level: 'fail', text: `placement: ${!p ? r.part : r.anchor} isn't on the board` }); continue; }
862
+ const pin = padsOnBoard(a).filter((q) => q.pin === r.pin), mine = padsOnBoard(p).filter((q) => q.net === r.net);
863
+ const d = Math.min(...mine.flatMap((q) => pin.map((x) => Math.hypot(x.bx - q.bx, x.by - q.by))));
864
+ if (!(d <= r.max + 1e-6)) out.push({ level: 'fail', text: `placement: ${r.part} is ${mm(d)} mm from ${r.anchor} pin ${r.pin} (${r.net}): at most ${mm(r.max)} (${mm(r.source)} on the source)` });
865
+ }
866
+ if (!out.length) out.push({ level: 'pass', text: `placement: all ${rules.length} small parts within reach of their anchors, as the source has them` });
867
+ return out;
868
+ }
869
+
870
+ /**
871
+ * Does the board join exactly the pins the circuit joins? Each of the circuit's nets (but planes) must be one group of
872
+ * pins on the board, with no other net's pins in it. Findings as checks() gives them ({ level, text }).
873
+ * @param {object[]} json Circuit JSON (render's) @param {object} circuit @param {{ planes?: string[] }} [o]
874
+ */
875
+ export function sameCircuit(json, circuit, o = {}, added = []) {
876
+ const onBoard = new Set(json.filter((e) => e.type === 'source_net').map((e) => e.name)); // nets the board has planes for
877
+ const left = { ...clone(circuit, o).nets }, all = { ...circuit.nets };
878
+ for (const a of added) { if (!all[a.net]) left[a.net] = true; all[a.net] = [...(all[a.net] || a.joins), a.pin]; } // declared new pins: expected too
879
+ const nets = Object.fromEntries(Object.entries(all).filter(([n]) => left[n] || onBoard.has(n))
880
+ .map(([n, pins]) => [n, pins.map((x) => { const i = x.indexOf('.'); return `${x.slice(0, i)}.pin${x.slice(i + 1)}`; })]));
881
+ const up = new Map(), find = (a) => { while (up.get(a) !== a) a = up.get(a); return a; };
882
+ const join = (a, b) => { up.set(find(a), find(b)); };
883
+ const comp = new Map(json.filter((e) => e.type === 'source_component').map((e) => [e.source_component_id, e]));
884
+ const name = new Map(json.filter((e) => e.type === 'source_port').map((e) => [e.source_port_id, `${comp.get(e.source_component_id)?.name}.${e.name}`]));
885
+ for (const id of name.keys()) up.set(id, id);
886
+ for (const c of comp.values()) for (const g of c.internally_connected_source_port_ids || []) g.forEach((id) => join(id, g[0]));
887
+ for (const t of json.filter((e) => e.type === 'source_trace')) {
888
+ t.connected_source_port_ids.forEach((id) => join(id, t.connected_source_port_ids[0]));
889
+ for (const n of t.connected_source_net_ids || []) { if (!up.has(n)) up.set(n, n); join(t.connected_source_port_ids[0], n); } // a pad joined to a plane
890
+ }
891
+ const group = new Map(); // pin name -> group
892
+ for (const [id, n] of name) group.set(n, find(id));
893
+ for (const [n, pins] of Object.entries(nets)) if (!left[n]) nets[n] = pins.filter((p) => group.has(p)); // a pin with no pad here (castellated): out of its plane too
894
+ const out = [], missing = [], split = [], shorted = [];
895
+ const owner = new Map(); // group -> net
896
+ for (const [net, pins] of Object.entries(nets)) {
897
+ const gs = new Set(pins.map((p) => group.get(p)));
898
+ if (gs.has(undefined)) { missing.push(`${net}: ${pins.filter((p) => !group.has(p)).join(', ')}`); continue; }
899
+ if (gs.size > 1) split.push(net);
900
+ for (const g of gs) { if (owner.has(g) && owner.get(g) !== net) shorted.push(`${owner.get(g)} and ${net}`); owner.set(g, net); }
901
+ }
902
+ const extra = []; // board pins in a net's group that the source doesn't put in that net
903
+ for (const [pin, g] of group) { const net = owner.get(g); if (net && !nets[net].includes(pin)) extra.push(`${pin} in ${net}`); }
904
+ if (extra.length) out.push({ level: 'fail', text: `${extra.length} pins joined to nets the source leaves them out of: ${extra.slice(0, 5).join(', ')}` });
905
+ const n = Object.keys(nets).length;
906
+ if (missing.length) out.push({ level: 'fail', text: `${missing.length} nets name pins the board doesn't have: ${missing.slice(0, 3).join('; ')}` });
907
+ if (split.length) out.push({ level: 'fail', text: `${split.length} nets are split in two or more on the board: ${split.slice(0, 5).join(', ')}` });
908
+ if (shorted.length) out.push({ level: 'fail', text: `nets joined that the source keeps apart: ${[...new Set(shorted)].slice(0, 5).join('; ')}` });
909
+ if (!out.length) out.push({ level: 'pass', text: `same circuit as the source: all ${n} nets join the same pins, and no others${Object.keys(all).length > n ? ` (${Object.keys(all).length - n} left to planes)` : ''}${added.length ? `, plus ${added.length} pins added: ${added.map((a) => `${a.pin} (${a.net.replace(/^\//, '')})`).join(', ')}` : ''}` });
910
+ return out;
911
+ }
912
+
913
+ // ---------- 3D models of parts ----------
914
+ /**
915
+ * A VRML model (KiCad's .wrl) as triangles, in mm: [[x, y, z] x3, ...]. KiCad's models are in tenths of an inch, z up
916
+ * out of the board, x and y as the footprint's (y towards its top). Faces with more than three corners are fanned.
917
+ * @param {string} text @param {number} [unit] mm per model unit (KiCad's: 2.54) @returns {number[][][]}
918
+ */
919
+ export function wrlMesh(text, unit = 2.54) {
920
+ const out = [];
921
+ for (const m of text.matchAll(/coordIndex\s*\[([^\]]*)\][\s\S]*?point\s*\[([^\]]*)\]/g)) {
922
+ const pts = m[2].split(',').map((p) => p.trim().split(/\s+/).map((n) => Number(n) * unit)).filter((p) => p.length === 3 && p.every(Number.isFinite));
923
+ let face = [];
924
+ for (const n of m[1].split(',').map((x) => Number(x.trim()))) {
925
+ if (n === -1) { for (let i = 1; i + 1 < face.length; i++) out.push([pts[face[0]], pts[face[i]], pts[face[i + 1]]]); face = []; }
926
+ else if (Number.isInteger(n) && pts[n]) face.push(n);
927
+ }
928
+ }
929
+ return out;
930
+ }
931
+
932
+ /**
933
+ * A STEP model's size: the box round every point it lists ({ min: [x, y, z], max }, mm), with no geometry kernel. For a
934
+ * model whose shape can't be shared (no licence) only its size is used, which is a fact about the part.
935
+ * @param {string} text @returns {{ min: number[], max: number[] } | null}
936
+ */
937
+ export function stepBounds(text) {
938
+ const k = /SI_UNIT\s*\(\s*\.MILLI\.\s*,\s*\.METRE\.\s*\)/i.test(text) ? 1 : /INCH/i.test(text) ? 25.4 : /SI_UNIT\s*\(\s*\$\s*,\s*\.METRE\./i.test(text) ? 1000 : 1;
939
+ const min = [Infinity, Infinity, Infinity], max = [-Infinity, -Infinity, -Infinity];
940
+ for (const m of text.matchAll(/CARTESIAN_POINT\s*\(\s*'[^']*'\s*,\s*\(\s*([-\d.Ee+]+)\s*,\s*([-\d.Ee+]+)\s*,\s*([-\d.Ee+]+)\s*\)/g))
941
+ for (let i = 0; i < 3; i++) { const v = Number(m[i + 1]) * k; min[i] = Math.min(min[i], v); max[i] = Math.max(max[i], v); }
942
+ return Number.isFinite(min[0]) ? { min: min.map(r4), max: max.map(r4) } : null;
943
+ }
944
+
945
+ // A box as triangles
946
+ /**
947
+ * Pin headers under a board, for its 3D model: at each hole, a square pin through the board and a plastic spacer under
948
+ * it, sized as a standard 2.54 mm male header (pin 0.64 mm square; spacer 2.54 mm square, 2.5 mm tall; 6 mm of pin
949
+ * below it, 3 mm above). Give the result as a part's `model`: { boxes } in the part's frame, z from the board's top.
950
+ * @param {{ x, y }[]} holes in the part's frame @param {object} [o] { thickness = 1.6, pitch = 2.54, pin = 0.64, spacer = 2.5, below = 6, above = 3 }
951
+ */
952
+ export function pinHeaders(holes, { thickness = 1.6, pitch = 2.54, pin = 0.64, spacer = 2.5, below = 6, above = 3 } = {}) {
953
+ const bottom = -thickness - spacer; // the spacer's underside, from the board's top
954
+ return { boxes: holes.flatMap(({ x, y }) => [
955
+ { min: [x - pitch / 2, y - pitch / 2, bottom], max: [x + pitch / 2, y + pitch / 2, -thickness] },
956
+ { min: [x - pin / 2, y - pin / 2, bottom - below], max: [x + pin / 2, y + pin / 2, -thickness + above] }]) };
957
+ }
958
+
959
+ function boxMesh({ min: [x0, y0, z0], max: [x1, y1, z1] }) {
960
+ const v = [[x0, y0, z0], [x1, y0, z0], [x1, y1, z0], [x0, y1, z0], [x0, y0, z1], [x1, y0, z1], [x1, y1, z1], [x0, y1, z1]];
961
+ return [[0, 2, 1], [0, 3, 2], [4, 5, 6], [4, 6, 7], [0, 1, 5], [0, 5, 4], [1, 2, 6], [1, 6, 5], [2, 3, 7], [2, 7, 6], [3, 0, 4], [3, 4, 7]].map((f) => f.map((i) => v[i]));
962
+ }
963
+
964
+ /**
965
+ * Each part's 3D model on the board, as triangles in the board's frame (board bottom at z = 0, top at thickness): the
966
+ * model's own scale, turn and offset as KiCad applies them, then the part's place; a part on the back hangs below,
967
+ * turned over. meshes: { file: triangles } for models with a mesh; a model with only a box is drawn as that box, and
968
+ * one with boxes (pinHeaders) as those.
969
+ * @param {object[]} json render's @param {{ thickness: number, meshes?: object }} o @returns {number[][][]}
970
+ */
971
+ export function partModels(json, { thickness, meshes = {} }) {
972
+ const rad = Math.PI / 180, out = [];
973
+ for (const c of json.filter((e) => e.type === 'cad_component' && e.rulecad_model)) {
974
+ const m = c.rulecad_model, tris = m.mesh ? meshes[m.mesh] : m.box ? boxMesh(m.box) : m.boxes ? m.boxes.flatMap(boxMesh) : null;
975
+ if (!tris) continue;
976
+ const [sx, sy, sz] = m.scale ?? [1, 1, 1], [rx, ry, rz] = (m.rotate ?? [0, 0, 0]).map((a) => -a * rad), [ox, oy, oz] = m.offset ?? [0, 0, 0];
977
+ const turn = (v) => { // KiCad's model turn: about x, then y, then z
978
+ let [x, y, z] = v;
979
+ [y, z] = [y * Math.cos(rx) - z * Math.sin(rx), y * Math.sin(rx) + z * Math.cos(rx)];
980
+ [x, z] = [x * Math.cos(ry) + z * Math.sin(ry), -x * Math.sin(ry) + z * Math.cos(ry)];
981
+ [x, y] = [x * Math.cos(rz) - y * Math.sin(rz), x * Math.sin(rz) + y * Math.cos(rz)];
982
+ return [x, y, z];
983
+ };
984
+ const back = m.layer === 'bottom', t = (m.rotation * Math.PI) / 180, ct = Math.cos(t), st = Math.sin(t), tt = (m.turn * Math.PI) / 180;
985
+ const place = (v) => {
986
+ let [x, y, z] = turn([v[0] * sx, v[1] * sy, v[2] * sz]);
987
+ x += ox; y += oy; z += oz;
988
+ if (m.turn) [x, y] = [x * Math.cos(tt) - y * Math.sin(tt), x * Math.sin(tt) + y * Math.cos(tt)]; // a part at an angle that isn't a quarter turn
989
+ if (back) { x = -x; y = -y; } // the part's own frame on the back is the footprint's turned half round (as its pads are)
990
+ const m1 = back ? -1 : 1;
991
+ return [r4(m.x + m1 * (ct * x - st * y)), r4(m.y + (st * x + ct * y)), r4(back ? -z : thickness + z)];
992
+ };
993
+ for (const tri of tris) out.push(tri.map(place));
994
+ }
995
+ return out;
996
+ }
997
+
357
998
  // ---------- board shapes ----------
358
999
  // Outlines for board.outline: closed polygons, counter-clockwise, centred on at (default the origin). Curves are cut
359
1000
  // into segments (default 8 per quarter circle: fine for a router and a fab, which mills them as arcs anyway).
@@ -395,13 +1036,15 @@ export const render = (board, options) => circuitJson(board, options); // option
395
1036
  // The board as a solid (previews, fits, the on-screen copy, the model page): the bare board, drilled, bottom at z = 0. Its
396
1037
  // copper is drawn in the 2D views (views), not in 3D. The board is a 2D outline with its holes, extruded: its faces
397
1038
  // triangulate cleanly (cylinders subtracted from a block leave long slivers).
398
- export function solids(json, { thickness, smooth = 16 }) { // smooth: segments per hole (a board without the variable gets 16)
1039
+ export function solids(json, { thickness, smooth = 16, models }) { // models: { file: triangles }, the parts' meshes (cad loads them) // smooth: segments per hole (a board without the variable gets 16)
399
1040
  const { rectangle, circle, polygon } = jscad.primitives, { subtract } = jscad.booleans, { extrudeLinear } = jscad.extrusions;
400
1041
  const b = json.find((e) => e.type === 'pcb_board');
401
1042
  const drills = json.filter((e) => e.type === 'pcb_hole' || e.type === 'pcb_plated_hole' || e.type === 'pcb_via')
402
- .map((e) => circle({ center: [e.x, e.y], radius: (e.hole_diameter ?? e.hole_width) / 2, segments: smooth }));
1043
+ .map((e) => circle({ center: [e.x + (e.hole_offset_x ?? 0), e.y + (e.hole_offset_y ?? 0)], radius: (e.hole_diameter ?? e.hole_width) / 2, segments: smooth })); // a hole off-centre in its pad, where the fab drills it
403
1044
  const outline = b.outline ? polygon({ points: b.outline.map((p) => [p.x, p.y]) }) : rectangle({ center: [b.center.x, b.center.y], size: [b.width, b.height] });
404
- return { board: extrudeLinear({ height: thickness }, drills.length ? subtract(outline, ...drills) : outline) };
1045
+ const board = extrudeLinear({ height: thickness }, drills.length ? subtract(outline, ...drills) : outline);
1046
+ const parts = models ? partModels(json, { thickness, meshes: models }) : [];
1047
+ return { board, ...(parts.length ? { components: jscad.geometries.geom3.fromPoints(parts) } : {}) }; // the parts' 3D models, where there are any
405
1048
  }
406
1049
 
407
1050
  // What a built board tells the parts around it, as numbers an assembly can use (board.pico_y): its outline (centre and
@@ -428,30 +1071,105 @@ export const holes = (json) => json.filter((e) => e.type === 'pcb_hole' && !e.pc
428
1071
 
429
1072
  // ---------- checks ----------
430
1073
  const mm = (x) => String(Number(x.toFixed(3))); // 0.30000000000000004 reads as 0.3
431
- // checks(json, v) -> findings ({ level, text }): tscircuit's own design checks, the fab's limits, and the matrix
432
- export async function checks(json, v, matrix) {
1074
+ // checks(json, v, matrix, source) -> findings ({ level, text }): tscircuit's own design checks, the fab's limits, the
1075
+ // matrix, and for a clone (source: { circuit, arranged }) the source's circuit and placement
1076
+ export async function checks(json, v, matrix, source) { // source: a clone's { circuit, arranged } (its own checks join these)
433
1077
  const { runAllChecks } = await import('@tscircuit/checks');
434
1078
  const out = [], j = v.jlcpcb;
435
1079
  const board = json.find((e) => e.type === 'pcb_board');
436
1080
  // On a shaped board, a part's box can reach past a curved edge when its copper doesn't (a ring on a round disc): that
437
1081
  // part is checked here pad by pad against the outline instead (below)
438
- const padsOf = (id) => json.filter((e) => e.pcb_component_id === id && ['pcb_smtpad', 'pcb_plated_hole'].includes(e.type));
1082
+ // Castellated pads sit on the edge by design: half holes the fab cuts through. They're checked against its rules for them below
1083
+ // (with the other pads of their pins: a header pad beside a half hole runs into it, as on a Pico)
1084
+ const castellated = json.filter((e) => e.type === 'pcb_plated_hole' && e.port_hints?.includes('castellated'));
1085
+ const pinOf = (e) => `${e.pcb_component_id}:${e.port_hints?.[1]}`, edgePins = new Set(castellated.map(pinOf));
1086
+ const halves = new Set(json.filter((e) => e.type === 'pcb_plated_hole' && edgePins.has(pinOf(e))).map((e) => e.pcb_plated_hole_id));
1087
+ const padsOf = (id) => json.filter((e) => e.pcb_component_id === id && ['pcb_smtpad', 'pcb_plated_hole'].includes(e.type) && !halves.has(e.pcb_plated_hole_id));
439
1088
  const fits = (id) => board.outline && padsOf(id).every((e) => (e.points || [e]).every((q) => inside(board.outline, q.x, q.y)));
440
- const drc = (await runAllChecks(json)).filter((e) => !(e.type === 'pcb_component_outside_board_error' && fits(e.pcb_component_id)));
1089
+ const onEdge = (e) => { const t = JSON.stringify(e); return [...halves].some((id) => new RegExp(`${id}(?!\\d)`).test(t)); };
1090
+ // 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
1091
+ // source's design (a mid-mount socket in its notch): said, not failed. Anything else near the edge fails as usual
1092
+ 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));
1093
+ const drc = (await runAllChecks(json)).filter((e) => !(e.type === 'pcb_component_outside_board_error' && fits(e.pcb_component_id)) && !onEdge(e))
1094
+ .filter((e) => !(same?.(e) && inherited.push(e)))
1095
+ .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
441
1096
  const problems = [...json, ...drc].filter((e) => /_error$/.test(e.type));
442
1097
  const seen = new Set(), errors = problems.filter((e) => !seen.has(e.message) && seen.add(e.message));
443
1098
  out.push(errors.length ? { level: 'fail', text: `${errors.length} design-rule errors: ${errors.slice(0, 3).map((e) => e.message).join('; ')}` } : { level: 'pass', text: 'tscircuit\'s design checks: no errors (traces, clearances, holes, board edge)' });
444
- const traces = json.filter((e) => e.type === 'pcb_trace'), unrouted = json.filter((e) => e.type === 'source_trace').length - traces.length;
1099
+ // Connections between pads: as many tracks as connections (the router names a net's pieces after its connections). To
1100
+ // a plane: a track to a via, or the pad's own hole
1101
+ const traces = json.filter((e) => e.type === 'pcb_trace'), toPlane = json.filter((e) => e.type === 'source_trace' && e.connected_source_net_ids?.length);
1102
+ const planeIds = new Set(toPlane.map((t) => t.source_trace_id)), tracked = new Set(traces.map((t) => t.source_trace_id));
1103
+ const holePorts = new Set(json.filter((e) => e.type === 'pcb_plated_hole').map((e) => json.find((p) => p.type === 'pcb_port' && p.pcb_port_id === e.pcb_port_id)?.source_port_id));
1104
+ const unrouted = json.filter((e) => e.type === 'source_trace').length - planeIds.size - traces.filter((t) => !planeIds.has(t.source_trace_id)).length
1105
+ + toPlane.filter((t) => !tracked.has(t.source_trace_id) && !holePorts.has(t.connected_source_port_ids[0])).length;
445
1106
  out.push(unrouted > 0 ? { level: 'fail', text: `${unrouted} connections have no track` } : { level: 'pass', text: `every connection is routed (${traces.length} tracks, ${json.filter((e) => e.type === 'pcb_via').length} vias)` });
1107
+ out.push(...planeChecks(json));
1108
+ // A clone's own routing, kept: every track and via of it on the board exactly as the source has it (smoothing and
1109
+ // repair move only the router's tracks), but for escapes cut back where a routed track turned straight back on them:
1110
+ // each of those a piece of the source's own track, named with how much went
1111
+ const keptCu = source?.arranged?.kept;
1112
+ if (keptCu?.tracks?.length) {
1113
+ const key = (x, y) => `${x.toFixed(4)},${y.toFixed(4)}`, seg = (layer, width, a, b) => `${layer} ${width} ${key(a.x, a.y)} ${key(b.x, b.y)}`;
1114
+ const tracksAt = new Set(keptCu.tracks.flatMap((g) => [seg(g.layer, g.width, g.a, g.b), seg(g.layer, g.width, g.b, g.a)])), viasAt = new Set(keptCu.vias.map((q) => key(q.x, q.y)));
1115
+ const theirs = (layer, width, a, b) => tracksAt.has(seg(layer, width, a, b));
1116
+ const laid = traces.filter((t) => t.rulecad_kept), isVia = (t) => t.route[1]?.route_type === 'via';
1117
+ const along = (o, p) => { const dx = o.b.x - o.a.x, dy = o.b.y - o.a.y, l = Math.hypot(dx, dy); return Math.abs((p.x - o.a.x) * dy - (p.y - o.a.y) * dx) / l < 1e-4 && ((p.x - o.a.x) * dx + (p.y - o.a.y) * dy) / l > -1e-4 && ((p.x - o.a.x) * dx + (p.y - o.a.y) * dy) / l < l + 1e-4; };
1118
+ const cutBy = [], moved = laid.filter((t) => {
1119
+ if (isVia(t)) return !viasAt.has(key(t.route[0].x, t.route[0].y));
1120
+ const [p, q] = t.route, w = p.width, layer = p.layer;
1121
+ if (t.route.length === 2 && theirs(layer, w, p, q)) return false;
1122
+ const o = t.rulecad_shortened; // a piece of the source's segment, from one of its ends
1123
+ if (o && t.route.length === 2 && theirs(layer, w, o.a, o.b) && along(o, p) && along(o, q) && [p, q].some((r) => [o.a, o.b].some((e) => key(e.x, e.y) === key(r.x, r.y)))) {
1124
+ cutBy.push(Math.hypot(o.b.x - o.a.x, o.b.y - o.a.y) - Math.hypot(q.x - p.x, q.y - p.y)); return false;
1125
+ }
1126
+ return true;
1127
+ });
1128
+ const gone = traces.flatMap((t) => (t.rulecad_trimmed || []).map((g) => ({ ...g, track: t })));
1129
+ const strays = gone.filter((g) => !theirs(g.a.layer, g.a.width, g.a, g.b));
1130
+ cutBy.push(...gone.map((g) => Math.hypot(g.b.x - g.a.x, g.b.y - g.a.y)));
1131
+ const escapes = traces.reduce((n, t) => n + (t.rulecad_cut || 0), 0);
1132
+ const vias = laid.filter(isVia).length, short = laid.filter((t) => t.rulecad_shortened).length, total = cutBy.reduce((n, d) => n + d, 0);
1133
+ out.push(moved.length || strays.length ? { level: 'fail', text: `${moved.length + strays.length} of the source's own tracks and vias aren't where the source has them` }
1134
+ : { level: 'pass', text: `the source's own routing as it was: ${laid.length - vias - short} tracks and ${vias} vias exactly where the source has them${cutBy.length ? `, but for ${escapes} escapes cut back where a routed track turned straight back on them (${gone.length} segments gone, ${short} shortened: ${mm(total)} mm of track in all)` : ''} (only the router's tracks are tidied)` });
1135
+ }
446
1136
  const thin = traces.flatMap((t) => t.route).filter((p) => p.width != null && p.width < j.track_min);
447
1137
  out.push(thin.length ? { level: 'fail', text: `tracks under JLCPCB's ${j.track_min} mm` } : { level: 'pass', text: `tracks ${mm(v.track ?? Math.min(...traces.flatMap((t) => t.route).map((p) => p.width).filter((w) => w != null)))} mm${v.clear != null ? `, gaps ${mm(v.clear)} mm` : ''}: over JLCPCB's ${j.track_min} / ${j.gap_min} mm` });
448
- const drills = json.filter((e) => e.type === 'pcb_hole' || e.type === 'pcb_plated_hole').map((e) => e.hole_diameter ?? e.hole_width);
1138
+ // Vias and plated holes against the fab's sizes, each measured from the board: the hole, the pad, and the ring
1139
+ // between them (under the recommended ring a warning, under the least a failure). A clone's vias as its source
1140
+ // has them are the source's design: said, not failed
1141
+ 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;
1142
+ 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' }));
1143
+ 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);
1144
+ const inherited_ = rings.filter((r) => asSrc(r.e) && r.ring < j.annular).length;
1145
+ if (rings.length) {
1146
+ 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)})` }
1147
+ : 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` }
1148
+ : 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` }
1149
+ : { 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` : ''}` });
1150
+ }
1151
+ // Silkscreen the fab can print: lines no thinner than silk_line, text no smaller than silk_text
1152
+ 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);
1153
+ const silkTexts = json.filter((e) => e.type === 'pcb_silkscreen_text' && e.font_size != null && e.font_size < j.silk_text);
1154
+ if (json.some((e) => /^pcb_silkscreen_/.test(e.type))) out.push(silkLines.length || silkTexts.length
1155
+ ? { level: 'fail', text: `silkscreen the fab can't print: ${[silkLines.length && `${silkLines.length} lines under ${j.silk_line} mm (${mm(Math.min(...silkLines.map((e) => e.stroke_width)))})`, silkTexts.length && `${silkTexts.length} texts under ${j.silk_text} mm high (${mm(Math.min(...silkTexts.map((e) => e.font_size)))})`].filter(Boolean).join(', ')}` }
1156
+ : { level: 'pass', text: `silkscreen: lines ${j.silk_line} mm or wider, text ${j.silk_text} mm or taller (JLCPCB's least)` });
1157
+ const drills = json.filter((e) => e.type === 'pcb_hole' || e.type === 'pcb_plated_hole' || e.type === 'pcb_via').map((e) => e.hole_diameter ?? e.hole_width);
449
1158
  if (drills.length) out.push(Math.min(...drills) < j.drill_min ? { level: 'fail', text: `a hole under JLCPCB's ${j.drill_min} mm` } : { level: 'pass', text: `${drills.length} holes, smallest ${Math.min(...drills)} mm (JLCPCB: ${j.drill_min} mm)` });
450
1159
  const b = json.find((e) => e.type === 'pcb_board'), size = `${b.width.toFixed(1)} × ${b.height.toFixed(1)} mm`;
451
1160
  if (b.outline) { // a shaped board: every pad and hole inside it
452
- const pads = json.filter((e) => ['pcb_smtpad', 'pcb_plated_hole', 'pcb_hole'].includes(e.type)), out_ = pads.filter((e) => (e.points || [e]).some((q) => !inside(b.outline, q.x, q.y)));
1161
+ const reaching = same ? same.reaching : new Set();
1162
+ const pads = json.filter((e) => ['pcb_smtpad', 'pcb_plated_hole', 'pcb_hole'].includes(e.type) && !halves.has(e.pcb_plated_hole_id) && !reaching.has(e.pcb_component_id)), out_ = pads.filter((e) => (e.points || [e]).some((q) => !inside(b.outline, q.x, q.y)));
453
1163
  out.push(out_.length ? { level: 'fail', text: `${out_.length} pads or holes outside the board's outline (first at ${mm(out_[0].x)}, ${mm(out_[0].y)} mm)` } : { level: 'pass', text: `shaped board (${b.outline.length} points): all ${pads.length} pads and holes inside it` });
454
1164
  }
1165
+ if (castellated.length) { // JLCPCB's rules for half holes: big enough, far enough apart
1166
+ const small = castellated.filter((e) => e.hole_diameter < (j.castellated_drill_min ?? 0.6));
1167
+ let gap = Infinity;
1168
+ for (const a of castellated) for (const c of castellated) if (a !== c) gap = Math.min(gap, Math.hypot(a.x - c.x, a.y - c.y) - (a.hole_diameter + c.hole_diameter) / 2);
1169
+ out.push(small.length || gap < (j.castellated_gap_min ?? 0.6)
1170
+ ? { level: 'fail', text: `castellated holes: ${small.length ? `${small.length} under JLCPCB's ${j.castellated_drill_min ?? 0.6} mm` : `${mm(gap)} mm apart, under JLCPCB's ${j.castellated_gap_min ?? 0.6} mm`}` }
1171
+ : { level: 'pass', text: `${castellated.length} castellated holes on the edge, ${mm(Math.min(...castellated.map((e) => e.hole_diameter)))} mm or more, ${mm(gap)} mm apart (JLCPCB: ${j.castellated_drill_min ?? 0.6} / ${j.castellated_gap_min ?? 0.6} mm). Order with castellated holes` });
1172
+ }
455
1173
  out.push(Math.max(b.width, b.height) <= j.cheap_size ? { level: 'pass', text: `${size}: within JLCPCB's lowest price (${j.cheap_size} × ${j.cheap_size} mm)` } : { level: 'info', text: `${size}: over ${j.cheap_size} × ${j.cheap_size} mm, priced by quote` });
456
1174
  if (matrix) {
457
1175
  const cells = new Set(matrix.keys.map((k) => `${k.row},${k.col}`)), gpio = [...Object.values(matrix.rows), ...Object.values(matrix.cols)];
@@ -459,11 +1177,69 @@ export async function checks(json, v, matrix) {
459
1177
  ? { 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(' ')})` }
460
1178
  : { level: 'fail', text: 'matrix: two keys share a row and column, or a GPIO is used twice' });
461
1179
  }
1180
+ 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)` : ''}` });
1181
+ if (source?.circuit) out.push(...sameCircuit(json, source.circuit, {}, source.arranged?.added || []), ...placementChecks(source.arranged || source.circuit, source.circuit.placement || learnPlacement(source.circuit)));
462
1182
  const notes = new Set([...json, ...drc].filter((e) => /_warning$/.test(e.type)).map((e) => e.type.replace(/^(source|pcb)_|_warning$/g, '').replace(/_/g, ' ')));
463
1183
  if (notes.size) out.push({ level: 'info', text: `tscircuit notes, none about the copper: ${[...notes].join(', ')}` });
464
1184
  return out;
465
1185
  }
466
1186
 
1187
+ // A clone's findings that the source has too: a pad whose centre is as far from the edge as on the source (to 0.02 mm),
1188
+ // a part that reaches past the outline there too, and the source's own vias, kept, where they touch its pads. Returns a test for a design-rule error, with .reaching:
1189
+ // the board's components that reach past it as on the source.
1190
+ function asSource(json, circuit, kept) {
1191
+ const toEdge = (pts, x, y) => { let d = Infinity; for (let i = 0; i < pts.length; i++) { const a = pts[i], b = pts[(i + 1) % pts.length], dx = b.x - a.x, dy = b.y - a.y, l = dx * dx + dy * dy, t = l ? Math.max(0, Math.min(1, ((x - a.x) * dx + (y - a.y) * dy) / l)) : 0; d = Math.min(d, Math.hypot(x - a.x - t * dx, y - a.y - t * dy)); } return d; };
1192
+ const src = new Map(), past = new Set(), so = circuit.outline;
1193
+ if (!so) return null;
1194
+ for (const p of circuit.parts) {
1195
+ for (const q of padsOnBoard(p)) { src.set(`${p.ref}.pin${q.pin}`, toEdge(so, q.bx, q.by)); if (!inside(so, q.bx, q.by)) past.add(p.ref); }
1196
+ for (const h of padsOnBoard({ ...p, pads: p.holes || [] })) if (!inside(so, h.bx, h.by)) past.add(p.ref); // its unplated holes too
1197
+ }
1198
+ const b = json.find((e) => e.type === 'pcb_board'), bo = b.outline;
1199
+ const comp = new Map(json.filter((e) => e.type === 'pcb_component').map((e) => [e.pcb_component_id, json.find((c) => c.source_component_id === e.source_component_id && c.type === 'source_component')?.name]));
1200
+ const reaching = new Set([...comp].filter(([, n]) => past.has(n)).map(([id]) => id));
1201
+ const sp = new Map(json.filter((e) => e.type === 'source_port').map((e) => [e.source_port_id, e]));
1202
+ const at = new Map();
1203
+ for (const e of json.filter((x) => (x.type === 'pcb_smtpad' || x.type === 'pcb_plated_hole') && x.pcb_port_id)) {
1204
+ const port = json.find((x) => x.type === 'pcb_port' && x.pcb_port_id === e.pcb_port_id), name = `${comp.get(e.pcb_component_id)}.${sp.get(port?.source_port_id)?.name}`;
1205
+ const c = e.type === 'pcb_smtpad' ? smtBounds(e) : e; if (!at.has(name)) at.set(name, c);
1206
+ }
1207
+ const test = (e) => {
1208
+ const m = e.message?.match(/^(?:SMT pad|Plated hole) (\S+) violates copper-to-board-edge/);
1209
+ if (m) { const c = at.get(m[1]), d = src.get(m[1]); return c != null && d != null && bo && Math.abs(toEdge(bo, c.x, c.y) - d) <= 0.02; }
1210
+ const k = e.message?.match(/^Component (\S+) extends outside board/);
1211
+ if (k) return past.has(k[1]);
1212
+ const v = e.message?.match(/^Via hole at \(([-\d.]+)mm, ([-\d.]+)mm\)/); // the source's own via, kept where it was
1213
+ return !!(v && kept?.vias.some((q) => Math.abs(q.x - Number(v[1])) < 0.01 && Math.abs(q.y - Number(v[2])) < 0.01));
1214
+ };
1215
+ test.reaching = reaching;
1216
+ return test;
1217
+ }
1218
+
1219
+ // Each plane net's vias and holes inside its plane's copper (the pour leaves a clear ring round the others)
1220
+ function planeChecks(json) {
1221
+ const nets = json.filter((e) => e.type === 'source_net'), out = [];
1222
+ if (!nets.length) return out;
1223
+ const inRing = (ring, p) => inside(ring.vertices, p.x, p.y);
1224
+ const covered = (pours, p) => pours.some((q) => inRing(q.brep_shape.outer_ring, p) && !q.brep_shape.inner_rings.some((r) => inRing(r, p)));
1225
+ const port = new Map(json.filter((e) => e.type === 'pcb_port').map((e) => [e.source_port_id, e.pcb_port_id]));
1226
+ for (const n of nets) {
1227
+ const pours = json.filter((e) => e.type === 'pcb_copper_pour' && e.source_net_id === n.source_net_id);
1228
+ const st = json.filter((e) => e.type === 'source_trace' && e.connected_source_net_ids?.includes(n.source_net_id));
1229
+ const ids = new Set(st.map((t) => t.source_trace_id)), pts = [];
1230
+ for (const t of json.filter((e) => e.type === 'pcb_trace' && ids.has(e.source_trace_id))) for (const v of json.filter((e) => e.type === 'pcb_via' && e.pcb_trace_id === t.pcb_trace_id)) pts.push(v);
1231
+ for (const t of st) { // a pin's hole (a castellated pin's header pad, not its half hole on the edge)
1232
+ const h = json.find((e) => e.type === 'pcb_plated_hole' && e.pcb_port_id === port.get(t.connected_source_port_ids[0]) && !e.port_hints?.includes('castellated'));
1233
+ if (h) pts.push(h);
1234
+ }
1235
+ const miss = pts.filter((p) => !covered(pours, p));
1236
+ out.push(!pours.length ? { level: 'fail', text: `plane ${n.name}: no copper drawn` }
1237
+ : miss.length ? { level: 'fail', text: `plane ${n.name}: ${miss.length} of its vias and holes are outside its copper (first at ${mm(miss[0].x)}, ${mm(miss[0].y)} mm)` }
1238
+ : { level: 'pass', text: `plane ${n.name} on ${pours[0].layer}: all ${st.length} pads reach it (${pts.length} vias and holes inside its copper)` });
1239
+ }
1240
+ return out;
1241
+ }
1242
+
467
1243
  // ---------- files ----------
468
1244
  // The fab files: Gerbers (KiCad's Protel names, which JLCPCB reads), drill files, BOM and placement -> { name: text }
469
1245
  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' };
@@ -471,7 +1247,7 @@ export async function fabFiles(json, name) {
471
1247
  const { convertSoupToGerberCommands, stringifyGerberCommandLayers, convertSoupToExcellonDrillCommands, stringifyExcellonDrill } = await import('circuit-json-to-gerber');
472
1248
  const { convertCircuitJsonToPickAndPlaceCsv } = await import('circuit-json-to-pnp-csv');
473
1249
  const out = {};
474
- for (const [layer, text] of Object.entries(stringifyGerberCommandLayers(convertSoupToGerberCommands(json)))) if (PROTEL[layer]) out[`${name}.${PROTEL[layer]}`] = text; // fab notes (B_Fab) stay out
1250
+ for (const [layer, text] of Object.entries(stringifyGerberCommandLayers(convertSoupToGerberCommands(json)))) { const ext = PROTEL[layer] ?? (layer.match(/^In(\d+)_Cu$/) ? `G${layer.match(/\d+/)[0]}` : null); if (ext) out[`${name}.${ext}`] = text; } // fab notes (B_Fab) stay out
475
1251
  out[`${name}-PTH.DRL`] = stringifyExcellonDrill(convertSoupToExcellonDrillCommands({ circuitJson: json, is_plated: true }));
476
1252
  out[`${name}-NPTH.DRL`] = stringifyExcellonDrill(convertSoupToExcellonDrillCommands({ circuitJson: json, is_plated: false }));
477
1253
  out[`${name}-bom.csv`] = bom(json);
@@ -479,17 +1255,20 @@ export async function fabFiles(json, name) {
479
1255
  return out;
480
1256
  }
481
1257
 
482
- // The BOM in JLCPCB's columns (Comment, Designator, Footprint, LCSC Part #), one line per kind of part. The LCSC
483
- // numbers are blank until parts are chosen for assembly; a hand-soldered board doesn't need them.
1258
+ // The BOM in JLCPCB's columns (Comment, Designator, Footprint, LCSC Part #), one line per kind of part. A part's LCSC
1259
+ // number comes with it when it has one (a clone's parts keep the source's); otherwise it's blank until parts are chosen
1260
+ // for assembly, and a hand-soldered board doesn't need them.
484
1261
  const FOOTPRINT = { K: 'Cherry MX, PCB mount', U: 'Raspberry Pi Pico, 0.1 in header pins', D: 'SOD-123' };
485
1262
  function bom(json) {
486
1263
  const lines = new Map(), q = (x) => `"${String(x).replace(/"/g, '""')}"`;
487
- for (const c of json.filter((e) => e.type === 'source_component')) {
488
- const comment = c.manufacturer_part_number || c.name, footprint = FOOTPRINT[c.name[0]] || '', key = `${comment}|${footprint}`;
489
- if (!lines.has(key)) lines.set(key, { comment, footprint, refs: [] });
1264
+ for (const c of json.filter((e) => e.type === 'source_component' && !e.exclude_from_bom)) {
1265
+ const lcsc = c.supplier_part_numbers?.jlcpcb?.[0] ?? '', comment = c.display_value || c.manufacturer_part_number || c.name;
1266
+ const footprint = lcsc ? '' : FOOTPRINT[c.name[0]] || ''; // a keyboard's parts by their letter; a part with an LCSC number is known by that
1267
+ const key = `${comment}|${footprint}|${lcsc}`;
1268
+ if (!lines.has(key)) lines.set(key, { comment, footprint, lcsc, refs: [] });
490
1269
  lines.get(key).refs.push(c.name);
491
1270
  }
492
- return ['Comment,Designator,Footprint,LCSC Part #', ...[...lines.values()].map((l) => [l.comment, l.refs.join(','), l.footprint, ''].map(q).join(','))].join('\n') + '\n';
1271
+ return ['Comment,Designator,Footprint,LCSC Part #', ...[...lines.values()].map((l) => [l.comment, l.refs.join(','), l.footprint, l.lcsc].map(q).join(','))].join('\n') + '\n';
493
1272
  }
494
1273
 
495
1274
  // KiCad's own files, to check with kicad-cli or finish by hand: { 'name.kicad_pcb': text, 'name.kicad_sch': text }