@rulecad/pcb 0.3.6 → 0.5.0

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