@rulecad/pcb 0.3.5 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (4) hide show
  1. package/README.md +81 -3
  2. package/circuit.mjs +627 -53
  3. package/package.json +6 -3
  4. package/pcb.mjs +812 -33
package/circuit.mjs CHANGED
@@ -6,9 +6,11 @@
6
6
  // board: { center: { x, y }, width, height, thickness, parts, traces, nets, track, silk, holes, autoroute }, or
7
7
  // { outline: [{ x, y }, ...], thickness, ... }: any shape, a closed polygon (counter-clockwise); its centre and size
8
8
  // are its bounds. pcb.shape makes common ones (rounded, bevelled, circle).
9
- // part { name, ftype: 'simple_switch' | 'simple_chip' | 'simple_diode', mpn, x, y, layer: 'top' | 'bottom',
9
+ // part { name, ftype: 'simple_switch' | 'simple_chip' | 'simple_diode', mpn, lcsc, value, x, y, layer: 'top' | 'bottom',
10
+ // bom: false (not bought: edge pads, test points), place: false (not placed by the assembler),
10
11
  // rotation: 0 | 90 | 180 | 270 (counter-clockwise, seen from the side the part is on; default 0),
11
12
  // pads: [{ pin, x, y, hole, outer }] (plated, relative to the part) or [{ pin, smd: true, hint, x, y, w, h }]
13
+ // (circle: true for a round one, corner: its corners' radius)
12
14
  // or [{ pin, smd: true, x, y, points: [[x, y], ...] }] (copper of any shape; x, y: where tracks join it),
13
15
  // holes: [{ x, y, d }], courtyard: { w, h } | null,
14
16
  // footprint: 'sod123' | 'jst4_sh' | 'pinrow4' ... (a footprinter string, SMD or through-hole, instead of pads),
@@ -18,8 +20,21 @@
18
20
  // nets { GND: ['U1.GND', 'J1.1', 'J2.1'] } or { GND: { pins: [...], width } }: each net's pins are joined by the
19
21
  // shortest set of connections between them (a minimum spanning tree), left to the autorouter, at the net's
20
22
  // width or board.track; pins are named part.pin, by the pin's label, its name or its number
21
- // silk { rect: { x, y, w, h }, layer } | { text, x, y, size, layer }
22
- // holes [{ x, y, d }] in the board (mounting holes)
23
+ // silk { rect: { x, y, w, h }, layer } | { text, x, y, size, layer, rotation } (rotation: degrees, counter-clockwise)
24
+ // effort how hard the autorouter searches (default its own, 1): more for a crowded board, at more time
25
+ // holes [{ x, y, d, keepout }] in the board (mounting holes; keepout: a radius the router keeps tracks out of, for a screw head)
26
+ // layers 2 (default), 4 or 6 copper layers: tracks on the outer two, planes inside
27
+ // clearance (mm) the router keeps from everything in its way (a clone: the source's); unset, the router's own
28
+ // smooth true: routed tracks pulled tight once routed (@rulecad/smooth), where the straight run keeps clearance
29
+ // neck (mm) a routed track still too close to another after repair is narrowed to this where they pass (the fab's smallest)
30
+ // planes { GND: { layer: 'inner1', pins: ['U1.GND', ...] } }: nets joined by copper filling an inner layer. Each SMD pad
31
+ // gets a via beside it before routing, or a track to one nearby; a pad with no room for
32
+ // either is routed to the nearest pad of its net that reaches the plane. via_pad, via_hole, plane_clearance
33
+ // (mm, defaults 0.6, 0.3, 0.2) size them
34
+ // copper { tracks: [{ a, b, width, layer, island }], vias: [{ x, y, pad, hole, island }], islands: [{ id, net, pins, via }] }:
35
+ // a source's own routing, kept (moveGroup's keep): laid as it is; its pins count as joined
36
+ // pads may be castellated ({ castellated: true }: a half hole on the edge, joined at its inner edge) or a rounded
37
+ // rectangle round their hole ({ rect: { w, h, offset: [x, y] } }: an oval pad, a hole off-centre)
23
38
  // All positions are in mm, in the board's own frame. A part on the bottom is seen from above: mirrored in x.
24
39
  import { fp } from '@tscircuit/footprinter';
25
40
  import { symbols } from 'schematic-symbols';
@@ -71,6 +86,7 @@ function strips(points, step) {
71
86
 
72
87
  // An SMD pad's box: a rectangle's own, a polygon's bounds
73
88
  export function smtBounds(e) {
89
+ if (e.shape === 'circle') return { x: e.x, y: e.y, w: e.radius * 2, h: e.radius * 2 };
74
90
  if (e.shape !== 'polygon') return { x: e.x, y: e.y, w: e.width, h: e.height };
75
91
  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);
76
92
  return { x: (x0 + x1) / 2, y: (y0 + y1) / 2, w: x1 - x0, h: y1 - y0 };
@@ -90,10 +106,12 @@ export async function circuitJson(board, { route = defaultRouter } = {}) {
90
106
  const sourceBoard = add('source_board', { source_group_id: 'source_group_0' });
91
107
 
92
108
  // ---- parts: source records, then their footprints on the board ----
109
+ const copper = copperLayers(board.layers ?? 2); // a hole or a via goes through all of them
93
110
  const ports = new Map(); // `${part}.${port name or hint}` -> { source, pcb, x, y, layers }
94
111
  const placed = [];
95
112
  for (const part of board.parts) {
96
113
  const comp = add('source_component', { ftype: part.ftype, name: part.name, manufacturer_part_number: part.mpn,
114
+ ...(part.lcsc ? { supplier_part_numbers: { jlcpcb: [part.lcsc] } } : {}), ...(part.value ? { display_value: part.value } : {}), ...(part.bom === false ? { exclude_from_bom: true } : {}),
97
115
  are_pins_interchangeable: part.ftype === 'simple_switch', source_group_id: 'source_group_0', subcircuit_id: SUB });
98
116
  const fpEls = part.footprint ? fp.string(part.footprint).circuitJson() : [];
99
117
  const mirror = part.layer === 'bottom' ? -1 : 1;
@@ -121,9 +139,14 @@ export async function circuitJson(board, { route = defaultRouter } = {}) {
121
139
  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) });
122
140
  }
123
141
  placed.push({ part, comp, pads, sourcePorts, fpEls, at, mirror, size });
142
+ if (part.model) { const { path, ...m } = part.model; // its 3D model: drawn by partModels, where the part is
143
+ 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,
144
+ subcircuit_id: SUB, rulecad_model: { ...m, source: path, x: part.x, y: part.y, rotation: part.rotation ?? 0, layer: part.layer } }); }
124
145
  }
125
- add('pcb_board', { source_board_id: sourceBoard.source_board_id, subcircuit_id: SUB, center: board.center, thickness: board.thickness, num_layers: 2,
126
- width: board.width, height: board.height, ...(board.outline ? { outline: board.outline.map(({ x, y }) => ({ x, y })) } : {}), material: 'fr4', ...FAB_MINIMUMS });
146
+ // (the vias the router may make: the board's sizes, else ones with the ring a fab recommends, 0.3 in 0.8)
147
+ add('pcb_board', { source_board_id: sourceBoard.source_board_id, subcircuit_id: SUB, center: board.center, thickness: board.thickness, num_layers: copper.length,
148
+ width: board.width, height: board.height, ...(board.outline ? { outline: board.outline.map(({ x, y }) => ({ x, y })) } : {}), material: 'fr4', ...FAB_MINIMUMS,
149
+ min_via_hole_diameter: board.via_hole ?? 0.3, min_via_pad_diameter: board.via_pad ?? 0.8 });
127
150
 
128
151
  for (const { part, comp, pads, sourcePorts, fpEls, at, mirror, size } of placed) {
129
152
  // The component sits at the middle of its pads and holes (as tscircuit places it: pick-and-place reads this)
@@ -131,22 +154,32 @@ export async function circuitJson(board, { route = defaultRouter } = {}) {
131
154
  ...(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]; })];
132
155
  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]))];
133
156
  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],
134
- layer: part.layer, rotation: part.rotation ?? 0, source_component_id: comp.source_component_id, subcircuit_id: SUB });
157
+ layer: part.layer, rotation: part.rotation ?? 0, source_component_id: comp.source_component_id, subcircuit_id: SUB, ...(part.place === false ? { do_not_place: true } : {}) });
135
158
  const own = { pcb_component_id: pc.pcb_component_id, subcircuit_id: SUB };
136
159
  pads.forEach((p, i) => {
137
- const layers = p.smd ? [part.layer] : ['top', 'bottom'];
160
+ const layers = p.smd ? [part.layer] : copper;
138
161
  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 });
139
162
  if (p.poly) { // copper of any shape: no paste (a contact, not a joint)
140
163
  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 });
141
164
  } else if (p.smd) {
142
- const pad = add('pcb_smtpad', { ...own, pcb_port_id: port.pcb_port_id, layer: part.layer, shape: 'rect', width: p.w, height: p.h, port_hints: [p.hint], is_covered_with_solder_mask: false, x: p.x, y: p.y });
165
+ 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,
166
+ ...(p.circle ? { shape: 'circle', radius: p.w / 2 } : { shape: 'rect', width: p.w, height: p.h, ...(p.corner ? { corner_radius: p.corner } : {}) }) });
143
167
  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 });
168
+ } else if (p.rect) { // an oval pad or a hole off-centre: a rounded rectangle, its hole offset turned with the part
169
+ const sz = size(p.rect.w, p.rect.h), o0 = at(0, 0), o1 = at(p.rect.offset[0], p.rect.offset[1]);
170
+ add('pcb_plated_hole', { ...own, pcb_port_id: port.pcb_port_id, shape: 'circular_hole_with_rect_pad', hole_shape: 'circle', pad_shape: 'rect', hole_diameter: p.hole,
171
+ 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,
172
+ port_hints: [`unnamed_platedhole${i + 1}`, p.pin], x: p.x, y: p.y, layers, is_covered_with_solder_mask: false });
144
173
  } else {
145
174
  add('pcb_plated_hole', { ...own, pcb_port_id: port.pcb_port_id, outer_diameter: p.outer, hole_diameter: p.hole, shape: 'circle',
146
- port_hints: [`unnamed_platedhole${i + 1}`, p.pin], x: p.x, y: p.y, layers, is_covered_with_solder_mask: false });
175
+ port_hints: [`unnamed_platedhole${i + 1}`, p.pin, ...(p.castellated ? ['castellated'] : [])], x: p.x, y: p.y, layers, is_covered_with_solder_mask: false });
147
176
  }
148
177
  Object.assign(sourcePorts[i], { _pcb: port });
149
- for (const key of [sourcePorts[i].name, ...sourcePorts[i].port_hints]) ports.set(`${part.name}.${key}`, { source: sourcePorts[i], pcb: port, x: p.x, y: p.y, layers });
178
+ // A castellated pad's centre is on the board's edge: tracks join it at its inner side, mid-way across its copper
179
+ // ring (on the ring's very edge, the router may not count the join as in the pad)
180
+ const join = p.castellated ? inward(board, p.x, p.y, (p.outer + (p.hole ?? p.outer)) / 4) : { x: p.x, y: p.y };
181
+ if (p.castellated) Object.assign(port, join);
182
+ 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 });
150
183
  });
151
184
  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 }); }
152
185
  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 }); }
@@ -154,19 +187,47 @@ export async function circuitJson(board, { route = defaultRouter } = {}) {
154
187
  for (const e of fpEls) {
155
188
  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 });
156
189
  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),
157
- font: e.font, font_size: e.type === 'pcb_silkscreen_text' ? 0.5 : 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 });
190
+ 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 });
158
191
  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 }); }
159
192
  }
160
193
  }
161
194
 
195
+ // ---- planes: each plane net's pads reach its inner layer, through their own holes or a via each ----
196
+ 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');
197
+ const netOf = new Map(); // `${part}.${pin}` -> net, for the pours
198
+ for (const [net, spec] of Object.entries(board.nets || {})) for (const pin of Array.isArray(spec) ? spec : spec.pins) netOf.set(pin, net);
199
+ for (const [net, spec] of Object.entries(board.planes || {})) for (const pin of spec.pins) netOf.set(pin, net);
200
+ const { nets: planeNets = null, links = [] } = board.planes ? planeVias(out, add, board, copper) : {};
201
+ if (board.copper) keptCopper(out, add, board, copper, planeNets || {});
202
+
162
203
  // ---- traces: drawn by rule, or left to the autorouter ----
163
204
  const port = (part, name) => { const p = ports.get(`${part}.${name}`); if (!p) throw new Error(`no port ${part}.${name}`); return p; };
164
- const toRoute = [], traces = [...(board.traces || []), ...netTraces(board, port)];
205
+ const joined = new Map(); // `${part}.${pin}` -> its group: kept islands sharing a pin (meeting at a pad) are one group
206
+ const up = new Map(), root = (g) => { while (up.get(g) !== g) g = up.get(g); return g; };
207
+ for (const k of board.copper?.islands || []) {
208
+ up.set(k.id, k.id);
209
+ for (const p of k.pins) { if (joined.has(p)) up.set(root(joined.get(p)), k.id); joined.set(p, k.id); }
210
+ }
211
+ for (const [p, g] of joined) joined.set(p, root(g));
212
+ const stubOf = new Map((board.copper?.stubs || []).map((b) => [b.pin, b]));
213
+ const layStub = (stub, id) => {
214
+ for (const g of board.copper.tracks.filter((x) => x.stub === stub.id))
215
+ 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 });
216
+ for (const v of board.copper.vias.filter((x) => x.stub === stub.id)) {
217
+ 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 });
218
+ 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 });
219
+ }
220
+ };
221
+ const toRoute = [], traces = [...(board.traces || []), ...netTraces(board, port, joined), ...links];
165
222
  for (const t of traces) {
166
223
  const a = port(...t.from), b = port(...t.to);
167
224
  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,
168
225
  display_name: `.${t.from.join(' > .')} to .${t.to.join(' > .')}`, min_trace_thickness: t.width });
169
- if (!t.path) { toRoute.push({ t, a, b, id: st.source_trace_id }); continue; }
226
+ if (!t.path) { // a kept escape (stub) from either pin: laid as part of this connection, which is routed from its end
227
+ 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('.'));
228
+ layStub(stub, st.source_trace_id); return { ...q, x: stub.end.x, y: stub.end.y, layers: [stub.end.layer] }; });
229
+ toRoute.push({ t, a: ends[0], b: ends[1], id: st.source_trace_id }); continue;
230
+ }
170
231
  // A drawn track runs on the layer its first pad is on (a through-hole pad: the front)
171
232
  const layer = t.layer ?? (a.layers.length === 1 ? a.layers[0] : 'top'); // or the layer it names
172
233
  const pts = [{ x: a.x, y: a.y }, ...t.path, { x: b.x, y: b.y }];
@@ -176,25 +237,375 @@ export async function circuitJson(board, { route = defaultRouter } = {}) {
176
237
 
177
238
  // ---- silkscreen and mounting holes ----
178
239
  for (const s of board.silk) {
179
- 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: 0.1, is_filled: false });
180
- 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: 0, pcb_component_id: null, subcircuit_id: SUB });
240
+ 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)
241
+ 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,
242
+ ...(s.to ? { rulecad_to: s.to } : {}) }); // an arrow to what it names, drawn once the label's place is final
181
243
  }
182
- 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 });
244
+ 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,
245
+ ...(h.keepout ? { rulecad_keepout: h.keepout } : {}) }); // a screw head's room: no track within keepout (mm, from its centre)
183
246
 
184
247
  // ---- the autorouter: what the rules don't draw ----
185
248
  if (toRoute.length) {
186
249
  if (!board.autoroute) throw new Error(`${toRoute.length} connections have no track and the board isn't autorouted`);
187
250
  const routed = await route(out, toRoute, board);
188
251
  for (const r of routed.traces) {
189
- const t = add('pcb_trace', { route: r.route, source_trace_id: r.source_trace_id, subcircuit_id: SUB });
190
- for (const v of r.vias) add('pcb_via', { pcb_trace_id: t.pcb_trace_id, ...v, subcircuit_id: SUB }); // whose via it is: the checks need it
252
+ const t = add('pcb_trace', { route: r.route, source_trace_id: r.source_trace_id, subcircuit_id: SUB, rulecad_routed: true });
253
+ 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
191
254
  }
255
+ if (board.smooth) await smoothRouted(out, board);
192
256
  }
257
+ if (planeNets) await pours(out, add, board, planeNets, netOf);
258
+ if (board.silk?.length) clearSilkAfter(out, add, board);
193
259
 
194
- schematic(out, add, placed, { ...board, traces }, port);
260
+ schematic(out, add, placed, { ...board, traces }, port, netOf);
195
261
  return out;
196
262
  }
197
263
 
264
+ // The routed tracks pulled tight (@rulecad/smooth): bend points dropped where a straight run keeps the board's clearance.
265
+ // Only the router's tracks move, never drawn or kept ones, with one exception: a kept escape (a source's stub) that a
266
+ // routed track turns straight back on is cut back to where the track can leave it cleanly (never its first segment,
267
+ // from the pin). Each cut is recorded (rulecad_trimmed on the track, rulecad_shortened on a shortened stub segment) and
268
+ // the checks name it. A track the design checks then find in a new error goes back as it was; if a cut is in one, the
269
+ // board is smoothed again without cuts
270
+ export async function smoothRouted(out, board) {
271
+ const { smoothCircuit } = await import('@rulecad/smooth');
272
+ const { runAllChecks } = await import('@tscircuit/checks');
273
+ // each error by its kind and the elements in it (its measurements change as tracks move), on a copy: the checks write
274
+ // into the routes they read
275
+ const errors = async () => (await runAllChecks(structuredClone(out))).filter((e) => /_error$/.test(e.type))
276
+ .map((e) => JSON.stringify([e.type, ...[...new Set(JSON.stringify(e).match(/pcb_[a-z_]+?_\d+/g) || [])].sort()]));
277
+ const before = new Set(await errors()), snapshot = structuredClone(out);
278
+ const run = (withLeads) => {
279
+ const chains = withLeads ? stubChains(out) : new Map();
280
+ const { routes, trimmed } = smoothCircuit(out, { movable: (e) => e.rulecad_routed === true, ...(board.clearance ? { clearance: board.clearance } : {}),
281
+ leads: (e) => { const c = chains.get(e.pcb_trace_id); return c && { start: c.start?.lead, end: c.end?.lead }; } });
282
+ const was = new Map(), cut = new Set();
283
+ 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); }
284
+ for (const [id, sides] of trimmed) for (const side of ['start', 'end']) if (sides[side]) {
285
+ 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);
286
+ // the chain's segments, root first: those wholly past the new joint go, the one it lands on is shortened
287
+ const segs = [...chain.segs].reverse(), gone = segs.slice(k - 1), last = segs[k - 2], at = lead[k - 1];
288
+ const end = chain.lead[k - 1], moved = Math.hypot(end.x - at.x, end.y - at.y) > 1e-9;
289
+ track.rulecad_trimmed = [...(track.rulecad_trimmed || []), ...gone.map((g) => ({ a: { ...g.trace.route[0] }, b: { ...g.trace.route[1] } }))];
290
+ for (const g of gone) { out.splice(out.indexOf(g.trace), 1); cut.add(g.trace.pcb_trace_id); }
291
+ if (moved) {
292
+ 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 } };
293
+ 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;
294
+ cut.add(last.trace.pcb_trace_id);
295
+ }
296
+ if (gone.length || moved) track.rulecad_cut = (track.rulecad_cut || 0) + 1; // escapes cut back from this track
297
+ cut.add(id);
298
+ }
299
+ return { was, cut };
300
+ };
301
+ let { was, cut } = run(true);
302
+ const fresh = async () => (await errors()).filter((x) => !before.has(x));
303
+ if (cut.size && (await fresh()).some((e) => [...cut].some((id) => e.includes(`"${id}"`)))) { // a cut in a new error: none, then
304
+ out.splice(0, out.length, ...snapshot);
305
+ ({ was } = run(false));
306
+ }
307
+ 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)
308
+ let back = 0;
309
+ for (const e of await fresh()) for (const [id, route] of was) if (e.includes(`"${id}"`)) {
310
+ out.find((x) => x.type === 'pcb_trace' && x.pcb_trace_id === id).route = route; was.delete(id); back++;
311
+ }
312
+ if (!back) break;
313
+ }
314
+ }
315
+
316
+ // 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
317
+ // pad), followed back from the joint segment by segment while it's a single line on one layer, stopping at a via or a
318
+ // branch. -> Map(pcb_trace_id -> { start, end }), each { lead: points from the stub's root to the joint, segs: the stub's
319
+ // segments, from the joint back }
320
+ export function stubChains(out) {
321
+ const near = (p, q) => Math.hypot(p.x - q.x, p.y - q.y) < 1e-6;
322
+ const routed = out.filter((e) => e.type === 'pcb_trace' && e.rulecad_routed);
323
+ const kept = out.filter((e) => e.type === 'pcb_trace' && e.rulecad_kept);
324
+ const chains = new Map();
325
+ for (const t of routed) for (const side of ['start', 'end']) {
326
+ const J = side === 'start' ? t.route[0] : t.route.at(-1);
327
+ if (J.route_type !== 'wire' || J.start_pcb_port_id || J.end_pcb_port_id) continue; // on a pad: no stub
328
+ if (routed.filter((u) => [u.route[0], u.route.at(-1)].some((p) => near(p, J))).length !== 1) continue; // other tracks meet there
329
+ const mine = kept.filter((k) => k.source_trace_id === t.source_trace_id);
330
+ const lead = [{ x: J.x, y: J.y, layer: J.layer }], segs = [], used = new Set();
331
+ for (let cur = J; ;) {
332
+ if (mine.some((k) => k.route[1]?.route_type === 'via' && near(k.route[0], cur))) break; // a via: the stub changes layer here
333
+ 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)));
334
+ if (next.length !== 1) break;
335
+ const k = next[0], far = near(k.route[0], cur) ? k.route[1] : k.route[0];
336
+ used.add(k); segs.push({ trace: k }); lead.push({ x: far.x, y: far.y, layer: J.layer }); cur = far;
337
+ }
338
+ if (segs.length >= 2) chains.set(t.pcb_trace_id, { ...chains.get(t.pcb_trace_id), [side]: { lead: lead.reverse(), segs } });
339
+ }
340
+ return chains;
341
+ }
342
+
343
+ // A point on (or near) the board's edge moved in by d, straight in from the nearest side of its bounds
344
+ function inward(board, x, y, d) {
345
+ 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;
346
+ 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]);
347
+ return { x: x + sides[0][1] * d, y: y + sides[0][2] * d };
348
+ }
349
+
350
+ // A plated hole's copper: its width and height (a round pad, or a rounded rectangle)
351
+ 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 });
352
+
353
+ // The source's copper kept with a block of parts (moveGroup's keep): its tracks and vias as they were, each island a
354
+ // source trace joining its pins (and its plane, if its via reaches one), so nothing routes them again
355
+ function keptCopper(out, add, board, copper, planeNets) {
356
+ const pins = padsByPin(out);
357
+ for (const k of board.copper.islands) { // (stubs are laid with the connection they start: see the traces below)
358
+ const ports = [...new Set(k.pins.flatMap((p) => (pins.get(p) || []).map((f) => f.sp.source_port_id)))];
359
+ const plane = k.via && planeNets[k.net];
360
+ if (!ports.length || (ports.length < 2 && !plane)) continue; // nothing left to join
361
+ 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` });
362
+ for (const g of board.copper.tracks.filter((t) => t.island === k.id))
363
+ 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 });
364
+ for (const v of board.copper.vias.filter((x) => x.island === k.id)) {
365
+ 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 });
366
+ 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 });
367
+ }
368
+ }
369
+ }
370
+
371
+ /**
372
+ * Labels slid clear of copper boxes ({ x, y, w, h }) and of each other: each across its reading direction, a step at a
373
+ * time up to reach, to the nearest clear place; one with nowhere clear stays, marked clash: true.
374
+ * @param {object[]} silk { text, x, y, size, rotation } @param {object[]} copper @param {object} o
375
+ */
376
+ export function slideClear(silk, copper, { reach = 1.5, step = 0.1, gap = 0.15, char = 0.75, bodies = [], area = null, near = 6 } = {}) {
377
+ const turned = (s) => (((s.rotation ?? 0) % 180) + 180) % 180 === 90;
378
+ 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 }; };
379
+ 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;
380
+ 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);
381
+ const placed = [], n = Math.round(reach / step), out = [...silk];
382
+ silk.forEach((s, k) => { // labels at their pins: slid across their reading direction to the nearest clear place
383
+ if (!s.text || s.to) return;
384
+ for (let i = 0; i <= 2 * n; i++) {
385
+ const d = (i % 2 ? 1 : -1) * Math.ceil(i / 2) * step, b = box(s, turned(s) ? d : 0, turned(s) ? 0 : d);
386
+ if (copper.some((c) => hits(b, c, gap)) || placed.some((o) => hits(b, o, gap))) continue;
387
+ placed.push(b);
388
+ out[k] = { ...s, x: Math.round(b.x * 1e4) / 1e4, y: Math.round(b.y * 1e4) / 1e4 };
389
+ return;
390
+ }
391
+ placed.push(box(s));
392
+ out[k] = { ...s, clash: true };
393
+ });
394
+ // Labels that point at what they name ({ to: { x, y } }, or a list of spots to choose from): the nearest clear place to
395
+ // where they're asked for, within `near` mm, clear of pads, parts' bodies and other labels, with a small triangle beside
396
+ // them, pointing at it, clear too. One with nowhere clear stays put, without its pointer
397
+ silk.forEach((s, k) => {
398
+ if (!s.text || !s.to) return;
399
+ const m = Math.round(near / step), spots = [], other = { ...s, rotation: turned(s) ? 0 : 90 }; // level or turned, whichever fits nearer
400
+ 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 });
401
+ spots.sort((a, b) => Math.hypot(a.dx, a.dy) - Math.hypot(b.dx, b.dy));
402
+ for (const { t, dx, dy } of spots) {
403
+ const b = box(t, dx, dy);
404
+ 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;
405
+ for (const to of [s.to].flat()) { // a spot, or several to choose from (past the end of a pad, or beside it)
406
+ const a = arrowPath(b, to);
407
+ if (a.length < 0.8 || copper.some((c) => hits(a.at, c, 0.1)) || placed.some((o) => hits(a.at, o, 0.1))) continue;
408
+ placed.push(b, a.at);
409
+ out[k] = { ...t, to, x: Math.round(b.x * 1e4) / 1e4, y: Math.round(b.y * 1e4) / 1e4 };
410
+ return;
411
+ }
412
+ }
413
+ placed.push(box(s));
414
+ const { to, ...rest } = s;
415
+ out[k] = { ...rest, clash: true };
416
+ });
417
+ return out;
418
+ }
419
+
420
+ /**
421
+ * A pointer from a label's box toward a spot: a small triangle just off the middle of the box's side nearest the spot,
422
+ * pointing at it. @param {{ x, y, w, h }} box @param {{ x, y }} to
423
+ * @returns {{ head: object[], at: { x, y, w, h }, length: number }} the triangle (closed), its box, the distance to `to`
424
+ */
425
+ export function arrowPath(box, to, { gap = 0.2, size = 0.6 } = {}) {
426
+ 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) }));
427
+ 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];
428
+ 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;
429
+ 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 };
430
+ 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 };
431
+ }
432
+
433
+ // After routing: silkscreen text the router's vias (or any copper) landed on slides clear, as clearLabels does before;
434
+ // then each label that points at its pin gets its triangle, beside where the label ended up
435
+ function clearSilkAfter(out, add, board) {
436
+ 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 })),
437
+ ...out.filter((e) => e.type === 'pcb_smtpad').map((e) => smtBounds(e)),
438
+ ...out.filter((e) => e.type === 'pcb_plated_hole').map((e) => ({ x: e.x, y: e.y, ...holeSize(e) }))];
439
+ const texts = out.filter((e) => e.type === 'pcb_silkscreen_text' && !e.pcb_component_id);
440
+ 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 }];
441
+ 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)) };
442
+ 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 });
443
+ texts.forEach((e, i) => {
444
+ e.anchor_position = { x: moved[i].x, y: moved[i].y };
445
+ if (!moved[i].to) { delete e.rulecad_to; return; }
446
+ const turned = (((e.ccw_rotation ?? 0) % 180) + 180) % 180 === 90, long = e.text.length * e.font_size * 0.75;
447
+ 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);
448
+ add('pcb_silkscreen_path', { pcb_component_id: null, layer: e.layer, route: a.head, stroke_width: board.silk_line ?? 0.15, subcircuit_id: SUB });
449
+ delete e.rulecad_to;
450
+ });
451
+ }
452
+
453
+ // Copper layers, top to bottom: 2, 4 or 6
454
+ function copperLayers(n) {
455
+ if (![2, 4, 6].includes(n)) throw new Error(`a board has 2, 4 or 6 copper layers, not ${n}`);
456
+ return ['top', ...Array.from({ length: n - 2 }, (_, i) => `inner${i + 1}`), 'bottom'];
457
+ }
458
+
459
+ // Every pad of a pin: `${part}.${pin}` -> [pcb pad elements] (pads named alike each have a port)
460
+ function padsByPin(out) {
461
+ const comp = new Map(out.filter((e) => e.type === 'source_component').map((e) => [e.source_component_id, e.name]));
462
+ const src = new Map(out.filter((e) => e.type === 'source_port').map((e) => [e.source_port_id, e]));
463
+ const port = new Map(out.filter((e) => e.type === 'pcb_port').map((e) => [e.pcb_port_id, src.get(e.source_port_id)]));
464
+ const map = new Map();
465
+ for (const e of out.filter((x) => (x.type === 'pcb_smtpad' || x.type === 'pcb_plated_hole') && x.pcb_port_id)) {
466
+ const sp = port.get(e.pcb_port_id);
467
+ 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 }]); }
468
+ }
469
+ return map;
470
+ }
471
+
472
+ // Plane vias. Each pad of a plane net gets to the plane: a plated hole goes through it already (and so does an SMD pad
473
+ // with one of its pin's plated holes in it: a chip's centre pad with its thermal vias); an SMD pad gets a via beside it
474
+ // 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
475
+ // the nearest pad of its net that reaches the plane. Returns { nets: { net: { layer, id } }, links }.
476
+ function planeVias(out, add, board, copper) {
477
+ 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 };
478
+ const width = board.plane_track ?? board.track ?? 0.25, pins = padsByPin(out), nets = {}, stuck = [];
479
+ const rects = out.filter((e) => e.type === 'pcb_smtpad').map((e) => ({ id: e.pcb_smtpad_id, layer: e.layer, ...smtBounds(e) }));
480
+ 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 })),
481
+ ...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 }))];
482
+ const segs = [], sameNet = Object.fromEntries(Object.keys(board.planes).map((n) => [n, []])); // plane tracks drawn so far; each net's vias
483
+ const kept = board.copper || { tracks: [], vias: [], islands: [] }; // the source's copper, kept: in the way, and some pads already reach their plane by it
484
+ for (const g of kept.tracks) if (g.layer === 'top' || g.layer === 'bottom') segs.push({ a: g.a, b: g.b, layer: g.layer, w: g.width });
485
+ for (const v of kept.vias) circles.push({ id: `kept${circles.length}`, x: v.x, y: v.y, r: v.pad / 2 });
486
+ const reachedBy = new Set(kept.islands.filter((k) => k.via && board.planes[k.net]).flatMap((k) => k.pins));
487
+ 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));
488
+ 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); };
489
+ const edge = (x, y) => { // how far inside the board
490
+ 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);
491
+ 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]));
492
+ return insidePolygon(b.outline, { x, y }) ? d : -d;
493
+ };
494
+ const viaFree = (x, y, own) => edge(x, y) >= via.pad / 2 + (b.min_board_edge_clearance ?? 0.2)
495
+ && rects.every((q) => toRect(x, y, q) >= via.pad / 2 + (q.id === own ? 0.1 : clear))
496
+ && circles.every((c) => Math.hypot(x - c.x, y - c.y) >= c.r + via.pad / 2 + clear)
497
+ && segs.every((g) => toSeg(x, y, g.a, g.b) >= via.pad / 2 + (g.w ?? width) / 2 + clear);
498
+ const trackFree = (a, c, layer, own) => {
499
+ const n = Math.max(2, Math.ceil(Math.hypot(c.x - a.x, c.y - a.y) / 0.05));
500
+ for (let i = 0; i <= n; i++) {
501
+ const x = a.x + ((c.x - a.x) * i) / n, y = a.y + ((c.y - a.y) * i) / n;
502
+ if (rects.some((q) => q.id !== own && q.layer === layer && toRect(x, y, q) < width / 2 + clear)) return false;
503
+ if (circles.some((q) => Math.hypot(x - q.x, y - q.y) < q.r + width / 2 + clear)) return false;
504
+ if (segs.some((g) => g.layer === layer && toSeg(x, y, g.a, g.b) < width / 2 + (g.w ?? width) / 2 + clear)) return false;
505
+ }
506
+ return true;
507
+ };
508
+ const comps = new Map(out.filter((e) => e.type === 'pcb_component').map((e) => [e.pcb_component_id, e.center]));
509
+ for (const [name, spec] of Object.entries(board.planes)) {
510
+ 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(', ')})`);
511
+ 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 });
512
+ nets[name] = { layer: spec.layer, id: net.source_net_id };
513
+ for (const pin of spec.pins) {
514
+ if (reachedBy.has(pin)) continue; // the source's own via, kept, takes it to the plane (keptCopper records it)
515
+ const found = pins.get(pin);
516
+ if (!found) throw new Error(`plane ${name}: no pin ${pin}`);
517
+ for (const { e, sp } of found) {
518
+ 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}` });
519
+ if (e.type === 'pcb_plated_hole') continue; // its barrel reaches every layer
520
+ 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
521
+ 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;
522
+ 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 };
523
+ const viaAt = (x, y) => ({ route_type: 'via', x, y, from_layer: e.layer, to_layer: e.layer === 'top' ? 'bottom' : 'top' });
524
+ const places = [];
525
+ {
526
+ const c = comps.get(e.pcb_component_id) || pad, out0 = Math.atan2(pad.y - c.y, pad.x - c.x) || 0;
527
+ const tries = [];
528
+ for (const gap of [0.1, 0.25, 0.45, 0.7, 1, 1.4]) for (let k = 0; k < 16; k++) {
529
+ const a = out0 + (k % 2 ? 1 : -1) * Math.ceil(k / 2) * (Math.PI / 8), ca = Math.cos(a), sa = Math.sin(a);
530
+ 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;
531
+ tries.push({ x: pad.x + ca * reach, y: pad.y + sa * reach });
532
+ }
533
+ const ok = tries.find((t) => viaFree(t.x, t.y, e.pcb_smtpad_id) && trackFree(pad, t, e.layer, e.pcb_smtpad_id));
534
+ // no room for its own: a short track to a via of the same net already placed, if one is clear to reach
535
+ 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)
536
+ .find((v) => trackFree(pad, v, e.layer, e.pcb_smtpad_id));
537
+ if (!ok && !shared) { stuck.push({ pin, name, x: pad.x, y: pad.y }); continue; }
538
+ segs.push({ a: { x: pad.x, y: pad.y }, b: ok || shared, layer: e.layer });
539
+ 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; }
540
+ places.push(ok);
541
+ }
542
+ 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),
543
+ ...(i < places.length - 1 ? [{ route_type: 'wire', x: v.x, y: v.y, width, layer: e.layer }] : [])])];
544
+ const t = add('pcb_trace', { route, source_trace_id: st.source_trace_id, subcircuit_id: SUB });
545
+ for (const v of places) {
546
+ sameNet[name].push(v);
547
+ 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 });
548
+ circles.push({ id: `via${circles.length}`, x: v.x, y: v.y, r: via.pad / 2 });
549
+ }
550
+ }
551
+ }
552
+ }
553
+ // Pads with no room for a via, nor one in reach: a routed track to the nearest pad of the same net that reaches the
554
+ // plane, as a board's power pins between close neighbours are wired. Its source trace to the net goes (the track joins it)
555
+ const reached = new Map(Object.keys(board.planes).map((n) => [n, []]));
556
+ for (const t of out.filter((x) => x.type === 'pcb_trace' && x.route[0].start_pcb_port_id)) {
557
+ 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;
558
+ 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] });
559
+ }
560
+ const links = [];
561
+ for (const s of stuck) {
562
+ 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];
563
+ 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`);
564
+ const i = out.findIndex((x) => x.type === 'source_trace' && x.display_name === `${s.pin} to ${s.name}`);
565
+ if (i >= 0) out.splice(i, 1);
566
+ const cut = (q) => { const k = q.indexOf('.'); return [q.slice(0, k), q.slice(k + 1)]; };
567
+ links.push({ from: cut(s.pin), to: cut(to.pin), width });
568
+ }
569
+ return { nets, links };
570
+ }
571
+
572
+ // The planes: each net's copper filling its inner layer, clear of every other net's holes and vias (tscircuit's copper
573
+ // pour solver), joined to its own by thermal spokes
574
+ async function pours(out, add, board, nets, netOf) {
575
+ const { CopperPourPipelineSolver, initializeManifoldGeometry } = await import('@tscircuit/copper-pour-solver');
576
+ await initializeManifoldGeometry();
577
+ 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]));
578
+ const src = new Map(out.filter((e) => e.type === 'source_port').map((e) => [e.source_port_id, e]));
579
+ 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;
580
+ 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; };
581
+ const traceNet = new Map();
582
+ for (const t of out.filter((e) => e.type === 'source_trace')) {
583
+ 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
584
+ : (() => { 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; })();
585
+ traceNet.set(t.source_trace_id, n);
586
+ }
587
+ const pcbTraceNet = new Map(out.filter((e) => e.type === 'pcb_trace').map((e) => [e.pcb_trace_id, traceNet.get(e.source_trace_id)]));
588
+ 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 },
589
+ { 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 }];
590
+ 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)) };
591
+ for (const [name, { layer, id }] of Object.entries(nets)) {
592
+ const pads = [
593
+ ...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}`;
594
+ 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 }
595
+ : { 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 }; }),
596
+ ...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 })),
597
+ ...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 })),
598
+ ...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,
599
+ shape: 'trace', width: e.route[0].width, segments: e.route.filter((p) => p.route_type === 'wire').map((p) => ({ x: p.x, y: p.y })) }))];
600
+ const solver = new CopperPourPipelineSolver({ pads, regionsForPour: [{ shape: 'rect', layer, bounds, outline, connectivityKey: name,
601
+ padMargin: board.plane_clearance ?? 0.2, traceMargin: board.plane_clearance ?? 0.2, board_edge_margin: board.plane_edge ?? 0.3,
602
+ use_thermal_reliefs: true, thermal_relief_spoke_width: 0.3, thermal_relief_spoke_count: 4 }] });
603
+ solver.solve();
604
+ if (solver.failed) throw new Error(`the ${name} plane couldn't be drawn: ${solver.error || 'no reason given'}`);
605
+ 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 });
606
+ }
607
+ }
608
+
198
609
  // 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
199
610
  function portNames(part, pads) {
200
611
  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'] }];
@@ -206,12 +617,15 @@ function portNames(part, pads) {
206
617
 
207
618
  // A net's connections: its pins joined by the shortest set of straight links between them (Prim's minimum spanning
208
619
  // tree, ties to the earlier pin), so the router gets short, sensible connections to route rather than a long chain
209
- function netTraces(board, port) {
620
+ function netTraces(board, port, joined = new Map()) {
210
621
  return Object.entries(board.nets || {}).flatMap(([net, spec]) => {
211
622
  const list = Array.isArray(spec) ? spec : spec.pins, width = (Array.isArray(spec) ? undefined : spec.width) ?? board.track;
212
623
  if (!width) throw new Error(`net ${net}: no track width. Give the board a track width (board.track) or the net one ({ pins, width })`);
213
624
  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)]; });
214
- const at = pins.map((p) => port(...p)), linked = [0], links = [];
625
+ // Pins the source's kept copper already joins come in together: only the joins between them are routed
626
+ const at = pins.map((p) => port(...p)), group = pins.map((p) => joined.get(p.join('.'))), links = [];
627
+ 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); };
628
+ take(0);
215
629
  while (linked.length < pins.length) {
216
630
  let best = null;
217
631
  for (const a of linked) for (let b = 0; b < pins.length; b++) {
@@ -219,29 +633,45 @@ function netTraces(board, port) {
219
633
  const d = Math.hypot(at[a].x - at[b].x, at[a].y - at[b].y);
220
634
  if (!best || d < best.d) best = { a, b, d };
221
635
  }
222
- linked.push(best.b); links.push({ from: pins[best.a], to: pins[best.b], width, net });
636
+ take(best.b); links.push({ from: pins[best.a], to: pins[best.b], width, net });
223
637
  }
224
638
  return links;
225
639
  });
226
640
  }
227
641
 
228
642
  // ---- the schematic: each part at the place the board gives it, wires between neighbours, labels to the chip ----
229
- function schematic(out, add, placed, board, port) {
643
+ function schematic(out, add, placed, board, port, netOf = new Map()) {
230
644
  const sch = new Map();
231
- for (const { part, comp, sourcePorts } of placed) {
232
- const s = part.sch || { x: 0, y: 0 };
645
+ // Parts with no place of their own on the schematic (a clone's: their board places would pile them up) go in rows,
646
+ // biggest first, with room between for the net labels on their pins
647
+ 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);
648
+ for (const p of [...auto].sort((a, b) => b.sourcePorts.length - a.sourcePorts.length)) {
649
+ const pins = new Set(p.sourcePorts.map((sp) => sp.name)).size;
650
+ 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
651
+ if (row.x > 0 && row.x + w > width) { row.x = 0; row.y -= row.h; row.h = 0; }
652
+ p.at = { x: row.x + w / 2, y: row.y - h / 2 }; row.x += w; row.h = Math.max(row.h, h);
653
+ }
654
+ for (const { part, comp, sourcePorts, at } of placed) {
655
+ const s = part.sch || at || { x: 0, y: 0 };
233
656
  if (part.ftype === 'simple_chip') { // a box: pins 1 to 20 down the left, 21 to 40 up the right, 0.2 apart
234
- const half = Math.ceil(sourcePorts.length / 2), size = { width: 1.9, height: (half + 1) * 0.2 };
657
+ // laid out here, a pin with several pads (a chip's centre pad and its thermal holes) is drawn once
658
+ const shown = at ? sourcePorts.filter((sp, i) => sourcePorts.findIndex((o) => o.name === sp.name) === i) : sourcePorts;
659
+ const half = Math.ceil(shown.length / 2), size = { width: 1.9, height: (half + 1) * 0.2 };
235
660
  const c = add('schematic_component', { center: { x: s.x, y: s.y }, rotation: 0, size, pin_spacing: 0.2, port_labels: part.sch?.pinLabels || {},
236
661
  source_component_id: comp.source_component_id, is_box_with_pins: true, schematic_group_id: 'schematic_group_0' });
237
- add('schematic_text', { text: part.mpn ?? part.name, schematic_component_id: c.schematic_component_id, anchor: 'left', rotation: 0,
662
+ 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,
238
663
  position: { x: s.x - size.width / 2, y: s.y - size.height / 2 - 0.23 }, color: '#006464', font_size: 0.18 });
239
- sourcePorts.forEach((sp, i) => {
240
- const left = i < half, k = left ? i : sourcePorts.length - 1 - i, side = left ? 'left' : 'right';
664
+ shown.forEach((sp, i) => {
665
+ const left = i < half, k = left ? i : shown.length - 1 - i, side = left ? 'left' : 'right';
241
666
  const center = { x: s.x + (left ? -1 : 1) * (size.width / 2 + 0.4), y: s.y + size.height / 2 - 0.2 * (k + 1) };
242
- sch.set(sp.source_port_id, add('schematic_port', { schematic_component_id: c.schematic_component_id, center, source_port_id: sp.source_port_id,
243
- 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 }));
667
+ const sp2 = add('schematic_port', { schematic_component_id: c.schematic_component_id, center, source_port_id: sp.source_port_id,
668
+ 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/, '') });
669
+ sch.set(sp.source_port_id, sp2);
670
+ // laid out here: each pin labelled with its net, in place of wires across the sheet
671
+ const net = at && [sp.name, ...(sp.port_hints || [])].map((k) => netOf.get(`${part.name}.${k}`)).find(Boolean);
672
+ 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 });
244
673
  });
674
+ 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
245
675
  continue;
246
676
  }
247
677
  const symbol = symbols[part.ftype === 'simple_diode' ? 'diode_down' : 'spst_switch_right'];
@@ -254,7 +684,9 @@ function schematic(out, add, placed, board, port) {
254
684
  });
255
685
  }
256
686
  // A wire between two parts' pins (L-shaped), or for a connection to the chip, a label at each end naming the pin
687
+ const labelled = new Set(placed.filter((p) => p.at).map((p) => p.part.name));
257
688
  for (const t of board.traces) {
689
+ if (labelled.has(t.from[0]) && labelled.has(t.to[0])) continue; // their pins carry their nets' names already
258
690
  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);
259
691
  const chip = [a, b].find((q) => placed.find((p) => p.sourcePorts.includes(q.source)).part.ftype === 'simple_chip');
260
692
  if (chip || t.net) { // a net's ends are labelled with the net's name
@@ -275,10 +707,17 @@ function schematic(out, add, placed, board, port) {
275
707
  // board. The board is described to it as tscircuit's own core describes it (pads, holes, the drawn tracks, and which
276
708
  // of them are connected), and the same solver runs with the same settings, so a board routes as it did there.
277
709
  // -> { traces: [{ route, source_trace_id, vias }] }
278
- export async function routeInput(json, toRoute) {
710
+ export async function routeInput(json, toRoute, board = {}) {
279
711
  const { getFullConnectivityMapFromCircuitJson } = await import('circuit-json-to-connectivity-map');
280
712
  const conn = getFullConnectivityMapFromCircuitJson(json);
281
- const linked = (id) => { const net = conn.getNetConnectedToId(id); return net ? [...new Set([id, net, ...conn.getIdsConnectedToNet(net)])] : [id]; };
713
+ // 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,
714
+ // so a short link between two close pads isn't tied to every pad of the net across the board (the router's topology
715
+ // merging then fails on far-off ones, such as a chip's thermal vias)
716
+ 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));
717
+ const linksAt = new Map();
718
+ 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]);
719
+ const linked = (id, port) => { const net = conn.getNetConnectedToId(id); if (!net) return [id];
720
+ return planeNet.has(net) ? [id, ...(port ? [port, ...(linksAt.get(port) || [])] : [])] : [...new Set([id, net, ...conn.getIdsConnectedToNet(net)])]; };
282
721
  const comp = Object.fromEntries(json.filter((e) => e.type === 'source_component').map((e) => [e.source_component_id, e.name]));
283
722
  const src = Object.fromEntries(json.filter((e) => e.type === 'source_port').map((e) => [e.source_port_id, e]));
284
723
  const pcbPort = Object.fromEntries(json.filter((e) => e.type === 'pcb_port').map((e) => [e.pcb_port_id, e]));
@@ -292,19 +731,26 @@ export async function routeInput(json, toRoute) {
292
731
  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
293
732
  if (e.type === 'pcb_smtpad' && e.shape === 'polygon') { // copper of any shape, as strips the router can see round
294
733
  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],
295
- center: { x: b.x, y: b.y }, width: b.w, height: b.h, connectedTo: linked(e.pcb_smtpad_id), ...joined(e) });
734
+ 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) });
296
735
  continue;
297
736
  }
298
737
  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],
299
- center: { x: b.x, y: b.y }, width: b.w, height: b.h, connectedTo: linked(e.pcb_smtpad_id), ...joined(e) }); }
738
+ 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) }); }
300
739
  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'],
301
- center: { x: e.x, y: e.y }, width: e.outer_diameter, height: e.outer_diameter, connectedTo: linked(e.pcb_plated_hole_id), ...joined(e) });
740
+ 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) });
302
741
  if (e.type === 'pcb_hole') obstacles.push({ componentId: e.pcb_component_id, obstacleId: e.pcb_hole_id, isNonPlatedHole: true, type: 'rect', shape: 'circle',
303
- layers: ['top', 'bottom'], center: { x: e.x, y: e.y }, width: e.hole_diameter, height: e.hole_diameter, connectedTo: [] });
742
+ 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
304
743
  }
305
- const traces = json.filter((e) => e.type === 'pcb_trace').map((e) => ({ type: 'pcb_trace', pcb_trace_id: e.pcb_trace_id, source_trace_id: e.source_trace_id,
306
- connection_name: e.source_trace_id, connectsTo: [e.route[0].start_pcb_port_id, e.route.at(-1).end_pcb_port_id],
307
- route: e.route.map((p) => ({ route_type: p.route_type, x: p.x, y: p.y, width: p.width, layer: p.layer })) }));
744
+ // Tracks already on the board, but a plane's vias inside a big pad: the pad is in the router's way already
745
+ const padOf = new Map(json.filter((e) => e.type === 'pcb_smtpad').map((e) => [e.pcb_port_id, smtBounds(e)]));
746
+ 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); };
747
+ const vias = json.filter((e) => e.type === 'pcb_via');
748
+ 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;
749
+ const outer = (e) => e.route.every((p) => p.route_type !== 'wire' || p.layer === 'top' || p.layer === 'bottom'); // the router works on the outer two
750
+ 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,
751
+ 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
752
+ route: e.route.map((p) => ({ route_type: p.route_type, x: p.x, y: p.y, width: p.width, layer: p.layer,
753
+ ...(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
308
754
  const connections = toRoute.map(({ t, a, b: z, id }) => ({ name: id, source_trace_id: id, nominalTraceWidth: t.width, width: t.width,
309
755
  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,
310
756
  port_selector: `${comp[q.source.source_component_id]}.${q.source.name}` })) }));
@@ -316,7 +762,8 @@ export async function routeInput(json, toRoute) {
316
762
  min_via_hole_diameter: b.min_via_hole_diameter, min_via_pad_diameter: b.min_via_pad_diameter,
317
763
  minTraceToPadEdgeClearance: b.min_trace_to_pad_edge_clearance, minTraceToHoleEdgeClearance: b.min_trace_to_hole_edge_clearance,
318
764
  minViaHoleEdgeToViaHoleEdgeClearance: b.min_via_hole_edge_to_via_hole_edge_clearance, minPlatedHoleDrillEdgeToDrillEdgeClearance: b.min_plated_hole_drill_edge_to_drill_edge_clearance,
319
- minPadEdgeToPadEdgeClearance: b.min_pad_edge_to_pad_edge_clearance, minBoardEdgeClearance: b.min_board_edge_clearance });
765
+ minPadEdgeToPadEdgeClearance: b.min_pad_edge_to_pad_edge_clearance, minBoardEdgeClearance: b.min_board_edge_clearance,
766
+ ...(board.clearance ? { defaultObstacleMargin: board.clearance } : {}) }); // a board's own clearance, kept from everything in the way
320
767
  }
321
768
 
322
769
  // The drawn tracks become fixed obstacles for the router: each segment a box a track wide (a diagonal one, a run of
@@ -346,13 +793,132 @@ function fixedTraces(input) {
346
793
  return { ...input, traces: [], obstacles: [...input.obstacles, ...obstacles] };
347
794
  }
348
795
 
349
- async function defaultRouter(json, toRoute) {
796
+ /**
797
+ * A route from the autorouter, cut where it changes layer inside a plated hole or a via: the router marks those as points
798
+ * "through an obstacle", which nothing downstream reads, but the hole's copper already joins the layers, so the route
799
+ * ends there on one layer and a second starts there on the other. A pass through anything else is an error.
800
+ * @param {object[]} route @param {object[]} holes pcb_plated_hole and pcb_via elements @returns {object[][]}
801
+ */
802
+ export function layerChanges(route, holes) {
803
+ const pieces = [[]];
804
+ for (const p of route) {
805
+ if (p.route_type !== 'through_obstacle') { pieces.at(-1).push(p); continue; }
806
+ const at = p.start, inHole = holes.some((h) => {
807
+ const r = Math.max(holeSize(h).w, holeSize(h).h) / 2;
808
+ return Math.hypot(at.x - h.x, at.y - h.y) <= r + 1e-6 && Math.hypot(p.end.x - h.x, p.end.y - h.y) <= r + 1e-6;
809
+ });
810
+ if (!inHole) throw new Error(`the autorouter ran a track through a part at (${at.x.toFixed(2)}, ${at.y.toFixed(2)}) mm: move the parts apart or give it more room`);
811
+ const width = p.width ?? pieces.at(-1).at(-1)?.width;
812
+ pieces.at(-1).push({ route_type: 'wire', x: at.x, y: at.y, width, layer: p.from_layer });
813
+ pieces.push([{ route_type: 'wire', x: p.end.x, y: p.end.y, width, layer: p.to_layer }]);
814
+ }
815
+ return pieces.filter((q) => q.length > 1);
816
+ }
817
+
818
+ // The autorouter, then repair: its tracks sometimes run too close to, or over, others. Those connections are pulled up and
819
+ // routed again together with every good track fixed in place, up to three rounds, keeping the best (on a board too tight
820
+ // for it, the checks then say where)
821
+ // Routed tracks laid as board elements, for routing round them or checking them
822
+ 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 },
823
+ ...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 }))]);
824
+
825
+ async function defaultRouter(json, toRoute, board) {
826
+ let traces = (await routeOnce(json, toRoute, board)).traces;
827
+ const { runAllChecks } = await import('@tscircuit/checks');
828
+ const problems = async (list) => (await runAllChecks([...json, ...lay(list)])).filter((e) => /_error$/.test(e.type));
829
+ let errors = await problems(traces), best = { traces, n: errors.length };
830
+ // Repair: the connections in errors pulled up and routed again round every good track, each round asking for a little
831
+ // more room than the last (so they don't land in the same squeeze), the best result kept
832
+ for (let round = 0; round < 3 && errors.length; round++) {
833
+ const bad = new Set();
834
+ 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);
835
+ bad.delete(undefined);
836
+ if (!bad.size) break;
837
+ const keep = traces.filter((t) => !bad.has(t.source_trace_id)), again = toRoute.filter((c) => bad.has(c.id));
838
+ const roomier = { ...board, clearance: (board.clearance ?? 0.1) + 0.05 * (round + 1) };
839
+ const minute = () => Date.now() + 60000; // each repair attempt gets a minute
840
+ let next = null;
841
+ try { next = [...keep, ...(await routeOnce([...json, ...lay(keep)], again, roomier, minute())).traces]; } catch {} // too tight together:
842
+ if (!next && again.length <= 4) { // a few go one at a time, each round everything else, the router searching harder if it must
843
+ next = traces;
844
+ for (const c of again) for (const effort of [1, 2]) {
845
+ const rest = next.filter((t) => t.source_trace_id !== c.id);
846
+ try { next = [...rest, ...(await routeOnce([...json, ...lay(rest)], [c], { ...roomier, effort }, minute())).traces]; break; } catch {}
847
+ }
848
+ }
849
+ if (!next) break; // too tight to better: the best result stands
850
+ traces = next; errors = await problems(traces);
851
+ if (errors.length < best.n) best = { traces, n: errors.length };
852
+ }
853
+ traces = best.traces;
854
+ if (board?.neck) traces = await neckDown(json, traces, board.neck);
855
+ return { traces };
856
+ }
857
+
858
+ /**
859
+ * Routed tracks still a little too close to another, or to the board's edge: straightened where the router doubled back,
860
+ * moved in from the edge, then necked down where they pass, the segment of each nearest the spot
861
+ * narrowed to neck (the fab's smallest track), which opens the gap. traces as the router gives them; returns them.
862
+ * @param {object[]} json @param {object[]} traces @param {number} neck
863
+ */
864
+ export async function neckDown(json, traces, neck) {
865
+ const { runAllChecks } = await import('@tscircuit/checks');
866
+ 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); };
867
+ const out = traces.map((t) => ({ ...t, route: t.route.map((p) => ({ ...p })) }));
868
+ 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 }));
869
+ const close = async () => (await runAllChecks([...json, ...lay()])).filter((e) => e.type === 'pcb_trace_error' && /too close|overlap/.test(e.message) && e.center);
870
+ // First, straighten: a routed track's kink by the spot (a bend point between two runs on one layer) is dropped when that
871
+ // leaves fewer problems; the router sometimes doubles back as it leaves its start
872
+ for (const e of await close()) for (const m of new Set(JSON.stringify(e).match(/pcb_trace_rt\d+/g) || [])) {
873
+ const r = out[Number(m.slice(12))].route, before = (await close()).length;
874
+ 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))
875
+ .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];
876
+ if (k === undefined || Math.hypot(r[k].x - e.center.x, r[k].y - e.center.y) > 1) continue;
877
+ const [gone] = r.splice(k, 1);
878
+ if ((await close()).length >= before) r.splice(k, 0, gone); // no better: put it back
879
+ }
880
+ // Then a stretch too close to the board's edge (the router sometimes hugs it): moved in by what it lacks, both its
881
+ // ends (not a pad's end), where that leaves no more problems than before
882
+ 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 })));
883
+ 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; };
884
+ for (const e of edge ? await close() : []) {
885
+ 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;
886
+ const r = out[Number(m[1])].route, by = Number(short[2]) - Number(short[1]) + 0.02;
887
+ 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];
888
+ if (i === undefined || toSeg(e.center, r[i], r[i + 1]) > 0.5) continue;
889
+ const near = edge.map((q, k) => [q, edge[(k + 1) % edge.length]]).sort((u, w) => toSeg(e.center, ...u) - toSeg(e.center, ...w))[0];
890
+ const len = Math.hypot(near[1].x - near[0].x, near[1].y - near[0].y) || 1;
891
+ let n = { x: -(near[1].y - near[0].y) / len, y: (near[1].x - near[0].x) / len };
892
+ 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
893
+ const before = (await close()).length, was = [r[i], r[i + 1]].map((q) => ({ x: q.x, y: q.y }));
894
+ for (const q of [r[i], r[i + 1]]) { q.x += n.x * by; q.y += n.y * by; }
895
+ if ((await close()).length >= before) [r[i], r[i + 1]].forEach((q, k) => Object.assign(q, was[k])); // no better: put it back
896
+ }
897
+ for (let pass = 0; pass < 4; pass++) { // two tracks close along a stretch: the next segment along, until they clear
898
+ 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 }));
899
+ const errors = (await runAllChecks([...json, ...laid])).filter((e) => e.type === 'pcb_trace_error' && /too close/.test(e.message) && e.center);
900
+ let narrowed = false;
901
+ for (const e of errors) for (const m of JSON.stringify(e).matchAll(/pcb_trace_rt(\d+)/g)) {
902
+ const r = out[Number(m[1])]?.route; if (!r) continue;
903
+ // the nearest segment still at full width (one already necked: the next along)
904
+ const order = r.map((_, i) => i).filter((i) => i < r.length - 1 && r[i].route_type === 'wire' && r[i + 1].route_type === 'wire')
905
+ .sort((i, k) => toSeg(e.center, r[i], r[i + 1]) - toSeg(e.center, r[k], r[k + 1]));
906
+ const i = order.find((k) => toSeg(e.center, r[k], r[k + 1]) < 1 && (r[k].width > neck || r[k + 1].width > neck));
907
+ 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; }
908
+ }
909
+ if (!narrowed) break;
910
+ }
911
+ return out;
912
+ }
913
+
914
+ async function routeOnce(json, toRoute, board, limit = 0) {
350
915
  // The autorouter uses JavaScript features from Node 22 (iterator helpers): say so, rather than fail inside it
351
916
  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`);
352
917
  const { AutoroutingPipelineSolver } = await import('@tscircuit/capacity-autorouter');
353
- const srj = await routeInput(json, toRoute);
354
- const solver = new AutoroutingPipelineSolver(srj, { cacheProvider: null });
355
- solver.solve();
918
+ const srj = await routeInput(json, toRoute, board);
919
+ const solver = new AutoroutingPipelineSolver(srj, { cacheProvider: null, ...(board.effort ? { effort: board.effort } : {}) }); // effort: how hard it searches (1, the router's own)
920
+ // stepped by hand, so a repair can be given a time limit (a first route has none)
921
+ while (!solver.solved && !solver.failed) { solver.step(); if (limit && Date.now() > limit) throw new Error('a repair took too long'); }
356
922
  if (solver.failed) throw new Error(`the autorouter couldn't route every connection: ${solver.error || 'no reason given'}`);
357
923
  // The routes for the connections asked for (the solver also hands back the fixed ones), each from its first pad to
358
924
  // its second, as tscircuit records them
@@ -362,7 +928,7 @@ async function defaultRouter(json, toRoute) {
362
928
  // by the pads they finish on; a piece that reaches a one-sided pad on the other layer gets a via there (the router
363
929
  // sometimes leaves it out), set back along the piece just clear of the pad, and a short track on the pad's layer.
364
930
  const pads = json.filter((e) => e.type === 'pcb_smtpad' || e.type === 'pcb_plated_hole').map((e) => e.type === 'pcb_smtpad'
365
- ? { port: e.pcb_port_id, ...smtBounds(e), layer: e.layer, points: e.points } : { port: e.pcb_port_id, x: e.x, y: e.y, w: e.outer_diameter, h: e.outer_diameter, layer: null });
931
+ ? { 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 });
366
932
  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));
367
933
  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
368
934
  const edge = json.find((e) => e.type === 'pcb_board')?.min_trace_to_pad_edge_clearance ?? 0.1;
@@ -373,21 +939,29 @@ async function defaultRouter(json, toRoute) {
373
939
  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 },
374
940
  { 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 }];
375
941
  };
942
+ 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
943
+ // A connection's end that isn't on a pad (a kept escape's end) stands for its pin
944
+ const ends = srj.connections.flatMap((c) => c.pointsToConnect).filter((q) => !padAt(q));
945
+ 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 }; };
946
+ 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
376
947
  for (const t of solver.getOutputSimplifiedPcbTraces()) {
377
948
  if (!asked.has(t.connection_name)) continue;
378
- let route = t.route.map((p) => ({ ...p }));
379
- const first = padAt(route[0]), last = padAt(route.at(-1));
949
+ for (const piece of layerChanges(t.route.map((p) => ({ ...p })), holes)) traces.push(finish(piece, t.connection_name));
950
+ }
951
+ function finish(piece, name) {
952
+ let route = piece;
953
+ const first = padAt(route[0]) ?? endAt(route[0]), last = padAt(route.at(-1)) ?? endAt(route.at(-1));
380
954
  const head = onto(first, route[0], route[1] || route[0]), tail = onto(last, route.at(-1), route.at(-2) || route.at(-1));
381
955
  if (head.length) route = [...head, ...route.slice(1)];
382
956
  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))];
383
- if (first) route[0].start_pcb_port_id = first.port;
384
- if (last) route.at(-1).end_pcb_port_id = last.port;
385
- traces.push({ route, source_trace_id: t.connection_name, vias: route.filter((p) => p.route_type === 'via').map((p) => ({ x: p.x, y: p.y,
386
- hole_diameter: srj.minViaHoleDiameter, outer_diameter: srj.minViaPadDiameter, layers: ['top', 'bottom'], from_layer: p.from_layer, to_layer: p.to_layer })) });
957
+ if (first) { if (first.stub) viaStub.push(first.port); else route[0].start_pcb_port_id = first.port; }
958
+ if (last) { if (last.stub) viaStub.push(last.port); else route.at(-1).end_pcb_port_id = last.port; }
959
+ return { route, source_trace_id: name, vias: route.filter((p) => p.route_type === 'via').map((p) => ({ x: p.x, y: p.y,
960
+ hole_diameter: srj.minViaHoleDiameter, outer_diameter: srj.minViaPadDiameter, layers: ['top', 'bottom'], from_layer: p.from_layer, to_layer: p.to_layer })) };
387
961
  }
388
962
  // Every pad asked for has a track (a pad counts as reached when another pad of the same pin, joined in its part, is)
389
963
  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}`]; }));
390
- const reached = new Set(traces.flatMap((t) => [t.route[0].start_pcb_port_id, t.route.at(-1).end_pcb_port_id]).map((id) => pinOf.get(id)));
964
+ 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)));
391
965
  const missing = srj.connections.flatMap((c) => c.pointsToConnect).filter((p) => !reached.has(pinOf.get(p.pcb_port_id)));
392
966
  if (missing.length) throw new Error(`the autorouter left ${missing.length} pads without a track (first: ${missing[0].port_selector})`);
393
967
  return { traces };