@rulecad/pcb 0.5.5 → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/circuit.mjs CHANGED
@@ -15,6 +15,8 @@
15
15
  // holes: [{ x, y, d }], courtyard: { w, h } | null,
16
16
  // footprint: 'sod123' | 'jst4_sh' | 'pinrow4' ... (a footprinter string, SMD or through-hole, instead of pads),
17
17
  // sch: { x, y, symbol?, pinLabels? } }
18
+ // a diode's two ports are its 'cathode' (pin 1, also 'K') and 'anode' (pin 2, also 'A'): a pad whose pin is
19
+ // 'cathode' or 'anode' is that end, else pad 1 is the cathode, as KiCad and assemblers number a diode's pads
18
20
  // trace { from: [part, port], to: [part, port], width, path: [{ x, y }] (absolute, between the two ports), layer }; a trace
19
21
  // without a path is left to the autorouter when board.autoroute is set
20
22
  // nets { GND: ['U1.GND', 'J1.1', 'J2.1'] } or { GND: { pins: [...], width } }: each net's pins are joined by the
@@ -41,7 +43,8 @@
41
43
  // a source's own routing, kept (moveGroup's keep): laid as it is; its pins count as joined. An island marked
42
44
  // after: true is laid once the rest is routed, unseen by the router
43
45
  // pads may be castellated ({ castellated: true }: a half hole on the edge, joined at its inner edge) or a rounded
44
- // rectangle round their hole ({ rect: { w, h, offset: [x, y] } }: an oval pad, a hole off-centre)
46
+ // rectangle round their hole ({ rect: { w, h, offset: [x, y], slot: [w, h] } }: an oval pad, a hole off-centre
47
+ // (offset: from the copper's centre to the hole; none, the hole at the centre), a slotted hole)
45
48
  // All positions are in mm, in the board's own frame. A part on the bottom is seen from above: mirrored in x.
46
49
  import { fp } from '@tscircuit/footprinter';
47
50
  import { symbols } from 'schematic-symbols';
@@ -58,13 +61,26 @@ function quarter(r = 0) {
58
61
  return t;
59
62
  }
60
63
  // The board's manufacturing minimums (mm): tscircuit's defaults, within what common fabs make. The router keeps to them.
61
- const FAB_MINIMUMS = { min_trace_width: 0.1, min_via_hole_diameter: 0.2, min_via_pad_diameter: 0.3, min_via_hole_edge_to_via_hole_edge_clearance: 0.1,
62
- min_trace_to_hole_edge_clearance: 0.2, min_trace_to_pad_edge_clearance: 0.1, min_pad_edge_to_pad_edge_clearance: 0.1,
63
- min_plated_hole_drill_edge_to_drill_edge_clearance: 0.15, min_board_edge_clearance: 0.2 };
64
+ const FAB_MINIMUMS = {
65
+ min_trace_width: 0.1,
66
+ min_via_hole_diameter: 0.2,
67
+ min_via_pad_diameter: 0.3,
68
+ min_via_hole_edge_to_via_hole_edge_clearance: 0.1,
69
+ min_trace_to_hole_edge_clearance: 0.2,
70
+ min_trace_to_pad_edge_clearance: 0.1,
71
+ min_pad_edge_to_pad_edge_clearance: 0.1,
72
+ min_plated_hole_drill_edge_to_drill_edge_clearance: 0.15,
73
+ min_board_edge_clearance: 0.2,
74
+ };
64
75
 
65
76
  // A board with an outline: its centre and size from the outline's bounds (an explicit centre, width or height wins)
66
77
  export function bounds(points) {
67
- const xs = points.map((p) => p.x), ys = points.map((p) => p.y), x0 = Math.min(...xs), x1 = Math.max(...xs), y0 = Math.min(...ys), y1 = Math.max(...ys);
78
+ const xs = points.map((p) => p.x),
79
+ ys = points.map((p) => p.y),
80
+ x0 = Math.min(...xs),
81
+ x1 = Math.max(...xs),
82
+ y0 = Math.min(...ys),
83
+ y1 = Math.max(...ys);
68
84
  return { center: { x: (x0 + x1) / 2, y: (y0 + y1) / 2 }, width: x1 - x0, height: y1 - y0 };
69
85
  }
70
86
 
@@ -72,23 +88,35 @@ export function bounds(points) {
72
88
  function insidePolygon(points, { x, y }) {
73
89
  let hit = false;
74
90
  for (let i = 0, j = points.length - 1; i < points.length; j = i++) {
75
- const a = points[i], b = points[j];
76
- if ((a.y > y) !== (b.y > y) && x < ((b.x - a.x) * (y - a.y)) / (b.y - a.y) + a.x) hit = !hit;
91
+ const a = points[i],
92
+ b = points[j];
93
+ if (a.y > y !== b.y > y && x < ((b.x - a.x) * (y - a.y)) / (b.y - a.y) + a.x) hit = !hit;
77
94
  }
78
95
  return hit;
79
96
  }
80
97
 
81
98
  // A polygon as horizontal strips step tall (each the span of the polygon across its middle): boxes a router can use
82
99
  function strips(points, step) {
83
- const ys = points.map((q) => q.y), y0 = Math.min(...ys), y1 = Math.max(...ys), out = [];
100
+ const ys = points.map((q) => q.y),
101
+ y0 = Math.min(...ys),
102
+ y1 = Math.max(...ys),
103
+ out = [];
84
104
  for (let y = y0; y < y1; y += step) {
85
- const mid = Math.min(y + step / 2, y1), xs = [];
105
+ const mid = Math.min(y + step / 2, y1),
106
+ xs = [];
86
107
  for (let i = 0, j = points.length - 1; i < points.length; j = i++) {
87
- const a = points[i], b = points[j];
88
- if ((a.y > mid) !== (b.y > mid)) xs.push(a.x + ((mid - a.y) * (b.x - a.x)) / (b.y - a.y));
108
+ const a = points[i],
109
+ b = points[j];
110
+ if (a.y > mid !== b.y > mid) xs.push(a.x + ((mid - a.y) * (b.x - a.x)) / (b.y - a.y));
89
111
  }
90
112
  xs.sort((p, q) => p - q);
91
- for (let k = 0; k + 1 < xs.length; k += 2) out.push({ x: (xs[k] + xs[k + 1]) / 2, y: y + Math.min(step, y1 - y) / 2, w: xs[k + 1] - xs[k], h: Math.min(step, y1 - y) });
113
+ for (let k = 0; k + 1 < xs.length; k += 2)
114
+ out.push({
115
+ x: (xs[k] + xs[k + 1]) / 2,
116
+ y: y + Math.min(step, y1 - y) / 2,
117
+ w: xs[k + 1] - xs[k],
118
+ h: Math.min(step, y1 - y),
119
+ });
92
120
  }
93
121
  return out;
94
122
  }
@@ -97,18 +125,71 @@ function strips(points, step) {
97
125
  export function smtBounds(e) {
98
126
  if (e.shape === 'circle') return { x: e.x, y: e.y, w: e.radius * 2, h: e.radius * 2 };
99
127
  if (e.shape !== 'polygon') return { x: e.x, y: e.y, w: e.width, h: e.height };
100
- const xs = e.points.map((q) => q.x), ys = e.points.map((q) => q.y), x0 = Math.min(...xs), x1 = Math.max(...xs), y0 = Math.min(...ys), y1 = Math.max(...ys);
128
+ const xs = e.points.map((q) => q.x),
129
+ ys = e.points.map((q) => q.y),
130
+ x0 = Math.min(...xs),
131
+ x1 = Math.max(...xs),
132
+ y0 = Math.min(...ys),
133
+ y1 = Math.max(...ys);
101
134
  return { x: (x0 + x1) / 2, y: (y0 + y1) / 2, w: x1 - x0, h: y1 - y0 };
102
135
  }
103
136
 
137
+ // A number as a message shows it: NaN and Infinity as themselves (JSON writes them null), nothing as nothing
138
+ const shownNumber = (n) =>
139
+ n === undefined ? 'nothing' : typeof n === 'number' ? String(n) : (JSON.stringify(n) ?? String(n));
140
+ const isPlace = (n) => typeof n === 'number' && Number.isFinite(n);
141
+
142
+ // A board refused before anything is built, in plain words, where it has no size or a place that isn't a number (a
143
+ // mistake that would otherwise surface far away, as "reading toFixed" or "Illegal Parameters")
144
+ function checkBoard(board) {
145
+ if (board == null || typeof board !== 'object' || Array.isArray(board))
146
+ throw new Error(
147
+ `the board is an object ({ center, width, height, thickness, parts, ... }), not ${shownNumber(board)}`,
148
+ );
149
+ const place = (what, at) => {
150
+ for (const [k, n] of Object.entries(at))
151
+ if (!isPlace(n)) throw new Error(`${what}: ${k} is ${shownNumber(n)}, and it must be a number, in mm`);
152
+ };
153
+ if (board.outline) {
154
+ if (!Array.isArray(board.outline)) throw new Error('the board outline is a list of points ({ x, y }, in mm)');
155
+ board.outline.forEach((q, i) => place(`the board outline's point ${i + 1}`, { x: q?.x, y: q?.y }));
156
+ } else {
157
+ for (const k of ['width', 'height'])
158
+ if (!(isPlace(board[k]) && board[k] > 0))
159
+ throw new Error(
160
+ `the board needs a size: its ${k} is ${shownNumber(board[k])}, and it must be a number above 0, in mm (or give an outline, a list of points)`,
161
+ );
162
+ if (board.center == null || typeof board.center !== 'object')
163
+ throw new Error(`the board needs its centre: center is ${shownNumber(board.center)}, and it is { x, y }, in mm`);
164
+ place("the board's centre", { x: board.center.x, y: board.center.y });
165
+ }
166
+ for (const part of board.parts || []) {
167
+ const who = `part ${part?.name ?? '(no name)'}`;
168
+ place(who, { x: part?.x, y: part?.y });
169
+ (part.pads || []).forEach((p, i) => place(`${who}, pad ${p?.pin ?? i + 1}`, { x: p?.x, y: p?.y }));
170
+ (part.holes || []).forEach((h, i) => place(`${who}, hole ${i + 1}`, { x: h?.x, y: h?.y, d: h?.d }));
171
+ }
172
+ (board.holes || []).forEach((h, i) => place(`the board's hole ${i + 1}`, { x: h?.x, y: h?.y, d: h?.d }));
173
+ (board.traces || []).forEach((t, i) =>
174
+ (t?.path || []).forEach((q, j) => place(`trace ${i + 1}, its point ${j + 1}`, { x: q?.x, y: q?.y })),
175
+ );
176
+ }
177
+
104
178
  export async function circuitJson(board, { route = defaultRouter } = {}) {
179
+ checkBoard(board);
105
180
  board = { parts: [], traces: [], silk: [], ...board }; // the lists are optional
106
181
  if (board.outline) {
107
182
  if (board.outline.length < 3) throw new Error('a board outline needs at least 3 points');
108
183
  board = { ...bounds(board.outline), ...board };
109
184
  }
110
- const out = [], next = {}, id = (type) => `${type}_${(next[type] = (next[type] ?? -1) + 1)}`;
111
- const add = (type, fields) => { const e = { type, [`${type}_id`]: id(type), ...fields }; out.push(e); return e; };
185
+ const out = [],
186
+ next = {},
187
+ id = (type) => `${type}_${(next[type] = (next[type] ?? -1) + 1)}`;
188
+ const add = (type, fields) => {
189
+ const e = { type, [`${type}_id`]: id(type), ...fields };
190
+ out.push(e);
191
+ return e;
192
+ };
112
193
 
113
194
  add('source_project_metadata', { software_used_string: '@rulecad/pcb' });
114
195
  add('source_group', { is_subcircuit: true, was_automatically_named: true, subcircuit_id: SUB });
@@ -120,168 +201,498 @@ export async function circuitJson(board, { route = defaultRouter } = {}) {
120
201
  const pinPads = new Map(); // `${part}.${pin name}` -> each of its pads: { key (in ports), x, y, reach (its copper's half size) }
121
202
  const placed = [];
122
203
  for (const part of board.parts) {
123
- const comp = add('source_component', { ftype: part.ftype, name: part.name, manufacturer_part_number: part.mpn,
124
- ...(part.lcsc ? { supplier_part_numbers: { jlcpcb: [part.lcsc] } } : {}), ...(part.value ? { display_value: part.value } : {}), ...(part.bom === false ? { exclude_from_bom: true } : {}),
125
- are_pins_interchangeable: part.ftype === 'simple_switch', source_group_id: 'source_group_0', subcircuit_id: SUB,
126
- ...(part.package || typeof part.footprint === 'string' ? { rulecad_package: part.package ?? part.footprint } : {}) }); // (for the BOM's footprint column)
204
+ const comp = add('source_component', {
205
+ ftype: part.ftype,
206
+ name: part.name,
207
+ manufacturer_part_number: part.mpn,
208
+ ...(part.lcsc ? { supplier_part_numbers: { jlcpcb: [part.lcsc] } } : {}),
209
+ ...(part.value ? { display_value: part.value } : {}),
210
+ ...(part.bom === false ? { exclude_from_bom: true } : {}),
211
+ are_pins_interchangeable: part.ftype === 'simple_switch',
212
+ source_group_id: 'source_group_0',
213
+ subcircuit_id: SUB,
214
+ ...(part.package || typeof part.footprint === 'string'
215
+ ? { rulecad_package: part.package ?? part.footprint }
216
+ : {}),
217
+ }); // (for the BOM's footprint column)
127
218
  const fpEls = part.footprint ? fp.string(part.footprint).circuitJson() : [];
128
219
  const mirror = part.layer === 'bottom' ? -1 : 1;
129
- const [cos, sin] = quarter(part.rotation), swap = sin !== 0;
220
+ const [cos, sin] = quarter(part.rotation),
221
+ swap = sin !== 0;
130
222
  const at = (x, y) => ({ x: part.x + mirror * (cos * x - sin * y), y: part.y + (sin * x + cos * y) });
131
223
  const size = (w, h) => (swap ? { w: h, h: w } : { w, h }); // a rectangle turned a quarter swaps its sides
132
224
  // Pads: from the description, or a footprint's SMD pads and plated holes (pin n: hints ['n'])
133
225
  const pads = part.footprint
134
- ? fpEls.filter((e) => e.type === 'pcb_smtpad' || e.type === 'pcb_plated_hole').map((e) => e.type === 'pcb_smtpad'
135
- ? { smd: true, pin: `pin${e.port_hints[0]}`, hint: e.port_hints[0], ...at(e.x, e.y), ...size(e.width, e.height) }
136
- : { pin: `pin${e.port_hints[0]}`, hint: e.port_hints[0], ...at(e.x, e.y), hole: e.hole_diameter ?? Math.min(e.hole_width, e.hole_height),
137
- outer: e.outer_diameter ?? Math.max(e.rect_pad_width ?? e.outer_width ?? 0, e.rect_pad_height ?? e.outer_height ?? 0) })
226
+ ? fpEls
227
+ .filter((e) => e.type === 'pcb_smtpad' || e.type === 'pcb_plated_hole')
228
+ .map((e) =>
229
+ e.type === 'pcb_smtpad'
230
+ ? {
231
+ smd: true,
232
+ pin: `pin${e.port_hints[0]}`,
233
+ hint: e.port_hints[0],
234
+ ...at(e.x, e.y),
235
+ ...size(e.width, e.height),
236
+ }
237
+ : {
238
+ pin: `pin${e.port_hints[0]}`,
239
+ hint: e.port_hints[0],
240
+ ...at(e.x, e.y),
241
+ hole: e.hole_diameter ?? Math.min(e.hole_width, e.hole_height),
242
+ outer:
243
+ e.outer_diameter ??
244
+ Math.max(e.rect_pad_width ?? e.outer_width ?? 0, e.rect_pad_height ?? e.outer_height ?? 0),
245
+ },
246
+ )
138
247
  : part.pads.map((p) => {
139
- if (!p.points) return { ...p, ...at(p.x, p.y), ...(p.smd ? size(p.w, p.h) : {}) };
140
- const poly = p.points.map(([x, y]) => at(x, y)), xs = poly.map((q) => q.x), ys = poly.map((q) => q.y);
141
- return { ...p, ...at(p.x, p.y), poly, w: Math.max(...xs) - Math.min(...xs), h: Math.max(...ys) - Math.min(...ys), cx: (Math.max(...xs) + Math.min(...xs)) / 2, cy: (Math.max(...ys) + Math.min(...ys)) / 2 };
142
- });
248
+ if (!p.points) return { ...p, ...at(p.x, p.y), ...(p.smd ? size(p.w, p.h) : {}) };
249
+ const poly = p.points.map(([x, y]) => at(x, y)),
250
+ xs = poly.map((q) => q.x),
251
+ ys = poly.map((q) => q.y);
252
+ return {
253
+ ...p,
254
+ ...at(p.x, p.y),
255
+ poly,
256
+ w: Math.max(...xs) - Math.min(...xs),
257
+ h: Math.max(...ys) - Math.min(...ys),
258
+ cx: (Math.max(...xs) + Math.min(...xs)) / 2,
259
+ cy: (Math.max(...ys) + Math.min(...ys)) / 2,
260
+ };
261
+ });
143
262
  const names = portNames(part, pads);
144
- const sourcePorts = pads.map((p, i) => add('source_port', { name: names[i].name, pin_number: names[i].n, port_hints: names[i].hints,
145
- source_component_id: comp.source_component_id, subcircuit_id: SUB }));
146
- if (part.ftype === 'simple_chip') { // pins with the same label are joined inside the part (a Pico's GND pins)
147
- const byName = new Map(); for (const sp of sourcePorts) byName.set(sp.name, [...(byName.get(sp.name) || []), sp]); // (Object.groupBy needs Node 21)
263
+ const sourcePorts = pads.map((p, i) =>
264
+ add('source_port', {
265
+ name: names[i].name,
266
+ pin_number: names[i].n,
267
+ port_hints: names[i].hints,
268
+ source_component_id: comp.source_component_id,
269
+ subcircuit_id: SUB,
270
+ }),
271
+ );
272
+ if (part.ftype === 'simple_chip') {
273
+ // pins with the same label are joined inside the part (a Pico's GND pins)
274
+ const byName = new Map();
275
+ for (const sp of sourcePorts) byName.set(sp.name, [...(byName.get(sp.name) || []), sp]); // (Object.groupBy needs Node 21)
148
276
  const groups = [...byName.values()].filter((g) => g.length > 1);
149
277
  if (groups.length) comp.internally_connected_source_port_ids = groups.map((g) => g.map((s) => s.source_port_id));
150
- for (const g of groups) add('source_component_internal_connection', { source_component_id: comp.source_component_id, subcircuit_id: SUB, source_port_ids: g.map((s) => s.source_port_id) });
278
+ for (const g of groups)
279
+ add('source_component_internal_connection', {
280
+ source_component_id: comp.source_component_id,
281
+ subcircuit_id: SUB,
282
+ source_port_ids: g.map((s) => s.source_port_id),
283
+ });
151
284
  }
152
285
  placed.push({ part, comp, pads, sourcePorts, fpEls, at, mirror, size });
153
- if (part.model) { const { path, ...m } = part.model; // its 3D model: drawn by partModels, where the part is
154
- add('cad_component', { source_component_id: comp.source_component_id, position: { x: part.x, y: part.y, z: 0 }, rotation: { x: 0, y: 0, z: part.rotation ?? 0 }, layer: part.layer,
155
- subcircuit_id: SUB, rulecad_model: { ...m, source: path, x: part.x, y: part.y, rotation: part.rotation ?? 0, layer: part.layer } }); }
286
+ if (part.model) {
287
+ const { path, ...m } = part.model; // its 3D model: drawn by partModels, where the part is
288
+ add('cad_component', {
289
+ source_component_id: comp.source_component_id,
290
+ position: { x: part.x, y: part.y, z: 0 },
291
+ rotation: { x: 0, y: 0, z: part.rotation ?? 0 },
292
+ layer: part.layer,
293
+ subcircuit_id: SUB,
294
+ rulecad_model: { ...m, source: path, x: part.x, y: part.y, rotation: part.rotation ?? 0, layer: part.layer },
295
+ });
296
+ }
156
297
  }
157
298
  // (the vias the router may make: the board's sizes, else ones with the ring a fab recommends, 0.3 in 0.8)
158
- add('pcb_board', { source_board_id: sourceBoard.source_board_id, subcircuit_id: SUB, center: board.center, thickness: board.thickness, num_layers: copper.length, ...(board.finish ? { rulecad_finish: true } : {}),
159
- width: board.width, height: board.height, ...(board.outline ? { outline: board.outline.map(({ x, y }) => ({ x, y })) } : {}), material: 'fr4', ...FAB_MINIMUMS,
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)
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 });
299
+ add('pcb_board', {
300
+ source_board_id: sourceBoard.source_board_id,
301
+ subcircuit_id: SUB,
302
+ center: board.center,
303
+ thickness: board.thickness,
304
+ num_layers: copper.length,
305
+ ...(board.finish ? { rulecad_finish: true } : {}),
306
+ width: board.width,
307
+ height: board.height,
308
+ ...(board.outline ? { outline: board.outline.map(({ x, y }) => ({ x, y })) } : {}),
309
+ material: 'fr4',
310
+ ...FAB_MINIMUMS,
311
+ ...(board.fab
312
+ ? {
313
+ min_trace_width: board.fab.track_min,
314
+ min_trace_to_pad_edge_clearance: board.fab.gap_min,
315
+ min_pad_edge_to_pad_edge_clearance: board.fab.gap_min,
316
+ min_via_hole_edge_to_via_hole_edge_clearance: board.fab.gap_min,
317
+ }
318
+ : {}), // (the fab's own, when the board names its rules)
319
+ min_via_hole_diameter: board.route_via?.hole ?? board.via_hole ?? 0.3,
320
+ min_via_pad_diameter: board.route_via?.pad ?? board.via_pad ?? 0.8,
321
+ });
162
322
 
163
323
  for (const { part, comp, pads, sourcePorts, fpEls, at, mirror, size } of placed) {
164
324
  // The component sits at the middle of its pads and holes (as tscircuit places it: pick-and-place reads this)
165
- const extent = [...pads.map((p) => (p.poly ? [p.cx - p.w / 2, p.cy - p.h / 2, p.cx + p.w / 2, p.cy + p.h / 2] : p.smd ? [p.x - p.w / 2, p.y - p.h / 2, p.x + p.w / 2, p.y + p.h / 2] : [p.x - p.outer / 2, p.y - p.outer / 2, p.x + p.outer / 2, p.y + p.outer / 2])),
166
- ...(part.holes || []).map((h) => { const q = at(h.x, h.y); return [q.x - h.d / 2, q.y - h.d / 2, q.x + h.d / 2, q.y + h.d / 2]; })];
167
- const box = [Math.min(...extent.map((e) => e[0])), Math.min(...extent.map((e) => e[1])), Math.max(...extent.map((e) => e[2])), Math.max(...extent.map((e) => e[3]))];
168
- const pc = add('pcb_component', { center: { x: (box[0] + box[2]) / 2, y: (box[1] + box[3]) / 2 }, width: box[2] - box[0], height: box[3] - box[1],
169
- layer: part.layer, rotation: part.rotation ?? 0, source_component_id: comp.source_component_id, subcircuit_id: SUB, ...(part.place === false ? { do_not_place: true } : {}) });
325
+ const extent = [
326
+ ...pads.map((p) =>
327
+ p.poly
328
+ ? [p.cx - p.w / 2, p.cy - p.h / 2, p.cx + p.w / 2, p.cy + p.h / 2]
329
+ : p.smd
330
+ ? [p.x - p.w / 2, p.y - p.h / 2, p.x + p.w / 2, p.y + p.h / 2]
331
+ : [p.x - p.outer / 2, p.y - p.outer / 2, p.x + p.outer / 2, p.y + p.outer / 2],
332
+ ),
333
+ ...(part.holes || []).map((h) => {
334
+ const q = at(h.x, h.y);
335
+ return [q.x - h.d / 2, q.y - h.d / 2, q.x + h.d / 2, q.y + h.d / 2];
336
+ }),
337
+ ];
338
+ const box = [
339
+ Math.min(...extent.map((e) => e[0])),
340
+ Math.min(...extent.map((e) => e[1])),
341
+ Math.max(...extent.map((e) => e[2])),
342
+ Math.max(...extent.map((e) => e[3])),
343
+ ];
344
+ const pc = add('pcb_component', {
345
+ center: { x: (box[0] + box[2]) / 2, y: (box[1] + box[3]) / 2 },
346
+ width: box[2] - box[0],
347
+ height: box[3] - box[1],
348
+ layer: part.layer,
349
+ rotation: part.rotation ?? 0,
350
+ source_component_id: comp.source_component_id,
351
+ subcircuit_id: SUB,
352
+ ...(part.place === false ? { do_not_place: true } : {}),
353
+ });
170
354
  const own = { pcb_component_id: pc.pcb_component_id, subcircuit_id: SUB };
171
355
  pads.forEach((p, i) => {
172
356
  const layers = p.smd ? [part.layer] : copper;
173
- const port = add('pcb_port', { pcb_component_id: pc.pcb_component_id, layers, subcircuit_id: SUB, x: p.x, y: p.y, source_port_id: sourcePorts[i].source_port_id });
174
- if (p.poly) { // copper of any shape: no paste (a contact, not a joint)
175
- add('pcb_smtpad', { ...own, pcb_port_id: port.pcb_port_id, layer: part.layer, shape: 'polygon', points: p.poly, port_hints: [p.hint ?? p.pin.replace(/^pin/, '')], is_covered_with_solder_mask: false });
357
+ const port = add('pcb_port', {
358
+ pcb_component_id: pc.pcb_component_id,
359
+ layers,
360
+ subcircuit_id: SUB,
361
+ x: p.x,
362
+ y: p.y,
363
+ source_port_id: sourcePorts[i].source_port_id,
364
+ });
365
+ if (p.poly) {
366
+ // copper of any shape: no paste (a contact, not a joint)
367
+ add('pcb_smtpad', {
368
+ ...own,
369
+ pcb_port_id: port.pcb_port_id,
370
+ layer: part.layer,
371
+ shape: 'polygon',
372
+ points: p.poly,
373
+ port_hints: [p.hint ?? p.pin.replace(/^pin/, '')],
374
+ is_covered_with_solder_mask: false,
375
+ });
176
376
  } else if (p.smd) {
177
- const pad = add('pcb_smtpad', { ...own, pcb_port_id: port.pcb_port_id, layer: part.layer, port_hints: [p.hint], is_covered_with_solder_mask: false, x: p.x, y: p.y,
178
- ...(p.circle ? { shape: 'circle', radius: p.w / 2 } : { shape: 'rect', width: p.w, height: p.h, ...(p.corner ? { corner_radius: p.corner } : {}) }) });
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 });
180
- } else if (p.rect) { // an oval pad or a hole off-centre: a rounded rectangle, its hole offset turned with the part
181
- const sz = size(p.rect.w, p.rect.h), o0 = at(0, 0), o1 = at(p.rect.offset[0], p.rect.offset[1]);
377
+ const pad = add('pcb_smtpad', {
378
+ ...own,
379
+ pcb_port_id: port.pcb_port_id,
380
+ layer: part.layer,
381
+ port_hints: [p.hint],
382
+ is_covered_with_solder_mask: false,
383
+ x: p.x,
384
+ y: p.y,
385
+ ...(p.circle
386
+ ? { shape: 'circle', radius: p.w / 2 }
387
+ : { shape: 'rect', width: p.w, height: p.h, ...(p.corner ? { corner_radius: p.corner } : {}) }),
388
+ });
389
+ add('pcb_solder_paste', {
390
+ layer: part.layer,
391
+ shape: 'rect',
392
+ width: p.w * PASTE,
393
+ height: p.h * PASTE,
394
+ x: p.x,
395
+ y: p.y,
396
+ pcb_component_id: pc.pcb_component_id,
397
+ pcb_smtpad_id: pad.pcb_smtpad_id,
398
+ subcircuit_id: SUB,
399
+ });
400
+ } else if (p.rect) {
401
+ // an oval pad or a hole off-centre: a rounded rectangle, its hole offset turned with the part
402
+ const sz = size(p.rect.w, p.rect.h),
403
+ o0 = at(0, 0),
404
+ [ox, oy] = p.rect.offset ?? [0, 0], // (a hole at the copper's centre when the pad gives no offset)
405
+ o1 = at(ox, oy);
182
406
  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',
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,
185
- port_hints: [`unnamed_platedhole${i + 1}`, p.pin], x: p.x, y: p.y, layers, is_covered_with_solder_mask: false });
407
+ add('pcb_plated_hole', {
408
+ ...own,
409
+ pcb_port_id: port.pcb_port_id,
410
+ ...(slot
411
+ ? { shape: 'pill_hole_with_rect_pad', hole_shape: 'pill', hole_width: slot.w, hole_height: slot.h }
412
+ : { shape: 'circular_hole_with_rect_pad', hole_shape: 'circle', hole_diameter: p.hole }),
413
+ pad_shape: 'rect',
414
+ rect_pad_width: sz.w,
415
+ rect_pad_height: sz.h,
416
+ rect_border_radius: Math.min(sz.w, sz.h) / 2,
417
+ hole_offset_x: Math.round((o1.x - o0.x) * 1e6) / 1e6,
418
+ hole_offset_y: Math.round((o1.y - o0.y) * 1e6) / 1e6,
419
+ port_hints: [`unnamed_platedhole${i + 1}`, p.pin],
420
+ x: p.x,
421
+ y: p.y,
422
+ layers,
423
+ is_covered_with_solder_mask: false,
424
+ });
186
425
  } else {
187
- add('pcb_plated_hole', { ...own, pcb_port_id: port.pcb_port_id, outer_diameter: p.outer, hole_diameter: p.hole, shape: 'circle',
188
- port_hints: [`unnamed_platedhole${i + 1}`, p.pin, ...(p.castellated ? ['castellated'] : [])], x: p.x, y: p.y, layers, is_covered_with_solder_mask: false });
426
+ add('pcb_plated_hole', {
427
+ ...own,
428
+ pcb_port_id: port.pcb_port_id,
429
+ outer_diameter: p.outer,
430
+ hole_diameter: p.hole,
431
+ shape: 'circle',
432
+ port_hints: [`unnamed_platedhole${i + 1}`, p.pin, ...(p.castellated ? ['castellated'] : [])],
433
+ x: p.x,
434
+ y: p.y,
435
+ layers,
436
+ is_covered_with_solder_mask: false,
437
+ });
189
438
  }
190
439
  Object.assign(sourcePorts[i], { _pcb: port });
191
440
  // A castellated pad's centre is on the board's edge: tracks join it at its inner side, mid-way across its copper
192
441
  // ring (on the ring's very edge, the router may not count the join as in the pad)
193
442
  const join = p.castellated ? inward(board, p.x, p.y, (p.outer + (p.hole ?? p.outer)) / 4) : { x: p.x, y: p.y };
194
443
  if (p.castellated) Object.assign(port, join);
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 });
444
+ for (const key of [sourcePorts[i].name, ...sourcePorts[i].port_hints])
445
+ ports.set(`${part.name}.${key}`, { source: sourcePorts[i], pcb: port, x: join.x, y: join.y, layers });
196
446
  // 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) || [];
447
+ const pin = `${part.name}.${sourcePorts[i].name}#${sourcePorts[i].pin_number}`,
448
+ list = pinPads.get(pin) || [];
198
449
  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);
450
+ list.push({
451
+ key: `${sourcePorts[i].name}#${sourcePorts[i].pin_number}#${list.length}`,
452
+ names: [sourcePorts[i].name, ...sourcePorts[i].port_hints].map((n) => `${part.name}.${n}`),
453
+ x: p.x,
454
+ y: p.y,
455
+ reach: Math.max(p.w ?? 0, p.h ?? 0, p.outer ?? 0, p.rect?.w ?? 0, p.rect?.h ?? 0) / 2,
456
+ });
457
+ pinPads.set(pin, list);
201
458
  });
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 }); }
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 }); }
459
+ for (const h of part.holes || []) {
460
+ const q = at(h.x, h.y);
461
+ add('pcb_hole', {
462
+ ...own,
463
+ hole_shape: 'circle',
464
+ hole_diameter: h.d,
465
+ x: q.x,
466
+ y: q.y,
467
+ is_covered_with_solder_mask: false,
468
+ });
469
+ }
470
+ if (part.courtyard) {
471
+ const c = size(part.courtyard.w, part.courtyard.h);
472
+ add('pcb_courtyard_rect', {
473
+ ...own,
474
+ layer: part.layer,
475
+ center: { x: part.x, y: part.y },
476
+ width: c.w,
477
+ height: c.h,
478
+ });
479
+ }
204
480
  // A footprint's own marks, mirrored with it on the bottom: fab notes, the reference, the courtyard
205
481
  for (const e of fpEls) {
206
- if (e.type === 'pcb_fabrication_note_path') add(e.type, { ...own, layer: part.layer, route: e.route.map((q) => at(q.x, q.y)), stroke_width: e.stroke_width });
207
- if (e.type === 'pcb_fabrication_note_text' || e.type === 'pcb_silkscreen_text') add(e.type, { anchor_alignment: 'center', anchor_position: at(e.anchor_position.x, e.anchor_position.y),
208
- font: e.font, font_size: e.type === 'pcb_silkscreen_text' ? board.silk_text ?? 1 : e.font_size, layer: part.layer, ...(e.type === 'pcb_silkscreen_text' ? { text: e.text.replace('{REF}', part.name), ccw_rotation: 0 } : { ccw_rotation: mirror < 0 ? 180 : 0, text: e.text }), ...own });
209
- if (e.type === 'pcb_courtyard_rect') { const c = size(e.width, e.height); add(e.type, { ...own, layer: part.layer, center: at(e.center.x, e.center.y), width: c.w, height: c.h }); }
482
+ if (e.type === 'pcb_fabrication_note_path')
483
+ add(e.type, {
484
+ ...own,
485
+ layer: part.layer,
486
+ route: e.route.map((q) => at(q.x, q.y)),
487
+ stroke_width: e.stroke_width,
488
+ });
489
+ if (e.type === 'pcb_fabrication_note_text' || e.type === 'pcb_silkscreen_text')
490
+ add(e.type, {
491
+ anchor_alignment: 'center',
492
+ anchor_position: at(e.anchor_position.x, e.anchor_position.y),
493
+ font: e.font,
494
+ font_size: e.type === 'pcb_silkscreen_text' ? (board.silk_text ?? 1) : e.font_size,
495
+ layer: part.layer,
496
+ ...(e.type === 'pcb_silkscreen_text'
497
+ ? { text: e.text.replace('{REF}', part.name), ccw_rotation: 0 }
498
+ : { ccw_rotation: mirror < 0 ? 180 : 0, text: e.text }),
499
+ ...own,
500
+ });
501
+ if (e.type === 'pcb_courtyard_rect') {
502
+ const c = size(e.width, e.height);
503
+ add(e.type, { ...own, layer: part.layer, center: at(e.center.x, e.center.y), width: c.w, height: c.h });
504
+ }
210
505
  }
211
506
  }
212
507
 
213
508
  // ---- planes: each plane net's pads reach its inner layer, through their own holes or a via each ----
214
- if (board.planes && copper.length < 4) throw new Error('planes need a board of 4 layers or more (board.layers): the outer two carry the tracks');
509
+ if (board.planes && copper.length < 4)
510
+ throw new Error('planes need a board of 4 layers or more (board.layers): the outer two carry the tracks');
215
511
  const netOf = new Map(); // `${part}.${pin}` -> net, for the pours
216
- for (const [net, spec] of Object.entries(board.nets || {})) for (const pin of Array.isArray(spec) ? spec : spec.pins) {
217
- if (netOf.has(pin) && netOf.get(pin) !== net) throw new Error(`${pin} is in two nets, ${netOf.get(pin)} and ${net}: a pin is on one net (join the nets, or take it out of one)`);
218
- netOf.set(pin, net);
219
- }
512
+ for (const [net, spec] of Object.entries(board.nets || {}))
513
+ for (const pin of Array.isArray(spec) ? spec : spec.pins) {
514
+ if (netOf.has(pin) && netOf.get(pin) !== net)
515
+ throw new Error(
516
+ `${pin} is in two nets, ${netOf.get(pin)} and ${net}: a pin is on one net (join the nets, or take it out of one)`,
517
+ );
518
+ netOf.set(pin, net);
519
+ }
220
520
  for (const [net, spec] of Object.entries(board.planes || {})) for (const pin of spec.pins) netOf.set(pin, net);
221
521
  const { nets: planeNets = null, links = [] } = board.planes ? planeVias(out, add, board, copper) : {};
222
522
  if (board.copper) keptCopper(out, add, board, copper, planeNets || {});
223
523
 
224
524
  // ---- traces: drawn by rule, or left to the autorouter ----
225
- const port = (part, name) => { const p = ports.get(`${part}.${name}`); if (!p) throw new Error(`no port ${part}.${name}`); return p; };
525
+ const port = (part, name) => {
526
+ const p = ports.get(`${part}.${name}`);
527
+ if (!p) throw new Error(`no port ${part}.${name}`);
528
+ return p;
529
+ };
226
530
  const joined = new Map(); // `${part}.${pin}` -> its group: kept islands sharing a pin (meeting at a pad) are one group
227
- const up = new Map(), root = (g) => { while (up.get(g) !== g) g = up.get(g); return g; };
531
+ const up = new Map(),
532
+ root = (g) => {
533
+ while (up.get(g) !== g) g = up.get(g);
534
+ return g;
535
+ };
228
536
  for (const k of board.copper?.islands || []) {
229
537
  up.set(k.id, k.id);
230
- for (const p of k.pins) { if (joined.has(p)) up.set(root(joined.get(p)), k.id); joined.set(p, k.id); }
538
+ for (const p of k.pins) {
539
+ if (joined.has(p)) up.set(root(joined.get(p)), k.id);
540
+ joined.set(p, k.id);
541
+ }
231
542
  }
232
543
  for (const [p, g] of joined) joined.set(p, root(g));
233
544
  const stubOf = new Map((board.copper?.stubs || []).map((b) => [b.pin, b]));
234
545
  const layStub = (stub, id) => {
235
546
  for (const g of board.copper.tracks.filter((x) => x.stub === stub.id))
236
- 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: id, subcircuit_id: SUB, rulecad_kept: true });
547
+ add('pcb_trace', {
548
+ route: [
549
+ { route_type: 'wire', x: g.a.x, y: g.a.y, width: g.width, layer: g.layer },
550
+ { route_type: 'wire', x: g.b.x, y: g.b.y, width: g.width, layer: g.layer },
551
+ ],
552
+ source_trace_id: id,
553
+ subcircuit_id: SUB,
554
+ rulecad_kept: true,
555
+ });
237
556
  for (const v of board.copper.vias.filter((x) => x.stub === stub.id)) {
238
- const tr = add('pcb_trace', { route: [{ route_type: 'wire', x: v.x, y: v.y, width: Math.min(v.pad, 0.2), layer: 'top' }, { route_type: 'via', x: v.x, y: v.y, from_layer: 'top', to_layer: 'bottom' }], source_trace_id: id, subcircuit_id: SUB, rulecad_kept: true });
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 });
557
+ const tr = add('pcb_trace', {
558
+ route: [
559
+ { route_type: 'wire', x: v.x, y: v.y, width: Math.min(v.pad, 0.2), layer: 'top' },
560
+ { route_type: 'via', x: v.x, y: v.y, from_layer: 'top', to_layer: 'bottom' },
561
+ ],
562
+ source_trace_id: id,
563
+ subcircuit_id: SUB,
564
+ rulecad_kept: true,
565
+ });
566
+ add('pcb_via', {
567
+ pcb_trace_id: tr.pcb_trace_id,
568
+ x: v.x,
569
+ y: v.y,
570
+ hole_diameter: v.hole,
571
+ outer_diameter: v.pad,
572
+ layers: copper,
573
+ from_layer: 'top',
574
+ to_layer: 'bottom',
575
+ subcircuit_id: SUB,
576
+ });
240
577
  }
241
578
  };
242
579
  // 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
580
  // 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
581
  // 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];
582
+ const netNamed = (names) =>
583
+ Object.entries(board.nets || {}).find(([, spec]) =>
584
+ (Array.isArray(spec) ? spec : spec.pins).some((p) => names.includes(p)),
585
+ )?.[0];
246
586
  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)
587
+ const net = pads.length > 1 && netNamed(pads[0].names),
588
+ part = pin.slice(0, pin.indexOf('.'));
589
+ if (
590
+ pads.length < 2 ||
591
+ !net ||
592
+ board.planes?.[net] ||
593
+ board.join_pads === false ||
594
+ pads[0].names.some((n) => joined.has(n))
595
+ )
596
+ return []; // (or the source's kept copper joins them)
597
+ return pads
598
+ .slice(1)
599
+ .filter((q, i) => Math.hypot(q.x - pads[i].x, q.y - pads[i].y) > q.reach + pads[i].reach)
250
600
  .map((q) => ({ from: [part, pads[0].key], to: [part, q.key], width: board.track, net }));
251
601
  });
252
- const toRoute = [], traces = [...(board.traces || []), ...netTraces(board, port, joined), ...links, ...samePin];
602
+ const toRoute = [],
603
+ traces = [...(board.traces || []), ...netTraces(board, port, joined), ...links, ...samePin];
253
604
  for (const t of traces) {
254
- const a = port(...t.from), b = port(...t.to);
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,
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)
257
- if (!t.path) { // a kept escape (stub) from either pin: laid as part of this connection, which is routed from its end
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('.'));
259
- layStub(stub, st.source_trace_id); return { ...q, x: stub.end.x, y: stub.end.y, layers: [stub.end.layer] }; });
260
- toRoute.push({ t, a: ends[0], b: ends[1], id: st.source_trace_id }); continue;
605
+ const a = port(...t.from),
606
+ b = port(...t.to);
607
+ const st = add('source_trace', {
608
+ connected_source_port_ids: [a.source.source_port_id, b.source.source_port_id],
609
+ connected_source_net_ids: [],
610
+ subcircuit_id: SUB,
611
+ display_name: `.${t.from.join(' > .')} to .${t.to.join(' > .')}`,
612
+ min_trace_thickness: t.width,
613
+ ...(t.net ? { rulecad_net: t.net } : {}),
614
+ }); // (the net's name: KiCad's files carry it)
615
+ if (!t.path) {
616
+ // a kept escape (stub) from either pin: laid as part of this connection, which is routed from its end
617
+ const ends = [a, b].map((q, i) => {
618
+ const stub = stubOf.get([t.from, t.to][i].join('.'));
619
+ if (!stub) return q;
620
+ stubOf.delete([t.from, t.to][i].join('.'));
621
+ layStub(stub, st.source_trace_id);
622
+ return { ...q, x: stub.end.x, y: stub.end.y, layers: [stub.end.layer] };
623
+ });
624
+ toRoute.push({ t, a: ends[0], b: ends[1], id: st.source_trace_id });
625
+ continue;
261
626
  }
262
627
  // A drawn track runs on the layer its first pad is on (a through-hole pad: the front)
263
628
  const layer = t.layer ?? (a.layers.length === 1 ? a.layers[0] : 'top'); // or the layer it names
264
629
  const pts = [{ x: a.x, y: a.y }, ...t.path, { x: b.x, y: b.y }];
265
- add('pcb_trace', { route: pts.map((q, i) => ({ route_type: 'wire', x: q.x, y: q.y, width: t.width, layer,
266
- ...(i === 0 ? { start_pcb_port_id: a.pcb.pcb_port_id } : {}), ...(i === pts.length - 1 ? { end_pcb_port_id: b.pcb.pcb_port_id } : {}) })), source_trace_id: st.source_trace_id, subcircuit_id: SUB });
630
+ add('pcb_trace', {
631
+ route: pts.map((q, i) => ({
632
+ route_type: 'wire',
633
+ x: q.x,
634
+ y: q.y,
635
+ width: t.width,
636
+ layer,
637
+ ...(i === 0 ? { start_pcb_port_id: a.pcb.pcb_port_id } : {}),
638
+ ...(i === pts.length - 1 ? { end_pcb_port_id: b.pcb.pcb_port_id } : {}),
639
+ })),
640
+ source_trace_id: st.source_trace_id,
641
+ subcircuit_id: SUB,
642
+ });
267
643
  }
268
644
 
269
645
  // ---- silkscreen and mounting holes ----
270
646
  for (const s of board.silk) {
271
- if (s.rect) add('pcb_silkscreen_rect', { pcb_component_id: null, layer: s.layer, center: { x: s.rect.x, y: s.rect.y }, width: s.rect.w, height: s.rect.h, subcircuit_id: SUB, stroke_width: Math.max(board.silk_line ?? 0.15, Math.min(s.rect.w, s.rect.h)), is_filled: true }); // (a bar: stroked as thick as it is, it's solid)
272
- else add('pcb_silkscreen_text', { anchor_alignment: 'center', anchor_position: { x: s.x, y: s.y }, font: 'tscircuit2024', font_size: s.size, layer: s.layer, text: s.text, ccw_rotation: s.rotation ?? 0, pcb_component_id: null, subcircuit_id: SUB,
273
- ...(s.to ? { rulecad_to: s.to } : {}) }); // an arrow to what it names, drawn once the label's place is final
647
+ if (s.rect)
648
+ add('pcb_silkscreen_rect', {
649
+ pcb_component_id: null,
650
+ layer: s.layer,
651
+ center: { x: s.rect.x, y: s.rect.y },
652
+ width: s.rect.w,
653
+ height: s.rect.h,
654
+ subcircuit_id: SUB,
655
+ stroke_width: Math.max(board.silk_line ?? 0.15, Math.min(s.rect.w, s.rect.h)),
656
+ is_filled: true,
657
+ }); // (a bar: stroked as thick as it is, it's solid)
658
+ else
659
+ add('pcb_silkscreen_text', {
660
+ anchor_alignment: 'center',
661
+ anchor_position: { x: s.x, y: s.y },
662
+ font: 'tscircuit2024',
663
+ font_size: s.size,
664
+ layer: s.layer,
665
+ text: s.text,
666
+ ccw_rotation: s.rotation ?? 0,
667
+ pcb_component_id: null,
668
+ subcircuit_id: SUB,
669
+ ...(s.to ? { rulecad_to: s.to } : {}),
670
+ }); // an arrow to what it names, drawn once the label's place is final
274
671
  }
275
- for (const h of board.holes || []) add('pcb_hole', { hole_shape: 'circle', hole_diameter: h.d, x: h.x, y: h.y, is_covered_with_solder_mask: false, subcircuit_id: SUB,
276
- ...(h.keepout ? { rulecad_keepout: h.keepout } : {}) }); // a screw head's room: no track within keepout (mm, from its centre)
672
+ for (const h of board.holes || [])
673
+ add('pcb_hole', {
674
+ hole_shape: 'circle',
675
+ hole_diameter: h.d,
676
+ x: h.x,
677
+ y: h.y,
678
+ is_covered_with_solder_mask: false,
679
+ subcircuit_id: SUB,
680
+ ...(h.keepout ? { rulecad_keepout: h.keepout } : {}),
681
+ }); // a screw head's room: no track within keepout (mm, from its centre)
277
682
 
278
683
  // ---- the autorouter: what the rules don't draw ----
279
684
  if (toRoute.length) {
280
685
  if (!board.autoroute) throw new Error(`${toRoute.length} connections have no track and the board isn't autorouted`);
281
686
  const routed = await route(out, toRoute, board);
282
687
  for (const r of routed.traces) {
283
- const t = add('pcb_trace', { route: r.route, source_trace_id: r.source_trace_id, subcircuit_id: SUB, rulecad_routed: true });
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
688
+ const t = add('pcb_trace', {
689
+ route: r.route,
690
+ source_trace_id: r.source_trace_id,
691
+ subcircuit_id: SUB,
692
+ rulecad_routed: true,
693
+ });
694
+ for (const v of r.vias)
695
+ add('pcb_via', { pcb_trace_id: t.pcb_trace_id, ...v, layers: copper, subcircuit_id: SUB }); // whose via it is: the checks need it
285
696
  }
286
697
  // kept copper laid once routed (an island marked after): unseen by the router, so the rest routes as it would
287
698
  // without it; smoothing and the checks see it
@@ -312,23 +723,37 @@ export async function finishTracks(out, board) {
312
723
  const { finishCircuit } = await import('@rulecad/smooth');
313
724
  const { runAllChecks } = await import('@tscircuit/checks');
314
725
  // each error by its kind and the elements in it, as smoothRouted keys them
315
- const errors = async (json) => (await runAllChecks(structuredClone(json))).filter((e) => /_error$/.test(e.type))
316
- .map((e) => JSON.stringify([e.type, ...[...new Set(JSON.stringify(e).match(/pcb_[a-z_]+?_\d+/g) || [])].sort()]));
317
- const before = new Set(await errors(out)), was = new Map(out.filter((e) => e.type === 'pcb_trace').map((e) => [e.pcb_trace_id, e]));
726
+ const errors = async (json) =>
727
+ (await runAllChecks(structuredClone(json)))
728
+ .filter((e) => /_error$/.test(e.type))
729
+ .map((e) => JSON.stringify([e.type, ...[...new Set(JSON.stringify(e).match(/pcb_[a-z_]+?_\d+/g) || [])].sort()]));
730
+ const before = new Set(await errors(out)),
731
+ was = new Map(out.filter((e) => e.type === 'pcb_trace').map((e) => [e.pcb_trace_id, e]));
318
732
  let { json } = finishCircuit(out, { ...(board.clearance ? { clearance: board.clearance } : {}) });
319
733
  // A change the design checks then find in a new error is undone (a pair redrawn together, both), the rest kept
320
734
  for (let round = 0; round < 6; round++) {
321
735
  const fresh = (await errors(json)).filter((e) => !before.has(e));
322
736
  if (!fresh.length) return void out.splice(0, out.length, ...json);
323
737
  const named = new Set(fresh.flatMap((e) => JSON.parse(e).slice(1)));
324
- const pairs = new Set(json.filter((e) => e.type === 'pcb_trace' && named.has(e.pcb_trace_id) && e.rulecad_pair).map((e) => e.rulecad_pair));
325
- const undo = (e) => e.type === 'pcb_trace' && (named.has(e.pcb_trace_id) || (e.rulecad_pair && pairs.has(e.rulecad_pair)));
738
+ const pairs = new Set(
739
+ json
740
+ .filter((e) => e.type === 'pcb_trace' && named.has(e.pcb_trace_id) && e.rulecad_pair)
741
+ .map((e) => e.rulecad_pair),
742
+ );
743
+ const undo = (e) =>
744
+ e.type === 'pcb_trace' && (named.has(e.pcb_trace_id) || (e.rulecad_pair && pairs.has(e.rulecad_pair)));
326
745
  let undone = 0;
327
746
  json = json.flatMap((e) => {
328
747
  if (!undo(e)) return [e];
329
- if (e.rulecad_fill) { undone++; return []; } // a fill: taken away
748
+ if (e.rulecad_fill) {
749
+ undone++;
750
+ return [];
751
+ } // a fill: taken away
330
752
  const o = was.get(e.pcb_trace_id);
331
- if (o && o !== e) { undone++; return [o]; } // a redrawn track: as it was
753
+ if (o && o !== e) {
754
+ undone++;
755
+ return [o];
756
+ } // a redrawn track: as it was
332
757
  return [e];
333
758
  });
334
759
  if (!undone) break; // (a new error in nothing the finish changed: leave the board as it was)
@@ -340,43 +765,83 @@ export async function smoothRouted(out, board) {
340
765
  const { runAllChecks } = await import('@tscircuit/checks');
341
766
  // each error by its kind and the elements in it (its measurements change as tracks move), on a copy: the checks write
342
767
  // into the routes they read
343
- const errors = async () => (await runAllChecks(structuredClone(out))).filter((e) => /_error$/.test(e.type))
344
- .map((e) => JSON.stringify([e.type, ...[...new Set(JSON.stringify(e).match(/pcb_[a-z_]+?_\d+/g) || [])].sort()]));
345
- const before = new Set(await errors()), snapshot = structuredClone(out);
768
+ const errors = async () =>
769
+ (await runAllChecks(structuredClone(out)))
770
+ .filter((e) => /_error$/.test(e.type))
771
+ .map((e) => JSON.stringify([e.type, ...[...new Set(JSON.stringify(e).match(/pcb_[a-z_]+?_\d+/g) || [])].sort()]));
772
+ const before = new Set(await errors()),
773
+ snapshot = structuredClone(out);
346
774
  const run = (withLeads) => {
347
775
  const chains = withLeads ? stubChains(out) : new Map();
348
- const { routes, trimmed } = smoothCircuit(out, { movable: (e) => e.rulecad_routed === true, ...(board.clearance ? { clearance: board.clearance } : {}),
349
- leads: (e) => { const c = chains.get(e.pcb_trace_id); return c && { start: c.start?.lead, end: c.end?.lead }; } });
350
- const was = new Map(), cut = new Set();
351
- for (const e of out) if (e.type === 'pcb_trace' && routes.has(e.pcb_trace_id)) { was.set(e.pcb_trace_id, e.route); e.route = routes.get(e.pcb_trace_id); }
352
- for (const [id, sides] of trimmed) for (const side of ['start', 'end']) if (sides[side]) {
353
- const chain = chains.get(id)[side], lead = sides[side], k = lead.length, track = out.find((x) => x.type === 'pcb_trace' && x.pcb_trace_id === id);
354
- // the chain's segments, root first: those wholly past the new joint go, the one it lands on is shortened
355
- const segs = [...chain.segs].reverse(), gone = segs.slice(k - 1), last = segs[k - 2], at = lead[k - 1];
356
- const end = chain.lead[k - 1], moved = Math.hypot(end.x - at.x, end.y - at.y) > 1e-9;
357
- track.rulecad_trimmed = [...(track.rulecad_trimmed || []), ...gone.map((g) => ({ a: { ...g.trace.route[0] }, b: { ...g.trace.route[1] } }))];
358
- for (const g of gone) { out.splice(out.indexOf(g.trace), 1); cut.add(g.trace.pcb_trace_id); }
359
- if (moved) {
360
- last.trace.rulecad_shortened = { a: { x: last.trace.route[0].x, y: last.trace.route[0].y }, b: { x: last.trace.route[1].x, y: last.trace.route[1].y } };
361
- const p = last.trace.route.find((q) => Math.hypot(q.x - end.x, q.y - end.y) < 1e-6); p.x = at.x; p.y = at.y;
362
- cut.add(last.trace.pcb_trace_id);
776
+ const { routes, trimmed } = smoothCircuit(out, {
777
+ movable: (e) => e.rulecad_routed === true,
778
+ ...(board.clearance ? { clearance: board.clearance } : {}),
779
+ leads: (e) => {
780
+ const c = chains.get(e.pcb_trace_id);
781
+ return c && { start: c.start?.lead, end: c.end?.lead };
782
+ },
783
+ });
784
+ const was = new Map(),
785
+ cut = new Set();
786
+ for (const e of out)
787
+ if (e.type === 'pcb_trace' && routes.has(e.pcb_trace_id)) {
788
+ was.set(e.pcb_trace_id, e.route);
789
+ e.route = routes.get(e.pcb_trace_id);
363
790
  }
364
- if (gone.length || moved) track.rulecad_cut = (track.rulecad_cut || 0) + 1; // escapes cut back from this track
365
- cut.add(id);
366
- }
791
+ for (const [id, sides] of trimmed)
792
+ for (const side of ['start', 'end'])
793
+ if (sides[side]) {
794
+ const chain = chains.get(id)[side],
795
+ lead = sides[side],
796
+ k = lead.length,
797
+ track = out.find((x) => x.type === 'pcb_trace' && x.pcb_trace_id === id);
798
+ // the chain's segments, root first: those wholly past the new joint go, the one it lands on is shortened
799
+ const segs = [...chain.segs].reverse(),
800
+ gone = segs.slice(k - 1),
801
+ last = segs[k - 2],
802
+ at = lead[k - 1];
803
+ const end = chain.lead[k - 1],
804
+ moved = Math.hypot(end.x - at.x, end.y - at.y) > 1e-9;
805
+ track.rulecad_trimmed = [
806
+ ...(track.rulecad_trimmed || []),
807
+ ...gone.map((g) => ({ a: { ...g.trace.route[0] }, b: { ...g.trace.route[1] } })),
808
+ ];
809
+ for (const g of gone) {
810
+ out.splice(out.indexOf(g.trace), 1);
811
+ cut.add(g.trace.pcb_trace_id);
812
+ }
813
+ if (moved) {
814
+ last.trace.rulecad_shortened = {
815
+ a: { x: last.trace.route[0].x, y: last.trace.route[0].y },
816
+ b: { x: last.trace.route[1].x, y: last.trace.route[1].y },
817
+ };
818
+ const p = last.trace.route.find((q) => Math.hypot(q.x - end.x, q.y - end.y) < 1e-6);
819
+ p.x = at.x;
820
+ p.y = at.y;
821
+ cut.add(last.trace.pcb_trace_id);
822
+ }
823
+ if (gone.length || moved) track.rulecad_cut = (track.rulecad_cut || 0) + 1; // escapes cut back from this track
824
+ cut.add(id);
825
+ }
367
826
  return { was, cut };
368
827
  };
369
828
  let { was, cut } = run(true);
370
829
  const fresh = async () => (await errors()).filter((x) => !before.has(x));
371
- if (cut.size && (await fresh()).some((e) => [...cut].some((id) => e.includes(`"${id}"`)))) { // a cut in a new error: none, then
830
+ if (cut.size && (await fresh()).some((e) => [...cut].some((id) => e.includes(`"${id}"`)))) {
831
+ // a cut in a new error: none, then
372
832
  out.splice(0, out.length, ...snapshot);
373
833
  ({ was } = run(false));
374
834
  }
375
- for (let round = 0; round < 5 && was.size; round++) { // (a track put back can be in the way of one pulled tight round its new path: again)
835
+ for (let round = 0; round < 5 && was.size; round++) {
836
+ // (a track put back can be in the way of one pulled tight round its new path: again)
376
837
  let back = 0;
377
- for (const e of await fresh()) for (const [id, route] of was) if (e.includes(`"${id}"`)) {
378
- out.find((x) => x.type === 'pcb_trace' && x.pcb_trace_id === id).route = route; was.delete(id); back++;
379
- }
838
+ for (const e of await fresh())
839
+ for (const [id, route] of was)
840
+ if (e.includes(`"${id}"`)) {
841
+ out.find((x) => x.type === 'pcb_trace' && x.pcb_trace_id === id).route = route;
842
+ was.delete(id);
843
+ back++;
844
+ }
380
845
  if (!back) break;
381
846
  }
382
847
  }
@@ -385,23 +850,61 @@ export async function smoothRouted(out, board) {
385
850
  // via and the track both a source's own copper), trace, seg (the segment's index) }: the nearest track for each via,
386
851
  // or (all) every track segment closer than under
387
852
  export function viaHoleGaps(json, { all = false, under = Infinity } = {}) {
388
- 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; };
389
- const join = (a, b) => { for (const x of [a, b]) if (!up.has(x)) up.set(x, x); up.set(find(a), find(b)); };
390
- 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); }
853
+ const up = new Map(),
854
+ find = (a) => {
855
+ while (up.get(a) !== a) {
856
+ up.set(a, up.get(up.get(a)));
857
+ a = up.get(a);
858
+ }
859
+ return a;
860
+ };
861
+ const join = (a, b) => {
862
+ for (const x of [a, b]) if (!up.has(x)) up.set(x, x);
863
+ up.set(find(a), find(b));
864
+ };
865
+ for (const e of json)
866
+ if (e.type === 'source_trace') {
867
+ join(e.source_trace_id, e.source_trace_id);
868
+ for (const id of [...(e.connected_source_port_ids || []), ...(e.connected_source_net_ids || [])])
869
+ join(e.source_trace_id, id);
870
+ }
391
871
  const traceOf = new Map(json.filter((e) => e.type === 'pcb_trace').map((t) => [t.pcb_trace_id, t]));
392
872
  const netOf = (t) => (t?.source_trace_id && up.has(t.source_trace_id) ? find(t.source_trace_id) : null);
393
- 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));
394
- 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 } }; };
873
+ const segs = json
874
+ .filter((e) => e.type === 'pcb_trace')
875
+ .flatMap((t) =>
876
+ t.route
877
+ .slice(1)
878
+ .map((q, i) => [t.route[i], q, t, i])
879
+ .filter(([p, q]) => p.route_type === 'wire' && q.route_type === 'wire' && p.layer === q.layer),
880
+ );
881
+ const toSeg = (c, a, b) => {
882
+ const dx = b.x - a.x,
883
+ dy = b.y - a.y,
884
+ l = dx * dx + dy * dy,
885
+ t = l ? Math.max(0, Math.min(1, ((c.x - a.x) * dx + (c.y - a.y) * dy) / l)) : 0;
886
+ 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 } };
887
+ };
395
888
  const out = [];
396
889
  for (const v of json.filter((e) => e.type === 'pcb_via')) {
397
- const vt = traceOf.get(v.pcb_trace_id), net = netOf(vt);
890
+ const vt = traceOf.get(v.pcb_trace_id),
891
+ net = netOf(vt);
398
892
  let best = null;
399
893
  for (const [a, b, t, i] of segs) {
400
894
  if (t === vt || (net != null && netOf(t) === net)) continue;
401
- 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;
402
- const { d, p } = toSeg(v, a, b), gap = d - v.hole_diameter / 2 - Math.max(a.width ?? 0, b.width ?? 0) / 2;
895
+ if (
896
+ Math.min(a.x, b.x) - 2 > v.x ||
897
+ Math.max(a.x, b.x) + 2 < v.x ||
898
+ Math.min(a.y, b.y) - 2 > v.y ||
899
+ Math.max(a.y, b.y) + 2 < v.y
900
+ )
901
+ continue;
902
+ const { d, p } = toSeg(v, a, b),
903
+ gap = d - v.hole_diameter / 2 - Math.max(a.width ?? 0, b.width ?? 0) / 2;
403
904
  const found = { via: v, gap, at: p, kept: !!(vt?.rulecad_kept && t.rulecad_kept), trace: t, seg: i };
404
- if (all) { if (gap < under) out.push(found); } else if (!best || gap < best.gap) best = found;
905
+ if (all) {
906
+ if (gap < under) out.push(found);
907
+ } else if (!best || gap < best.gap) best = found;
405
908
  }
406
909
  if (best) out.push(best);
407
910
  }
@@ -415,30 +918,57 @@ export function viaHoleGaps(json, { all = false, under = Infinity } = {}) {
415
918
  // a new error goes back
416
919
  export async function viaHoleRepair(out, gapMin, neck = 0) {
417
920
  const { runAllChecks } = await import('@tscircuit/checks');
418
- const errors = async () => (await runAllChecks(structuredClone(out))).filter((e) => /_error$/.test(e.type))
419
- .map((e) => JSON.stringify([e.type, ...[...new Set(JSON.stringify(e).match(/pcb_[a-z_]+?_\d+/g) || [])].sort()]));
420
- const before = new Set(await errors()), tried = new Set();
921
+ const errors = async () =>
922
+ (await runAllChecks(structuredClone(out)))
923
+ .filter((e) => /_error$/.test(e.type))
924
+ .map((e) => JSON.stringify([e.type, ...[...new Set(JSON.stringify(e).match(/pcb_[a-z_]+?_\d+/g) || [])].sort()]));
925
+ const before = new Set(await errors()),
926
+ tried = new Set();
421
927
  const short = () => viaHoleGaps(out, { all: true, under: gapMin - 1e-6 }).filter((g) => g.trace.rulecad_routed);
422
928
  const width = (g) => Math.max(g.trace.route[g.seg].width ?? 0, g.trace.route[g.seg + 1].width ?? 0);
423
- const necked = (r, i) => r.map((q, k) => (k === i || k === i + 1 ? { ...q, width: Math.min(q.width ?? neck, neck) } : q));
929
+ const necked = (r, i) =>
930
+ r.map((q, k) => (k === i || k === i + 1 ? { ...q, width: Math.min(q.width ?? neck, neck) } : q));
424
931
  // First, necked down where they pass (nothing moves, so nothing new comes close): every segment that's then far enough
425
- 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);
932
+ if (neck)
933
+ for (const g of short())
934
+ if (width(g) > neck && g.gap + (width(g) - neck) / 2 >= gapMin) g.trace.route = necked(g.trace.route, g.seg);
426
935
  // Then the rest bowed out round the via (and necked, so the bow is smaller), one per track a round, each checked
427
936
  for (let round = 0; round < 6; round++) {
428
- const was = new Map(), done = new Set();
937
+ const was = new Map(),
938
+ done = new Set();
429
939
  for (const g of short().sort((x, y) => x.gap - y.gap)) {
430
- const t = g.trace, key = `${t.pcb_trace_id}:${g.via.pcb_via_id}`;
940
+ const t = g.trace,
941
+ key = `${t.pcb_trace_id}:${g.via.pcb_via_id}`;
431
942
  if (done.has(t.pcb_trace_id) || tried.has(key)) continue; // (one bow a track a round: its segments' places change)
432
943
  let r = t.route;
433
- 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);
944
+ const w = width(g),
945
+ thin = neck && w > neck ? neck : w,
946
+ a = r[g.seg],
947
+ b = r[g.seg + 1],
948
+ len = Math.hypot(b.x - a.x, b.y - a.y);
434
949
  if (len < 1e-6) continue;
435
950
  if (thin < w) r = necked(r, g.seg);
436
- 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);
437
- 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;
438
- 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
439
- const s0 = Math.max(0, along - half), s1 = Math.min(len, along + half), ramp = Math.min(need * 2, s0, len - s1);
440
- 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; };
441
- const bow = [ramp > 0 ? pt(s0 - ramp, 0) : null, pt(s0, need), pt(s1, need), ramp > 0 ? pt(s1 + ramp, 0) : null].filter(Boolean)
951
+ const u = { x: (b.x - a.x) / len, y: (b.y - a.y) / len },
952
+ off = { x: g.at.x - g.via.x, y: g.at.y - g.via.y },
953
+ d = Math.hypot(off.x, off.y);
954
+ const n = d > 1e-9 ? { x: off.x / d, y: off.y / d } : { x: -u.y, y: u.x },
955
+ need = gapMin - g.gap - (w - thin) / 2 + 0.01;
956
+ const along = (g.at.x - a.x) * u.x + (g.at.y - a.y) * u.y,
957
+ half = g.via.outer_diameter / 2 + need + 0.15; // the stretch beside the via
958
+ const s0 = Math.max(0, along - half),
959
+ s1 = Math.min(len, along + half),
960
+ ramp = Math.min(need * 2, s0, len - s1);
961
+ const pt = (s, k) => {
962
+ const { start_pcb_port_id, end_pcb_port_id, ...q } = {
963
+ ...r[g.seg],
964
+ width: thin,
965
+ x: a.x + u.x * s + n.x * k,
966
+ y: a.y + u.y * s + n.y * k,
967
+ };
968
+ return q;
969
+ };
970
+ const bow = [ramp > 0 ? pt(s0 - ramp, 0) : null, pt(s0, need), pt(s1, need), ramp > 0 ? pt(s1 + ramp, 0) : null]
971
+ .filter(Boolean)
442
972
  .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);
443
973
  was.set(t.pcb_trace_id, { route: t.route, key });
444
974
  t.route = [...r.slice(0, g.seg + 1), ...bow, ...r.slice(g.seg + 1)];
@@ -446,20 +976,36 @@ export async function viaHoleRepair(out, gapMin, neck = 0) {
446
976
  }
447
977
  if (!was.size) break;
448
978
  // a bow in a new error: the track as it was before it, and that bow not tried again
449
- for (const e of (await errors()).filter((x) => !before.has(x))) for (const [id, w] of was) if (e.includes(`"${id}"`)) {
450
- out.find((x) => x.type === 'pcb_trace' && x.pcb_trace_id === id).route = w.route; tried.add(w.key); was.delete(id);
451
- }
979
+ for (const e of (await errors()).filter((x) => !before.has(x)))
980
+ for (const [id, w] of was)
981
+ if (e.includes(`"${id}"`)) {
982
+ out.find((x) => x.type === 'pcb_trace' && x.pcb_trace_id === id).route = w.route;
983
+ tried.add(w.key);
984
+ was.delete(id);
985
+ }
452
986
  }
453
987
  // 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
454
988
  // there) a few hundredths of a millimetre, the first way round that clears every track near it, each move checked
455
989
  const vias = new Map(out.filter((e) => e.type === 'pcb_via').map((v) => [v.pcb_via_id, v]));
456
990
  for (const g of short()) {
457
- 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);
991
+ const v = vias.get(g.via.pcb_via_id),
992
+ own = out.find((e) => e.type === 'pcb_trace' && e.pcb_trace_id === v.pcb_trace_id);
458
993
  if (!own?.rulecad_routed || tried.has(`via:${v.pcb_via_id}`)) continue;
459
994
  tried.add(`via:${v.pcb_via_id}`);
460
- 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;
461
- const place = (x, y) => { v.x = x; v.y = y; own.route = was_.route.map((q) => (at(q) ? { ...q, x, y } : q)); };
462
- const worst = () => Math.min(gapMin, ...viaHoleGaps(out, { all: true, under: gapMin }).filter((h) => h.via === v).map((h) => h.gap));
995
+ const was_ = { x: v.x, y: v.y, route: own.route },
996
+ at = (q) => Math.hypot(q.x - was_.x, q.y - was_.y) < 1e-6;
997
+ const place = (x, y) => {
998
+ v.x = x;
999
+ v.y = y;
1000
+ own.route = was_.route.map((q) => (at(q) ? { ...q, x, y } : q));
1001
+ };
1002
+ const worst = () =>
1003
+ Math.min(
1004
+ gapMin,
1005
+ ...viaHoleGaps(out, { all: true, under: gapMin })
1006
+ .filter((h) => h.via === v)
1007
+ .map((h) => h.gap),
1008
+ );
463
1009
  let fixed = false;
464
1010
  for (const step of [0.01, 0.02, 0.03, 0.05]) {
465
1011
  for (let k = 0; k < 16 && !fixed; k++) {
@@ -478,34 +1024,64 @@ export async function viaHoleRepair(out, gapMin, neck = 0) {
478
1024
  // width it loses, each change checked
479
1025
  export async function gapRepair(out, gapMin, neck) {
480
1026
  const { runAllChecks } = await import('@tscircuit/checks');
481
- const errors = async () => (await runAllChecks(structuredClone(out))).filter((e) => /_error$/.test(e.type))
482
- .map((e) => JSON.stringify([e.type, ...[...new Set(JSON.stringify(e).match(/pcb_[a-z_]+?_\d+/g) || [])].sort()]));
483
- const parent = new Map(), root = (x) => { while (parent.get(x) !== x) x = parent.get(x); return x; };
1027
+ const errors = async () =>
1028
+ (await runAllChecks(structuredClone(out)))
1029
+ .filter((e) => /_error$/.test(e.type))
1030
+ .map((e) => JSON.stringify([e.type, ...[...new Set(JSON.stringify(e).match(/pcb_[a-z_]+?_\d+/g) || [])].sort()]));
1031
+ const parent = new Map(),
1032
+ root = (x) => {
1033
+ while (parent.get(x) !== x) x = parent.get(x);
1034
+ return x;
1035
+ };
484
1036
  for (const t of out.filter((e) => e.type === 'source_trace')) {
485
1037
  const ends = [t.source_trace_id, ...(t.connected_source_port_ids || []), ...(t.connected_source_net_ids || [])];
486
1038
  for (const e of ends) if (!parent.has(e)) parent.set(e, e);
487
1039
  for (const e of ends.slice(1)) parent.set(root(e), root(ends[0]));
488
1040
  }
489
1041
  const netOf = (t) => (parent.has(t.source_trace_id) ? root(t.source_trace_id) : t.pcb_trace_id);
490
- 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); };
491
- 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 }))
492
- .filter((g) => g.a.route_type === 'wire' && g.b.route_type === 'wire' && g.a.layer === g.b.layer));
493
- const w = (g) => Math.max(g.a.width ?? 0, g.b.width ?? 0), before = new Set(await errors()), was = new Map();
494
- for (let x = 0; x < segs.length; x++) for (let y = x + 1; y < segs.length; y++) {
495
- const g = segs[x], h = segs[y];
496
- if (g.t === h.t || g.a.layer !== h.a.layer || netOf(g.t) === netOf(h.t)) continue;
497
- 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;
498
- 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;
499
- if (d <= 1e-6 || d >= gapMin - 1e-9) continue;
500
- for (const s of [g, h]) if (s.t.rulecad_routed && w(s) > neck) {
501
- if (!was.has(s.t.pcb_trace_id)) was.set(s.t.pcb_trace_id, s.t.route);
502
- 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));
503
- s.a = s.t.route[s.i]; s.b = s.t.route[s.i + 1];
1042
+ const ps = (p, o) => {
1043
+ const dx = o.b.x - o.a.x,
1044
+ dy = o.b.y - o.a.y,
1045
+ l = dx * dx + dy * dy,
1046
+ t = l ? Math.max(0, Math.min(1, ((p.x - o.a.x) * dx + (p.y - o.a.y) * dy) / l)) : 0;
1047
+ return Math.hypot(p.x - o.a.x - t * dx, p.y - o.a.y - t * dy);
1048
+ };
1049
+ const segs = out
1050
+ .filter((e) => e.type === 'pcb_trace')
1051
+ .flatMap((t) =>
1052
+ t.route
1053
+ .slice(1)
1054
+ .map((q, i) => ({ t, i, a: t.route[i], b: q }))
1055
+ .filter((g) => g.a.route_type === 'wire' && g.b.route_type === 'wire' && g.a.layer === g.b.layer),
1056
+ );
1057
+ const w = (g) => Math.max(g.a.width ?? 0, g.b.width ?? 0),
1058
+ before = new Set(await errors()),
1059
+ was = new Map();
1060
+ for (let x = 0; x < segs.length; x++)
1061
+ for (let y = x + 1; y < segs.length; y++) {
1062
+ const g = segs[x],
1063
+ h = segs[y];
1064
+ if (g.t === h.t || g.a.layer !== h.a.layer || netOf(g.t) === netOf(h.t)) continue;
1065
+ 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)
1066
+ continue;
1067
+ 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;
1068
+ if (d <= 1e-6 || d >= gapMin - 1e-9) continue;
1069
+ for (const s of [g, h])
1070
+ if (s.t.rulecad_routed && w(s) > neck) {
1071
+ if (!was.has(s.t.pcb_trace_id)) was.set(s.t.pcb_trace_id, s.t.route);
1072
+ s.t.route = s.t.route.map((q, k) =>
1073
+ k === s.i || k === s.i + 1 ? { ...q, width: Math.min(q.width ?? neck, neck) } : q,
1074
+ );
1075
+ s.a = s.t.route[s.i];
1076
+ s.b = s.t.route[s.i + 1];
1077
+ }
504
1078
  }
505
- }
506
- for (const e of (await errors()).filter((x) => !before.has(x))) for (const [id, route] of was) if (e.includes(`"${id}"`)) {
507
- out.find((x) => x.type === 'pcb_trace' && x.pcb_trace_id === id).route = route; was.delete(id);
508
- }
1079
+ for (const e of (await errors()).filter((x) => !before.has(x)))
1080
+ for (const [id, route] of was)
1081
+ if (e.includes(`"${id}"`)) {
1082
+ out.find((x) => x.type === 'pcb_trace' && x.pcb_trace_id === id).route = route;
1083
+ was.delete(id);
1084
+ }
509
1085
  }
510
1086
 
511
1087
  // 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
@@ -517,48 +1093,106 @@ export function stubChains(out) {
517
1093
  const routed = out.filter((e) => e.type === 'pcb_trace' && e.rulecad_routed);
518
1094
  const kept = out.filter((e) => e.type === 'pcb_trace' && e.rulecad_kept);
519
1095
  const chains = new Map();
520
- for (const t of routed) for (const side of ['start', 'end']) {
521
- const J = side === 'start' ? t.route[0] : t.route.at(-1);
522
- if (J.route_type !== 'wire' || J.start_pcb_port_id || J.end_pcb_port_id) continue; // on a pad: no stub
523
- if (routed.filter((u) => [u.route[0], u.route.at(-1)].some((p) => near(p, J))).length !== 1) continue; // other tracks meet there
524
- const mine = kept.filter((k) => k.source_trace_id === t.source_trace_id);
525
- const lead = [{ x: J.x, y: J.y, layer: J.layer }], segs = [], used = new Set();
526
- for (let cur = J; ;) {
527
- if (mine.some((k) => k.route[1]?.route_type === 'via' && near(k.route[0], cur))) break; // a via: the stub changes layer here
528
- const next = mine.filter((k) => !used.has(k) && k.route.length === 2 && k.route.every((p) => p.route_type === 'wire' && p.layer === J.layer) && k.route.some((p) => near(p, cur)));
529
- if (next.length !== 1) break;
530
- const k = next[0], far = near(k.route[0], cur) ? k.route[1] : k.route[0];
531
- used.add(k); segs.push({ trace: k }); lead.push({ x: far.x, y: far.y, layer: J.layer }); cur = far;
1096
+ for (const t of routed)
1097
+ for (const side of ['start', 'end']) {
1098
+ const J = side === 'start' ? t.route[0] : t.route.at(-1);
1099
+ if (J.route_type !== 'wire' || J.start_pcb_port_id || J.end_pcb_port_id) continue; // on a pad: no stub
1100
+ if (routed.filter((u) => [u.route[0], u.route.at(-1)].some((p) => near(p, J))).length !== 1) continue; // other tracks meet there
1101
+ const mine = kept.filter((k) => k.source_trace_id === t.source_trace_id);
1102
+ const lead = [{ x: J.x, y: J.y, layer: J.layer }],
1103
+ segs = [],
1104
+ used = new Set();
1105
+ for (let cur = J; ;) {
1106
+ if (mine.some((k) => k.route[1]?.route_type === 'via' && near(k.route[0], cur))) break; // a via: the stub changes layer here
1107
+ const next = mine.filter(
1108
+ (k) =>
1109
+ !used.has(k) &&
1110
+ k.route.length === 2 &&
1111
+ k.route.every((p) => p.route_type === 'wire' && p.layer === J.layer) &&
1112
+ k.route.some((p) => near(p, cur)),
1113
+ );
1114
+ if (next.length !== 1) break;
1115
+ const k = next[0],
1116
+ far = near(k.route[0], cur) ? k.route[1] : k.route[0];
1117
+ used.add(k);
1118
+ segs.push({ trace: k });
1119
+ lead.push({ x: far.x, y: far.y, layer: J.layer });
1120
+ cur = far;
1121
+ }
1122
+ if (segs.length >= 2)
1123
+ chains.set(t.pcb_trace_id, { ...chains.get(t.pcb_trace_id), [side]: { lead: lead.reverse(), segs } });
532
1124
  }
533
- if (segs.length >= 2) chains.set(t.pcb_trace_id, { ...chains.get(t.pcb_trace_id), [side]: { lead: lead.reverse(), segs } });
534
- }
535
1125
  return chains;
536
1126
  }
537
1127
 
538
1128
  // A point on (or near) the board's edge moved in by d, straight in from the nearest side of its bounds
539
1129
  function inward(board, x, y, d) {
540
- const l = board.center.x - board.width / 2, r = board.center.x + board.width / 2, b = board.center.y - board.height / 2, t = board.center.y + board.height / 2;
541
- const sides = [[x - l, 1, 0], [r - x, -1, 0], [y - b, 0, 1], [t - y, 0, -1]].sort((p, q) => p[0] - q[0]);
1130
+ const l = board.center.x - board.width / 2,
1131
+ r = board.center.x + board.width / 2,
1132
+ b = board.center.y - board.height / 2,
1133
+ t = board.center.y + board.height / 2;
1134
+ const sides = [
1135
+ [x - l, 1, 0],
1136
+ [r - x, -1, 0],
1137
+ [y - b, 0, 1],
1138
+ [t - y, 0, -1],
1139
+ ].sort((p, q) => p[0] - q[0]);
542
1140
  return { x: x + sides[0][1] * d, y: y + sides[0][2] * d };
543
1141
  }
544
1142
 
545
1143
  // A plated hole's copper: its width and height (a round pad, or a rounded rectangle)
546
- export const holeSize = (e) => (e.outer_diameter != null ? { w: e.outer_diameter, h: e.outer_diameter } : { w: e.rect_pad_width ?? e.outer_width, h: e.rect_pad_height ?? e.outer_height });
1144
+ export const holeSize = (e) =>
1145
+ e.outer_diameter != null
1146
+ ? { w: e.outer_diameter, h: e.outer_diameter }
1147
+ : { w: e.rect_pad_width ?? e.outer_width, h: e.rect_pad_height ?? e.outer_height };
547
1148
 
548
1149
  // The source's copper kept with a block of parts (moveGroup's keep): its tracks and vias as they were, each island a
549
1150
  // source trace joining its pins (and its plane, if its via reaches one), so nothing routes them again
550
1151
  function keptCopper(out, add, board, copper, planeNets, later = false) {
551
1152
  const pins = padsByPin(out);
552
- for (const k of board.copper.islands.filter((x) => !!x.after === later)) { // (stubs are laid with the connection they start: see the traces below)
1153
+ for (const k of board.copper.islands.filter((x) => !!x.after === later)) {
1154
+ // (stubs are laid with the connection they start: see the traces below)
553
1155
  const ports = [...new Set(k.pins.flatMap((p) => (pins.get(p) || []).map((f) => f.sp.source_port_id)))];
554
1156
  const plane = k.via && planeNets[k.net];
555
1157
  if (!ports.length || (ports.length < 2 && !plane)) continue; // nothing left to join
556
- 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 } : {}) });
1158
+ const st = add('source_trace', {
1159
+ connected_source_port_ids: ports,
1160
+ connected_source_net_ids: plane ? [plane.id] : [],
1161
+ subcircuit_id: SUB,
1162
+ display_name: `${k.pins.join(', ')}: the source's own copper`,
1163
+ ...(k.net ? { rulecad_net: k.net } : {}),
1164
+ });
557
1165
  for (const g of board.copper.tracks.filter((t) => t.island === k.id))
558
- 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 });
1166
+ add('pcb_trace', {
1167
+ route: [
1168
+ { route_type: 'wire', x: g.a.x, y: g.a.y, width: g.width, layer: g.layer },
1169
+ { route_type: 'wire', x: g.b.x, y: g.b.y, width: g.width, layer: g.layer },
1170
+ ],
1171
+ source_trace_id: st.source_trace_id,
1172
+ subcircuit_id: SUB,
1173
+ rulecad_kept: true,
1174
+ });
559
1175
  for (const v of board.copper.vias.filter((x) => x.island === k.id)) {
560
- const t = add('pcb_trace', { route: [{ route_type: 'wire', x: v.x, y: v.y, width: Math.min(v.pad, 0.2), layer: 'top' }, { route_type: 'via', x: v.x, y: v.y, from_layer: 'top', to_layer: 'bottom' }], source_trace_id: st.source_trace_id, subcircuit_id: SUB, rulecad_kept: true });
561
- add('pcb_via', { pcb_trace_id: t.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 });
1176
+ const t = add('pcb_trace', {
1177
+ route: [
1178
+ { route_type: 'wire', x: v.x, y: v.y, width: Math.min(v.pad, 0.2), layer: 'top' },
1179
+ { route_type: 'via', x: v.x, y: v.y, from_layer: 'top', to_layer: 'bottom' },
1180
+ ],
1181
+ source_trace_id: st.source_trace_id,
1182
+ subcircuit_id: SUB,
1183
+ rulecad_kept: true,
1184
+ });
1185
+ add('pcb_via', {
1186
+ pcb_trace_id: t.pcb_trace_id,
1187
+ x: v.x,
1188
+ y: v.y,
1189
+ hole_diameter: v.hole,
1190
+ outer_diameter: v.pad,
1191
+ layers: copper,
1192
+ from_layer: 'top',
1193
+ to_layer: 'bottom',
1194
+ subcircuit_id: SUB,
1195
+ });
562
1196
  }
563
1197
  }
564
1198
  }
@@ -568,16 +1202,32 @@ function keptCopper(out, add, board, copper, planeNets, later = false) {
568
1202
  * time up to reach, to the nearest clear place; one with nowhere clear stays, marked clash: true.
569
1203
  * @param {object[]} silk { text, x, y, size, rotation } @param {object[]} copper @param {object} o
570
1204
  */
571
- export function slideClear(silk, copper, { reach = 1.5, step = 0.1, gap = 0.15, char = 0.75, bodies = [], area = null, near = 6 } = {}) {
1205
+ export function slideClear(
1206
+ silk,
1207
+ copper,
1208
+ { reach = 1.5, step = 0.1, gap = 0.15, char = 0.75, bodies = [], area = null, near = 6 } = {},
1209
+ ) {
572
1210
  const turned = (s) => (((s.rotation ?? 0) % 180) + 180) % 180 === 90;
573
- const box = (s, dx = 0, dy = 0) => { const long = s.text.length * s.size * char; return { x: s.x + dx, y: s.y + dy, w: turned(s) ? s.size : long, h: turned(s) ? long : s.size }; };
1211
+ const box = (s, dx = 0, dy = 0) => {
1212
+ const long = s.text.length * s.size * char;
1213
+ return { x: s.x + dx, y: s.y + dy, w: turned(s) ? s.size : long, h: turned(s) ? long : s.size };
1214
+ };
574
1215
  const hits = (a, b, g) => Math.abs(a.x - b.x) < (a.w + b.w) / 2 + g && Math.abs(a.y - b.y) < (a.h + b.h) / 2 + g;
575
- const within = (b) => !area || (b.x - b.w / 2 >= area.minX && b.x + b.w / 2 <= area.maxX && b.y - b.h / 2 >= area.minY && b.y + b.h / 2 <= area.maxY);
576
- const placed = [], n = Math.round(reach / step), out = [...silk];
577
- silk.forEach((s, k) => { // labels at their pins: slid across their reading direction to the nearest clear place
1216
+ const within = (b) =>
1217
+ !area ||
1218
+ (b.x - b.w / 2 >= area.minX &&
1219
+ b.x + b.w / 2 <= area.maxX &&
1220
+ b.y - b.h / 2 >= area.minY &&
1221
+ b.y + b.h / 2 <= area.maxY);
1222
+ const placed = [],
1223
+ n = Math.round(reach / step),
1224
+ out = [...silk];
1225
+ silk.forEach((s, k) => {
1226
+ // labels at their pins: slid across their reading direction to the nearest clear place
578
1227
  if (!s.text || s.to) return;
579
1228
  for (let i = 0; i <= 2 * n; i++) {
580
- const d = (i % 2 ? 1 : -1) * Math.ceil(i / 2) * step, b = box(s, turned(s) ? d : 0, turned(s) ? 0 : d);
1229
+ const d = (i % 2 ? 1 : -1) * Math.ceil(i / 2) * step,
1230
+ b = box(s, turned(s) ? d : 0, turned(s) ? 0 : d);
581
1231
  if (copper.some((c) => hits(b, c, gap)) || placed.some((o) => hits(b, o, gap))) continue;
582
1232
  placed.push(b);
583
1233
  out[k] = { ...s, x: Math.round(b.x * 1e4) / 1e4, y: Math.round(b.y * 1e4) / 1e4 };
@@ -591,15 +1241,26 @@ export function slideClear(silk, copper, { reach = 1.5, step = 0.1, gap = 0.15,
591
1241
  // them, pointing at it, clear too. One with nowhere clear stays put, without its pointer
592
1242
  silk.forEach((s, k) => {
593
1243
  if (!s.text || !s.to) return;
594
- const m = Math.round(near / step), spots = [], other = { ...s, rotation: turned(s) ? 0 : 90 }; // level or turned, whichever fits nearer
595
- for (let i = -m; i <= m; i += 2) for (let j = -m; j <= m; j += 2) for (const t of [s, other]) spots.push({ t, dx: i * step, dy: j * step });
1244
+ const m = Math.round(near / step),
1245
+ spots = [],
1246
+ other = { ...s, rotation: turned(s) ? 0 : 90 }; // level or turned, whichever fits nearer
1247
+ for (let i = -m; i <= m; i += 2)
1248
+ for (let j = -m; j <= m; j += 2) for (const t of [s, other]) spots.push({ t, dx: i * step, dy: j * step });
596
1249
  spots.sort((a, b) => Math.hypot(a.dx, a.dy) - Math.hypot(b.dx, b.dy));
597
1250
  for (const { t, dx, dy } of spots) {
598
1251
  const b = box(t, dx, dy);
599
- if (!within(b) || copper.some((c) => hits(b, c, gap)) || bodies.some((c) => hits(b, c, gap)) || placed.some((o) => hits(b, o, gap))) continue;
600
- for (const to of [s.to].flat()) { // a spot, or several to choose from (past the end of a pad, or beside it)
1252
+ if (
1253
+ !within(b) ||
1254
+ copper.some((c) => hits(b, c, gap)) ||
1255
+ bodies.some((c) => hits(b, c, gap)) ||
1256
+ placed.some((o) => hits(b, o, gap))
1257
+ )
1258
+ continue;
1259
+ for (const to of [s.to].flat()) {
1260
+ // a spot, or several to choose from (past the end of a pad, or beside it)
601
1261
  const a = arrowPath(b, to);
602
- if (a.length < 0.8 || copper.some((c) => hits(a.at, c, 0.1)) || placed.some((o) => hits(a.at, o, 0.1))) continue;
1262
+ if (a.length < 0.8 || copper.some((c) => hits(a.at, c, 0.1)) || placed.some((o) => hits(a.at, o, 0.1)))
1263
+ continue;
603
1264
  placed.push(b, a.at);
604
1265
  out[k] = { ...t, to, x: Math.round(b.x * 1e4) / 1e4, y: Math.round(b.y * 1e4) / 1e4 };
605
1266
  return;
@@ -618,29 +1279,84 @@ export function slideClear(silk, copper, { reach = 1.5, step = 0.1, gap = 0.15,
618
1279
  * @returns {{ head: object[], at: { x, y, w, h }, length: number }} the triangle (closed), its box, the distance to `to`
619
1280
  */
620
1281
  export function arrowPath(box, to, { gap = 0.2, size = 0.6 } = {}) {
621
- const sides = [[1, 0], [-1, 0], [0, 1], [0, -1]].map(([ix, iy]) => ({ x: box.x + ix * (box.w / 2 + gap), y: box.y + iy * (box.h / 2 + gap) }));
1282
+ const sides = [
1283
+ [1, 0],
1284
+ [-1, 0],
1285
+ [0, 1],
1286
+ [0, -1],
1287
+ ].map(([ix, iy]) => ({ x: box.x + ix * (box.w / 2 + gap), y: box.y + iy * (box.h / 2 + gap) }));
622
1288
  const from = sides.sort((a, b) => Math.hypot(a.x - to.x, a.y - to.y) - Math.hypot(b.x - to.x, b.y - to.y))[0];
623
- const len = Math.hypot(to.x - from.x, to.y - from.y) || 1, ux = (to.x - from.x) / len, uy = (to.y - from.y) / len;
624
- const tip = { x: from.x + ux * size, y: from.y + uy * size }, b1 = { x: from.x - uy * size / 2, y: from.y + ux * size / 2 }, b2 = { x: from.x + uy * size / 2, y: from.y - ux * size / 2 };
625
- return { head: [b1, tip, b2, b1], at: { x: from.x + ux * size / 2, y: from.y + uy * size / 2, w: size, h: size }, length: len };
1289
+ const len = Math.hypot(to.x - from.x, to.y - from.y) || 1,
1290
+ ux = (to.x - from.x) / len,
1291
+ uy = (to.y - from.y) / len;
1292
+ const tip = { x: from.x + ux * size, y: from.y + uy * size },
1293
+ b1 = { x: from.x - (uy * size) / 2, y: from.y + (ux * size) / 2 },
1294
+ b2 = { x: from.x + (uy * size) / 2, y: from.y - (ux * size) / 2 };
1295
+ return {
1296
+ head: [b1, tip, b2, b1],
1297
+ at: { x: from.x + (ux * size) / 2, y: from.y + (uy * size) / 2, w: size, h: size },
1298
+ length: len,
1299
+ };
626
1300
  }
627
1301
 
628
1302
  // After routing: silkscreen text the router's vias (or any copper) landed on slides clear, as clearLabels does before;
629
1303
  // then each label that points at its pin gets its triangle, beside where the label ended up
630
1304
  function clearSilkAfter(out, add, board) {
631
- const copper = [...out.filter((e) => e.type === 'pcb_via').map((e) => ({ x: e.x, y: e.y, w: e.outer_diameter, h: e.outer_diameter })),
1305
+ const copper = [
1306
+ ...out
1307
+ .filter((e) => e.type === 'pcb_via')
1308
+ .map((e) => ({ x: e.x, y: e.y, w: e.outer_diameter, h: e.outer_diameter })),
632
1309
  ...out.filter((e) => e.type === 'pcb_smtpad').map((e) => smtBounds(e)),
633
- ...out.filter((e) => e.type === 'pcb_plated_hole').map((e) => ({ x: e.x, y: e.y, ...holeSize(e) }))];
1310
+ ...out.filter((e) => e.type === 'pcb_plated_hole').map((e) => ({ x: e.x, y: e.y, ...holeSize(e) })),
1311
+ ];
634
1312
  const texts = out.filter((e) => e.type === 'pcb_silkscreen_text' && !e.pcb_component_id);
635
- const b = out.find((e) => e.type === 'pcb_board'), pts = b.outline || [{ x: b.center.x - b.width / 2, y: b.center.y - b.height / 2 }, { x: b.center.x + b.width / 2, y: b.center.y + b.height / 2 }];
636
- const area = { minX: Math.min(...pts.map((q) => q.x)), maxX: Math.max(...pts.map((q) => q.x)), minY: Math.min(...pts.map((q) => q.y)), maxY: Math.max(...pts.map((q) => q.y)) };
637
- const moved = slideClear(texts.map((e) => ({ text: e.text, x: e.anchor_position.x, y: e.anchor_position.y, size: e.font_size, rotation: e.ccw_rotation, to: e.rulecad_to })), copper, { area });
1313
+ const b = out.find((e) => e.type === 'pcb_board'),
1314
+ pts = b.outline || [
1315
+ { x: b.center.x - b.width / 2, y: b.center.y - b.height / 2 },
1316
+ { x: b.center.x + b.width / 2, y: b.center.y + b.height / 2 },
1317
+ ];
1318
+ const area = {
1319
+ minX: Math.min(...pts.map((q) => q.x)),
1320
+ maxX: Math.max(...pts.map((q) => q.x)),
1321
+ minY: Math.min(...pts.map((q) => q.y)),
1322
+ maxY: Math.max(...pts.map((q) => q.y)),
1323
+ };
1324
+ const moved = slideClear(
1325
+ texts.map((e) => ({
1326
+ text: e.text,
1327
+ x: e.anchor_position.x,
1328
+ y: e.anchor_position.y,
1329
+ size: e.font_size,
1330
+ rotation: e.ccw_rotation,
1331
+ to: e.rulecad_to,
1332
+ })),
1333
+ copper,
1334
+ { area },
1335
+ );
638
1336
  texts.forEach((e, i) => {
639
1337
  e.anchor_position = { x: moved[i].x, y: moved[i].y };
640
- if (!moved[i].to) { delete e.rulecad_to; return; }
641
- const turned = (((e.ccw_rotation ?? 0) % 180) + 180) % 180 === 90, long = e.text.length * e.font_size * 0.75;
642
- const a = arrowPath({ x: e.anchor_position.x, y: e.anchor_position.y, w: turned ? e.font_size : long, h: turned ? long : e.font_size }, e.rulecad_to);
643
- add('pcb_silkscreen_path', { pcb_component_id: null, layer: e.layer, route: a.head, stroke_width: board.silk_line ?? 0.15, subcircuit_id: SUB });
1338
+ if (!moved[i].to) {
1339
+ delete e.rulecad_to;
1340
+ return;
1341
+ }
1342
+ const turned = (((e.ccw_rotation ?? 0) % 180) + 180) % 180 === 90,
1343
+ long = e.text.length * e.font_size * 0.75;
1344
+ const a = arrowPath(
1345
+ {
1346
+ x: e.anchor_position.x,
1347
+ y: e.anchor_position.y,
1348
+ w: turned ? e.font_size : long,
1349
+ h: turned ? long : e.font_size,
1350
+ },
1351
+ e.rulecad_to,
1352
+ );
1353
+ add('pcb_silkscreen_path', {
1354
+ pcb_component_id: null,
1355
+ layer: e.layer,
1356
+ route: a.head,
1357
+ stroke_width: board.silk_line ?? 0.15,
1358
+ subcircuit_id: SUB,
1359
+ });
644
1360
  delete e.rulecad_to;
645
1361
  });
646
1362
  }
@@ -659,7 +1375,10 @@ function padsByPin(out) {
659
1375
  const map = new Map();
660
1376
  for (const e of out.filter((x) => (x.type === 'pcb_smtpad' || x.type === 'pcb_plated_hole') && x.pcb_port_id)) {
661
1377
  const sp = port.get(e.pcb_port_id);
662
- for (const key of new Set([sp.name, ...(sp.port_hints || [])])) { const k = `${comp.get(sp.source_component_id)}.${key}`; map.set(k, [...(map.get(k) || []), { e, sp }]); }
1378
+ for (const key of new Set([sp.name, ...(sp.port_hints || [])])) {
1379
+ const k = `${comp.get(sp.source_component_id)}.${key}`;
1380
+ map.set(k, [...(map.get(k) || []), { e, sp }]);
1381
+ }
663
1382
  }
664
1383
  return map;
665
1384
  }
@@ -669,78 +1388,186 @@ function padsByPin(out) {
669
1388
  // and a short track (the nearest clear spot, outward from its part first); failing that, a track to a via of its net nearby; failing that, a link for the router to
670
1389
  // the nearest pad of its net that reaches the plane. Returns { nets: { net: { layer, id } }, links }.
671
1390
  function planeVias(out, add, board, copper) {
672
- const b = out.find((e) => e.type === 'pcb_board'), clear = board.plane_clearance ?? 0.2, via = { hole: board.via_hole ?? 0.3, pad: board.via_pad ?? 0.8 };
673
- const width = board.plane_track ?? board.track ?? 0.25, pins = padsByPin(out), nets = {}, stuck = [];
674
- const rects = out.filter((e) => e.type === 'pcb_smtpad').map((e) => ({ id: e.pcb_smtpad_id, layer: e.layer, ...smtBounds(e) }));
675
- const circles = [...out.filter((e) => e.type === 'pcb_plated_hole').map((e) => ({ id: e.pcb_plated_hole_id, x: e.x, y: e.y, r: Math.max(holeSize(e).w, holeSize(e).h) / 2 })),
676
- ...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 }))];
677
- const segs = [], sameNet = Object.fromEntries(Object.keys(board.planes).map((n) => [n, []])); // plane tracks drawn so far; each net's vias
1391
+ const b = out.find((e) => e.type === 'pcb_board'),
1392
+ clear = board.plane_clearance ?? 0.2,
1393
+ via = { hole: board.via_hole ?? 0.3, pad: board.via_pad ?? 0.8 };
1394
+ const width = board.plane_track ?? board.track ?? 0.25,
1395
+ pins = padsByPin(out),
1396
+ nets = {},
1397
+ stuck = [];
1398
+ const rects = out
1399
+ .filter((e) => e.type === 'pcb_smtpad')
1400
+ .map((e) => ({ id: e.pcb_smtpad_id, layer: e.layer, ...smtBounds(e) }));
1401
+ const circles = [
1402
+ ...out
1403
+ .filter((e) => e.type === 'pcb_plated_hole')
1404
+ .map((e) => ({ id: e.pcb_plated_hole_id, x: e.x, y: e.y, r: Math.max(holeSize(e).w, holeSize(e).h) / 2 })),
1405
+ ...out
1406
+ .filter((e) => e.type === 'pcb_hole')
1407
+ .map((e) => ({ id: e.pcb_hole_id, x: e.x, y: e.y, r: e.hole_diameter / 2 })),
1408
+ ];
1409
+ const segs = [],
1410
+ sameNet = Object.fromEntries(Object.keys(board.planes).map((n) => [n, []])); // plane tracks drawn so far; each net's vias
678
1411
  const kept = board.copper || { tracks: [], vias: [], islands: [] }; // the source's copper, kept: in the way, and some pads already reach their plane by it
679
1412
  const laterIds = new Set((kept.islands || []).filter((k) => k.after).map((k) => k.id)); // (laid once routed: not in the router's way)
680
- 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 });
681
- 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 });
1413
+ for (const g of kept.tracks)
1414
+ if ((g.layer === 'top' || g.layer === 'bottom') && !laterIds.has(g.island))
1415
+ segs.push({ a: g.a, b: g.b, layer: g.layer, w: g.width });
1416
+ for (const v of kept.vias)
1417
+ if (!laterIds.has(v.island)) circles.push({ id: `kept${circles.length}`, x: v.x, y: v.y, r: v.pad / 2 });
682
1418
  const reachedBy = new Set(kept.islands.filter((k) => k.via && board.planes[k.net]).flatMap((k) => k.pins));
683
- 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));
684
- 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); };
685
- const edge = (x, y) => { // how far inside the board
686
- if (!b.outline) return Math.min(x - (b.center.x - b.width / 2), b.center.x + b.width / 2 - x, y - (b.center.y - b.height / 2), b.center.y + b.height / 2 - y);
687
- let d = Infinity; for (let i = 0; i < b.outline.length; i++) d = Math.min(d, toSeg(x, y, b.outline[i], b.outline[(i + 1) % b.outline.length]));
1419
+ const toRect = (x, y, q) =>
1420
+ Math.hypot(Math.max(Math.abs(x - q.x) - q.w / 2, 0), Math.max(Math.abs(y - q.y) - q.h / 2, 0));
1421
+ const toSeg = (x, y, a, c) => {
1422
+ const dx = c.x - a.x,
1423
+ dy = c.y - a.y,
1424
+ l = dx * dx + dy * dy,
1425
+ t = l ? Math.max(0, Math.min(1, ((x - a.x) * dx + (y - a.y) * dy) / l)) : 0;
1426
+ return Math.hypot(x - a.x - t * dx, y - a.y - t * dy);
1427
+ };
1428
+ const edge = (x, y) => {
1429
+ // how far inside the board
1430
+ if (!b.outline)
1431
+ return Math.min(
1432
+ x - (b.center.x - b.width / 2),
1433
+ b.center.x + b.width / 2 - x,
1434
+ y - (b.center.y - b.height / 2),
1435
+ b.center.y + b.height / 2 - y,
1436
+ );
1437
+ let d = Infinity;
1438
+ for (let i = 0; i < b.outline.length; i++)
1439
+ d = Math.min(d, toSeg(x, y, b.outline[i], b.outline[(i + 1) % b.outline.length]));
688
1440
  return insidePolygon(b.outline, { x, y }) ? d : -d;
689
1441
  };
690
- const viaFree = (x, y, own) => edge(x, y) >= via.pad / 2 + (b.min_board_edge_clearance ?? 0.2)
691
- && rects.every((q) => toRect(x, y, q) >= via.pad / 2 + (q.id === own ? 0.1 : clear))
692
- && circles.every((c) => Math.hypot(x - c.x, y - c.y) >= c.r + via.pad / 2 + clear)
693
- && segs.every((g) => toSeg(x, y, g.a, g.b) >= via.pad / 2 + (g.w ?? width) / 2 + clear);
1442
+ const viaFree = (x, y, own) =>
1443
+ edge(x, y) >= via.pad / 2 + (b.min_board_edge_clearance ?? 0.2) &&
1444
+ rects.every((q) => toRect(x, y, q) >= via.pad / 2 + (q.id === own ? 0.1 : clear)) &&
1445
+ circles.every((c) => Math.hypot(x - c.x, y - c.y) >= c.r + via.pad / 2 + clear) &&
1446
+ segs.every((g) => toSeg(x, y, g.a, g.b) >= via.pad / 2 + (g.w ?? width) / 2 + clear);
694
1447
  const trackFree = (a, c, layer, own) => {
695
1448
  const n = Math.max(2, Math.ceil(Math.hypot(c.x - a.x, c.y - a.y) / 0.05));
696
1449
  for (let i = 0; i <= n; i++) {
697
- const x = a.x + ((c.x - a.x) * i) / n, y = a.y + ((c.y - a.y) * i) / n;
1450
+ const x = a.x + ((c.x - a.x) * i) / n,
1451
+ y = a.y + ((c.y - a.y) * i) / n;
698
1452
  if (rects.some((q) => q.id !== own && q.layer === layer && toRect(x, y, q) < width / 2 + clear)) return false;
699
1453
  if (circles.some((q) => Math.hypot(x - q.x, y - q.y) < q.r + width / 2 + clear)) return false;
700
- if (segs.some((g) => g.layer === layer && toSeg(x, y, g.a, g.b) < width / 2 + (g.w ?? width) / 2 + clear)) return false;
1454
+ if (segs.some((g) => g.layer === layer && toSeg(x, y, g.a, g.b) < width / 2 + (g.w ?? width) / 2 + clear))
1455
+ return false;
701
1456
  }
702
1457
  return true;
703
1458
  };
704
1459
  const comps = new Map(out.filter((e) => e.type === 'pcb_component').map((e) => [e.pcb_component_id, e.center]));
705
1460
  for (const [name, spec] of Object.entries(board.planes)) {
706
- if (!copper.includes(spec.layer) || /^(top|bottom)$/.test(spec.layer)) throw new Error(`plane ${name}: "${spec.layer}" isn't an inner layer of this board (${copper.slice(1, -1).join(', ')})`);
707
- const net = add('source_net', { name, member_source_group_ids: [], is_ground: /gnd|ground/i.test(name), is_power: /^\+|vcc|vdd|3v3|5v/i.test(name), subcircuit_id: SUB });
1461
+ if (!copper.includes(spec.layer) || /^(top|bottom)$/.test(spec.layer))
1462
+ throw new Error(
1463
+ `plane ${name}: "${spec.layer}" isn't an inner layer of this board (${copper.slice(1, -1).join(', ')})`,
1464
+ );
1465
+ const net = add('source_net', {
1466
+ name,
1467
+ member_source_group_ids: [],
1468
+ is_ground: /gnd|ground/i.test(name),
1469
+ is_power: /^\+|vcc|vdd|3v3|5v/i.test(name),
1470
+ subcircuit_id: SUB,
1471
+ });
708
1472
  nets[name] = { layer: spec.layer, id: net.source_net_id };
709
1473
  for (const pin of spec.pins) {
710
1474
  if (reachedBy.has(pin)) continue; // the source's own via, kept, takes it to the plane (keptCopper records it)
711
1475
  const found = pins.get(pin);
712
1476
  if (!found) throw new Error(`plane ${name}: no pin ${pin}`);
713
1477
  for (const { e, sp } of found) {
714
- const st = add('source_trace', { connected_source_port_ids: [sp.source_port_id], connected_source_net_ids: [net.source_net_id], subcircuit_id: SUB, display_name: `${pin} to ${name}` });
1478
+ const st = add('source_trace', {
1479
+ connected_source_port_ids: [sp.source_port_id],
1480
+ connected_source_net_ids: [net.source_net_id],
1481
+ subcircuit_id: SUB,
1482
+ display_name: `${pin} to ${name}`,
1483
+ });
715
1484
  if (e.type === 'pcb_plated_hole') continue; // its barrel reaches every layer
716
1485
  const sb = smtBounds(e); // a pad with a plated hole of its own pin in it (a chip's centre pad with its thermal vias) has one too
717
- if (found.some((f) => f.e.type === 'pcb_plated_hole' && Math.abs(f.e.x - sb.x) <= sb.w / 2 && Math.abs(f.e.y - sb.y) <= sb.h / 2)) continue;
718
- const pad = { x: e.x ?? smtBounds(e).x, y: e.y ?? smtBounds(e).y, ...smtBounds(e) }, start = { route_type: 'wire', x: pad.x, y: pad.y, width, layer: e.layer, start_pcb_port_id: e.pcb_port_id };
719
- const viaAt = (x, y) => ({ route_type: 'via', x, y, from_layer: e.layer, to_layer: e.layer === 'top' ? 'bottom' : 'top' });
1486
+ if (
1487
+ found.some(
1488
+ (f) =>
1489
+ f.e.type === 'pcb_plated_hole' &&
1490
+ Math.abs(f.e.x - sb.x) <= sb.w / 2 &&
1491
+ Math.abs(f.e.y - sb.y) <= sb.h / 2,
1492
+ )
1493
+ )
1494
+ continue;
1495
+ const pad = { x: e.x ?? smtBounds(e).x, y: e.y ?? smtBounds(e).y, ...smtBounds(e) },
1496
+ start = { route_type: 'wire', x: pad.x, y: pad.y, width, layer: e.layer, start_pcb_port_id: e.pcb_port_id };
1497
+ const viaAt = (x, y) => ({
1498
+ route_type: 'via',
1499
+ x,
1500
+ y,
1501
+ from_layer: e.layer,
1502
+ to_layer: e.layer === 'top' ? 'bottom' : 'top',
1503
+ });
720
1504
  const places = [];
721
1505
  {
722
- const c = comps.get(e.pcb_component_id) || pad, out0 = Math.atan2(pad.y - c.y, pad.x - c.x) || 0;
1506
+ const c = comps.get(e.pcb_component_id) || pad,
1507
+ out0 = Math.atan2(pad.y - c.y, pad.x - c.x) || 0;
723
1508
  const tries = [];
724
- for (const gap of [0.1, 0.25, 0.45, 0.7, 1, 1.4]) for (let k = 0; k < 16; k++) {
725
- const a = out0 + (k % 2 ? 1 : -1) * Math.ceil(k / 2) * (Math.PI / 8), ca = Math.cos(a), sa = Math.sin(a);
726
- const reach = Math.min(Math.abs(ca) > 1e-9 ? pad.w / 2 / Math.abs(ca) : Infinity, Math.abs(sa) > 1e-9 ? pad.h / 2 / Math.abs(sa) : Infinity) + gap + via.pad / 2;
727
- tries.push({ x: pad.x + ca * reach, y: pad.y + sa * reach });
728
- }
729
- const ok = tries.find((t) => viaFree(t.x, t.y, e.pcb_smtpad_id) && trackFree(pad, t, e.layer, e.pcb_smtpad_id));
1509
+ for (const gap of [0.1, 0.25, 0.45, 0.7, 1, 1.4])
1510
+ for (let k = 0; k < 16; k++) {
1511
+ const a = out0 + (k % 2 ? 1 : -1) * Math.ceil(k / 2) * (Math.PI / 8),
1512
+ ca = Math.cos(a),
1513
+ sa = Math.sin(a);
1514
+ const reach =
1515
+ Math.min(
1516
+ Math.abs(ca) > 1e-9 ? pad.w / 2 / Math.abs(ca) : Infinity,
1517
+ Math.abs(sa) > 1e-9 ? pad.h / 2 / Math.abs(sa) : Infinity,
1518
+ ) +
1519
+ gap +
1520
+ via.pad / 2;
1521
+ tries.push({ x: pad.x + ca * reach, y: pad.y + sa * reach });
1522
+ }
1523
+ const ok = tries.find(
1524
+ (t) => viaFree(t.x, t.y, e.pcb_smtpad_id) && trackFree(pad, t, e.layer, e.pcb_smtpad_id),
1525
+ );
730
1526
  // no room for its own: a short track to a via of the same net already placed, if one is clear to reach
731
- const shared = !ok && sameNet[name].map((v) => ({ ...v, d: Math.hypot(v.x - pad.x, v.y - pad.y) })).filter((v) => v.d <= 3).sort((a, c) => a.d - c.d)
732
- .find((v) => trackFree(pad, v, e.layer, e.pcb_smtpad_id));
733
- if (!ok && !shared) { stuck.push({ pin, name, x: pad.x, y: pad.y }); continue; }
1527
+ const shared =
1528
+ !ok &&
1529
+ sameNet[name]
1530
+ .map((v) => ({ ...v, d: Math.hypot(v.x - pad.x, v.y - pad.y) }))
1531
+ .filter((v) => v.d <= 3)
1532
+ .sort((a, c) => a.d - c.d)
1533
+ .find((v) => trackFree(pad, v, e.layer, e.pcb_smtpad_id));
1534
+ if (!ok && !shared) {
1535
+ stuck.push({ pin, name, x: pad.x, y: pad.y });
1536
+ continue;
1537
+ }
734
1538
  segs.push({ a: { x: pad.x, y: pad.y }, b: ok || shared, layer: e.layer });
735
- if (shared) { add('pcb_trace', { route: [start, { route_type: 'wire', x: shared.x, y: shared.y, width, layer: e.layer }], source_trace_id: st.source_trace_id, subcircuit_id: SUB }); continue; }
1539
+ if (shared) {
1540
+ add('pcb_trace', {
1541
+ route: [start, { route_type: 'wire', x: shared.x, y: shared.y, width, layer: e.layer }],
1542
+ source_trace_id: st.source_trace_id,
1543
+ subcircuit_id: SUB,
1544
+ });
1545
+ continue;
1546
+ }
736
1547
  places.push(ok);
737
1548
  }
738
- const route = [start, ...places.flatMap((v, i) => [{ route_type: 'wire', x: v.x, y: v.y, width, layer: e.layer }, viaAt(v.x, v.y),
739
- ...(i < places.length - 1 ? [{ route_type: 'wire', x: v.x, y: v.y, width, layer: e.layer }] : [])])];
1549
+ const route = [
1550
+ start,
1551
+ ...places.flatMap((v, i) => [
1552
+ { route_type: 'wire', x: v.x, y: v.y, width, layer: e.layer },
1553
+ viaAt(v.x, v.y),
1554
+ ...(i < places.length - 1 ? [{ route_type: 'wire', x: v.x, y: v.y, width, layer: e.layer }] : []),
1555
+ ]),
1556
+ ];
740
1557
  const t = add('pcb_trace', { route, source_trace_id: st.source_trace_id, subcircuit_id: SUB });
741
1558
  for (const v of places) {
742
1559
  sameNet[name].push(v);
743
- add('pcb_via', { pcb_trace_id: t.pcb_trace_id, x: v.x, y: v.y, hole_diameter: via.hole, outer_diameter: via.pad, layers: copper, from_layer: e.layer, to_layer: viaAt().to_layer, subcircuit_id: SUB });
1560
+ add('pcb_via', {
1561
+ pcb_trace_id: t.pcb_trace_id,
1562
+ x: v.x,
1563
+ y: v.y,
1564
+ hole_diameter: via.hole,
1565
+ outer_diameter: via.pad,
1566
+ layers: copper,
1567
+ from_layer: e.layer,
1568
+ to_layer: viaAt().to_layer,
1569
+ subcircuit_id: SUB,
1570
+ });
744
1571
  circles.push({ id: `via${circles.length}`, x: v.x, y: v.y, r: via.pad / 2 });
745
1572
  }
746
1573
  }
@@ -750,16 +1577,31 @@ function planeVias(out, add, board, copper) {
750
1577
  // plane, as a board's power pins between close neighbours are wired. Its source trace to the net goes (the track joins it)
751
1578
  const reached = new Map(Object.keys(board.planes).map((n) => [n, []]));
752
1579
  for (const t of out.filter((x) => x.type === 'pcb_trace' && x.route[0].start_pcb_port_id)) {
753
- const st = out.find((x) => x.source_trace_id === t.source_trace_id), n = out.find((x) => x.type === 'source_net' && x.source_net_id === st.connected_source_net_ids?.[0])?.name;
754
- if (n) reached.get(n).push({ x: t.route[0].x, y: t.route[0].y, pin: [...pins].find(([, l]) => l.some((q) => q.e.pcb_port_id === t.route[0].start_pcb_port_id))?.[0] });
1580
+ const st = out.find((x) => x.source_trace_id === t.source_trace_id),
1581
+ n = out.find((x) => x.type === 'source_net' && x.source_net_id === st.connected_source_net_ids?.[0])?.name;
1582
+ if (n)
1583
+ reached.get(n).push({
1584
+ x: t.route[0].x,
1585
+ y: t.route[0].y,
1586
+ pin: [...pins].find(([, l]) => l.some((q) => q.e.pcb_port_id === t.route[0].start_pcb_port_id))?.[0],
1587
+ });
755
1588
  }
756
1589
  const links = [];
757
1590
  for (const s of stuck) {
758
- const to = reached.get(s.name).filter((r) => r.pin && r.pin !== s.pin).sort((a, c) => Math.hypot(a.x - s.x, a.y - s.y) - Math.hypot(c.x - s.x, c.y - s.y))[0];
759
- if (!to) throw new Error(`no way for ${s.pin} to reach the ${s.name} plane: no room for a via, and no other pad of ${s.name} reaches it`);
1591
+ const to = reached
1592
+ .get(s.name)
1593
+ .filter((r) => r.pin && r.pin !== s.pin)
1594
+ .sort((a, c) => Math.hypot(a.x - s.x, a.y - s.y) - Math.hypot(c.x - s.x, c.y - s.y))[0];
1595
+ if (!to)
1596
+ throw new Error(
1597
+ `no way for ${s.pin} to reach the ${s.name} plane: no room for a via, and no other pad of ${s.name} reaches it`,
1598
+ );
760
1599
  const i = out.findIndex((x) => x.type === 'source_trace' && x.display_name === `${s.pin} to ${s.name}`);
761
1600
  if (i >= 0) out.splice(i, 1);
762
- const cut = (q) => { const k = q.indexOf('.'); return [q.slice(0, k), q.slice(k + 1)]; };
1601
+ const cut = (q) => {
1602
+ const k = q.indexOf('.');
1603
+ return [q.slice(0, k), q.slice(k + 1)];
1604
+ };
763
1605
  links.push({ from: cut(s.pin), to: cut(to.pin), width });
764
1606
  }
765
1607
  return { nets, links };
@@ -770,66 +1612,222 @@ function planeVias(out, add, board, copper) {
770
1612
  async function pours(out, add, board, nets, netOf) {
771
1613
  const { CopperPourPipelineSolver, initializeManifoldGeometry } = await import('@tscircuit/copper-pour-solver');
772
1614
  await initializeManifoldGeometry();
773
- const b = out.find((e) => e.type === 'pcb_board'), comp = new Map(out.filter((e) => e.type === 'source_component').map((e) => [e.source_component_id, e.name]));
1615
+ const b = out.find((e) => e.type === 'pcb_board'),
1616
+ comp = new Map(out.filter((e) => e.type === 'source_component').map((e) => [e.source_component_id, e.name]));
774
1617
  const src = new Map(out.filter((e) => e.type === 'source_port').map((e) => [e.source_port_id, e]));
775
- const portNet = (id) => { const sp = src.get(out.find((e) => e.pcb_port_id === id && e.type === 'pcb_port')?.source_port_id); if (!sp) return null;
776
- for (const k of [sp.name, ...(sp.port_hints || [])]) { const n = netOf.get(`${comp.get(sp.source_component_id)}.${k}`); if (n) return n; } return null; };
1618
+ const portNet = (id) => {
1619
+ const sp = src.get(out.find((e) => e.pcb_port_id === id && e.type === 'pcb_port')?.source_port_id);
1620
+ if (!sp) return null;
1621
+ for (const k of [sp.name, ...(sp.port_hints || [])]) {
1622
+ const n = netOf.get(`${comp.get(sp.source_component_id)}.${k}`);
1623
+ if (n) return n;
1624
+ }
1625
+ return null;
1626
+ };
777
1627
  const traceNet = new Map();
778
1628
  for (const t of out.filter((e) => e.type === 'source_trace')) {
779
- const n = t.connected_source_net_ids?.length ? out.find((e) => e.source_net_id === t.connected_source_net_ids[0] && e.type === 'source_net')?.name
780
- : (() => { for (const id of t.connected_source_port_ids) { const pp = out.find((e) => e.type === 'pcb_port' && e.source_port_id === id); const n2 = pp && portNet(pp.pcb_port_id); if (n2) return n2; } return null; })();
1629
+ const n = t.connected_source_net_ids?.length
1630
+ ? out.find((e) => e.source_net_id === t.connected_source_net_ids[0] && e.type === 'source_net')?.name
1631
+ : (() => {
1632
+ for (const id of t.connected_source_port_ids) {
1633
+ const pp = out.find((e) => e.type === 'pcb_port' && e.source_port_id === id);
1634
+ const n2 = pp && portNet(pp.pcb_port_id);
1635
+ if (n2) return n2;
1636
+ }
1637
+ return null;
1638
+ })();
781
1639
  traceNet.set(t.source_trace_id, n);
782
1640
  }
783
- const pcbTraceNet = new Map(out.filter((e) => e.type === 'pcb_trace').map((e) => [e.pcb_trace_id, traceNet.get(e.source_trace_id)]));
784
- const outline = b.outline || [{ x: b.center.x - b.width / 2, y: b.center.y - b.height / 2 }, { x: b.center.x + b.width / 2, y: b.center.y - b.height / 2 },
785
- { x: b.center.x + b.width / 2, y: b.center.y + b.height / 2 }, { x: b.center.x - b.width / 2, y: b.center.y + b.height / 2 }];
786
- const bounds = { minX: Math.min(...outline.map((p) => p.x)), maxX: Math.max(...outline.map((p) => p.x)), minY: Math.min(...outline.map((p) => p.y)), maxY: Math.max(...outline.map((p) => p.y)) };
1641
+ const pcbTraceNet = new Map(
1642
+ out.filter((e) => e.type === 'pcb_trace').map((e) => [e.pcb_trace_id, traceNet.get(e.source_trace_id)]),
1643
+ );
1644
+ const outline = b.outline || [
1645
+ { x: b.center.x - b.width / 2, y: b.center.y - b.height / 2 },
1646
+ { x: b.center.x + b.width / 2, y: b.center.y - b.height / 2 },
1647
+ { x: b.center.x + b.width / 2, y: b.center.y + b.height / 2 },
1648
+ { x: b.center.x - b.width / 2, y: b.center.y + b.height / 2 },
1649
+ ];
1650
+ const bounds = {
1651
+ minX: Math.min(...outline.map((p) => p.x)),
1652
+ maxX: Math.max(...outline.map((p) => p.x)),
1653
+ minY: Math.min(...outline.map((p) => p.y)),
1654
+ maxY: Math.max(...outline.map((p) => p.y)),
1655
+ };
787
1656
  for (const [name, { layer, id }] of Object.entries(nets)) {
788
1657
  const pads = [
789
- ...out.filter((e) => e.type === 'pcb_plated_hole').map((e) => { const { w, h } = holeSize(e), key = portNet(e.pcb_port_id) ?? `none:${e.pcb_plated_hole_id}`;
790
- return e.shape === 'circle' ? { padId: e.pcb_plated_hole_id, connectivityKey: key, layer, shape: 'circle', x: e.x, y: e.y, radius: w / 2, isPlatedHole: true }
791
- : { padId: e.pcb_plated_hole_id, connectivityKey: key, layer, shape: 'pill', x: e.x, y: e.y, width: w, height: h, radius: Math.min(w, h) / 2, ccwRotation: 0, isPlatedHole: true }; }),
792
- ...out.filter((e) => e.type === 'pcb_via').map((e) => ({ padId: e.pcb_via_id, connectivityKey: pcbTraceNet.get(e.pcb_trace_id) ?? `none:${e.pcb_via_id}`, layer, shape: 'circle', x: e.x, y: e.y, radius: e.outer_diameter / 2 })),
793
- ...out.filter((e) => e.type === 'pcb_hole').map((e) => ({ padId: e.pcb_hole_id, connectivityKey: `hole:${e.pcb_hole_id}`, layer, shape: 'circle', x: e.x, y: e.y, radius: e.hole_diameter / 2 })),
794
- ...out.filter((e) => e.type === 'pcb_trace' && e.route.some((p) => p.layer === layer)).map((e) => ({ padId: e.pcb_trace_id, connectivityKey: pcbTraceNet.get(e.pcb_trace_id) ?? `none:${e.pcb_trace_id}`, layer,
795
- shape: 'trace', width: e.route[0].width, segments: e.route.filter((p) => p.route_type === 'wire').map((p) => ({ x: p.x, y: p.y })) }))];
796
- const solver = new CopperPourPipelineSolver({ pads, regionsForPour: [{ shape: 'rect', layer, bounds, outline, connectivityKey: name,
797
- padMargin: board.plane_clearance ?? 0.2, traceMargin: board.plane_clearance ?? 0.2, board_edge_margin: board.plane_edge ?? 0.3,
798
- use_thermal_reliefs: true, thermal_relief_spoke_width: 0.3, thermal_relief_spoke_count: 4 }] });
1658
+ ...out
1659
+ .filter((e) => e.type === 'pcb_plated_hole')
1660
+ .map((e) => {
1661
+ const { w, h } = holeSize(e),
1662
+ key = portNet(e.pcb_port_id) ?? `none:${e.pcb_plated_hole_id}`;
1663
+ return e.shape === 'circle'
1664
+ ? {
1665
+ padId: e.pcb_plated_hole_id,
1666
+ connectivityKey: key,
1667
+ layer,
1668
+ shape: 'circle',
1669
+ x: e.x,
1670
+ y: e.y,
1671
+ radius: w / 2,
1672
+ isPlatedHole: true,
1673
+ }
1674
+ : {
1675
+ padId: e.pcb_plated_hole_id,
1676
+ connectivityKey: key,
1677
+ layer,
1678
+ shape: 'pill',
1679
+ x: e.x,
1680
+ y: e.y,
1681
+ width: w,
1682
+ height: h,
1683
+ radius: Math.min(w, h) / 2,
1684
+ ccwRotation: 0,
1685
+ isPlatedHole: true,
1686
+ };
1687
+ }),
1688
+ ...out
1689
+ .filter((e) => e.type === 'pcb_via')
1690
+ .map((e) => ({
1691
+ padId: e.pcb_via_id,
1692
+ connectivityKey: pcbTraceNet.get(e.pcb_trace_id) ?? `none:${e.pcb_via_id}`,
1693
+ layer,
1694
+ shape: 'circle',
1695
+ x: e.x,
1696
+ y: e.y,
1697
+ radius: e.outer_diameter / 2,
1698
+ })),
1699
+ ...out
1700
+ .filter((e) => e.type === 'pcb_hole')
1701
+ .map((e) => ({
1702
+ padId: e.pcb_hole_id,
1703
+ connectivityKey: `hole:${e.pcb_hole_id}`,
1704
+ layer,
1705
+ shape: 'circle',
1706
+ x: e.x,
1707
+ y: e.y,
1708
+ radius: e.hole_diameter / 2,
1709
+ })),
1710
+ ...out
1711
+ .filter((e) => e.type === 'pcb_trace' && e.route.some((p) => p.layer === layer))
1712
+ .map((e) => ({
1713
+ padId: e.pcb_trace_id,
1714
+ connectivityKey: pcbTraceNet.get(e.pcb_trace_id) ?? `none:${e.pcb_trace_id}`,
1715
+ layer,
1716
+ shape: 'trace',
1717
+ width: e.route[0].width,
1718
+ segments: e.route.filter((p) => p.route_type === 'wire').map((p) => ({ x: p.x, y: p.y })),
1719
+ })),
1720
+ ];
1721
+ const solver = new CopperPourPipelineSolver({
1722
+ pads,
1723
+ regionsForPour: [
1724
+ {
1725
+ shape: 'rect',
1726
+ layer,
1727
+ bounds,
1728
+ outline,
1729
+ connectivityKey: name,
1730
+ padMargin: board.plane_clearance ?? 0.2,
1731
+ traceMargin: board.plane_clearance ?? 0.2,
1732
+ board_edge_margin: board.plane_edge ?? 0.3,
1733
+ use_thermal_reliefs: true,
1734
+ thermal_relief_spoke_width: 0.3,
1735
+ thermal_relief_spoke_count: 4,
1736
+ },
1737
+ ],
1738
+ });
799
1739
  solver.solve();
800
1740
  if (solver.failed) throw new Error(`the ${name} plane couldn't be drawn: ${solver.error || 'no reason given'}`);
801
- for (const shape of solver.getOutput().brep_shapes) add('pcb_copper_pour', { layer, shape: 'brep', brep_shape: shape, source_net_id: id, covered_with_solder_mask: true, subcircuit_id: SUB });
1741
+ for (const shape of solver.getOutput().brep_shapes)
1742
+ add('pcb_copper_pour', {
1743
+ layer,
1744
+ shape: 'brep',
1745
+ brep_shape: shape,
1746
+ source_net_id: id,
1747
+ covered_with_solder_mask: true,
1748
+ subcircuit_id: SUB,
1749
+ });
802
1750
  }
803
1751
  }
804
1752
 
805
- // A part's port names, in pad order: a switch's pin1 and pin2, a diode's anode and cathode, a chip's pins by label
1753
+ // A part's port names, in pad order: a switch's pin1 and pin2, a diode's cathode and anode by its pads (diodePorts), a chip's pins by label
806
1754
  function portNames(part, pads) {
807
- if (part.ftype === 'simple_diode') return [{ name: 'pin1', n: 1, hints: ['pin1', 'pos', 'anode', 'left', '1'] }, { name: 'pin2', n: 2, hints: ['pin2', 'neg', 'cathode', 'right', '2'] }];
1755
+ if (part.ftype === 'simple_diode') return diodePorts(part, pads);
808
1756
  return (part.pads || pads).map((p) => {
809
- const n = Number(p.pin.replace(/\D/g, '')), label = part.sch?.pinLabels?.[p.pin];
1757
+ const n = Number(p.pin.replace(/\D/g, '')),
1758
+ label = part.sch?.pinLabels?.[p.pin];
810
1759
  return { name: label || p.pin, n, hints: label ? [label, p.pin, String(n)] : [p.pin, String(n)] };
811
1760
  });
812
1761
  }
813
1762
 
1763
+ // A diode's two ports, each named for the end of the diode its pad is. A pad that says which end it is (do35's
1764
+ // 'cathode' and 'anode') is that end; otherwise pad 1 is the cathode (K) and pad 2 the anode (A), as KiCad's diode
1765
+ // footprints and assemblers number them. The cathode is port 1 and the anode port 2, whatever order the pads come in,
1766
+ // so a KiCad export and a placement file give pad 1 as the cathode, and the band goes at that end.
1767
+ function diodePorts(part, pads) {
1768
+ if (pads.length !== 2)
1769
+ throw new Error(`${part.name}: a diode has two pads, one for each end, and this one has ${pads.length}`);
1770
+ const said = pads.map((p) =>
1771
+ /^(anode|a)$/i.test(p.pin) ? 'anode' : /^(cathode|k)$/i.test(p.pin) ? 'cathode' : null,
1772
+ );
1773
+ const other = (end) => (end === 'anode' ? 'cathode' : 'anode');
1774
+ const byNumber = (p) => (Number(String(p.hint ?? p.pin).replace(/\D/g, '')) === 1 ? 'cathode' : 'anode');
1775
+ const ends = said.map((s, i) => s ?? (said[1 - i] ? other(said[1 - i]) : byNumber(pads[i])));
1776
+ if (ends[0] === ends[1])
1777
+ throw new Error(
1778
+ `${part.name}: both of the diode's pads are its ${ends[0]}. Name one pad 'cathode' and the other 'anode', or number them 1 (cathode) and 2 (anode)`,
1779
+ );
1780
+ return ends.map((end) =>
1781
+ end === 'cathode'
1782
+ ? { name: 'pin1', n: 1, end, hints: ['pin1', 'cathode', 'neg', 'K', '1'] }
1783
+ : { name: 'pin2', n: 2, end, hints: ['pin2', 'anode', 'pos', 'A', '2'] },
1784
+ );
1785
+ }
1786
+
814
1787
  // A net's connections: its pins joined by the shortest set of straight links between them (Prim's minimum spanning
815
1788
  // tree, ties to the earlier pin), so the router gets short, sensible connections to route rather than a long chain
816
1789
  function netTraces(board, port, joined = new Map()) {
1790
+ const diodes = (board.parts || []).filter((q) => q.ftype === 'simple_diode').map((q) => q.name);
817
1791
  return Object.entries(board.nets || {}).flatMap(([net, spec]) => {
818
- const list = Array.isArray(spec) ? spec : spec.pins, width = (Array.isArray(spec) ? undefined : spec.width) ?? board.track;
819
- if (!width) throw new Error(`net ${net}: no track width. Give the board a track width (board.track) or the net one ({ pins, width })`);
820
- const pins = list.map((p) => { const i = String(p).indexOf('.'); if (i < 1) throw new Error(`net ${net}: "${p}" should name a part and a pin, like U1.GND`); return [p.slice(0, i), p.slice(i + 1)]; });
1792
+ const list = Array.isArray(spec) ? spec : spec.pins,
1793
+ width = (Array.isArray(spec) ? undefined : spec.width) ?? board.track;
1794
+ if (!width)
1795
+ throw new Error(
1796
+ `net ${net}: no track width. Give the board a track width (board.track) or the net one ({ pins, width })`,
1797
+ );
1798
+ const pins = list.map((p) => {
1799
+ const i = String(p).indexOf('.');
1800
+ if (i < 1) throw new Error(`net ${net}: "${p}" should name a part and a pin, like U1.GND`);
1801
+ return [p.slice(0, i), p.slice(i + 1)];
1802
+ });
821
1803
  // Pins the source's kept copper already joins come in together: only the joins between them are routed
822
- const at = pins.map((p) => port(...p)), group = pins.map((p) => joined.get(p.join('.'))), links = [];
823
- const linked = [], take = (i) => { for (let j = 0; j < pins.length; j++) if (j === i || (group[i] && group[j] === group[i])) if (!linked.includes(j)) linked.push(j); };
1804
+ const at = pins.map((p) => port(...p)),
1805
+ group = pins.map((p) => joined.get(p.join('.'))),
1806
+ links = [];
1807
+ // a net on both ends of one diode joins its cathode to its anode: the diode is shorted, and does nothing
1808
+ for (const d of diodes) {
1809
+ const ends = new Set(pins.flatMap((p, i) => (p[0] === d ? [at[i].source.name] : [])));
1810
+ if (ends.size > 1)
1811
+ throw new Error(
1812
+ `net ${net}: it joins both ends of diode ${d} (its cathode and its anode), which shorts the diode: take one of them off the net`,
1813
+ );
1814
+ }
1815
+ const linked = [],
1816
+ take = (i) => {
1817
+ for (let j = 0; j < pins.length; j++)
1818
+ if (j === i || (group[i] && group[j] === group[i])) if (!linked.includes(j)) linked.push(j);
1819
+ };
824
1820
  take(0);
825
1821
  while (linked.length < pins.length) {
826
1822
  let best = null;
827
- for (const a of linked) for (let b = 0; b < pins.length; b++) {
828
- if (linked.includes(b)) continue;
829
- const d = Math.hypot(at[a].x - at[b].x, at[a].y - at[b].y);
830
- if (!best || d < best.d) best = { a, b, d };
831
- }
832
- take(best.b); links.push({ from: pins[best.a], to: pins[best.b], width, net });
1823
+ for (const a of linked)
1824
+ for (let b = 0; b < pins.length; b++) {
1825
+ if (linked.includes(b)) continue;
1826
+ const d = Math.hypot(at[a].x - at[b].x, at[a].y - at[b].y);
1827
+ if (!best || d < best.d) best = { a, b, d };
1828
+ }
1829
+ take(best.b);
1830
+ links.push({ from: pins[best.a], to: pins[best.b], width, net });
833
1831
  }
834
1832
  return links;
835
1833
  });
@@ -840,65 +1838,161 @@ function schematic(out, add, placed, board, port, netOf = new Map()) {
840
1838
  const sch = new Map();
841
1839
  // Parts with no place of their own on the schematic (a clone's: their board places would pile them up) go in rows,
842
1840
  // biggest first, with room between for the net labels on their pins
843
- const auto = placed.filter((p) => !p.part.sch), row = { x: 0, y: 0, h: 0 }, width = Math.max(12, Math.sqrt(auto.length) * 3.5);
1841
+ const auto = placed.filter((p) => !p.part.sch),
1842
+ row = { x: 0, y: 0, h: 0 },
1843
+ width = Math.max(12, Math.sqrt(auto.length) * 3.5);
844
1844
  for (const p of [...auto].sort((a, b) => b.sourcePorts.length - a.sourcePorts.length)) {
845
1845
  const pins = new Set(p.sourcePorts.map((sp) => sp.name)).size;
846
- const w = 1.9 + 2 * 2.2, h = (Math.ceil(pins / 2) + 1) * 0.2 + 0.8; // the box, its pins' labels either side, its title
847
- if (row.x > 0 && row.x + w > width) { row.x = 0; row.y -= row.h; row.h = 0; }
848
- p.at = { x: row.x + w / 2, y: row.y - h / 2 }; row.x += w; row.h = Math.max(row.h, h);
1846
+ const w = 1.9 + 2 * 2.2,
1847
+ h = (Math.ceil(pins / 2) + 1) * 0.2 + 0.8; // the box, its pins' labels either side, its title
1848
+ if (row.x > 0 && row.x + w > width) {
1849
+ row.x = 0;
1850
+ row.y -= row.h;
1851
+ row.h = 0;
1852
+ }
1853
+ p.at = { x: row.x + w / 2, y: row.y - h / 2 };
1854
+ row.x += w;
1855
+ row.h = Math.max(row.h, h);
849
1856
  }
850
1857
  for (const { part, comp, sourcePorts, at } of placed) {
851
1858
  const s = part.sch || at || { x: 0, y: 0 };
852
- if (part.ftype === 'simple_chip') { // a box: pins 1 to 20 down the left, 21 to 40 up the right, 0.2 apart
1859
+ if (part.ftype === 'simple_chip') {
1860
+ // a box: pins 1 to 20 down the left, 21 to 40 up the right, 0.2 apart
853
1861
  // laid out here, a pin with several pads (a chip's centre pad and its thermal holes) is drawn once
854
- const shown = at ? sourcePorts.filter((sp, i) => sourcePorts.findIndex((o) => o.name === sp.name) === i) : sourcePorts;
855
- const half = Math.ceil(shown.length / 2), size = { width: 1.9, height: (half + 1) * 0.2 };
856
- const c = add('schematic_component', { center: { x: s.x, y: s.y }, rotation: 0, size, pin_spacing: 0.2, port_labels: part.sch?.pinLabels || {},
857
- source_component_id: comp.source_component_id, is_box_with_pins: true, schematic_group_id: 'schematic_group_0' });
858
- add('schematic_text', { text: at ? `${part.name}${part.value ? ` ${part.value}` : ''}` : part.mpn ?? part.name, schematic_component_id: c.schematic_component_id, anchor: 'left', rotation: 0,
859
- position: { x: s.x - size.width / 2, y: s.y - size.height / 2 - 0.23 }, color: '#006464', font_size: 0.18 });
1862
+ const shown = at
1863
+ ? sourcePorts.filter((sp, i) => sourcePorts.findIndex((o) => o.name === sp.name) === i)
1864
+ : sourcePorts;
1865
+ const half = Math.ceil(shown.length / 2),
1866
+ size = { width: 1.9, height: (half + 1) * 0.2 };
1867
+ const c = add('schematic_component', {
1868
+ center: { x: s.x, y: s.y },
1869
+ rotation: 0,
1870
+ size,
1871
+ pin_spacing: 0.2,
1872
+ port_labels: part.sch?.pinLabels || {},
1873
+ source_component_id: comp.source_component_id,
1874
+ is_box_with_pins: true,
1875
+ schematic_group_id: 'schematic_group_0',
1876
+ });
1877
+ add('schematic_text', {
1878
+ text: at ? `${part.name}${part.value ? ` ${part.value}` : ''}` : (part.mpn ?? part.name),
1879
+ schematic_component_id: c.schematic_component_id,
1880
+ anchor: 'left',
1881
+ rotation: 0,
1882
+ position: { x: s.x - size.width / 2, y: s.y - size.height / 2 - 0.23 },
1883
+ color: '#006464',
1884
+ font_size: 0.18,
1885
+ });
860
1886
  shown.forEach((sp, i) => {
861
- const left = i < half, k = left ? i : shown.length - 1 - i, side = left ? 'left' : 'right';
1887
+ const left = i < half,
1888
+ k = left ? i : shown.length - 1 - i,
1889
+ side = left ? 'left' : 'right';
862
1890
  const center = { x: s.x + (left ? -1 : 1) * (size.width / 2 + 0.4), y: s.y + size.height / 2 - 0.2 * (k + 1) };
863
- const sp2 = add('schematic_port', { schematic_component_id: c.schematic_component_id, center, source_port_id: sp.source_port_id,
864
- facing_direction: side, distance_from_component_edge: 0.4, side_of_component: side, pin_number: sp.pin_number, true_ccw_index: i, display_pin_label: sp.name.replace(/^pin/, '') });
1891
+ const sp2 = add('schematic_port', {
1892
+ schematic_component_id: c.schematic_component_id,
1893
+ center,
1894
+ source_port_id: sp.source_port_id,
1895
+ facing_direction: side,
1896
+ distance_from_component_edge: 0.4,
1897
+ side_of_component: side,
1898
+ pin_number: sp.pin_number,
1899
+ true_ccw_index: i,
1900
+ display_pin_label: sp.name.replace(/^pin/, ''),
1901
+ });
865
1902
  sch.set(sp.source_port_id, sp2);
866
1903
  // laid out here: each pin labelled with its net, in place of wires across the sheet
867
1904
  const net = at && [sp.name, ...(sp.port_hints || [])].map((k) => netOf.get(`${part.name}.${k}`)).find(Boolean);
868
- if (net) add('schematic_net_label', { text: net.replace(/^\//, ''), anchor_position: center, center, anchor_side: left ? 'right' : 'left', source_port_id: sp.source_port_id });
1905
+ if (net)
1906
+ add('schematic_net_label', {
1907
+ text: net.replace(/^\//, ''),
1908
+ anchor_position: center,
1909
+ center,
1910
+ anchor_side: left ? 'right' : 'left',
1911
+ source_port_id: sp.source_port_id,
1912
+ });
869
1913
  });
870
- for (const sp of sourcePorts) if (!sch.has(sp.source_port_id)) sch.set(sp.source_port_id, sch.get(shown.find((o) => o.name === sp.name).source_port_id)); // its other pads: drawn as one
1914
+ for (const sp of sourcePorts)
1915
+ if (!sch.has(sp.source_port_id))
1916
+ sch.set(sp.source_port_id, sch.get(shown.find((o) => o.name === sp.name).source_port_id)); // its other pads: drawn as one
871
1917
  continue;
872
1918
  }
873
1919
  const symbol = symbols[part.ftype === 'simple_diode' ? 'diode_down' : 'spst_switch_right'];
874
- const c = add('schematic_component', { center: { x: s.x, y: s.y }, rotation: 0, size: symbol.size, source_component_id: comp.source_component_id,
875
- is_box_with_pins: true, symbol_name: part.ftype === 'simple_diode' ? 'diode_down' : 'spst_switch_right', schematic_group_id: 'schematic_group_0' });
1920
+ const c = add('schematic_component', {
1921
+ center: { x: s.x, y: s.y },
1922
+ rotation: 0,
1923
+ size: symbol.size,
1924
+ source_component_id: comp.source_component_id,
1925
+ is_box_with_pins: true,
1926
+ symbol_name: part.ftype === 'simple_diode' ? 'diode_down' : 'spst_switch_right',
1927
+ schematic_group_id: 'schematic_group_0',
1928
+ });
876
1929
  // one symbol pin per pin: a pin with more than one pad (a hybrid switch's) draws its other pads as that one
877
1930
  const firsts = sourcePorts.filter((sp, i) => sourcePorts.findIndex((o) => o.name === sp.name) === i);
878
1931
  firsts.forEach((sp, i) => {
879
- const q = symbol.ports[i], center = { x: s.x + q.x - symbol.center.x, y: s.y + q.y - symbol.center.y };
880
- sch.set(sp.source_port_id, add('schematic_port', { schematic_component_id: c.schematic_component_id, center, source_port_id: sp.source_port_id,
881
- facing_direction: part.ftype === 'simple_diode' ? (i ? 'down' : 'up') : (i ? 'right' : 'left'), distance_from_component_edge: 0.4 }));
1932
+ // (the diode symbol's first port is its anode, at the top: each diode port goes to its own end of the symbol)
1933
+ const k = part.ftype === 'simple_diode' ? (sp.port_hints.includes('anode') ? 0 : 1) : i;
1934
+ const q = symbol.ports[k],
1935
+ center = { x: s.x + q.x - symbol.center.x, y: s.y + q.y - symbol.center.y };
1936
+ sch.set(
1937
+ sp.source_port_id,
1938
+ add('schematic_port', {
1939
+ schematic_component_id: c.schematic_component_id,
1940
+ center,
1941
+ source_port_id: sp.source_port_id,
1942
+ facing_direction: part.ftype === 'simple_diode' ? (k ? 'down' : 'up') : k ? 'right' : 'left',
1943
+ distance_from_component_edge: 0.4,
1944
+ }),
1945
+ );
882
1946
  });
883
- for (const sp of sourcePorts) if (!sch.has(sp.source_port_id)) sch.set(sp.source_port_id, sch.get(firsts.find((o) => o.name === sp.name).source_port_id));
1947
+ for (const sp of sourcePorts)
1948
+ if (!sch.has(sp.source_port_id))
1949
+ sch.set(sp.source_port_id, sch.get(firsts.find((o) => o.name === sp.name).source_port_id));
884
1950
  }
885
1951
  // A wire between two parts' pins (L-shaped), or for a connection to the chip, a label at each end naming the pin
886
1952
  const labelled = new Set(placed.filter((p) => p.at).map((p) => p.part.name));
887
1953
  for (const t of board.traces) {
888
1954
  if (labelled.has(t.from[0]) && labelled.has(t.to[0])) continue; // their pins carry their nets' names already
889
- const a = port(...t.from), b = port(...t.to), pa = sch.get(a.source.source_port_id), pb = sch.get(b.source.source_port_id);
1955
+ const a = port(...t.from),
1956
+ b = port(...t.to),
1957
+ pa = sch.get(a.source.source_port_id),
1958
+ pb = sch.get(b.source.source_port_id);
890
1959
  const chip = [a, b].find((q) => placed.find((p) => p.sourcePorts.includes(q.source)).part.ftype === 'simple_chip');
891
- if (chip || t.net) { // a net's ends are labelled with the net's name
1960
+ if (chip || t.net) {
1961
+ // a net's ends are labelled with the net's name
892
1962
  // At the chip, the label points out from its side of the box; at the matrix, it hangs below the pin
893
- for (const [q, sp] of [[pa, a], [pb, b]]) add('schematic_net_label', { text: t.net ?? chip.source.name, anchor_position: q.center, center: q.center,
894
- anchor_side: q.side_of_component === 'left' ? 'right' : q.side_of_component === 'right' ? 'left' : 'top', source_port_id: sp.source.source_port_id });
1963
+ for (const [q, sp] of [
1964
+ [pa, a],
1965
+ [pb, b],
1966
+ ])
1967
+ add('schematic_net_label', {
1968
+ text: t.net ?? chip.source.name,
1969
+ anchor_position: q.center,
1970
+ center: q.center,
1971
+ anchor_side: q.side_of_component === 'left' ? 'right' : q.side_of_component === 'right' ? 'left' : 'top',
1972
+ source_port_id: sp.source.source_port_id,
1973
+ });
895
1974
  continue;
896
1975
  }
897
1976
  const corner = { x: pb.center.x, y: pa.center.y };
898
- add('schematic_trace', { source_trace_id: `${pa.schematic_port_id}-${pb.schematic_port_id}`, junctions: [],
899
- edges: [{ from: pa.center, to: corner }, { from: corner, to: pb.center }].filter((e) => e.from.x !== e.to.x || e.from.y !== e.to.y) });
1977
+ add('schematic_trace', {
1978
+ source_trace_id: `${pa.schematic_port_id}-${pb.schematic_port_id}`,
1979
+ junctions: [],
1980
+ edges: [
1981
+ { from: pa.center, to: corner },
1982
+ { from: corner, to: pb.center },
1983
+ ].filter((e) => e.from.x !== e.to.x || e.from.y !== e.to.y),
1984
+ });
900
1985
  }
901
- add('schematic_group', { is_subcircuit: true, subcircuit_id: SUB, name: 'board', center: { x: 0, y: 0 }, width: 0, height: 0, schematic_component_ids: [], source_group_id: 'source_group_0' });
1986
+ add('schematic_group', {
1987
+ is_subcircuit: true,
1988
+ subcircuit_id: SUB,
1989
+ name: 'board',
1990
+ center: { x: 0, y: 0 },
1991
+ width: 0,
1992
+ height: 0,
1993
+ schematic_component_ids: [],
1994
+ source_group_id: 'source_group_0',
1995
+ });
902
1996
  }
903
1997
 
904
1998
  // ---- the autorouter ----
@@ -912,62 +2006,184 @@ export async function routeInput(json, toRoute, board = {}) {
912
2006
  // A plane net's pads (GND, 3V3) are joined by the plane, not by tracks: each is joined only to the links routed from it,
913
2007
  // so a short link between two close pads isn't tied to every pad of the net across the board (the router's topology
914
2008
  // merging then fails on far-off ones, such as a chip's thermal vias)
915
- const planeNet = new Set(json.filter((e) => e.type === 'source_net' && board.planes?.[e.name]).map((e) => conn.getNetConnectedToId(e.source_net_id)).filter(Boolean));
2009
+ const planeNet = new Set(
2010
+ json
2011
+ .filter((e) => e.type === 'source_net' && board.planes?.[e.name])
2012
+ .map((e) => conn.getNetConnectedToId(e.source_net_id))
2013
+ .filter(Boolean),
2014
+ );
916
2015
  const linksAt = new Map();
917
- for (const { a, b: z, id } of toRoute) for (const q of [a, z]) linksAt.set(q.pcb.pcb_port_id, [...(linksAt.get(q.pcb.pcb_port_id) || []), id]);
918
- const linked = (id, port) => { const net = conn.getNetConnectedToId(id); if (!net) return [id];
919
- return planeNet.has(net) ? [id, ...(port ? [port, ...(linksAt.get(port) || [])] : [])] : [...new Set([id, net, ...conn.getIdsConnectedToNet(net)])]; };
920
- const comp = Object.fromEntries(json.filter((e) => e.type === 'source_component').map((e) => [e.source_component_id, e.name]));
2016
+ for (const { a, b: z, id } of toRoute)
2017
+ for (const q of [a, z]) linksAt.set(q.pcb.pcb_port_id, [...(linksAt.get(q.pcb.pcb_port_id) || []), id]);
2018
+ const linked = (id, port) => {
2019
+ const net = conn.getNetConnectedToId(id);
2020
+ if (!net) return [id];
2021
+ return planeNet.has(net)
2022
+ ? [id, ...(port ? [port, ...(linksAt.get(port) || [])] : [])]
2023
+ : [...new Set([id, net, ...conn.getIdsConnectedToNet(net)])];
2024
+ };
2025
+ const comp = Object.fromEntries(
2026
+ json.filter((e) => e.type === 'source_component').map((e) => [e.source_component_id, e.name]),
2027
+ );
921
2028
  const src = Object.fromEntries(json.filter((e) => e.type === 'source_port').map((e) => [e.source_port_id, e]));
922
2029
  const pcbPort = Object.fromEntries(json.filter((e) => e.type === 'pcb_port').map((e) => [e.pcb_port_id, e]));
923
- const meta = (e, idKey) => { const sp = src[pcbPort[e.pcb_port_id]?.source_port_id];
924
- return { [idKey]: e[idKey], pcb_port_id: e.pcb_port_id, source_component_name: comp[sp?.source_component_id], source_port_name: sp?.name }; };
2030
+ const meta = (e, idKey) => {
2031
+ const sp = src[pcbPort[e.pcb_port_id]?.source_port_id];
2032
+ return {
2033
+ [idKey]: e[idKey],
2034
+ pcb_port_id: e.pcb_port_id,
2035
+ source_component_name: comp[sp?.source_component_id],
2036
+ source_port_name: sp?.name,
2037
+ };
2038
+ };
925
2039
  // Pads joined inside their part (a Pico's GND pins) say so: the router may join them on the board too
926
2040
  const inside = new Map();
927
- for (const e of json.filter((x) => x.type === 'source_component_internal_connection')) for (const id of e.source_port_ids) inside.set(id, [...(inside.get(id) || []), e.source_component_internal_connection_id]);
928
- const joined = (e) => { const ids = inside.get(pcbPort[e.pcb_port_id]?.source_port_id); return ids ? { offBoardConnectsTo: ids, netIsAssignable: true } : {}; };
929
- const b = json.find((e) => e.type === 'pcb_board'), obstacles = [];
930
- for (const kind of ['pcb_smtpad', 'pcb_plated_hole', 'pcb_hole']) for (const e of json.filter((x) => x.type === kind)) { // by kind, as core lists them
931
- if (e.type === 'pcb_smtpad' && e.shape === 'polygon') { // copper of any shape, as strips the router can see round
932
- for (const b of strips(e.points, 0.25)) obstacles.push({ circuitJsonMetadata: meta(e, 'pcb_smtpad_id'), componentId: e.pcb_component_id, type: 'rect', layers: [e.layer],
933
- center: { x: b.x, y: b.y }, width: b.w, height: b.h, connectedTo: linked(e.pcb_smtpad_id, e.pcb_port_id), ...joined(e) });
934
- continue;
2041
+ for (const e of json.filter((x) => x.type === 'source_component_internal_connection'))
2042
+ for (const id of e.source_port_ids)
2043
+ inside.set(id, [...(inside.get(id) || []), e.source_component_internal_connection_id]);
2044
+ const joined = (e) => {
2045
+ const ids = inside.get(pcbPort[e.pcb_port_id]?.source_port_id);
2046
+ return ids ? { offBoardConnectsTo: ids, netIsAssignable: true } : {};
2047
+ };
2048
+ const b = json.find((e) => e.type === 'pcb_board'),
2049
+ obstacles = [];
2050
+ for (const kind of ['pcb_smtpad', 'pcb_plated_hole', 'pcb_hole'])
2051
+ for (const e of json.filter((x) => x.type === kind)) {
2052
+ // by kind, as core lists them
2053
+ if (e.type === 'pcb_smtpad' && e.shape === 'polygon') {
2054
+ // copper of any shape, as strips the router can see round
2055
+ for (const b of strips(e.points, 0.25))
2056
+ obstacles.push({
2057
+ circuitJsonMetadata: meta(e, 'pcb_smtpad_id'),
2058
+ componentId: e.pcb_component_id,
2059
+ type: 'rect',
2060
+ layers: [e.layer],
2061
+ center: { x: b.x, y: b.y },
2062
+ width: b.w,
2063
+ height: b.h,
2064
+ connectedTo: linked(e.pcb_smtpad_id, e.pcb_port_id),
2065
+ ...joined(e),
2066
+ });
2067
+ continue;
2068
+ }
2069
+ if (e.type === 'pcb_smtpad') {
2070
+ const b = smtBounds(e);
2071
+ obstacles.push({
2072
+ circuitJsonMetadata: meta(e, 'pcb_smtpad_id'),
2073
+ componentId: e.pcb_component_id,
2074
+ type: 'rect',
2075
+ layers: [e.layer],
2076
+ center: { x: b.x, y: b.y },
2077
+ width: b.w,
2078
+ height: b.h,
2079
+ connectedTo: linked(e.pcb_smtpad_id, e.pcb_port_id),
2080
+ ...joined(e),
2081
+ });
2082
+ }
2083
+ if (e.type === 'pcb_plated_hole')
2084
+ obstacles.push({
2085
+ circuitJsonMetadata: meta(e, 'pcb_plated_hole_id'),
2086
+ componentId: e.pcb_component_id,
2087
+ type: 'oval',
2088
+ layers: ['top', 'bottom'],
2089
+ center: { x: e.x, y: e.y },
2090
+ width: holeSize(e).w,
2091
+ height: holeSize(e).h,
2092
+ connectedTo: linked(e.pcb_plated_hole_id, e.pcb_port_id),
2093
+ ...joined(e),
2094
+ });
2095
+ if (e.type === 'pcb_hole')
2096
+ obstacles.push({
2097
+ componentId: e.pcb_component_id,
2098
+ obstacleId: e.pcb_hole_id,
2099
+ isNonPlatedHole: true,
2100
+ type: 'rect',
2101
+ shape: 'circle',
2102
+ layers: ['top', 'bottom'],
2103
+ center: { x: e.x, y: e.y },
2104
+ width: 2 * (e.rulecad_keepout ?? e.hole_diameter / 2),
2105
+ height: 2 * (e.rulecad_keepout ?? e.hole_diameter / 2),
2106
+ connectedTo: [],
2107
+ }); // with a screw head's room round it
935
2108
  }
936
- if (e.type === 'pcb_smtpad') { const b = smtBounds(e); obstacles.push({ circuitJsonMetadata: meta(e, 'pcb_smtpad_id'), componentId: e.pcb_component_id, type: 'rect', layers: [e.layer],
937
- center: { x: b.x, y: b.y }, width: b.w, height: b.h, connectedTo: linked(e.pcb_smtpad_id, e.pcb_port_id), ...joined(e) }); }
938
- if (e.type === 'pcb_plated_hole') obstacles.push({ circuitJsonMetadata: meta(e, 'pcb_plated_hole_id'), componentId: e.pcb_component_id, type: 'oval', layers: ['top', 'bottom'],
939
- center: { x: e.x, y: e.y }, width: holeSize(e).w, height: holeSize(e).h, connectedTo: linked(e.pcb_plated_hole_id, e.pcb_port_id), ...joined(e) });
940
- if (e.type === 'pcb_hole') obstacles.push({ componentId: e.pcb_component_id, obstacleId: e.pcb_hole_id, isNonPlatedHole: true, type: 'rect', shape: 'circle',
941
- layers: ['top', 'bottom'], center: { x: e.x, y: e.y }, width: 2 * (e.rulecad_keepout ?? e.hole_diameter / 2), height: 2 * (e.rulecad_keepout ?? e.hole_diameter / 2), connectedTo: [] }); // with a screw head's room round it
942
- }
943
2109
  // Tracks already on the board, but a plane's vias inside a big pad: the pad is in the router's way already
944
2110
  const padOf = new Map(json.filter((e) => e.type === 'pcb_smtpad').map((e) => [e.pcb_port_id, smtBounds(e)]));
945
- const inPad = (e) => { const d = padOf.get(e.route[0].start_pcb_port_id); return d && e.route.every((p) => Math.abs(p.x - d.x) <= d.w / 2 && Math.abs(p.y - d.y) <= d.h / 2); };
2111
+ const inPad = (e) => {
2112
+ const d = padOf.get(e.route[0].start_pcb_port_id);
2113
+ return d && e.route.every((p) => Math.abs(p.x - d.x) <= d.w / 2 && Math.abs(p.y - d.y) <= d.h / 2);
2114
+ };
946
2115
  const vias = json.filter((e) => e.type === 'pcb_via');
947
- const viaSize = (id, p) => vias.find((v) => v.pcb_trace_id === id && Math.abs(v.x - p.x) < 1e-6 && Math.abs(v.y - p.y) < 1e-6)?.outer_diameter;
2116
+ const viaSize = (id, p) =>
2117
+ vias.find((v) => v.pcb_trace_id === id && Math.abs(v.x - p.x) < 1e-6 && Math.abs(v.y - p.y) < 1e-6)?.outer_diameter;
948
2118
  const outer = (e) => e.route.every((p) => p.route_type !== 'wire' || p.layer === 'top' || p.layer === 'bottom'); // the router works on the outer two
949
- const traces = json.filter((e) => e.type === 'pcb_trace' && !inPad(e) && outer(e)).map((e) => ({ type: 'pcb_trace', pcb_trace_id: e.pcb_trace_id, source_trace_id: e.source_trace_id,
950
- connection_name: e.source_trace_id, connectsTo: [e.route[0].start_pcb_port_id, e.route.at(-1).end_pcb_port_id].filter(Boolean), // a plane's track ends at its via
951
- route: e.route.map((p) => ({ route_type: p.route_type, x: p.x, y: p.y, width: p.width, layer: p.layer,
952
- ...(p.route_type === 'via' ? { from_layer: p.from_layer, to_layer: p.to_layer, via_diameter: viaSize(e.pcb_trace_id, p) } : {}) })) })); // each via at its real size
953
- const connections = toRoute.map(({ t, a, b: z, id }) => ({ name: id, source_trace_id: id, nominalTraceWidth: t.width, width: t.width,
954
- pointsToConnect: [a, z].map((q) => ({ x: q.x, y: q.y, layer: q.layers.length === 1 ? q.layers[0] : 'top', ...(q.layers.length === 1 ? { onlyLayer: q.layers[0] } : {}), pointId: q.pcb.pcb_port_id, pcb_port_id: q.pcb.pcb_port_id,
955
- port_selector: `${comp[q.source.source_component_id]}.${q.source.name}` })) }));
956
- return fixedTraces({ bounds: { minX: b.center.x - b.width / 2, maxX: b.center.x + b.width / 2, minY: b.center.y - b.height / 2, maxY: b.center.y + b.height / 2 },
2119
+ const traces = json
2120
+ .filter((e) => e.type === 'pcb_trace' && !inPad(e) && outer(e))
2121
+ .map((e) => ({
2122
+ type: 'pcb_trace',
2123
+ pcb_trace_id: e.pcb_trace_id,
2124
+ source_trace_id: e.source_trace_id,
2125
+ connection_name: e.source_trace_id,
2126
+ connectsTo: [e.route[0].start_pcb_port_id, e.route.at(-1).end_pcb_port_id].filter(Boolean), // a plane's track ends at its via
2127
+ route: e.route.map((p) => ({
2128
+ route_type: p.route_type,
2129
+ x: p.x,
2130
+ y: p.y,
2131
+ width: p.width,
2132
+ layer: p.layer,
2133
+ ...(p.route_type === 'via'
2134
+ ? { from_layer: p.from_layer, to_layer: p.to_layer, via_diameter: viaSize(e.pcb_trace_id, p) }
2135
+ : {}),
2136
+ })),
2137
+ })); // each via at its real size
2138
+ const connections = toRoute.map(({ t, a, b: z, id }) => ({
2139
+ name: id,
2140
+ source_trace_id: id,
2141
+ nominalTraceWidth: t.width,
2142
+ width: t.width,
2143
+ pointsToConnect: [a, z].map((q) => ({
2144
+ x: q.x,
2145
+ y: q.y,
2146
+ layer: q.layers.length === 1 ? q.layers[0] : 'top',
2147
+ ...(q.layers.length === 1 ? { onlyLayer: q.layers[0] } : {}),
2148
+ pointId: q.pcb.pcb_port_id,
2149
+ pcb_port_id: q.pcb.pcb_port_id,
2150
+ port_selector: `${comp[q.source.source_component_id]}.${q.source.name}`,
2151
+ })),
2152
+ }));
2153
+ return fixedTraces({
2154
+ bounds: {
2155
+ minX: b.center.x - b.width / 2,
2156
+ maxX: b.center.x + b.width / 2,
2157
+ minY: b.center.y - b.height / 2,
2158
+ maxY: b.center.y + b.height / 2,
2159
+ },
957
2160
  ...(b.outline ? { outline: b.outline } : {}), // the router keeps tracks inside a shaped board
958
- obstacles, connections, traces, layerCount: 2, allowBlindAndBuriedVias: false, minTraceWidth: 0.15, nominalTraceWidth: 0.15, // tscircuit's defaults
2161
+ obstacles,
2162
+ connections,
2163
+ traces,
2164
+ layerCount: 2,
2165
+ allowBlindAndBuriedVias: false,
2166
+ minTraceWidth: 0.15,
2167
+ nominalTraceWidth: 0.15, // tscircuit's defaults
959
2168
  // the board's fab minimums, under the names the router reads
960
- minViaDiameter: b.min_via_pad_diameter, minViaHoleDiameter: b.min_via_hole_diameter, minViaPadDiameter: b.min_via_pad_diameter,
961
- min_via_hole_diameter: b.min_via_hole_diameter, min_via_pad_diameter: b.min_via_pad_diameter,
962
- minTraceToPadEdgeClearance: b.min_trace_to_pad_edge_clearance, minTraceToHoleEdgeClearance: b.min_trace_to_hole_edge_clearance,
963
- minViaHoleEdgeToViaHoleEdgeClearance: b.min_via_hole_edge_to_via_hole_edge_clearance, minPlatedHoleDrillEdgeToDrillEdgeClearance: b.min_plated_hole_drill_edge_to_drill_edge_clearance,
964
- minPadEdgeToPadEdgeClearance: b.min_pad_edge_to_pad_edge_clearance, minBoardEdgeClearance: b.min_board_edge_clearance,
965
- ...(board.clearance ? { defaultObstacleMargin: board.clearance } : {}) }); // a board's own clearance, kept from everything in the way
2169
+ minViaDiameter: b.min_via_pad_diameter,
2170
+ minViaHoleDiameter: b.min_via_hole_diameter,
2171
+ minViaPadDiameter: b.min_via_pad_diameter,
2172
+ min_via_hole_diameter: b.min_via_hole_diameter,
2173
+ min_via_pad_diameter: b.min_via_pad_diameter,
2174
+ minTraceToPadEdgeClearance: b.min_trace_to_pad_edge_clearance,
2175
+ minTraceToHoleEdgeClearance: b.min_trace_to_hole_edge_clearance,
2176
+ minViaHoleEdgeToViaHoleEdgeClearance: b.min_via_hole_edge_to_via_hole_edge_clearance,
2177
+ minPlatedHoleDrillEdgeToDrillEdgeClearance: b.min_plated_hole_drill_edge_to_drill_edge_clearance,
2178
+ minPadEdgeToPadEdgeClearance: b.min_pad_edge_to_pad_edge_clearance,
2179
+ minBoardEdgeClearance: b.min_board_edge_clearance,
2180
+ ...(board.clearance ? { defaultObstacleMargin: board.clearance } : {}),
2181
+ }); // a board's own clearance, kept from everything in the way
966
2182
  }
967
2183
 
968
2184
  // The drawn tracks become fixed obstacles for the router: each segment a box a track wide (a diagonal one, a run of
969
2185
  // boxes about a track-width long), each via a square. Ported from tscircuit core's withFixedTraces (MIT licence,
970
- // github.com/tscircuit/core), so a board is routed around them as it is there.
2186
+ // github.com/tscircuit/core), so a board is routed around them as it is there: its notice is in THIRD-PARTY.md.
971
2187
  function fixedTraces(input) {
972
2188
  const obstacles = [];
973
2189
  for (const trace of input.traces) {
@@ -975,7 +2191,14 @@ function fixedTraces(input) {
975
2191
  trace.route.forEach((p, i) => {
976
2192
  if (p.route_type === 'via') {
977
2193
  const d = p.via_diameter ?? input.minViaPadDiameter ?? input.minViaDiameter ?? 0.6;
978
- obstacles.push({ type: 'rect', center: { x: p.x, y: p.y }, width: d, height: d, layers: ['top', 'bottom'], connectedTo });
2194
+ obstacles.push({
2195
+ type: 'rect',
2196
+ center: { x: p.x, y: p.y },
2197
+ width: d,
2198
+ height: d,
2199
+ layers: ['top', 'bottom'],
2200
+ connectedTo,
2201
+ });
979
2202
  }
980
2203
  const q = trace.route[i + 1];
981
2204
  if (!q || !['wire', 'via'].includes(p.route_type) || !['wire', 'via'].includes(q.route_type)) return;
@@ -983,9 +2206,18 @@ function fixedTraces(input) {
983
2206
  const layer = p.route_type === 'wire' ? p.layer : p.to_layer;
984
2207
  const steps = p.x === q.x || p.y === q.y ? 1 : Math.max(1, Math.ceil(Math.hypot(q.x - p.x, q.y - p.y) / width));
985
2208
  for (let k = 0; k < steps; k++) {
986
- const x1 = p.x + ((q.x - p.x) * k) / steps, y1 = p.y + ((q.y - p.y) * k) / steps;
987
- const x2 = p.x + ((q.x - p.x) * (k + 1)) / steps, y2 = p.y + ((q.y - p.y) * (k + 1)) / steps;
988
- obstacles.push({ type: 'rect', center: { x: (x1 + x2) / 2, y: (y1 + y2) / 2 }, width: Math.abs(x2 - x1) + width, height: Math.abs(y2 - y1) + width, layers: [layer], connectedTo });
2209
+ const x1 = p.x + ((q.x - p.x) * k) / steps,
2210
+ y1 = p.y + ((q.y - p.y) * k) / steps;
2211
+ const x2 = p.x + ((q.x - p.x) * (k + 1)) / steps,
2212
+ y2 = p.y + ((q.y - p.y) * (k + 1)) / steps;
2213
+ obstacles.push({
2214
+ type: 'rect',
2215
+ center: { x: (x1 + x2) / 2, y: (y1 + y2) / 2 },
2216
+ width: Math.abs(x2 - x1) + width,
2217
+ height: Math.abs(y2 - y1) + width,
2218
+ layers: [layer],
2219
+ connectedTo,
2220
+ });
989
2221
  }
990
2222
  });
991
2223
  }
@@ -1001,15 +2233,33 @@ function fixedTraces(input) {
1001
2233
  export function layerChanges(route, holes) {
1002
2234
  const pieces = [[]];
1003
2235
  for (const p of route) {
1004
- if (p.route_type !== 'through_obstacle') { pieces.at(-1).push(p); continue; }
2236
+ if (p.route_type !== 'through_obstacle') {
2237
+ pieces.at(-1).push(p);
2238
+ continue;
2239
+ }
1005
2240
  // The router sees a hole or via as a square round its copper, so it may mark the change anywhere in that square,
1006
2241
  // corners included: in it counts, and the track is taken on to the hole's centre on each side, so it joins its copper
1007
- 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;
1008
- 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); });
1009
- 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`);
2242
+ const at = p.start,
2243
+ inSquare = (q, h, r) => Math.abs(q.x - h.x) <= r + 1e-6 && Math.abs(q.y - h.y) <= r + 1e-6;
2244
+ const hole = holes.find((h) => {
2245
+ const r = Math.max(holeSize(h).w, holeSize(h).h) / 2;
2246
+ return inSquare(at, h, r) && inSquare(p.end, h, r);
2247
+ });
2248
+ if (!hole)
2249
+ throw new Error(
2250
+ `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`,
2251
+ );
1010
2252
  const width = p.width ?? pieces.at(-1).at(-1)?.width;
1011
- 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 });
1012
- 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 }]);
2253
+ pieces
2254
+ .at(-1)
2255
+ .push(
2256
+ { route_type: 'wire', x: at.x, y: at.y, width, layer: p.from_layer },
2257
+ { route_type: 'wire', x: hole.x, y: hole.y, width, layer: p.from_layer },
2258
+ );
2259
+ pieces.push([
2260
+ { route_type: 'wire', x: hole.x, y: hole.y, width, layer: p.to_layer },
2261
+ { route_type: 'wire', x: p.end.x, y: p.end.y, width, layer: p.to_layer },
2262
+ ]);
1013
2263
  }
1014
2264
  return pieces.filter((q) => q.length > 1);
1015
2265
  }
@@ -1018,35 +2268,70 @@ export function layerChanges(route, holes) {
1018
2268
  // routed again together with every good track fixed in place, up to three rounds, keeping the best (on a board too tight
1019
2269
  // for it, the checks then say where)
1020
2270
  // Routed tracks laid as board elements, for routing round them or checking them
1021
- const lay = (list) => list.flatMap((t, i) => [{ type: 'pcb_trace', pcb_trace_id: `pcb_trace_rt${i}`, route: t.route, source_trace_id: t.source_trace_id, subcircuit_id: SUB },
1022
- ...t.vias.map((v, k) => ({ type: 'pcb_via', pcb_via_id: `pcb_via_rv${i}x${k}`, pcb_trace_id: `pcb_trace_rt${i}`, ...v, layers: v.layers, subcircuit_id: SUB }))]);
2271
+ const lay = (list) =>
2272
+ list.flatMap((t, i) => [
2273
+ {
2274
+ type: 'pcb_trace',
2275
+ pcb_trace_id: `pcb_trace_rt${i}`,
2276
+ route: t.route,
2277
+ source_trace_id: t.source_trace_id,
2278
+ subcircuit_id: SUB,
2279
+ },
2280
+ ...t.vias.map((v, k) => ({
2281
+ type: 'pcb_via',
2282
+ pcb_via_id: `pcb_via_rv${i}x${k}`,
2283
+ pcb_trace_id: `pcb_trace_rt${i}`,
2284
+ ...v,
2285
+ layers: v.layers,
2286
+ subcircuit_id: SUB,
2287
+ })),
2288
+ ]);
1023
2289
 
1024
2290
  async function defaultRouter(json, toRoute, board) {
1025
2291
  let traces = (await routeOnce(json, toRoute, board)).traces;
1026
2292
  const { runAllChecks } = await import('@tscircuit/checks');
1027
2293
  const problems = async (list) => (await runAllChecks([...json, ...lay(list)])).filter((e) => /_error$/.test(e.type));
1028
- let errors = await problems(traces), best = { traces, n: errors.length };
2294
+ let errors = await problems(traces),
2295
+ best = { traces, n: errors.length };
1029
2296
  // Repair: the connections in errors pulled up and routed again round every good track, each round asking for a little
1030
2297
  // more room than the last (so they don't land in the same squeeze), the best result kept
1031
2298
  for (let round = 0; round < 3 && errors.length; round++) {
1032
2299
  const bad = new Set();
1033
- for (const e of errors) for (const m of JSON.stringify(e).matchAll(/pcb_(?:trace_rt|via_rv)(\d+)/g)) bad.add(traces[Number(m[1])]?.source_trace_id);
2300
+ for (const e of errors)
2301
+ for (const m of JSON.stringify(e).matchAll(/pcb_(?:trace_rt|via_rv)(\d+)/g))
2302
+ bad.add(traces[Number(m[1])]?.source_trace_id);
1034
2303
  bad.delete(undefined);
1035
2304
  if (!bad.size) break;
1036
- const keep = traces.filter((t) => !bad.has(t.source_trace_id)), again = toRoute.filter((c) => bad.has(c.id));
2305
+ const keep = traces.filter((t) => !bad.has(t.source_trace_id)),
2306
+ again = toRoute.filter((c) => bad.has(c.id));
1037
2307
  const roomier = { ...board, clearance: (board.clearance ?? 0.1) + 0.05 * (round + 1) };
1038
2308
  const minute = () => Date.now() + 60000; // each repair attempt gets a minute
1039
2309
  let next = null;
1040
- try { next = [...keep, ...(await routeOnce([...json, ...lay(keep)], again, roomier, minute())).traces]; } catch {} // too tight together:
1041
- if (!next && again.length <= 4) { // a few go one at a time, each round everything else, the router searching harder if it must
2310
+ try {
2311
+ next = [...keep, ...(await routeOnce([...json, ...lay(keep)], again, roomier, minute())).traces];
2312
+ } catch {
2313
+ // (too tight together: below, a few are routed one at a time)
2314
+ }
2315
+ if (!next && again.length <= 4) {
2316
+ // a few go one at a time, each round everything else, the router searching harder if it must
1042
2317
  next = traces;
1043
- for (const c of again) for (const effort of [1, 2]) {
1044
- const rest = next.filter((t) => t.source_trace_id !== c.id);
1045
- try { next = [...rest, ...(await routeOnce([...json, ...lay(rest)], [c], { ...roomier, effort }, minute())).traces]; break; } catch {}
1046
- }
2318
+ for (const c of again)
2319
+ for (const effort of [1, 2]) {
2320
+ const rest = next.filter((t) => t.source_trace_id !== c.id);
2321
+ try {
2322
+ next = [
2323
+ ...rest,
2324
+ ...(await routeOnce([...json, ...lay(rest)], [c], { ...roomier, effort }, minute())).traces,
2325
+ ];
2326
+ break;
2327
+ } catch {
2328
+ // (this one won't route this way: the router tries harder, or the next goes)
2329
+ }
2330
+ }
1047
2331
  }
1048
2332
  if (!next) break; // too tight to better: the best result stands
1049
- traces = next; errors = await problems(traces);
2333
+ traces = next;
2334
+ errors = await problems(traces);
1050
2335
  if (errors.length < best.n) best = { traces, n: errors.length };
1051
2336
  }
1052
2337
  traces = best.traces;
@@ -1062,96 +2347,269 @@ async function defaultRouter(json, toRoute, board) {
1062
2347
  */
1063
2348
  export async function neckDown(json, traces, neck) {
1064
2349
  const { runAllChecks } = await import('@tscircuit/checks');
1065
- const toSeg = (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); };
2350
+ const toSeg = (p, a, b) => {
2351
+ const dx = b.x - a.x,
2352
+ dy = b.y - a.y,
2353
+ l = dx * dx + dy * dy,
2354
+ t = l ? Math.max(0, Math.min(1, ((p.x - a.x) * dx + (p.y - a.y) * dy) / l)) : 0;
2355
+ return Math.hypot(p.x - a.x - t * dx, p.y - a.y - t * dy);
2356
+ };
1066
2357
  const out = traces.map((t) => ({ ...t, route: t.route.map((p) => ({ ...p })) }));
1067
- const lay = () => out.map((t, i) => ({ type: 'pcb_trace', pcb_trace_id: `pcb_trace_rt${i}`, route: t.route, source_trace_id: t.source_trace_id, subcircuit_id: SUB }));
1068
- const close = async () => (await runAllChecks([...json, ...lay()])).filter((e) => e.type === 'pcb_trace_error' && /too close|overlap/.test(e.message) && e.center);
2358
+ const lay = () =>
2359
+ out.map((t, i) => ({
2360
+ type: 'pcb_trace',
2361
+ pcb_trace_id: `pcb_trace_rt${i}`,
2362
+ route: t.route,
2363
+ source_trace_id: t.source_trace_id,
2364
+ subcircuit_id: SUB,
2365
+ }));
2366
+ const close = async () =>
2367
+ (await runAllChecks([...json, ...lay()])).filter(
2368
+ (e) => e.type === 'pcb_trace_error' && /too close|overlap/.test(e.message) && e.center,
2369
+ );
1069
2370
  // First, straighten: a routed track's kink by the spot (a bend point between two runs on one layer) is dropped when that
1070
2371
  // leaves fewer problems; the router sometimes doubles back as it leaves its start
1071
- for (const e of await close()) for (const m of new Set(JSON.stringify(e).match(/pcb_trace_rt\d+/g) || [])) {
1072
- const r = out[Number(m.slice(12))].route, before = (await close()).length;
1073
- const k = r.map((_, i) => i).filter((i) => i > 0 && i < r.length - 1 && [r[i - 1], r[i], r[i + 1]].every((p) => p.route_type === 'wire' && p.layer === r[i].layer))
1074
- .sort((i, j) => Math.hypot(r[i].x - e.center.x, r[i].y - e.center.y) - Math.hypot(r[j].x - e.center.x, r[j].y - e.center.y))[0];
1075
- if (k === undefined || Math.hypot(r[k].x - e.center.x, r[k].y - e.center.y) > 1) continue;
1076
- const [gone] = r.splice(k, 1);
1077
- if ((await close()).length >= before) r.splice(k, 0, gone); // no better: put it back
1078
- }
2372
+ for (const e of await close())
2373
+ for (const m of new Set(JSON.stringify(e).match(/pcb_trace_rt\d+/g) || [])) {
2374
+ const r = out[Number(m.slice(12))].route,
2375
+ before = (await close()).length;
2376
+ const k = r
2377
+ .map((_, i) => i)
2378
+ .filter(
2379
+ (i) =>
2380
+ i > 0 &&
2381
+ i < r.length - 1 &&
2382
+ [r[i - 1], r[i], r[i + 1]].every((p) => p.route_type === 'wire' && p.layer === r[i].layer),
2383
+ )
2384
+ .sort(
2385
+ (i, j) =>
2386
+ Math.hypot(r[i].x - e.center.x, r[i].y - e.center.y) - Math.hypot(r[j].x - e.center.x, r[j].y - e.center.y),
2387
+ )[0];
2388
+ if (k === undefined || Math.hypot(r[k].x - e.center.x, r[k].y - e.center.y) > 1) continue;
2389
+ const [gone] = r.splice(k, 1);
2390
+ if ((await close()).length >= before) r.splice(k, 0, gone); // no better: put it back
2391
+ }
1079
2392
  // Then a stretch too close to the board's edge (the router sometimes hugs it): moved in by what it lacks, both its
1080
2393
  // ends (not a pad's end), where that leaves no more problems than before
1081
- const b = json.find((e) => e.type === 'pcb_board'), edge = b?.outline || (b && [[-1, -1], [1, -1], [1, 1], [-1, 1]].map(([sx, sy]) => ({ x: b.center.x + sx * b.width / 2, y: b.center.y + sy * b.height / 2 })));
1082
- const inside = (q) => { let n = false; for (let a = 0, z = edge.length - 1; a < edge.length; z = a++) if ((edge[a].y > q.y) !== (edge[z].y > q.y) && q.x < ((edge[z].x - edge[a].x) * (q.y - edge[a].y)) / (edge[z].y - edge[a].y) + edge[a].x) n = !n; return n; };
2394
+ const b = json.find((e) => e.type === 'pcb_board'),
2395
+ edge =
2396
+ b?.outline ||
2397
+ (b &&
2398
+ [
2399
+ [-1, -1],
2400
+ [1, -1],
2401
+ [1, 1],
2402
+ [-1, 1],
2403
+ ].map(([sx, sy]) => ({ x: b.center.x + (sx * b.width) / 2, y: b.center.y + (sy * b.height) / 2 })));
2404
+ const inside = (q) => {
2405
+ let n = false;
2406
+ for (let a = 0, z = edge.length - 1; a < edge.length; z = a++)
2407
+ if (
2408
+ edge[a].y > q.y !== edge[z].y > q.y &&
2409
+ q.x < ((edge[z].x - edge[a].x) * (q.y - edge[a].y)) / (edge[z].y - edge[a].y) + edge[a].x
2410
+ )
2411
+ n = !n;
2412
+ return n;
2413
+ };
1083
2414
  for (const e of edge ? await close() : []) {
1084
- const short = e.message.match(/board edge \(([\d.]+)mm < ([\d.]+)mm/); const m = JSON.stringify(e).match(/pcb_trace_rt(\d+)/); if (!short || !m) continue;
1085
- const r = out[Number(m[1])].route, by = Number(short[2]) - Number(short[1]) + 0.02;
1086
- const i = r.map((_, k) => k).filter((k) => k > 0 && k < r.length - 2 && r[k].route_type === 'wire' && r[k + 1].route_type === 'wire').sort((k, j) => toSeg(e.center, r[k], r[k + 1]) - toSeg(e.center, r[j], r[j + 1]))[0];
2415
+ const short = e.message.match(/board edge \(([\d.]+)mm < ([\d.]+)mm/);
2416
+ const m = JSON.stringify(e).match(/pcb_trace_rt(\d+)/);
2417
+ if (!short || !m) continue;
2418
+ const r = out[Number(m[1])].route,
2419
+ by = Number(short[2]) - Number(short[1]) + 0.02;
2420
+ const i = r
2421
+ .map((_, k) => k)
2422
+ .filter((k) => k > 0 && k < r.length - 2 && r[k].route_type === 'wire' && r[k + 1].route_type === 'wire')
2423
+ .sort((k, j) => toSeg(e.center, r[k], r[k + 1]) - toSeg(e.center, r[j], r[j + 1]))[0];
1087
2424
  if (i === undefined || toSeg(e.center, r[i], r[i + 1]) > 0.5) continue;
1088
- const near = edge.map((q, k) => [q, edge[(k + 1) % edge.length]]).sort((u, w) => toSeg(e.center, ...u) - toSeg(e.center, ...w))[0];
2425
+ const near = edge
2426
+ .map((q, k) => [q, edge[(k + 1) % edge.length]])
2427
+ .sort((u, w) => toSeg(e.center, ...u) - toSeg(e.center, ...w))[0];
1089
2428
  const len = Math.hypot(near[1].x - near[0].x, near[1].y - near[0].y) || 1;
1090
2429
  let n = { x: -(near[1].y - near[0].y) / len, y: (near[1].x - near[0].x) / len };
1091
2430
  if (!inside({ x: e.center.x + n.x * 0.3, y: e.center.y + n.y * 0.3 })) n = { x: -n.x, y: -n.y }; // the way into the board
1092
- const before = (await close()).length, was = [r[i], r[i + 1]].map((q) => ({ x: q.x, y: q.y }));
1093
- for (const q of [r[i], r[i + 1]]) { q.x += n.x * by; q.y += n.y * by; }
2431
+ const before = (await close()).length,
2432
+ was = [r[i], r[i + 1]].map((q) => ({ x: q.x, y: q.y }));
2433
+ for (const q of [r[i], r[i + 1]]) {
2434
+ q.x += n.x * by;
2435
+ q.y += n.y * by;
2436
+ }
1094
2437
  if ((await close()).length >= before) [r[i], r[i + 1]].forEach((q, k) => Object.assign(q, was[k])); // no better: put it back
1095
2438
  }
1096
- for (let pass = 0; pass < 4; pass++) { // two tracks close along a stretch: the next segment along, until they clear
1097
- const laid = out.map((t, i) => ({ type: 'pcb_trace', pcb_trace_id: `pcb_trace_rt${i}`, route: t.route, source_trace_id: t.source_trace_id, subcircuit_id: SUB }));
1098
- const errors = (await runAllChecks([...json, ...laid])).filter((e) => e.type === 'pcb_trace_error' && /too close/.test(e.message) && e.center);
1099
- let narrowed = false;
1100
- for (const e of errors) for (const m of JSON.stringify(e).matchAll(/pcb_trace_rt(\d+)/g)) {
1101
- const r = out[Number(m[1])]?.route; if (!r) continue;
1102
- // the nearest segment still at full width (one already necked: the next along)
1103
- const order = r.map((_, i) => i).filter((i) => i < r.length - 1 && r[i].route_type === 'wire' && r[i + 1].route_type === 'wire')
1104
- .sort((i, k) => toSeg(e.center, r[i], r[i + 1]) - toSeg(e.center, r[k], r[k + 1]));
1105
- const i = order.find((k) => toSeg(e.center, r[k], r[k + 1]) < 1 && (r[k].width > neck || r[k + 1].width > neck));
1106
- if (i !== undefined) { r[i].width = Math.min(r[i].width, neck); r[i + 1].width = Math.min(r[i + 1].width, neck); narrowed = true; }
1107
- }
1108
- if (!narrowed) break;
2439
+ for (let pass = 0; pass < 4; pass++) {
2440
+ // two tracks close along a stretch: the next segment along, until they clear
2441
+ const laid = out.map((t, i) => ({
2442
+ type: 'pcb_trace',
2443
+ pcb_trace_id: `pcb_trace_rt${i}`,
2444
+ route: t.route,
2445
+ source_trace_id: t.source_trace_id,
2446
+ subcircuit_id: SUB,
2447
+ }));
2448
+ const errors = (await runAllChecks([...json, ...laid])).filter(
2449
+ (e) => e.type === 'pcb_trace_error' && /too close/.test(e.message) && e.center,
2450
+ );
2451
+ let narrowed = false;
2452
+ for (const e of errors)
2453
+ for (const m of JSON.stringify(e).matchAll(/pcb_trace_rt(\d+)/g)) {
2454
+ const r = out[Number(m[1])]?.route;
2455
+ if (!r) continue;
2456
+ // the nearest segment still at full width (one already necked: the next along)
2457
+ const order = r
2458
+ .map((_, i) => i)
2459
+ .filter((i) => i < r.length - 1 && r[i].route_type === 'wire' && r[i + 1].route_type === 'wire')
2460
+ .sort((i, k) => toSeg(e.center, r[i], r[i + 1]) - toSeg(e.center, r[k], r[k + 1]));
2461
+ const i = order.find(
2462
+ (k) => toSeg(e.center, r[k], r[k + 1]) < 1 && (r[k].width > neck || r[k + 1].width > neck),
2463
+ );
2464
+ if (i !== undefined) {
2465
+ r[i].width = Math.min(r[i].width, neck);
2466
+ r[i + 1].width = Math.min(r[i + 1].width, neck);
2467
+ narrowed = true;
2468
+ }
2469
+ }
2470
+ if (!narrowed) break;
1109
2471
  }
1110
2472
  return out;
1111
2473
  }
1112
2474
 
1113
2475
  // The autorouter's pipelines, tried in order until one routes the board: its own, then its others, each a different search
1114
- const PIPELINES = ['AutoroutingPipelineSolver', 'AutoroutingPipelineSolver4', 'AutoroutingPipelineSolver5', 'AutoroutingPipelineSolver6', 'AutoroutingPipelineSolver8'];
2476
+ const PIPELINES = [
2477
+ 'AutoroutingPipelineSolver',
2478
+ 'AutoroutingPipelineSolver4',
2479
+ 'AutoroutingPipelineSolver5',
2480
+ 'AutoroutingPipelineSolver6',
2481
+ 'AutoroutingPipelineSolver8',
2482
+ ];
1115
2483
 
1116
- // The route cache: a file per router input, named by its hash and the router's version. Nothing (null) when unset
2484
+ // The route cache: a route per router input, keyed by the SHA-256 (64 hex digits) of the input and the router's
2485
+ // version. Kept in the store routeStore() was given, else as a file of that name in the folder RULECAD_ROUTE_CACHE
2486
+ // names; nothing (null) when neither is set. (cad's design sandbox can't write files: its runner sets a store that
2487
+ // reads the folder and hands what it routed back to the tool, which writes it.)
2488
+ let routes = null;
2489
+ /**
2490
+ * Where the autorouter's results are kept, in place of the RULECAD_ROUTE_CACHE folder: `get(key)` gives a route's
2491
+ * text (JSON) or undefined, `put(key, text)` keeps one; null goes back to the folder. Keys are 64 hex digits.
2492
+ * @param {{ get: (key: string) => string | undefined, put: (key: string, text: string) => void } | null} store
2493
+ */
2494
+ export function routeStore(store) {
2495
+ routes = store;
2496
+ }
1117
2497
  async function routeCache(input) {
1118
2498
  const dir = typeof process !== 'undefined' && process.env?.RULECAD_ROUTE_CACHE;
1119
- if (!dir) return null;
1120
- const [fs, path, crypto, { createRequire }] = await Promise.all([import('node:fs'), import('node:path'), import('node:crypto'), import('node:module')]);
2499
+ if (!dir && !routes) return null;
2500
+ const [fs, path, crypto, { createRequire }] = await Promise.all([
2501
+ import('node:fs'),
2502
+ import('node:path'),
2503
+ import('node:crypto'),
2504
+ import('node:module'),
2505
+ ]);
1121
2506
  let version = '?';
1122
- try { version = createRequire(import.meta.url)('@tscircuit/capacity-autorouter/package.json').version; } catch {}
1123
- const file = path.join(dir, `${crypto.createHash('sha256').update(JSON.stringify([version, input])).digest('hex')}.json`);
2507
+ try {
2508
+ version = createRequire(import.meta.url)('@tscircuit/capacity-autorouter/package.json').version;
2509
+ } catch {
2510
+ // (the router's package.json can't be read: its version is '?' in the cache key)
2511
+ }
2512
+ const key = crypto
2513
+ .createHash('sha256')
2514
+ .update(JSON.stringify([version, input]))
2515
+ .digest('hex');
2516
+ if (routes) {
2517
+ const store = routes;
2518
+ return {
2519
+ read: () => {
2520
+ try {
2521
+ const text = store.get(key);
2522
+ return text === undefined ? null : JSON.parse(text);
2523
+ } catch {
2524
+ return null;
2525
+ }
2526
+ },
2527
+ write: (traces) => {
2528
+ try {
2529
+ store.put(key, JSON.stringify(traces));
2530
+ } catch {
2531
+ // (a cache that can't be written is only slower)
2532
+ }
2533
+ },
2534
+ };
2535
+ }
2536
+ const file = path.join(dir, `${key}.json`);
1124
2537
  return {
1125
- read: () => { try { return JSON.parse(fs.readFileSync(file, 'utf8')); } catch { return null; } },
1126
- write: (traces) => { try { fs.mkdirSync(dir, { recursive: true }); fs.writeFileSync(file, JSON.stringify(traces)); } catch {} }, // (a cache that can't be written is only slower)
2538
+ read: () => {
2539
+ try {
2540
+ return JSON.parse(fs.readFileSync(file, 'utf8'));
2541
+ } catch {
2542
+ return null;
2543
+ }
2544
+ },
2545
+ write: (traces) => {
2546
+ try {
2547
+ fs.mkdirSync(dir, { recursive: true });
2548
+ fs.writeFileSync(file, JSON.stringify(traces));
2549
+ } catch {
2550
+ // (a cache that can't be written is only slower)
2551
+ }
2552
+ },
1127
2553
  };
1128
2554
  }
1129
2555
 
1130
2556
  async function routeOnce(json, toRoute, board, limit = 0) {
1131
- // The autorouter uses JavaScript features from Node 22 (iterator helpers): say so, rather than fail inside it
1132
- 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`);
2557
+ // The autorouter uses JavaScript features from Node 22 (iterator helpers), and stops inside itself on anything
2558
+ // older: say what pcb needs instead. pcb states Node 24 (package.json engines, for circuit-to-svg and
2559
+ // jscad-electronics), the number the message gives; routing is left to run on 22 and 23, as it did before.
2560
+ if (Number(process.versions.node.split('.')[0]) < 22)
2561
+ throw new Error(
2562
+ `routing a board's remaining connections needs Node 24 or newer, which @rulecad/pcb asks for (this is Node ${process.versions.node}): install a newer Node and build again`,
2563
+ );
1133
2564
  const router = await import('@tscircuit/capacity-autorouter');
1134
2565
  const srj = await routeInput(json, toRoute, board);
1135
2566
  // The router's own pipeline first. If it gives up, one of its later stages throws (its via clean-up can, on a crowded
1136
2567
  // two-sided board: "a layer transition without a via"), or what it hands back fails here (a pad left without a
1137
2568
  // track, a track through a part), the next one: a different search from the start
1138
- const pipelines = [...new Set([board.pipeline || PIPELINES[0], ...PIPELINES])], tried = [];
2569
+ const pipelines = [...new Set([board.pipeline || PIPELINES[0], ...PIPELINES])],
2570
+ tried = [];
1139
2571
  // A route already found for this very input (RULECAD_ROUTE_CACHE: a folder; cad sets its workspace's .cache/routes):
1140
2572
  // its tracks as the router handed them back, so a board whose routing is unchanged builds in seconds, not the
1141
2573
  // router's minutes, while what comes after routing (repairs, smoothing, the finish) can still change
1142
2574
  const cache = await routeCache([srj, pipelines, board.effort ?? null, limit ? 'repair' : 'route']);
1143
2575
  const hit = cache?.read();
1144
- if (hit) try { return routedTraces({ getOutputSimplifiedPcbTraces: () => structuredClone(hit) }, srj, json); } catch {} // (a stale one: route again)
2576
+ if (hit)
2577
+ try {
2578
+ return routedTraces({ getOutputSimplifiedPcbTraces: () => structuredClone(hit) }, srj, json);
2579
+ } catch {
2580
+ // (a stale one: route again)
2581
+ }
1145
2582
  for (const name of pipelines) {
1146
2583
  if (!router[name]) continue;
1147
2584
  const solver = new router[name](srj, { cacheProvider: null, ...(board.effort ? { effort: board.effort } : {}) }); // effort: how hard it searches (1, the router's own)
1148
2585
  // stepped by hand, so a repair can be given a time limit (a first route has none)
1149
- 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 }); } }
1150
- catch (e) { if (e.late) throw e; solver.failed = true; solver.error = solver.error || e.message; }
1151
- if (solver.failed) { tried.push(`${name}: ${solver.error || 'no reason given'}`); continue; }
1152
- try { const done = routedTraces(solver, srj, json); cache?.write(solver.getOutputSimplifiedPcbTraces()); return done; } catch (e) { tried.push(`${name}: ${e.message}`); }
2586
+ try {
2587
+ while (!solver.solved && !solver.failed) {
2588
+ solver.step();
2589
+ if (limit && Date.now() > limit) throw Object.assign(new Error('a repair took too long'), { late: true });
2590
+ }
2591
+ } catch (e) {
2592
+ if (e.late) throw e;
2593
+ solver.failed = true;
2594
+ solver.error = solver.error || e.message;
2595
+ }
2596
+ if (solver.failed) {
2597
+ tried.push(`${name}: ${solver.error || 'no reason given'}`);
2598
+ continue;
2599
+ }
2600
+ try {
2601
+ const done = routedTraces(solver, srj, json);
2602
+ cache?.write(solver.getOutputSimplifiedPcbTraces());
2603
+ return done;
2604
+ } catch (e) {
2605
+ tried.push(`${name}: ${e.message}`);
2606
+ }
1153
2607
  }
1154
- 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');
2608
+ throw new Error(
2609
+ tried.length > 1
2610
+ ? `the autorouter couldn't route every connection, with any of its pipelines (${tried.join('; ')})`
2611
+ : tried[0]?.replace(/^\w+: /, '') || 'the autorouter has none of its pipelines',
2612
+ );
1155
2613
  }
1156
2614
 
1157
2615
  // What a solved pipeline hands back, as tracks on the board: throws if a pad is left without a track or a track runs
@@ -1159,47 +2617,109 @@ async function routeOnce(json, toRoute, board, limit = 0) {
1159
2617
  function routedTraces(solver, srj, json) {
1160
2618
  // The routes for the connections asked for (the solver also hands back the fixed ones), each from its first pad to
1161
2619
  // its second, as tscircuit records them
1162
- const traces = [], asked = new Map(srj.connections.map((c) => [c.name, c.pointsToConnect]));
1163
- const far = (p, q) => Math.hypot(p.x - q.x, p.y - q.y);
2620
+ const traces = [],
2621
+ asked = new Map(srj.connections.map((c) => [c.name, c.pointsToConnect]));
1164
2622
  // The router hands back each net as pieces of track, named after one of its connections. A piece's ends are named
1165
2623
  // by the pads they finish on; a piece that reaches a one-sided pad on the other layer gets a via there (the router
1166
2624
  // sometimes leaves it out), set back along the piece just clear of the pad, and a short track on the pad's layer.
1167
- const pads = json.filter((e) => e.type === 'pcb_smtpad' || e.type === 'pcb_plated_hole').map((e) => e.type === 'pcb_smtpad'
1168
- ? { port: e.pcb_port_id, ...smtBounds(e), layer: e.layer, points: e.points } : { port: e.pcb_port_id, x: e.x, y: e.y, ...holeSize(e), layer: null });
1169
- const within = (d, p) => Math.abs(p.x - d.x) <= d.w / 2 + 1e-6 && Math.abs(p.y - d.y) <= d.h / 2 + 1e-6 && (!d.points || insidePolygon(d.points, p));
2625
+ const pads = json
2626
+ .filter((e) => e.type === 'pcb_smtpad' || e.type === 'pcb_plated_hole')
2627
+ .map((e) =>
2628
+ e.type === 'pcb_smtpad'
2629
+ ? { port: e.pcb_port_id, ...smtBounds(e), layer: e.layer, points: e.points }
2630
+ : { port: e.pcb_port_id, x: e.x, y: e.y, ...holeSize(e), layer: null },
2631
+ );
2632
+ const within = (d, p) =>
2633
+ Math.abs(p.x - d.x) <= d.w / 2 + 1e-6 &&
2634
+ Math.abs(p.y - d.y) <= d.h / 2 + 1e-6 &&
2635
+ (!d.points || insidePolygon(d.points, p));
1170
2636
  const padAt = (p) => pads.filter((d) => within(d, p)).sort((a, b) => a.w * a.h - b.w * b.h)[0]; // the smallest pad there
1171
2637
  const edge = json.find((e) => e.type === 'pcb_board')?.min_trace_to_pad_edge_clearance ?? 0.1;
1172
2638
  const onto = (pad, p, q) => {
1173
2639
  if (!pad?.layer || p.route_type !== 'wire' || p.layer === pad.layer) return [];
1174
2640
  const back = Math.max(pad.w, pad.h) / 2 + srj.minViaPadDiameter / 2 + edge;
1175
- const len = Math.hypot(q.x - p.x, q.y - p.y) || 1, t = Math.min(back / len, 1), v = { x: p.x + (q.x - p.x) * t, y: p.y + (q.y - p.y) * t };
1176
- return [{ route_type: 'wire', x: p.x, y: p.y, width: p.width, layer: pad.layer }, { route_type: 'wire', x: v.x, y: v.y, width: p.width, layer: pad.layer },
1177
- { route_type: 'via', x: v.x, y: v.y, from_layer: pad.layer, to_layer: p.layer }, { route_type: 'wire', x: v.x, y: v.y, width: p.width, layer: p.layer }];
2641
+ const len = Math.hypot(q.x - p.x, q.y - p.y) || 1,
2642
+ t = Math.min(back / len, 1),
2643
+ v = { x: p.x + (q.x - p.x) * t, y: p.y + (q.y - p.y) * t };
2644
+ return [
2645
+ { route_type: 'wire', x: p.x, y: p.y, width: p.width, layer: pad.layer },
2646
+ { route_type: 'wire', x: v.x, y: v.y, width: p.width, layer: pad.layer },
2647
+ { route_type: 'via', x: v.x, y: v.y, from_layer: pad.layer, to_layer: p.layer },
2648
+ { route_type: 'wire', x: v.x, y: v.y, width: p.width, layer: p.layer },
2649
+ ];
1178
2650
  };
1179
2651
  const holes = json.filter((e) => e.type === 'pcb_plated_hole' || e.type === 'pcb_via'); // copper joining the layers: a track may change layer in it
1180
2652
  // A connection's end that isn't on a pad (a kept escape's end) stands for its pin
1181
2653
  const ends = srj.connections.flatMap((c) => c.pointsToConnect).filter((q) => !padAt(q));
1182
- const endAt = (p) => { const q = ends.find((e) => Math.hypot(e.x - p.x, e.y - p.y) < 0.02); return q && { port: q.pcb_port_id, layer: null, w: 0, h: 0, stub: true }; };
2654
+ const endAt = (p) => {
2655
+ const q = ends.find((e) => Math.hypot(e.x - p.x, e.y - p.y) < 0.02);
2656
+ return q && { port: q.pcb_port_id, layer: null, w: 0, h: 0, stub: true };
2657
+ };
1183
2658
  const viaStub = []; // pins reached at a kept escape's end: the track ends there, not on the pad, so it isn't marked as the pad's
1184
2659
  for (const t of solver.getOutputSimplifiedPcbTraces()) {
1185
2660
  if (!asked.has(t.connection_name)) continue;
1186
- for (const piece of layerChanges(t.route.map((p) => ({ ...p })), holes)) traces.push(finish(piece, t.connection_name));
2661
+ for (const piece of layerChanges(
2662
+ t.route.map((p) => ({ ...p })),
2663
+ holes,
2664
+ ))
2665
+ traces.push(finish(piece, t.connection_name));
1187
2666
  }
1188
2667
  function finish(piece, name) {
1189
2668
  let route = piece;
1190
- const first = padAt(route[0]) ?? endAt(route[0]), last = padAt(route.at(-1)) ?? endAt(route.at(-1));
1191
- const head = onto(first, route[0], route[1] || route[0]), tail = onto(last, route.at(-1), route.at(-2) || route.at(-1));
2669
+ const first = padAt(route[0]) ?? endAt(route[0]),
2670
+ last = padAt(route.at(-1)) ?? endAt(route.at(-1));
2671
+ const head = onto(first, route[0], route[1] || route[0]),
2672
+ tail = onto(last, route.at(-1), route.at(-2) || route.at(-1));
1192
2673
  if (head.length) route = [...head, ...route.slice(1)];
1193
- if (tail.length) route = [...route.slice(0, -1), ...tail.reverse().map((q) => (q.route_type === 'via' ? { ...q, from_layer: q.to_layer, to_layer: q.from_layer } : q))];
1194
- if (first) { if (first.stub) viaStub.push(first.port); else route[0].start_pcb_port_id = first.port; }
1195
- if (last) { if (last.stub) viaStub.push(last.port); else route.at(-1).end_pcb_port_id = last.port; }
1196
- return { route, source_trace_id: name, vias: route.filter((p) => p.route_type === 'via').map((p) => ({ x: p.x, y: p.y,
1197
- hole_diameter: srj.minViaHoleDiameter, outer_diameter: srj.minViaPadDiameter, layers: ['top', 'bottom'], from_layer: p.from_layer, to_layer: p.to_layer })) };
2674
+ if (tail.length)
2675
+ route = [
2676
+ ...route.slice(0, -1),
2677
+ ...tail
2678
+ .reverse()
2679
+ .map((q) => (q.route_type === 'via' ? { ...q, from_layer: q.to_layer, to_layer: q.from_layer } : q)),
2680
+ ];
2681
+ if (first) {
2682
+ if (first.stub) viaStub.push(first.port);
2683
+ else route[0].start_pcb_port_id = first.port;
2684
+ }
2685
+ if (last) {
2686
+ if (last.stub) viaStub.push(last.port);
2687
+ else route.at(-1).end_pcb_port_id = last.port;
2688
+ }
2689
+ return {
2690
+ route,
2691
+ source_trace_id: name,
2692
+ vias: route
2693
+ .filter((p) => p.route_type === 'via')
2694
+ .map((p) => ({
2695
+ x: p.x,
2696
+ y: p.y,
2697
+ hole_diameter: srj.minViaHoleDiameter,
2698
+ outer_diameter: srj.minViaPadDiameter,
2699
+ layers: ['top', 'bottom'],
2700
+ from_layer: p.from_layer,
2701
+ to_layer: p.to_layer,
2702
+ })),
2703
+ };
1198
2704
  }
1199
2705
  // Every pad asked for has a track (a pad counts as reached when another pad of the same pin, joined in its part, is)
1200
- const pinOf = new Map(json.filter((e) => e.type === 'pcb_port').map((e) => { const sp = json.find((x) => x.type === 'source_port' && x.source_port_id === e.source_port_id); return [e.pcb_port_id, `${sp?.source_component_id}:${sp?.name}`]; }));
1201
- const reached = new Set([...traces.flatMap((t) => [t.route[0].start_pcb_port_id, t.route.at(-1).end_pcb_port_id]), ...viaStub].map((id) => pinOf.get(id)));
1202
- const missing = srj.connections.flatMap((c) => c.pointsToConnect).filter((p) => !reached.has(pinOf.get(p.pcb_port_id)));
1203
- if (missing.length) throw new Error(`the autorouter left ${missing.length} pads without a track (first: ${missing[0].port_selector})`);
2706
+ const pinOf = new Map(
2707
+ json
2708
+ .filter((e) => e.type === 'pcb_port')
2709
+ .map((e) => {
2710
+ const sp = json.find((x) => x.type === 'source_port' && x.source_port_id === e.source_port_id);
2711
+ return [e.pcb_port_id, `${sp?.source_component_id}:${sp?.name}`];
2712
+ }),
2713
+ );
2714
+ const reached = new Set(
2715
+ [...traces.flatMap((t) => [t.route[0].start_pcb_port_id, t.route.at(-1).end_pcb_port_id]), ...viaStub].map((id) =>
2716
+ pinOf.get(id),
2717
+ ),
2718
+ );
2719
+ const missing = srj.connections
2720
+ .flatMap((c) => c.pointsToConnect)
2721
+ .filter((p) => !reached.has(pinOf.get(p.pcb_port_id)));
2722
+ if (missing.length)
2723
+ throw new Error(`the autorouter left ${missing.length} pads without a track (first: ${missing[0].port_selector})`);
1204
2724
  return { traces };
1205
2725
  }