@rulecad/pcb 0.6.0 → 0.7.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +40 -0
- package/README.md +21 -8
- package/circuit.mjs +1956 -474
- package/kicad.mjs +409 -77
- package/package.json +5 -5
- package/pcb.mjs +2486 -601
package/pcb.mjs
CHANGED
|
@@ -27,7 +27,9 @@ import { fixingModel } from '@rulecad/fixings';
|
|
|
27
27
|
// at the back (+y)
|
|
28
28
|
export function grid(rows, cols, pitch) {
|
|
29
29
|
const keys = [];
|
|
30
|
-
for (let r = 0; r < rows; r++)
|
|
30
|
+
for (let r = 0; r < rows; r++)
|
|
31
|
+
for (let c = 0; c < cols; c++)
|
|
32
|
+
keys.push({ r, c, n: r * cols + c + 1, x: (c - (cols - 1) / 2) * pitch, y: ((rows - 1) / 2 - r) * pitch });
|
|
31
33
|
return keys;
|
|
32
34
|
}
|
|
33
35
|
|
|
@@ -38,7 +40,8 @@ const hole = (x, y, d) => ({ x, y, d });
|
|
|
38
40
|
// ---------- mounting holes, by thread ----------
|
|
39
41
|
// Which figure of a thread's rule set each fit of hole is: ISO 273's close, normal and loose clearance holes
|
|
40
42
|
const MOUNT_FITS = { clearance: 'clearance', close: 'clearance_close', loose: 'clearance_loose' };
|
|
41
|
-
const shown = (x) =>
|
|
43
|
+
const shown = (x) =>
|
|
44
|
+
x === undefined ? 'nothing' : typeof x === 'number' ? String(x) : (JSON.stringify(x) ?? String(x)); // (NaN as NaN)
|
|
42
45
|
|
|
43
46
|
/**
|
|
44
47
|
* A board's mounting hole, named by its screw's thread and sized from the thread's rule set (@rulecad/fixings reads
|
|
@@ -54,64 +57,140 @@ const shown = (x) => (x === undefined ? 'nothing' : JSON.stringify(x) ?? String(
|
|
|
54
57
|
* @returns {{ x: number, y: number, d: number, keepout?: number, thread: string, fit: string }}
|
|
55
58
|
*/
|
|
56
59
|
export function mount(thread, x, y, o = {}) {
|
|
57
|
-
const what = 'mount',
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
60
|
+
const what = 'mount',
|
|
61
|
+
example = "mount('M2', 10, 5) or mount('M2', 10, 5, { fit: 'close' })";
|
|
62
|
+
if (o == null || typeof o !== 'object' || Array.isArray(o))
|
|
63
|
+
throw new Error(`${what}: the options are an object ({ fit, d, keepout }), not ${shown(o)}: ${example}`);
|
|
64
|
+
const known = ['fit', 'd', 'keepout', 'set', 'sets'],
|
|
65
|
+
odd = Object.keys(o).filter((k) => !known.includes(k));
|
|
66
|
+
if (odd.length)
|
|
67
|
+
throw new Error(
|
|
68
|
+
`${what}: no option ${odd.map((k) => `"${k}"`).join(', ')} (there are ${known.join(', ')}): ${example}`,
|
|
69
|
+
);
|
|
70
|
+
for (const [k, n] of [
|
|
71
|
+
['x', x],
|
|
72
|
+
['y', y],
|
|
73
|
+
])
|
|
74
|
+
if (typeof n !== 'number' || !Number.isFinite(n))
|
|
75
|
+
throw new Error(`${what}: ${k} is a number, in mm in the board's frame (got ${shown(n)}): ${example}`);
|
|
62
76
|
const fit = o.fit ?? 'clearance';
|
|
63
|
-
if (!(fit in MOUNT_FITS))
|
|
64
|
-
|
|
65
|
-
if (o.
|
|
77
|
+
if (!(fit in MOUNT_FITS))
|
|
78
|
+
throw new Error(`${what}: fit is ${Object.keys(MOUNT_FITS).join(', ')} (got ${shown(fit)})`);
|
|
79
|
+
if (o.keepout != null && !(typeof o.keepout === 'number' && o.keepout > 0))
|
|
80
|
+
throw new Error(`${what}: keepout is a radius above 0, in mm from the hole's centre (got ${shown(o.keepout)})`);
|
|
81
|
+
if (o.set != null && (typeof o.set !== 'object' || Array.isArray(o.set)))
|
|
82
|
+
throw new Error(`${what}: set is the thread's figures as a design reads them (v.m2), not ${shown(o.set)}`);
|
|
66
83
|
let m;
|
|
67
|
-
try {
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
84
|
+
try {
|
|
85
|
+
m = fixingModel(thread, {}, { sets: o.sets });
|
|
86
|
+
} catch (e) {
|
|
87
|
+
throw new Error(`${what}: ${String(e.message).replace(/^fixingModel: /, '')}`);
|
|
88
|
+
} // (a name that is no thread, a thread with no rule set)
|
|
89
|
+
if (m.item !== 'thread')
|
|
90
|
+
throw new Error(
|
|
91
|
+
`${what}: name the thread alone ('${m.thread}'), not ${shown(thread)}: the hole is for any screw on it`,
|
|
92
|
+
);
|
|
93
|
+
if (o.set?.thread != null && String(o.set.thread) !== m.thread)
|
|
94
|
+
throw new Error(`${what}: set is ${shown(o.set.thread)}'s figures, and the hole is for ${m.thread}`);
|
|
95
|
+
const figure = MOUNT_FITS[fit],
|
|
96
|
+
own = o.set?.[figure],
|
|
97
|
+
ruled = m.figures[figure]?.value;
|
|
71
98
|
let d;
|
|
72
99
|
if (o.d != null) {
|
|
73
|
-
if (!(typeof o.d === 'number' && o.d > 0))
|
|
74
|
-
|
|
100
|
+
if (!(typeof o.d === 'number' && o.d > 0))
|
|
101
|
+
throw new Error(`${what}: d is the hole's diameter, in mm, above 0 (got ${shown(o.d)})`);
|
|
102
|
+
if (o.d <= m.major)
|
|
103
|
+
throw new Error(
|
|
104
|
+
`${what}: a ${o.d} mm hole is no wider than ${m.thread}'s ${m.major} mm thread (${m.set}.major_diameter): the screw would not pass. ${m.thread}'s clearance hole is ${ruled ?? 'not in its rule set'}${ruled != null ? ' mm' : ''}`,
|
|
105
|
+
);
|
|
75
106
|
d = o.d;
|
|
76
107
|
} else {
|
|
77
108
|
d = typeof own === 'number' ? own : ruled;
|
|
78
|
-
if (typeof d !== 'number')
|
|
109
|
+
if (typeof d !== 'number')
|
|
110
|
+
throw new Error(`${what}: ${m.thread} has no ${figure} in its rule set (${m.set}): give the hole as d`);
|
|
79
111
|
}
|
|
80
|
-
return {
|
|
112
|
+
return {
|
|
113
|
+
...hole(x, y, d),
|
|
114
|
+
...(o.keepout != null ? { keepout: o.keepout } : {}),
|
|
115
|
+
thread: m.thread,
|
|
116
|
+
fit: o.d != null ? 'given' : fit,
|
|
117
|
+
};
|
|
81
118
|
}
|
|
82
119
|
|
|
83
120
|
// An MX switch, PCB mount: two pins, the centre post and the two fixing pegs
|
|
84
121
|
export function mx(name, x, y, m, sch = {}) {
|
|
85
|
-
return {
|
|
86
|
-
|
|
122
|
+
return {
|
|
123
|
+
name,
|
|
124
|
+
ftype: 'simple_switch',
|
|
125
|
+
mpn: 'Cherry MX (PCB mount)',
|
|
126
|
+
package: 'Cherry MX, PCB mount',
|
|
127
|
+
x,
|
|
128
|
+
y,
|
|
129
|
+
layer: 'top',
|
|
130
|
+
sch,
|
|
131
|
+
pads: [
|
|
132
|
+
pad('pin1', m.pcb_pin1_x, m.pcb_pin1_y, m.pcb_pin_drill, m.pcb_pin_pad),
|
|
133
|
+
pad('pin2', m.pcb_pin2_x, m.pcb_pin2_y, m.pcb_pin_drill, m.pcb_pin_pad),
|
|
134
|
+
],
|
|
87
135
|
holes: [hole(0, 0, m.pcb_centre_hole), hole(-m.pcb_peg_x, 0, m.pcb_peg_hole), hole(m.pcb_peg_x, 0, m.pcb_peg_hole)],
|
|
88
|
-
courtyard: { w: m.pcb_body, h: m.pcb_body }
|
|
136
|
+
courtyard: { w: m.pcb_body, h: m.pcb_body },
|
|
137
|
+
}; // the housing's footprint on the board
|
|
89
138
|
}
|
|
90
139
|
|
|
91
140
|
// A Raspberry Pi Pico on header pins, USB at the back (+y): pins 1 to 20 down its left edge, 21 to 40 up its right
|
|
92
141
|
export function pico(name, x, y, p, sch = {}) {
|
|
93
142
|
const pins = [];
|
|
94
143
|
for (let n = 1; n <= 40; n++) {
|
|
95
|
-
const left = n <= 20,
|
|
96
|
-
|
|
144
|
+
const left = n <= 20,
|
|
145
|
+
i = left ? n - 1 : 40 - n;
|
|
146
|
+
pins.push(pad(`pin${n}`, ((left ? -1 : 1) * p.pin_rows) / 2, (19 / 2 - i) * p.pin_pitch, p.pin_hole, p.pin_pad));
|
|
97
147
|
}
|
|
98
|
-
return {
|
|
148
|
+
return {
|
|
149
|
+
name,
|
|
150
|
+
ftype: 'simple_chip',
|
|
151
|
+
mpn: 'Raspberry Pi Pico',
|
|
152
|
+
package: 'Raspberry Pi Pico, 0.1 in header pins',
|
|
153
|
+
x,
|
|
154
|
+
y,
|
|
155
|
+
layer: 'top',
|
|
156
|
+
sch,
|
|
157
|
+
pads: pins,
|
|
158
|
+
courtyard: { w: p.width, h: p.length },
|
|
159
|
+
};
|
|
99
160
|
}
|
|
100
161
|
// Where a Pico pin is, from its centre
|
|
101
|
-
export const picoPin = (n, p) => {
|
|
162
|
+
export const picoPin = (n, p) => {
|
|
163
|
+
const left = n <= 20,
|
|
164
|
+
i = left ? n - 1 : 40 - n;
|
|
165
|
+
return { x: ((left ? -1 : 1) * p.pin_rows) / 2, y: (19 / 2 - i) * p.pin_pitch };
|
|
166
|
+
};
|
|
102
167
|
// The Pico's GPIO pins down one edge: [{ pin, gpio }]
|
|
103
|
-
export const picoGpio = (side) =>
|
|
168
|
+
export const picoGpio = (side) =>
|
|
169
|
+
Object.entries(loadRuleSet('pico').rules[`gpio_${side}`].pins).map(([pin, gpio]) => ({ pin: Number(pin), gpio }));
|
|
104
170
|
|
|
105
171
|
// ---------- any board ----------
|
|
106
172
|
// Parts for any board, not only keyboards. Each returns a part as circuit.mjs describes it: put them in board.parts, join
|
|
107
173
|
// their pins with board.nets, and set board.autoroute. o (all optional): { rotation: 0 | 90 | 180 | 270, layer,
|
|
108
174
|
// mpn, labels: { pin1: 'GND', ... }, sch: { x, y }, model: { boxes: [{ min, max }] } (its 3D body in its own frame, z up
|
|
109
175
|
// from the board's face, mm) }. Pin labels name the pins in nets ('U1.GND') and on the schematic.
|
|
110
|
-
const chip = (name, x, y, o, more) => ({
|
|
111
|
-
|
|
176
|
+
const chip = (name, x, y, o, more) => ({
|
|
177
|
+
name,
|
|
178
|
+
ftype: 'simple_chip',
|
|
179
|
+
x,
|
|
180
|
+
y,
|
|
181
|
+
layer: o.layer ?? 'top',
|
|
182
|
+
rotation: o.rotation ?? 0,
|
|
183
|
+
mpn: o.mpn,
|
|
184
|
+
...(o.package ? { package: o.package } : {}),
|
|
185
|
+
courtyard: o.courtyard ?? null,
|
|
186
|
+
sch: { x: o.sch?.x ?? x / 2, y: o.sch?.y ?? y / 2, pinLabels: o.labels ?? {} },
|
|
187
|
+
...(o.model ? { model: o.model } : {}),
|
|
188
|
+
...more,
|
|
189
|
+
});
|
|
112
190
|
const pinNo = (p) => Number(p.pin.replace(/\D/g, ''));
|
|
113
191
|
// A rule set's pin map ({ "1": "GND", ... }) as pin labels ({ pin1: 'GND', ... })
|
|
114
|
-
const labelsFrom = (set, rule) =>
|
|
192
|
+
const labelsFrom = (set, rule) =>
|
|
193
|
+
Object.fromEntries(Object.entries(loadRuleSet(set).rules[rule].pins).map(([n, l]) => [`pin${n}`, l]));
|
|
115
194
|
|
|
116
195
|
/**
|
|
117
196
|
* Any standard footprint as a part, by its footprinter name: 'jst4_sh', 'pinrow4', 'soic8', '0603', 'sot23' ...
|
|
@@ -129,64 +208,169 @@ export const part = (name, footprint, x, y, o = {}) => chip(name, x, y, o, { foo
|
|
|
129
208
|
// apart, share one hole round both of theirs. Each switch's two pins keep their own holes: pin1 is MX's pin 1 and
|
|
130
209
|
// Choc's pin 1 (2.7 mm apart, behind the centre), pin2 MX's pin 2 and Choc's pin 2, each pair one pin, joined by a track
|
|
131
210
|
export function hybridSwitch(name, x, y, m, c, sch = {}) {
|
|
132
|
-
const pegX = (m.pcb_peg_x + c.pcb_peg_x) / 2,
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
211
|
+
const pegX = (m.pcb_peg_x + c.pcb_peg_x) / 2,
|
|
212
|
+
pegD = Math.abs(m.pcb_peg_x - c.pcb_peg_x) + Math.max(m.pcb_peg_hole, c.pcb_peg_hole); // round both pegs' holes
|
|
213
|
+
return {
|
|
214
|
+
name,
|
|
215
|
+
ftype: 'simple_switch',
|
|
216
|
+
mpn: 'Cherry MX or Kailh Choc v1 (PCB mount)',
|
|
217
|
+
package: 'Cherry MX / Kailh Choc v1 hybrid, PCB mount',
|
|
218
|
+
x,
|
|
219
|
+
y,
|
|
220
|
+
layer: 'top',
|
|
221
|
+
sch,
|
|
222
|
+
pads: [
|
|
223
|
+
pad('pin1', m.pcb_pin1_x, m.pcb_pin1_y, m.pcb_pin_drill, m.pcb_pin_pad),
|
|
224
|
+
pad('pin1', c.pcb_pin1_x, c.pcb_pin1_y, c.pcb_pin_drill, c.pcb_pin_pad),
|
|
225
|
+
pad('pin2', m.pcb_pin2_x, m.pcb_pin2_y, m.pcb_pin_drill, m.pcb_pin_pad),
|
|
226
|
+
pad('pin2', c.pcb_pin2_x, c.pcb_pin2_y, c.pcb_pin_drill, c.pcb_pin_pad),
|
|
227
|
+
],
|
|
136
228
|
holes: [hole(0, 0, Math.max(m.pcb_centre_hole, c.pcb_centre_hole)), hole(-pegX, 0, pegD), hole(pegX, 0, pegD)],
|
|
137
|
-
courtyard: { w: Math.max(m.pcb_body, c.pcb_body), h: Math.max(m.pcb_body, c.pcb_body) }
|
|
229
|
+
courtyard: { w: Math.max(m.pcb_body, c.pcb_body), h: Math.max(m.pcb_body, c.pcb_body) },
|
|
230
|
+
};
|
|
138
231
|
}
|
|
139
232
|
// A DO-35 axial diode (a 1N4148: d, the do35 rules) lying flat between its two leads, bent down 0.3 in apart: cathode
|
|
140
233
|
// on the left (a square pad, and the band on its body), anode on the right, turned by rotation. Its 3D model is the body
|
|
141
234
|
// and the leads, through the board (thickness) and trimmed below it
|
|
142
235
|
export function do35(name, x, y, d, { rotation = 0, thickness = 1.6, sch = {}, mpn = '1N4148', layer = 'top' } = {}) {
|
|
143
|
-
const h = d.pitch / 2,
|
|
144
|
-
|
|
145
|
-
|
|
236
|
+
const h = d.pitch / 2,
|
|
237
|
+
bl = d.body_length / 2,
|
|
238
|
+
r = d.body_d / 2,
|
|
239
|
+
l = d.lead_d / 2,
|
|
240
|
+
axis = r; // the body's axis, a radius up
|
|
241
|
+
return {
|
|
242
|
+
name,
|
|
243
|
+
ftype: 'simple_diode',
|
|
244
|
+
mpn,
|
|
245
|
+
package: 'DO-35, axial, 0.3 in',
|
|
246
|
+
x,
|
|
247
|
+
y,
|
|
248
|
+
layer,
|
|
249
|
+
rotation,
|
|
250
|
+
sch,
|
|
251
|
+
bom: false,
|
|
252
|
+
place: false,
|
|
253
|
+
pads: [
|
|
254
|
+
{ pin: 'cathode', x: -h, y: 0, hole: d.drill, outer: d.pad, rect: { w: d.pad, h: d.pad, offset: [0, 0] } },
|
|
255
|
+
pad('anode', h, 0, d.drill, d.pad),
|
|
256
|
+
],
|
|
146
257
|
courtyard: null,
|
|
147
|
-
model: {
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
258
|
+
model: {
|
|
259
|
+
boxes: [
|
|
260
|
+
{ min: [-bl, -r, 0], max: [bl, r, 2 * r] }, // the glass body (a box round it)
|
|
261
|
+
...[-1, 1].flatMap((s) => [
|
|
262
|
+
{
|
|
263
|
+
min: [Math.min(s * bl, s * h) - (s > 0 ? 0 : l), -l, axis - l],
|
|
264
|
+
max: [Math.max(s * bl, s * h) + (s > 0 ? l : 0), l, axis + l],
|
|
265
|
+
}, // out along the axis
|
|
266
|
+
{ min: [s * h - l, -l, -thickness - d.lead_out], max: [s * h + l, l, axis + l] },
|
|
267
|
+
]),
|
|
268
|
+
],
|
|
269
|
+
},
|
|
270
|
+
}; // bent down through the board
|
|
152
271
|
}
|
|
153
272
|
|
|
154
273
|
// A single-row 0.1 in strip's 3D model, for header() parts (its pins along the part's y, as header() lays them):
|
|
155
274
|
// kind 'socket', a female socket's body (height tall) on the board; 'pins', a male header's spacer on the board and its
|
|
156
275
|
// pins above it (pin_above past the spacer) and through it
|
|
157
|
-
export function stripModel(
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
276
|
+
export function stripModel(
|
|
277
|
+
n,
|
|
278
|
+
{
|
|
279
|
+
pitch = 2.54,
|
|
280
|
+
kind = 'socket',
|
|
281
|
+
height = 8.5,
|
|
282
|
+
spacer = 2.5,
|
|
283
|
+
pin = 0.64,
|
|
284
|
+
pin_above = 6,
|
|
285
|
+
thickness = 1.6,
|
|
286
|
+
below = 3,
|
|
287
|
+
} = {},
|
|
288
|
+
) {
|
|
289
|
+
const half = (n * pitch) / 2,
|
|
290
|
+
ys = Array.from({ length: n }, (_, i) => ((n - 1) / 2 - i) * pitch);
|
|
291
|
+
if (kind === 'socket')
|
|
292
|
+
return {
|
|
293
|
+
boxes: [
|
|
294
|
+
{ min: [-pitch / 2, -half, 0], max: [pitch / 2, half, height] },
|
|
295
|
+
...ys.map((y) => ({ min: [-pin / 2, y - pin / 2, -thickness - below], max: [pin / 2, y + pin / 2, 0] })),
|
|
296
|
+
],
|
|
297
|
+
};
|
|
298
|
+
return {
|
|
299
|
+
boxes: [
|
|
300
|
+
{ min: [-pitch / 2, -half, 0], max: [pitch / 2, half, spacer] },
|
|
301
|
+
...ys.map((y) => ({
|
|
302
|
+
min: [-pin / 2, y - pin / 2, -thickness - below],
|
|
303
|
+
max: [pin / 2, y + pin / 2, spacer + pin_above],
|
|
304
|
+
})),
|
|
305
|
+
],
|
|
306
|
+
};
|
|
162
307
|
}
|
|
163
308
|
|
|
164
309
|
export function header(name, x, y, r, o = {}) {
|
|
165
|
-
|
|
310
|
+
if (!(Number.isInteger(o.pins) && o.pins > 0))
|
|
311
|
+
throw new Error(
|
|
312
|
+
`header ${name}: how many pins? pins is ${shown(o.pins)}, and it must be a whole number above 0: header('${name}', x, y, r, { pins: 4 })`,
|
|
313
|
+
);
|
|
314
|
+
const n = o.pins,
|
|
315
|
+
two = (o.rows ?? 1) === 2,
|
|
316
|
+
pads = [];
|
|
166
317
|
for (let i = 0; i < n; i++) {
|
|
167
318
|
const py = ((n - 1) / 2 - i) * r.pitch;
|
|
168
319
|
pads.push(pad(`pin${i + 1}`, two ? -r.row_spacing / 2 : 0, py, r.drill, r.pad));
|
|
169
320
|
if (two) pads.push(pad(`pin${2 * n - i}`, r.row_spacing / 2, py, r.drill, r.pad));
|
|
170
321
|
}
|
|
171
|
-
return chip(
|
|
322
|
+
return chip(
|
|
323
|
+
name,
|
|
324
|
+
x,
|
|
325
|
+
y,
|
|
326
|
+
{ package: `${two ? '2 × ' : ''}${n}-pin header, ${r.pitch} mm`, ...o },
|
|
327
|
+
{ pads: pads.sort((a, b) => pinNo(a) - pinNo(b)) },
|
|
328
|
+
);
|
|
172
329
|
}
|
|
173
330
|
|
|
174
331
|
/** A Seeed Studio XIAO module (any of the family) on header pins, USB at +y, from the xiao rules; pins labelled D0..D10, 5V, GND, 3V3. */
|
|
175
332
|
export const xiao = (name, x, y, r, o = {}) =>
|
|
176
|
-
header(name, x, y, r, {
|
|
333
|
+
header(name, x, y, r, {
|
|
334
|
+
pins: r.pins / 2,
|
|
335
|
+
rows: 2,
|
|
336
|
+
mpn: 'Seeed Studio XIAO',
|
|
337
|
+
package: 'Seeed Studio XIAO, 0.1 in header pins',
|
|
338
|
+
courtyard: { w: r.width, h: r.length },
|
|
339
|
+
labels: labelsFrom('xiao', 'pins'),
|
|
340
|
+
...o,
|
|
341
|
+
});
|
|
177
342
|
|
|
178
343
|
/** A Qwiic / STEMMA QT socket (JST SH, 4 pins, side entry), from the qwiic rules: the plug goes in from +y, the tabs' side. */
|
|
179
344
|
export function qwiic(name, x, y, r, o = {}) {
|
|
180
|
-
const n = r.pins,
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
345
|
+
const n = r.pins,
|
|
346
|
+
smd = (k, x, y, w, h) => ({ pin: `pin${k}`, smd: true, hint: String(k), x, y, w, h });
|
|
347
|
+
const pads = Array.from({ length: n }, (_, i) =>
|
|
348
|
+
smd(i + 1, (i - (n - 1) / 2) * r.pitch, r.pad_y, r.pad_w, r.pad_h),
|
|
349
|
+
).concat([-1, 1].map((side, i) => smd(n + i + 1, side * r.tab_x, r.tab_y, r.tab_w, r.tab_h)));
|
|
350
|
+
return chip(
|
|
351
|
+
name,
|
|
352
|
+
x,
|
|
353
|
+
y,
|
|
354
|
+
{
|
|
355
|
+
mpn: 'JST SM04B-SRSS-TB',
|
|
356
|
+
package: 'JST SH, 4 pins, side entry',
|
|
357
|
+
labels: { ...labelsFrom('qwiic', 'pins'), pin5: 'TAB1', pin6: 'TAB2' },
|
|
358
|
+
...o,
|
|
359
|
+
},
|
|
360
|
+
{ pads },
|
|
361
|
+
);
|
|
184
362
|
}
|
|
185
363
|
|
|
186
364
|
/** A JST PH socket (2.0 mm, through-hole), from the jstph rules: o.pins pins in a row along x (default 2). */
|
|
187
365
|
export function jstph(name, x, y, r, o = {}) {
|
|
188
366
|
const n = o.pins ?? 2;
|
|
189
|
-
return chip(
|
|
367
|
+
return chip(
|
|
368
|
+
name,
|
|
369
|
+
x,
|
|
370
|
+
y,
|
|
371
|
+
{ mpn: `JST B${n}B-PH-K-S`, package: `JST PH, ${n} pins`, ...o },
|
|
372
|
+
{ pads: Array.from({ length: n }, (_, i) => pad(`pin${i + 1}`, (i - (n - 1) / 2) * r.pitch, 0, r.drill, r.pad)) },
|
|
373
|
+
);
|
|
190
374
|
}
|
|
191
375
|
|
|
192
376
|
// ---------- the keyboard ----------
|
|
@@ -195,23 +379,43 @@ export function jstph(name, x, y, r, o = {}) {
|
|
|
195
379
|
// the columns whose positions they are closest to (so a row with fewer keys leaves the columns it has no key for).
|
|
196
380
|
export function fromLayout(list, pitch) {
|
|
197
381
|
const ks = list.map((k, i) => ({ label: k.label, u: k.u, n: i + 1, r: k.index, x: k.x * pitch, y: k.y * pitch }));
|
|
198
|
-
const rows = [...new Set(ks.map((k) => k.r))].sort((a, b) => a - b),
|
|
199
|
-
|
|
382
|
+
const rows = [...new Set(ks.map((k) => k.r))].sort((a, b) => a - b),
|
|
383
|
+
inRow = (r) => ks.filter((k) => k.r === r).sort((a, b) => a.x - b.x);
|
|
384
|
+
const anchors = inRow(rows.reduce((best, r) => (inRow(r).length > inRow(best).length ? r : best), rows[0])).map(
|
|
385
|
+
(k) => k.x,
|
|
386
|
+
);
|
|
200
387
|
for (const r of rows) {
|
|
201
|
-
const row = inRow(r),
|
|
388
|
+
const row = inRow(r),
|
|
389
|
+
n = row.length,
|
|
390
|
+
M = anchors.length,
|
|
391
|
+
f = [],
|
|
392
|
+
from = [];
|
|
202
393
|
// f[i][j]: the least total offset placing the first i + 1 keys with key i on column j (columns rising left to right)
|
|
203
394
|
for (let i = 0; i < n; i++) {
|
|
204
|
-
f[i] = [];
|
|
395
|
+
f[i] = [];
|
|
396
|
+
from[i] = [];
|
|
205
397
|
for (let j = 0; j < M; j++) {
|
|
206
398
|
const cost = Math.abs(row[i].x - anchors[j]);
|
|
207
|
-
if (i === 0) {
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
399
|
+
if (i === 0) {
|
|
400
|
+
f[i][j] = cost;
|
|
401
|
+
continue;
|
|
402
|
+
}
|
|
403
|
+
let best = Infinity,
|
|
404
|
+
at = -1;
|
|
405
|
+
for (let q = 0; q < j; q++)
|
|
406
|
+
if (f[i - 1][q] < best) {
|
|
407
|
+
best = f[i - 1][q];
|
|
408
|
+
at = q;
|
|
409
|
+
}
|
|
410
|
+
f[i][j] = best + cost;
|
|
411
|
+
from[i][j] = at;
|
|
211
412
|
}
|
|
212
413
|
}
|
|
213
414
|
let j = f[n - 1].indexOf(Math.min(...f[n - 1]));
|
|
214
|
-
for (let i = n - 1; i >= 0; i--) {
|
|
415
|
+
for (let i = n - 1; i >= 0; i--) {
|
|
416
|
+
row[i].c = j;
|
|
417
|
+
j = from[i][j];
|
|
418
|
+
}
|
|
215
419
|
}
|
|
216
420
|
return ks;
|
|
217
421
|
}
|
|
@@ -230,19 +434,34 @@ export function fromLayout(list, pitch) {
|
|
|
230
434
|
// across every lane nearer than it, so a lane may be given a nearer place only if its run covers none of the other
|
|
231
435
|
// lanes' pins. { id: place }, 0 the nearest. (When no lane qualifies, the shortest run takes the place: the checks say)
|
|
232
436
|
export function laneOrder(lanes) {
|
|
233
|
-
const out = {},
|
|
437
|
+
const out = {},
|
|
438
|
+
left = [...lanes],
|
|
439
|
+
covers = (l, y) => y > Math.min(l.from, l.to) - 1e-9 && y < Math.max(l.from, l.to) + 1e-9;
|
|
234
440
|
for (let place = 0; left.length; place++) {
|
|
235
|
-
const next =
|
|
236
|
-
|
|
441
|
+
const next =
|
|
442
|
+
left.find((l) => left.every((o) => o === l || !covers(l, o.to))) ??
|
|
443
|
+
[...left].sort((a, b) => Math.abs(a.to - a.from) - Math.abs(b.to - b.from))[0];
|
|
444
|
+
out[next.id] = place;
|
|
445
|
+
left.splice(left.indexOf(next), 1);
|
|
237
446
|
}
|
|
238
447
|
return out;
|
|
239
448
|
}
|
|
240
449
|
|
|
241
450
|
export function keyboard(v, keys) {
|
|
242
|
-
const m = v.mx,
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
451
|
+
const m = v.mx,
|
|
452
|
+
p = v.pico,
|
|
453
|
+
d = v.sod123,
|
|
454
|
+
lane = v.track + v.clear,
|
|
455
|
+
half = m.pitch / 2,
|
|
456
|
+
under = v.controller === 'under';
|
|
457
|
+
const rows = [...new Set(keys.map((k) => k.r))].sort((a, b) => a - b),
|
|
458
|
+
cols = [...new Set(keys.map((k) => k.c))].sort((a, b) => a - b);
|
|
459
|
+
const keyBox = {
|
|
460
|
+
left: Math.min(...keys.map((k) => k.x - (k.u || 1) * half)),
|
|
461
|
+
right: Math.max(...keys.map((k) => k.x + (k.u || 1) * half)),
|
|
462
|
+
top: Math.max(...keys.map((k) => k.y)) + half,
|
|
463
|
+
bottom: Math.min(...keys.map((k) => k.y)) - half,
|
|
464
|
+
};
|
|
246
465
|
const rowY = (r) => keys.find((k) => k.r === r).y;
|
|
247
466
|
|
|
248
467
|
// Around each switch (from its centre): the diode on the back below the post, its anode lane right of the right peg,
|
|
@@ -251,66 +470,139 @@ export function keyboard(v, keys) {
|
|
|
251
470
|
// On the back, turned half round, the diode's pad 1 (its cathode, as KiCad and assemblers number it) is at -pad_x
|
|
252
471
|
// and its anode at +pad_x: the anode by its switch's pin, the cathode on the row line's side
|
|
253
472
|
const diode = { x: anodeX - d.pad_x, y: -(m.pcb_centre_hole / 2 + v.clear + d.pad_h / 2) };
|
|
254
|
-
const cathodeX = anodeX - 2 * d.pad_x,
|
|
255
|
-
|
|
473
|
+
const cathodeX = anodeX - 2 * d.pad_x,
|
|
474
|
+
lineY = diode.y - d.pad_h / 2 - v.clear - v.track / 2;
|
|
475
|
+
const jogX = -(m.pcb_centre_hole / 2 + (m.pcb_peg_x - m.pcb_peg_hole / 2 - m.pcb_centre_hole / 2) / 2),
|
|
476
|
+
slant = Math.abs(m.pcb_pin2_x) - Math.abs(jogX);
|
|
256
477
|
const pegEdge = m.pcb_peg_x + m.pcb_peg_hole / 2 + v.clear + v.track / 2; // a track this far from a key's centre clears its pegs
|
|
257
478
|
// Between key rows r and r + 1 the front copper is free from below row r's posts to above row r + 1's pins
|
|
258
479
|
const bandTop = (r) => rowY(r) - m.pcb_centre_hole / 2 - v.clear - v.track / 2;
|
|
259
480
|
const bandBottom = (r) => rowY(r + 1) + m.pcb_pin1_y + m.pcb_pin_pad / 2 + v.clear + v.track / 2;
|
|
260
481
|
|
|
261
482
|
// ---- the Pico ----
|
|
262
|
-
const SX = 3,
|
|
263
|
-
|
|
483
|
+
const SX = 3,
|
|
484
|
+
SY = 2.5; // schematic grid
|
|
485
|
+
const other = Object.entries(loadRuleSet('pico').rules.other_pins.pins).map(([pin, name]) => ({
|
|
486
|
+
pin: Number(pin),
|
|
487
|
+
gpio: name,
|
|
488
|
+
}));
|
|
264
489
|
const gpio = [...picoGpio('left'), ...picoGpio('right')];
|
|
265
490
|
const pinLabels = Object.fromEntries([...gpio, ...other].map((g) => [`pin${g.pin}`, g.gpio]));
|
|
266
|
-
const sch = { x: (cols.length + 1.5) * SX, y: -(rows.length - 1) * SY / 2, pinLabels };
|
|
267
|
-
let left = keyBox.left - v.margin,
|
|
491
|
+
const sch = { x: (cols.length + 1.5) * SX, y: (-(rows.length - 1) * SY) / 2, pinLabels };
|
|
492
|
+
let left = keyBox.left - v.margin,
|
|
493
|
+
right = keyBox.right + v.margin,
|
|
494
|
+
pico0,
|
|
495
|
+
pinAt,
|
|
496
|
+
pinRows = [];
|
|
268
497
|
if (under) {
|
|
269
498
|
// Its pin rows in the gaps below key rows mcu_row and mcu_row + 1: clear of the row line above (back copper), the
|
|
270
499
|
// next row's pins below and the switch housings either side, and 0.7 in apart
|
|
271
|
-
const r0 = rows[v.mcu_row],
|
|
272
|
-
|
|
500
|
+
const r0 = rows[v.mcu_row],
|
|
501
|
+
r1 = rows[v.mcu_row + 1],
|
|
502
|
+
r2 = rows[v.mcu_row + 2];
|
|
503
|
+
if (r2 == null)
|
|
504
|
+
throw new Error(
|
|
505
|
+
`mcu_row ${v.mcu_row}: the Pico's pins need the two gaps below it, and there are ${rows.length} rows`,
|
|
506
|
+
);
|
|
273
507
|
const keep = p.pin_pad / 2 + v.clear + v.track / 2;
|
|
274
508
|
const bodyKeep = m.pcb_body / 2 + v.clear + p.pin_pad / 2; // header joints stay out from under the switch housings
|
|
275
|
-
const hi = (r) => Math.min(rowY(r) + lineY - keep, rowY(r) - bodyKeep),
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
const
|
|
509
|
+
const hi = (r) => Math.min(rowY(r) + lineY - keep, rowY(r) - bodyKeep),
|
|
510
|
+
lo = (r) =>
|
|
511
|
+
Math.max(rowY(r + 1) + m.pcb_pin1_y + m.pcb_pin_pad / 2 + v.clear + p.pin_pad / 2, rowY(r + 1) + bodyKeep);
|
|
512
|
+
const top = Math.min(hi(r0), hi(r1) + p.pin_rows),
|
|
513
|
+
bottom = Math.max(lo(r0), lo(r1) + p.pin_rows);
|
|
514
|
+
if (top < bottom) throw new Error("the Pico's pin rows don't fit between the key rows");
|
|
515
|
+
const ya = (top + bottom) / 2,
|
|
516
|
+
cy = ya - p.pin_rows / 2,
|
|
517
|
+
toLeft = v.mcu_side !== 'right';
|
|
279
518
|
const cx = toLeft ? left + p.usb_overhang + p.length / 2 : right - p.usb_overhang - p.length / 2;
|
|
280
519
|
// Seen from above the board the Pico is upside down (mirrored), USB towards mcu_side
|
|
281
|
-
pinAt = (n) => {
|
|
520
|
+
pinAt = (n) => {
|
|
521
|
+
const q = picoPin(n, p),
|
|
522
|
+
mx_ = -q.x,
|
|
523
|
+
my = q.y;
|
|
524
|
+
return toLeft ? { x: cx - my, y: cy + mx_ } : { x: cx + my, y: cy - mx_ };
|
|
525
|
+
};
|
|
282
526
|
pico0 = { x: cx, y: cy, toLeft };
|
|
283
|
-
for (const [gap, ys] of [
|
|
284
|
-
|
|
527
|
+
for (const [gap, ys] of [
|
|
528
|
+
[r0, ya],
|
|
529
|
+
[r1, ya - p.pin_rows],
|
|
530
|
+
]) {
|
|
531
|
+
const xs = Array.from({ length: 40 }, (_, i) => pinAt(i + 1))
|
|
532
|
+
.filter((q) => Math.abs(q.y - ys) < p.pin_pitch / 2)
|
|
533
|
+
.map((q) => q.x)
|
|
534
|
+
.sort((a, b) => a - b);
|
|
285
535
|
pinRows.push({ gap, y: ys, xs, keep });
|
|
286
536
|
}
|
|
287
537
|
} else {
|
|
288
538
|
// Beside the keys, mcu_gap off them, or further out when the lanes to its pins (one a column on the front, one a
|
|
289
539
|
// row on the back, a lane apart) wouldn't fit between the keys and its pins
|
|
290
|
-
const lanesWide = Math.max(cols.length, rows.length) * lane,
|
|
291
|
-
|
|
292
|
-
|
|
540
|
+
const lanesWide = Math.max(cols.length, rows.length) * lane,
|
|
541
|
+
pinsIn = p.width / 2 + picoPin(1, p).x - p.pin_pad / 2 - v.clear - v.track / 2; // the left pins' near edge and clearance, in from the Pico's edge
|
|
542
|
+
const cx = keyBox.right + Math.max(v.mcu_gap, lanesWide + v.clear - pinsIn) + p.width / 2,
|
|
543
|
+
cy = (keyBox.top + keyBox.bottom) / 2;
|
|
544
|
+
pinAt = (n) => {
|
|
545
|
+
const q = picoPin(n, p);
|
|
546
|
+
return { x: cx + q.x, y: cy + q.y };
|
|
547
|
+
};
|
|
293
548
|
pico0 = { x: cx, y: cy };
|
|
294
549
|
right = cx + p.width / 2 + v.margin;
|
|
295
550
|
}
|
|
296
|
-
const picoPart = {
|
|
297
|
-
|
|
298
|
-
|
|
551
|
+
const picoPart = {
|
|
552
|
+
name: 'U1',
|
|
553
|
+
ftype: 'simple_chip',
|
|
554
|
+
mpn: 'Raspberry Pi Pico',
|
|
555
|
+
package: 'Raspberry Pi Pico, 0.1 in header pins',
|
|
556
|
+
x: pico0.x,
|
|
557
|
+
y: pico0.y,
|
|
558
|
+
layer: 'top',
|
|
559
|
+
sch,
|
|
560
|
+
pads: Array.from({ length: 40 }, (_, i) => {
|
|
561
|
+
const q = pinAt(i + 1);
|
|
562
|
+
return pad(`pin${i + 1}`, q.x - pico0.x, q.y - pico0.y, p.pin_hole, p.pin_pad);
|
|
563
|
+
}),
|
|
564
|
+
courtyard: under ? null : { w: p.width, h: p.length },
|
|
565
|
+
};
|
|
299
566
|
|
|
300
|
-
const parts = [picoPart],
|
|
567
|
+
const parts = [picoPart],
|
|
568
|
+
traces = [];
|
|
301
569
|
const pts = (list) => list.map(([x, y]) => ({ x, y })); // a track's corners between its two pads, on the board
|
|
302
570
|
for (const k of keys) {
|
|
303
|
-
parts.push(mx(`K${k.n}`, k.x, k.y, m, { x: k.c * SX, y: -k.r * SY }),
|
|
304
|
-
|
|
305
|
-
|
|
571
|
+
parts.push(mx(`K${k.n}`, k.x, k.y, m, { x: k.c * SX, y: -k.r * SY }), {
|
|
572
|
+
name: `D${k.n}`,
|
|
573
|
+
ftype: 'simple_diode',
|
|
574
|
+
footprint: 'sod123',
|
|
575
|
+
package: 'SOD-123',
|
|
576
|
+
mpn: '1N4148W',
|
|
577
|
+
x: k.x + diode.x,
|
|
578
|
+
y: k.y + diode.y,
|
|
579
|
+
layer: 'bottom',
|
|
580
|
+
rotation: 180,
|
|
581
|
+
sch: { x: k.c * SX + 1, y: -k.r * SY - 0.8 },
|
|
582
|
+
});
|
|
583
|
+
traces.push({
|
|
584
|
+
from: [`D${k.n}`, 'anode'],
|
|
585
|
+
to: [`K${k.n}`, 'pin1'],
|
|
586
|
+
width: v.track,
|
|
587
|
+
path: pts([[k.x + anodeX, k.y + m.pcb_pin1_y]]),
|
|
588
|
+
});
|
|
306
589
|
}
|
|
307
590
|
|
|
308
591
|
// ---- rows: cathode to cathode along the back ----
|
|
309
592
|
for (const r of rows) {
|
|
310
593
|
const ks = keys.filter((k) => k.r === r).sort((a, b) => a.x - b.x);
|
|
311
594
|
for (let i = 1; i < ks.length; i++) {
|
|
312
|
-
const a = ks[i - 1],
|
|
313
|
-
|
|
595
|
+
const a = ks[i - 1],
|
|
596
|
+
b = ks[i];
|
|
597
|
+
traces.push({
|
|
598
|
+
from: [`D${a.n}`, 'cathode'],
|
|
599
|
+
to: [`D${b.n}`, 'cathode'],
|
|
600
|
+
width: v.track,
|
|
601
|
+
path: pts([
|
|
602
|
+
[a.x + cathodeX, a.y + lineY],
|
|
603
|
+
[b.x + cathodeX, b.y + lineY],
|
|
604
|
+
]),
|
|
605
|
+
});
|
|
314
606
|
}
|
|
315
607
|
}
|
|
316
608
|
|
|
@@ -318,7 +610,8 @@ export function keyboard(v, keys) {
|
|
|
318
610
|
// Down the lane between post and left peg; between rows, across the free band to the next key's lane (a key of
|
|
319
611
|
// another column in the way: through the gap between two keys of that row); past the Pico's pins, between two of them
|
|
320
612
|
const corridor = (r, x) => {
|
|
321
|
-
const ks = keys.filter((k) => k.r === r).sort((a, b) => a.x - b.x),
|
|
613
|
+
const ks = keys.filter((k) => k.r === r).sort((a, b) => a.x - b.x),
|
|
614
|
+
gaps = [];
|
|
322
615
|
for (let i = 1; i < ks.length; i++) gaps.push([ks[i - 1].x + pegEdge, ks[i].x - pegEdge]);
|
|
323
616
|
gaps.push([-Infinity, ks[0].x - pegEdge], [ks.at(-1).x + pegEdge, Infinity]);
|
|
324
617
|
const ok = gaps.filter(([a, b]) => b - a > 0).map(([a, b]) => Math.min(Math.max(x, a + v.track), b - v.track));
|
|
@@ -333,9 +626,11 @@ export function keyboard(v, keys) {
|
|
|
333
626
|
let x = A.x + jogX;
|
|
334
627
|
const pts = [[x, A.y + m.pcb_pin2_y - slant]];
|
|
335
628
|
for (let r = A.r; r < B.r; r++) {
|
|
336
|
-
const next = rows[rows.indexOf(r) + 1],
|
|
629
|
+
const next = rows[rows.indexOf(r) + 1],
|
|
630
|
+
target = next === B.r ? B.x + jogX : corridor(next, x);
|
|
337
631
|
pts.push([x, bandTop(r)]);
|
|
338
|
-
const pr = pinRows.find((q) => q.gap === r),
|
|
632
|
+
const pr = pinRows.find((q) => q.gap === r),
|
|
633
|
+
xg = pr && throughPins(pr, x, target, target);
|
|
339
634
|
if (xg != null) pts.push([xg, pr.y + pr.keep], [xg, pr.y - pr.keep]);
|
|
340
635
|
pts.push([target, bandBottom(r)]);
|
|
341
636
|
x = target;
|
|
@@ -348,27 +643,49 @@ export function keyboard(v, keys) {
|
|
|
348
643
|
for (const c of cols) {
|
|
349
644
|
const ks = keys.filter((k) => k.c === c).sort((a, b) => a.r - b.r);
|
|
350
645
|
for (let j = 1; j < ks.length; j++) {
|
|
351
|
-
const a = ks[j - 1],
|
|
646
|
+
const a = ks[j - 1],
|
|
647
|
+
b = ks[j];
|
|
352
648
|
traces.push({ from: [`K${a.n}`, 'pin2'], to: [`K${b.n}`, 'pin2'], width: v.track, path: pts(columnPath(a, b)) });
|
|
353
649
|
}
|
|
354
650
|
}
|
|
355
651
|
|
|
356
652
|
// ---- the Pico's connections ----
|
|
357
|
-
const rowPin = {},
|
|
653
|
+
const rowPin = {},
|
|
654
|
+
colPin = {};
|
|
358
655
|
if (under) {
|
|
359
656
|
// Each row and column takes the free GPIO nearest it, nearest pairs first; then a track the autorouter finds
|
|
360
|
-
const ends = [
|
|
361
|
-
...
|
|
657
|
+
const ends = [
|
|
658
|
+
...rows.map((r) => ({
|
|
659
|
+
kind: 'row',
|
|
660
|
+
id: r,
|
|
661
|
+
at: keys
|
|
662
|
+
.filter((k) => k.r === r)
|
|
663
|
+
.map((k) => ({ x: k.x + cathodeX, y: k.y + diode.y, sel: [`D${k.n}`, 'cathode'] })),
|
|
664
|
+
})),
|
|
665
|
+
...cols.map((c) => ({
|
|
666
|
+
kind: 'col',
|
|
667
|
+
id: c,
|
|
668
|
+
at: keys
|
|
669
|
+
.filter((k) => k.c === c)
|
|
670
|
+
.map((k) => ({ x: k.x + m.pcb_pin2_x, y: k.y + m.pcb_pin2_y, sel: [`K${k.n}`, 'pin2'] })),
|
|
671
|
+
})),
|
|
672
|
+
];
|
|
362
673
|
const free = [...gpio];
|
|
363
674
|
const dist = (e, g) => Math.min(...e.at.map((q) => Math.hypot(q.x - pinAt(g.pin).x, q.y - pinAt(g.pin).y)));
|
|
364
675
|
const left_ = [...ends];
|
|
365
676
|
while (left_.length) {
|
|
366
677
|
if (!free.length) throw new Error(`the Pico has ${gpio.length} GPIO; this matrix needs ${ends.length}`);
|
|
367
678
|
let best = null;
|
|
368
|
-
for (const e of left_)
|
|
369
|
-
|
|
679
|
+
for (const e of left_)
|
|
680
|
+
for (const g of free) {
|
|
681
|
+
const dd = dist(e, g);
|
|
682
|
+
if (!best || dd < best.dd) best = { e, g, dd };
|
|
683
|
+
}
|
|
684
|
+
left_.splice(left_.indexOf(best.e), 1);
|
|
685
|
+
free.splice(free.indexOf(best.g), 1);
|
|
370
686
|
(best.e.kind === 'row' ? rowPin : colPin)[best.e.id] = best.g;
|
|
371
|
-
const q = pinAt(best.g.pin),
|
|
687
|
+
const q = pinAt(best.g.pin),
|
|
688
|
+
near = [...best.e.at].sort((a, b) => Math.hypot(a.x - q.x, a.y - q.y) - Math.hypot(b.x - q.x, b.y - q.y))[0];
|
|
372
689
|
traces.push({ from: near.sel, to: ['U1', `pin${best.g.pin}`], width: v.track }); // no path: the autorouter's
|
|
373
690
|
}
|
|
374
691
|
} else {
|
|
@@ -378,36 +695,78 @@ export function keyboard(v, keys) {
|
|
|
378
695
|
// the keys, right, and up or down a lane (front) to its pin's height and in. Each lane runs in to its pin across
|
|
379
696
|
// the lanes nearer the Pico, so those must end before it: lanes are given out nearest first to whichever would
|
|
380
697
|
// cross none of the rest (laneOrder), and the depths below the keys the same way
|
|
381
|
-
const nearPins = pinAt(1).x - p.pin_pad / 2 - v.clear - v.track / 2,
|
|
698
|
+
const nearPins = pinAt(1).x - p.pin_pad / 2 - v.clear - v.track / 2,
|
|
699
|
+
free = picoGpio('left'),
|
|
700
|
+
take = (pin) =>
|
|
701
|
+
free.splice(
|
|
702
|
+
free.findIndex((g) => g.pin === pin),
|
|
703
|
+
1,
|
|
704
|
+
)[0];
|
|
382
705
|
let above = Infinity; // the last row's pin: the next row's is below it, leaving enough below for the rest
|
|
383
706
|
rows.forEach((r, i) => {
|
|
384
|
-
const y = rowY(r) + lineY,
|
|
385
|
-
|
|
707
|
+
const y = rowY(r) + lineY,
|
|
708
|
+
rest = rows.length - 1 - i;
|
|
709
|
+
const best = free
|
|
710
|
+
.filter((g) => pinAt(g.pin).y < above && free.filter((o) => pinAt(o.pin).y < pinAt(g.pin).y).length >= rest)
|
|
711
|
+
.sort((a, b) => Math.abs(pinAt(a.pin).y - y) - Math.abs(pinAt(b.pin).y - y))[0];
|
|
386
712
|
if (!best) throw new Error(`the Pico's left edge has no GPIO left for row ${r}`);
|
|
387
|
-
rowPin[r] = take(best.pin);
|
|
713
|
+
rowPin[r] = take(best.pin);
|
|
714
|
+
above = pinAt(best.pin).y;
|
|
388
715
|
});
|
|
389
716
|
// The columns' pins: the nearest to the runs below the keys, all above them or all below (lanes up or lanes
|
|
390
717
|
// down, not both: their runs would cross each other's lanes), above when there are enough
|
|
391
|
-
const depthLine = keyBox.bottom - (cols.length + 1) / 2 * lane;
|
|
392
|
-
const byDepth = (list) =>
|
|
393
|
-
|
|
718
|
+
const depthLine = keyBox.bottom - ((cols.length + 1) / 2) * lane;
|
|
719
|
+
const byDepth = (list) =>
|
|
720
|
+
[...list].sort((a, b) => Math.abs(pinAt(a.pin).y - depthLine) - Math.abs(pinAt(b.pin).y - depthLine));
|
|
721
|
+
const over = free.filter((g) => pinAt(g.pin).y > depthLine),
|
|
722
|
+
belowLine = free.filter((g) => pinAt(g.pin).y <= depthLine);
|
|
394
723
|
const nearDepth = byDepth(over.length >= cols.length ? over : belowLine.length >= cols.length ? belowLine : free);
|
|
395
|
-
if (nearDepth.length < cols.length)
|
|
396
|
-
|
|
724
|
+
if (nearDepth.length < cols.length)
|
|
725
|
+
throw new Error(
|
|
726
|
+
`${cols.length} columns need ${cols.length} more GPIO on the Pico's left edge; ${nearDepth.length} are left`,
|
|
727
|
+
);
|
|
728
|
+
cols.forEach((c, i) => {
|
|
729
|
+
colPin[c] = nearDepth[i];
|
|
730
|
+
});
|
|
397
731
|
const rowLane = laneOrder(rows.map((r) => ({ id: r, from: rowY(r) + lineY, to: pinAt(rowPin[r].pin).y })));
|
|
398
732
|
for (const r of rows) {
|
|
399
|
-
const last = keys
|
|
400
|
-
|
|
401
|
-
|
|
733
|
+
const last = keys
|
|
734
|
+
.filter((k) => k.r === r)
|
|
735
|
+
.sort((a, b) => a.x - b.x)
|
|
736
|
+
.at(-1),
|
|
737
|
+
pinY = pinAt(rowPin[r].pin).y,
|
|
738
|
+
laneX = nearPins - rowLane[r] * lane;
|
|
739
|
+
traces.push({
|
|
740
|
+
from: [`D${last.n}`, 'cathode'],
|
|
741
|
+
to: ['U1', `pin${rowPin[r].pin}`],
|
|
742
|
+
width: v.track,
|
|
743
|
+
path: pts([
|
|
744
|
+
[last.x + cathodeX, last.y + lineY],
|
|
745
|
+
[laneX, last.y + lineY],
|
|
746
|
+
[laneX, pinY],
|
|
747
|
+
]),
|
|
748
|
+
});
|
|
402
749
|
}
|
|
403
750
|
// The depths: a lane's run below the keys crosses the lanes further out on its way in, so where their pins are
|
|
404
751
|
// above the runs the nearer lane runs deeper (and ends lower), where below, shallower
|
|
405
752
|
const pinsAbove = cols.filter((c) => pinAt(colPin[c].pin).y > depthLine).length >= cols.length / 2;
|
|
406
753
|
const colLane = laneOrder(cols.map((c) => ({ id: c, from: depthLine, to: pinAt(colPin[c].pin).y })));
|
|
407
754
|
cols.forEach((c) => {
|
|
408
|
-
const last = keys.filter((k) => k.c === c).sort((a, b) => b.r - a.r)[0],
|
|
409
|
-
|
|
410
|
-
|
|
755
|
+
const last = keys.filter((k) => k.c === c).sort((a, b) => b.r - a.r)[0],
|
|
756
|
+
i = colLane[c],
|
|
757
|
+
depth = keyBox.bottom - (pinsAbove ? cols.length - i : i + 1) * lane,
|
|
758
|
+
laneX = nearPins - i * lane;
|
|
759
|
+
traces.push({
|
|
760
|
+
from: [`K${last.n}`, 'pin2'],
|
|
761
|
+
to: ['U1', `pin${colPin[c].pin}`],
|
|
762
|
+
width: v.track,
|
|
763
|
+
path: pts([
|
|
764
|
+
[last.x + jogX, last.y + m.pcb_pin2_y - slant],
|
|
765
|
+
[last.x + jogX, depth],
|
|
766
|
+
[laneX, depth],
|
|
767
|
+
[laneX, pinAt(colPin[c].pin).y],
|
|
768
|
+
]),
|
|
769
|
+
});
|
|
411
770
|
});
|
|
412
771
|
}
|
|
413
772
|
|
|
@@ -415,76 +774,224 @@ export function keyboard(v, keys) {
|
|
|
415
774
|
const lanesBelow = under ? 0 : cols.length * lane;
|
|
416
775
|
const top = Math.max(keyBox.top, under ? -Infinity : pico0.y + p.length / 2) + v.margin;
|
|
417
776
|
const bottom = Math.min(keyBox.bottom - lanesBelow, under ? Infinity : pico0.y - p.length / 2) - v.margin;
|
|
418
|
-
const cx = (left + right) / 2,
|
|
419
|
-
|
|
777
|
+
const cx = (left + right) / 2,
|
|
778
|
+
cy = (top + bottom) / 2,
|
|
779
|
+
inset = v.margin / 2;
|
|
780
|
+
const corners = v.mount_holes
|
|
781
|
+
? [
|
|
782
|
+
[left + inset, top - inset],
|
|
783
|
+
[right - inset, top - inset],
|
|
784
|
+
[left + inset, bottom + inset],
|
|
785
|
+
[right - inset, bottom + inset],
|
|
786
|
+
]
|
|
787
|
+
: [];
|
|
420
788
|
// Silkscreen for whoever solders it: the Pico's outline (on the side it's fitted) with USB marked, each switch's
|
|
421
789
|
// outline, and a bar at each diode's cathode (on the back, between its pads, next to the cathode)
|
|
422
|
-
const silk = v.jlcpcb.silk_line * 2,
|
|
790
|
+
const silk = v.jlcpcb.silk_line * 2,
|
|
791
|
+
text = v.jlcpcb.silk_text * 2;
|
|
423
792
|
const rect = (x, y, w, ht, layer) => ({ rect: { x, y, w, h: ht }, layer });
|
|
424
|
-
const outline = (x, y, w, ht, layer = 'top') => [
|
|
425
|
-
|
|
426
|
-
|
|
793
|
+
const outline = (x, y, w, ht, layer = 'top') => [
|
|
794
|
+
rect(x, y + ht / 2, w, silk, layer),
|
|
795
|
+
rect(x, y - ht / 2, w, silk, layer),
|
|
796
|
+
rect(x - w / 2, y, silk, ht, layer),
|
|
797
|
+
rect(x + w / 2, y, silk, ht, layer),
|
|
798
|
+
];
|
|
799
|
+
const usbAt = under
|
|
800
|
+
? { x: pico0.x + (pico0.toLeft ? -1 : 1) * (p.length / 2 - text * 1.5), y: pico0.y }
|
|
801
|
+
: { x: pico0.x, y: pico0.y + p.length / 2 - text };
|
|
802
|
+
const marks = [
|
|
803
|
+
...(under ? outline(pico0.x, pico0.y, p.length, p.width, 'bottom') : outline(pico0.x, pico0.y, p.width, p.length)),
|
|
427
804
|
{ text: 'USB', x: usbAt.x, y: usbAt.y, size: text, layer: under ? 'bottom' : 'top' },
|
|
428
805
|
...keys.flatMap((k) => outline(k.x, k.y, m.pcb_body, m.pcb_body)),
|
|
429
806
|
...keys.map((k) => rect(k.x + cathodeX + d.pad_w / 2 + silk * 2, k.y + diode.y, silk, d.pad_h, 'bottom')),
|
|
430
|
-
...(v.margin >= text * 2
|
|
431
|
-
|
|
432
|
-
|
|
433
|
-
|
|
807
|
+
...(v.margin >= text * 2
|
|
808
|
+
? [
|
|
809
|
+
{
|
|
810
|
+
text: 'rulecad: diodes point to the rows',
|
|
811
|
+
x: (keyBox.left + keyBox.right) / 2,
|
|
812
|
+
y: bottom + v.margin / 2,
|
|
813
|
+
size: text,
|
|
814
|
+
layer: 'bottom',
|
|
815
|
+
},
|
|
816
|
+
]
|
|
817
|
+
: []),
|
|
818
|
+
];
|
|
819
|
+
const board = {
|
|
820
|
+
center: { x: cx, y: cy },
|
|
821
|
+
width: right - left,
|
|
822
|
+
height: top - bottom,
|
|
823
|
+
thickness: v.thickness,
|
|
824
|
+
autoroute: under,
|
|
825
|
+
silk_line: v.jlcpcb.silk_line,
|
|
826
|
+
silk_text: v.jlcpcb.silk_text,
|
|
827
|
+
via_hole: 0.3,
|
|
828
|
+
via_pad: 0.3 + 2 * v.jlcpcb.annular,
|
|
829
|
+
fab: v.jlcpcb, // (vias with the ring the fab recommends; the fab's minimums for the router)
|
|
830
|
+
parts,
|
|
831
|
+
traces,
|
|
832
|
+
silk: marks,
|
|
833
|
+
holes: corners.map(([x, y]) => mount('M2', x, y, { set: v.m2 })),
|
|
834
|
+
}; // (the m2 rules' clearance hole, as the fab drills it)
|
|
434
835
|
const matrix = {
|
|
435
836
|
keys: keys.map((k) => ({ key: `K${k.n}`, ...(k.label ? { label: k.label } : {}), row: k.r, col: k.c })),
|
|
436
|
-
rows: Object.fromEntries(rows.map((r) => [r, rowPin[r].gpio])),
|
|
837
|
+
rows: Object.fromEntries(rows.map((r) => [r, rowPin[r].gpio])),
|
|
838
|
+
cols: Object.fromEntries(cols.map((c) => [c, colPin[c].gpio])),
|
|
437
839
|
...(under ? { pico: { x: pico0.x, y: pico0.y, usb: pico0.toLeft ? 'left' : 'right' } } : {}),
|
|
438
840
|
};
|
|
439
841
|
return { board, matrix };
|
|
440
842
|
}
|
|
441
843
|
|
|
442
844
|
// ---------- footprints from KiCad ----------
|
|
845
|
+
// A pad's copper turned by deg (counter-clockwise, y up) about its centre (x, y): its outline as points relative to the
|
|
846
|
+
// part, the corners rounded to r (KiCad's oval and rounded pads), as circuit.mjs takes copper of any shape
|
|
847
|
+
function turnedPad(x, y, w, h, deg, r) {
|
|
848
|
+
const a = (deg * Math.PI) / 180,
|
|
849
|
+
c = Math.cos(a),
|
|
850
|
+
s = Math.sin(a);
|
|
851
|
+
const outline = r > 0 ? shape.rounded(w, h, Math.min(r, w / 2, h / 2), { segments: 4 }) : shape.rect(w, h);
|
|
852
|
+
const pts = outline.map((q) => [r4(x + q.x * c - q.y * s), r4(y + q.x * s + q.y * c)]);
|
|
853
|
+
return pts.filter((q, i) => {
|
|
854
|
+
const n = pts[(i + 1) % pts.length];
|
|
855
|
+
return q[0] !== n[0] || q[1] !== n[1];
|
|
856
|
+
}); // (a stadium's arcs meet: one point where they do)
|
|
857
|
+
}
|
|
858
|
+
|
|
859
|
+
// One KiCad pad (the text from its name to its layers) as fromKicad gives it, or null for a pad with nothing to place
|
|
860
|
+
function kicadPad(name, kind, shape_, rest, holes) {
|
|
861
|
+
const at = rest.match(/\(at\s+([-\d.]+)\s+([-\d.]+)(?:\s+([-\d.]+))?\)/),
|
|
862
|
+
sz = rest.match(/\(size\s+([-\d.]+)\s+([-\d.]+)\)/);
|
|
863
|
+
if (!at || !sz) return null;
|
|
864
|
+
const deg = turnOf(Number(at[3] || 0)),
|
|
865
|
+
turn = deg % 180 === 90;
|
|
866
|
+
const p = {
|
|
867
|
+
name,
|
|
868
|
+
shape: shape_,
|
|
869
|
+
rest,
|
|
870
|
+
deg,
|
|
871
|
+
turn,
|
|
872
|
+
quarter: deg % 90 === 0,
|
|
873
|
+
size: [Number(sz[1]), Number(sz[2])], // (KiCad's own, before any turn)
|
|
874
|
+
w: Number(turn ? sz[2] : sz[1]),
|
|
875
|
+
h: Number(turn ? sz[1] : sz[2]),
|
|
876
|
+
x: r4(Number(at[1])),
|
|
877
|
+
y: r4(-Number(at[2])),
|
|
878
|
+
drill: rest.match(/\(drill\s+(oval\s+)?([-\d.]+)(?:\s+([-\d.]+))?/),
|
|
879
|
+
};
|
|
880
|
+
if (kind === 'np_thru_hole') {
|
|
881
|
+
if (p.drill) holes.push({ x: p.x, y: p.y, d: Number(p.drill[2]) });
|
|
882
|
+
return null;
|
|
883
|
+
} // a locating peg's hole: unplated, nothing to connect
|
|
884
|
+
if (!name) return null; // (an unnamed plated pad: mechanical)
|
|
885
|
+
if (kind === 'smd') return kicadSmdPad(p);
|
|
886
|
+
return kind === 'thru_hole' ? kicadPlatedPad(p) : null;
|
|
887
|
+
}
|
|
888
|
+
|
|
889
|
+
// An SMD pad: a rectangle, or turned by other than a quarter, its copper as points, turned
|
|
890
|
+
function kicadSmdPad({ name, shape, rest, deg, quarter, size, w, h, x, y }) {
|
|
891
|
+
const round = shape === 'circle' || (shape === 'oval' && w === h); // (the same however it's turned)
|
|
892
|
+
if (quarter || round) return { pin: name, smd: true, x, y, w, h };
|
|
893
|
+
const ratio = rest.match(/\(roundrect_rratio\s+([\d.]+)\)/),
|
|
894
|
+
short = Math.min(...size);
|
|
895
|
+
const r = shape === 'oval' ? short / 2 : shape === 'roundrect' ? (ratio ? Number(ratio[1]) : 0.25) * short : 0;
|
|
896
|
+
return { pin: name, smd: true, x, y, points: turnedPad(x, y, size[0], size[1], deg, r) };
|
|
897
|
+
}
|
|
898
|
+
|
|
899
|
+
// A plated pad: round, or with rect for oval copper, a slotted hole or a hole off its centre
|
|
900
|
+
function kicadPlatedPad({ name, shape, rest, deg, turn, quarter, w, h, x, y, drill }) {
|
|
901
|
+
if (!drill) throw new Error(`fromKicad: pad "${name}" is a through-hole pad with no drill`);
|
|
902
|
+
// A hole set off the pad's centre: KiCad drills at the pad's place and moves its copper by the offset, turned with
|
|
903
|
+
// the pad. Here a pad sits at its copper, with the hole's offset from it
|
|
904
|
+
const off = rest.match(/\(offset\s+([-\d.]+)\s+([-\d.]+)\)/),
|
|
905
|
+
ox = off ? Number(off[1]) : 0,
|
|
906
|
+
oy = off ? -Number(off[2]) : 0,
|
|
907
|
+
t = (deg * Math.PI) / 180,
|
|
908
|
+
o = [r4(ox * Math.cos(t) - oy * Math.sin(t)), r4(ox * Math.sin(t) + oy * Math.cos(t))];
|
|
909
|
+
// An oval pad keeps its oval copper, a slotted hole its slot ([w, h], turned with the pad)
|
|
910
|
+
const d = Number(drill[2]),
|
|
911
|
+
long = Number(drill[3]),
|
|
912
|
+
slot = drill[1] && drill[3] && long !== d ? (turn ? [long, d] : [d, long]) : null;
|
|
913
|
+
const oval = ['oval', 'rect', 'roundrect'].includes(shape) && w !== h;
|
|
914
|
+
if (!quarter && (oval || slot))
|
|
915
|
+
throw new Error(
|
|
916
|
+
`fromKicad: pad "${name}" is turned ${deg}°, and a through-hole pad that isn't round can turn only by quarter turns here: turn it in KiCad to 0°, 90°, 180° or 270° and turn the part instead`,
|
|
917
|
+
);
|
|
918
|
+
return {
|
|
919
|
+
pin: name,
|
|
920
|
+
x: r4(x + o[0]),
|
|
921
|
+
y: r4(y + o[1]),
|
|
922
|
+
hole: slot ? Math.min(...slot) : d,
|
|
923
|
+
outer: Math.max(w, h),
|
|
924
|
+
...(oval || slot || o[0] || o[1]
|
|
925
|
+
? { rect: { w, h, offset: [r4(-o[0]), r4(-o[1])], ...(slot ? { slot } : {}) } }
|
|
926
|
+
: {}),
|
|
927
|
+
};
|
|
928
|
+
}
|
|
929
|
+
|
|
443
930
|
/**
|
|
444
|
-
* A KiCad footprint (.kicad_mod text) as pad data: { pads, courtyard: { w, h } }, in mm, y up
|
|
445
|
-
* Keep the result in a rule set's "footprints" (with its source), and place it with footprint():
|
|
446
|
-
* reads files. SMD pads: { pin, smd: true, x, y, w, h } (a turned
|
|
447
|
-
*
|
|
448
|
-
*
|
|
449
|
-
*
|
|
931
|
+
* A KiCad footprint (.kicad_mod text, KiCad 6 or later) as pad data: { pads, courtyard: { w, h } }, in mm, y up
|
|
932
|
+
* (KiCad's y is down). Keep the result in a rule set's "footprints" (with its source), and place it with footprint():
|
|
933
|
+
* a design never reads files. SMD pads: { pin, smd: true, x, y, w, h } (a pad turned a quarter: its w and h swapped),
|
|
934
|
+
* or, turned by any other angle, { pin, smd: true, x, y, points: [[x, y], ...] } (its copper's outline, rounded as
|
|
935
|
+
* KiCad's oval and rounded pads are; no solder paste is laid on such a pad). Plated holes: { pin, x, y, hole, outer };
|
|
936
|
+
* one that isn't round (oval copper, a slotted hole, a hole off its pad's centre) has rect: { w, h, offset: [x, y],
|
|
937
|
+
* slot?: [w, h] }: its copper's size, the hole's place from the copper's centre (x, y), and a slotted hole's size.
|
|
938
|
+
* Unplated holes in holes: [{ x, y, d }].
|
|
939
|
+
* Pads named alike (several GND pads) keep their name; unnamed plated pads (mechanical) are left out. Text that isn't
|
|
940
|
+
* a footprint, a KiCad 5 footprint ("(module"), one with nothing on it, and a through-hole pad that isn't round turned
|
|
941
|
+
* by other than a quarter turn are refused.
|
|
450
942
|
* @param {string} text @returns {{ pads: object[], holes?: object[], courtyard: { w: number, h: number } | null }}
|
|
451
943
|
*/
|
|
452
944
|
export function fromKicad(text) {
|
|
453
|
-
if (
|
|
454
|
-
|
|
945
|
+
if (typeof text === 'string' && /^\s*\(module\s/.test(text))
|
|
946
|
+
throw new Error(
|
|
947
|
+
'fromKicad: this is a KiCad 5 footprint (it starts with "(module"): open it in KiCad 6 or later, save it, and import the saved file',
|
|
948
|
+
);
|
|
949
|
+
if (typeof text !== 'string' || !/^\s*\(footprint\s/.test(text))
|
|
950
|
+
throw new Error('fromKicad: not a KiCad footprint (a .kicad_mod starts with "(footprint")');
|
|
951
|
+
const pads = [],
|
|
952
|
+
holes = [];
|
|
455
953
|
for (const m of text.matchAll(/\(pad\s+"([^"]*)"\s+(smd|thru_hole|np_thru_hole)\s+(\w+)([\s\S]*?)\(layers/g)) {
|
|
456
|
-
const [,
|
|
457
|
-
|
|
458
|
-
if (!at || !sz) continue;
|
|
459
|
-
const turn = ((num(at[3] || 0) % 180) + 180) % 180 === 90, w = num(turn ? sz[2] : sz[1]), h = num(turn ? sz[1] : sz[2]);
|
|
460
|
-
const x = +num(at[1]).toFixed(4), y = +(-num(at[2])).toFixed(4);
|
|
461
|
-
const drill = rest.match(/\(drill\s+(oval\s+)?([-\d.]+)(?:\s+([-\d.]+))?/);
|
|
462
|
-
if (kind === 'np_thru_hole') { if (drill) holes.push({ x, y, d: num(drill[2]) }); continue; } // a locating peg's hole: unplated, nothing to connect
|
|
463
|
-
if (!name) continue; // (an unnamed plated pad: mechanical)
|
|
464
|
-
if (kind === 'smd') pads.push({ pin: name, smd: true, x, y, w, h });
|
|
465
|
-
else if (kind === 'thru_hole') {
|
|
466
|
-
// An oval pad keeps its oval copper; a slot is drilled round at its narrow width (boards here can't carry slots),
|
|
467
|
-
// and says so
|
|
468
|
-
const d = num(drill[2]), slot = drill[1] && drill[3] && num(drill[3]) !== d ? (turn ? [num(drill[3]), d] : [d, num(drill[3])]) : null;
|
|
469
|
-
const oval = shape === 'oval' || (shape === 'rect' || shape === 'roundrect') ? w !== h : false;
|
|
470
|
-
pads.push({ pin: name, x, y, hole: slot ? Math.min(...slot) : d, outer: Math.max(w, h), ...(oval ? { rect: { w, h } } : {}), ...(slot ? { slot } : {}) });
|
|
471
|
-
}
|
|
954
|
+
const p = kicadPad(m[1], m[2], m[3], m[4], holes);
|
|
955
|
+
if (p) pads.push(p);
|
|
472
956
|
}
|
|
473
957
|
if (!pads.length && !holes.length) throw new Error('fromKicad: the footprint has no pads');
|
|
474
|
-
const pts = text
|
|
475
|
-
.
|
|
958
|
+
const pts = text
|
|
959
|
+
.split(/\n\s*(?=\(fp_|\(pad|\(model|\(zone)/)
|
|
960
|
+
.filter((el) => /^\(fp_(?:line|rect|poly)/.test(el) && /\(layer\s+"F\.CrtYd"\)/.test(el)) // the courtyard's corners
|
|
961
|
+
.flatMap((el) =>
|
|
962
|
+
[...el.matchAll(/\((?:start|end|xy)\s+([-\d.]+)\s+([-\d.]+)\)/g)].map((m) => [Number(m[1]), Number(m[2])]),
|
|
963
|
+
);
|
|
476
964
|
const span = (k) => Math.max(...pts.map((p) => p[k])) - Math.min(...pts.map((p) => p[k]));
|
|
477
|
-
return {
|
|
965
|
+
return {
|
|
966
|
+
pads,
|
|
967
|
+
...(holes.length ? { holes } : {}),
|
|
968
|
+
courtyard: pts.length ? { w: +span(0).toFixed(3), h: +span(1).toFixed(3) } : null,
|
|
969
|
+
};
|
|
478
970
|
}
|
|
479
971
|
|
|
480
972
|
/**
|
|
481
973
|
* A part from footprint data (fromKicad's, kept in a rule set): pads as given, pins named by pad name (GND pads
|
|
482
974
|
* alike are joined in the part); data.labels ({ pin1: 'GND' }) and data.mpn name them. o: as part() (rotation,
|
|
483
|
-
* layer, mpn, labels, sch).
|
|
975
|
+
* layer, mpn, labels, sch). A plated pad's rect (oval copper, its hole's offset and slot) is kept; data from before
|
|
976
|
+
* the slot moved into rect (slot beside it, no offset) is read the same.
|
|
484
977
|
*/
|
|
485
978
|
export function footprint(name, data, x, y, o = {}) {
|
|
486
|
-
const pads = data.pads.map((p
|
|
487
|
-
|
|
979
|
+
const pads = data.pads.map((p) => {
|
|
980
|
+
const hint = String(p.pin);
|
|
981
|
+
if (p.smd && p.points) return { pin: `pin${p.pin}`, smd: true, hint, x: p.x, y: p.y, points: p.points };
|
|
982
|
+
if (p.smd) return { pin: `pin${p.pin}`, smd: true, hint, x: p.x, y: p.y, w: p.w, h: p.h };
|
|
983
|
+
const slot = p.rect?.slot ?? p.slot;
|
|
984
|
+
const rect =
|
|
985
|
+
p.rect || slot ? { w: p.outer, h: p.outer, offset: [0, 0], ...p.rect, ...(slot ? { slot } : {}) } : null;
|
|
986
|
+
return { ...pad(`pin${p.pin}`, p.x, p.y, p.hole, p.outer), ...(rect ? { rect } : {}) };
|
|
987
|
+
});
|
|
988
|
+
return chip(
|
|
989
|
+
name,
|
|
990
|
+
x,
|
|
991
|
+
y,
|
|
992
|
+
{ courtyard: data.courtyard, mpn: data.mpn, labels: data.labels, ...o },
|
|
993
|
+
{ pads, ...(data.holes?.length ? { holes: data.holes.map((h) => hole(h.x, h.y, h.d)) } : {}) },
|
|
994
|
+
);
|
|
488
995
|
}
|
|
489
996
|
|
|
490
997
|
// ---------- whole boards from KiCad: clones ----------
|
|
@@ -498,8 +1005,11 @@ function sexpr(text) {
|
|
|
498
1005
|
const stack = [[]];
|
|
499
1006
|
for (const t of text.match(/"(?:[^"\\]|\\.)*"|\(|\)|[^\s()"]+/g) || []) {
|
|
500
1007
|
if (t === '(') stack.push([]);
|
|
501
|
-
else if (t === ')') {
|
|
502
|
-
|
|
1008
|
+
else if (t === ')') {
|
|
1009
|
+
const l = stack.pop();
|
|
1010
|
+
if (!stack.length) throw new Error('not a KiCad file: a ")" closes nothing');
|
|
1011
|
+
stack.at(-1).push(l);
|
|
1012
|
+
} else stack.at(-1).push(t[0] === '"' ? t.slice(1, -1).replace(/\\(.)/g, '$1') : t);
|
|
503
1013
|
}
|
|
504
1014
|
if (stack.length !== 1) throw new Error('not a KiCad file: a "(" is never closed');
|
|
505
1015
|
return stack[0][0];
|
|
@@ -507,18 +1017,27 @@ function sexpr(text) {
|
|
|
507
1017
|
const kidsOf = (l, name) => l.filter((c) => Array.isArray(c) && c[0] === name);
|
|
508
1018
|
const kidOf = (l, name) => kidsOf(l, name)[0];
|
|
509
1019
|
const r4 = (n) => Math.round(n * 1e4) / 1e4 || 0; // 0.1 mm to the micron, and never -0
|
|
510
|
-
const turnOf = (deg) => ((Math.round(deg * 1e3) / 1e3 % 360) + 360) % 360;
|
|
1020
|
+
const turnOf = (deg) => (((Math.round(deg * 1e3) / 1e3) % 360) + 360) % 360;
|
|
511
1021
|
|
|
512
1022
|
// Edge.Cuts pieces ({ a, b } lines, arcs already cut into lines) joined end to end into closed loops
|
|
513
1023
|
function loops(pieces, tol = 0.005) {
|
|
514
|
-
const same = (p, q) => Math.abs(p.x - q.x) < tol && Math.abs(p.y - q.y) < tol,
|
|
1024
|
+
const same = (p, q) => Math.abs(p.x - q.x) < tol && Math.abs(p.y - q.y) < tol,
|
|
1025
|
+
out = [],
|
|
1026
|
+
left = [...pieces];
|
|
515
1027
|
while (left.length) {
|
|
516
|
-
const loop = [left[0].a, left[0].b];
|
|
1028
|
+
const loop = [left[0].a, left[0].b];
|
|
1029
|
+
left.shift();
|
|
517
1030
|
for (let found = true; found && !same(loop[0], loop.at(-1));) {
|
|
518
1031
|
found = false;
|
|
519
1032
|
for (let i = 0; i < left.length; i++) {
|
|
520
|
-
const s = left[i],
|
|
521
|
-
|
|
1033
|
+
const s = left[i],
|
|
1034
|
+
end = loop.at(-1);
|
|
1035
|
+
if (same(s.a, end) || same(s.b, end)) {
|
|
1036
|
+
loop.push(same(s.a, end) ? s.b : s.a);
|
|
1037
|
+
left.splice(i, 1);
|
|
1038
|
+
found = true;
|
|
1039
|
+
break;
|
|
1040
|
+
}
|
|
522
1041
|
}
|
|
523
1042
|
}
|
|
524
1043
|
if (same(loop[0], loop.at(-1)) && loop.length > 3) out.push(loop.slice(0, -1));
|
|
@@ -526,26 +1045,60 @@ function loops(pieces, tol = 0.005) {
|
|
|
526
1045
|
}
|
|
527
1046
|
return out;
|
|
528
1047
|
}
|
|
529
|
-
const area = (pts) =>
|
|
1048
|
+
const area = (pts) =>
|
|
1049
|
+
pts.reduce((s, p, i) => {
|
|
1050
|
+
const q = pts[(i + 1) % pts.length];
|
|
1051
|
+
return s + p.x * q.y - q.x * p.y;
|
|
1052
|
+
}, 0) / 2;
|
|
530
1053
|
|
|
531
1054
|
// The source's own tracks and vias, with their nets, in the circuit's frame: { tracks: [{ a, b, width, layer, net }],
|
|
532
1055
|
// vias: [{ x, y, pad, hole, net }] }. Layers as boards here name them (top, inner1, ..., bottom)
|
|
533
1056
|
function sourceCopper(root, to) {
|
|
534
|
-
const names = new Map(kidsOf(root, 'net').map((n) => [n[1], n[2]])),
|
|
535
|
-
|
|
1057
|
+
const names = new Map(kidsOf(root, 'net').map((n) => [n[1], n[2]])),
|
|
1058
|
+
layer = (l) => (l === 'F.Cu' ? 'top' : l === 'B.Cu' ? 'bottom' : `inner${l.match(/\d+/)[0]}`);
|
|
1059
|
+
const pt = (l) => to({ x: Number(l[1]), y: Number(l[2]) }),
|
|
1060
|
+
netOf = (e) => {
|
|
1061
|
+
const n = kidOf(e, 'net');
|
|
1062
|
+
return n ? (n[2] ?? names.get(n[1]) ?? null) : null;
|
|
1063
|
+
};
|
|
536
1064
|
return {
|
|
537
|
-
tracks: kidsOf(root, 'segment').map((g) => ({
|
|
538
|
-
|
|
1065
|
+
tracks: kidsOf(root, 'segment').map((g) => ({
|
|
1066
|
+
a: pt(kidOf(g, 'start')),
|
|
1067
|
+
b: pt(kidOf(g, 'end')),
|
|
1068
|
+
width: Number(kidOf(g, 'width')[1]),
|
|
1069
|
+
layer: layer(kidOf(g, 'layer')[1]),
|
|
1070
|
+
net: netOf(g),
|
|
1071
|
+
})),
|
|
1072
|
+
vias: kidsOf(root, 'via').map((v) => ({
|
|
1073
|
+
...pt(kidOf(v, 'at')),
|
|
1074
|
+
pad: Number(kidOf(v, 'size')[1]),
|
|
1075
|
+
hole: Number(kidOf(v, 'drill')[1]),
|
|
1076
|
+
net: netOf(v),
|
|
1077
|
+
})),
|
|
539
1078
|
};
|
|
540
1079
|
}
|
|
541
1080
|
|
|
542
1081
|
// The sizes the source uses most: its vias ({ via: { pad, hole } }), its narrowest track, its zones' clearance
|
|
543
1082
|
function commonest(root) {
|
|
544
|
-
const most = (list) => {
|
|
1083
|
+
const most = (list) => {
|
|
1084
|
+
const n = new Map();
|
|
1085
|
+
for (const k of list) n.set(k, (n.get(k) || 0) + 1);
|
|
1086
|
+
return [...n].sort((a, b) => b[1] - a[1])[0]?.[0];
|
|
1087
|
+
};
|
|
545
1088
|
const via = most(kidsOf(root, 'via').map((v) => `${kidOf(v, 'size')?.[1]} ${kidOf(v, 'drill')?.[1]}`));
|
|
546
|
-
const widths = kidsOf(root, 'segment')
|
|
547
|
-
|
|
548
|
-
|
|
1089
|
+
const widths = kidsOf(root, 'segment')
|
|
1090
|
+
.map((g) => Number(kidOf(g, 'width')?.[1]))
|
|
1091
|
+
.filter((w) => w > 0);
|
|
1092
|
+
const clear = most(
|
|
1093
|
+
kidsOf(root, 'zone')
|
|
1094
|
+
.map((z) => kidOf(kidOf(z, 'connect_pads') || [], 'clearance')?.[1])
|
|
1095
|
+
.filter(Boolean),
|
|
1096
|
+
);
|
|
1097
|
+
return {
|
|
1098
|
+
...(via ? { via: { pad: Number(via.split(' ')[0]), hole: Number(via.split(' ')[1]) } } : {}),
|
|
1099
|
+
...(widths.length ? { track: Math.min(...widths) } : {}),
|
|
1100
|
+
...(clear ? { clearance: Number(clear) } : {}),
|
|
1101
|
+
};
|
|
549
1102
|
}
|
|
550
1103
|
|
|
551
1104
|
/**
|
|
@@ -562,78 +1115,188 @@ function commonest(root) {
|
|
|
562
1115
|
export function fromKicadPcb(text) {
|
|
563
1116
|
const root = sexpr(text);
|
|
564
1117
|
if (root?.[0] !== 'kicad_pcb') throw new Error('not a KiCad board: a .kicad_pcb starts with (kicad_pcb');
|
|
565
|
-
if (!kidOf(root, 'footprint'))
|
|
566
|
-
|
|
567
|
-
|
|
568
|
-
|
|
569
|
-
|
|
570
|
-
|
|
571
|
-
|
|
1118
|
+
if (!kidOf(root, 'footprint'))
|
|
1119
|
+
throw new Error(
|
|
1120
|
+
'no footprints in this board: KiCad 6 or later is needed (older files call them "module": open and save it in KiCad 6+)',
|
|
1121
|
+
);
|
|
1122
|
+
const layers = kidOf(root, 'layers')
|
|
1123
|
+
.slice(1)
|
|
1124
|
+
.filter((l) => l[2] === 'signal')
|
|
1125
|
+
.map((l) => l[1]);
|
|
1126
|
+
const num = Number,
|
|
1127
|
+
pieces = [],
|
|
1128
|
+
holes = [],
|
|
1129
|
+
raw = [];
|
|
1130
|
+
const edge = (l, place) => {
|
|
1131
|
+
// a line or an arc on Edge.Cuts, as straight pieces in the board's frame
|
|
1132
|
+
if (kidOf(l, 'layer')?.[1] !== 'Edge.Cuts') return;
|
|
1133
|
+
const pt = (k) => {
|
|
1134
|
+
const p = kidOf(l, k);
|
|
1135
|
+
return p && place(num(p[1]), num(p[2]));
|
|
1136
|
+
};
|
|
1137
|
+
const a = pt('start'),
|
|
1138
|
+
b = pt('end'),
|
|
1139
|
+
m = pt('mid');
|
|
572
1140
|
if (!a || !b) return;
|
|
573
1141
|
if (!m) return pieces.push({ a, b });
|
|
574
|
-
const ax = b.x - a.x,
|
|
575
|
-
|
|
576
|
-
|
|
577
|
-
|
|
578
|
-
|
|
579
|
-
|
|
1142
|
+
const ax = b.x - a.x,
|
|
1143
|
+
ay = b.y - a.y,
|
|
1144
|
+
bx = m.x - a.x,
|
|
1145
|
+
by = m.y - a.y,
|
|
1146
|
+
d = 2 * (ax * by - ay * bx); // the circle through a, m, b
|
|
1147
|
+
const cx = a.x + (by * (ax * ax + ay * ay) - ay * (bx * bx + by * by)) / d,
|
|
1148
|
+
cy = a.y + (ax * (bx * bx + by * by) - bx * (ax * ax + ay * ay)) / d;
|
|
1149
|
+
const r = Math.hypot(a.x - cx, a.y - cy),
|
|
1150
|
+
at = (p) => Math.atan2(p.y - cy, p.x - cx),
|
|
1151
|
+
t0 = at(a);
|
|
1152
|
+
let t1 = at(b),
|
|
1153
|
+
tm = at(m);
|
|
1154
|
+
const norm = (t) => (((t - t0) % (2 * Math.PI)) + 2 * Math.PI) % (2 * Math.PI);
|
|
1155
|
+
t1 = norm(t1);
|
|
1156
|
+
tm = norm(tm);
|
|
1157
|
+
const sweep = tm < t1 ? t1 : t1 - 2 * Math.PI,
|
|
1158
|
+
n = Math.max(2, Math.ceil(Math.abs(sweep) / (Math.PI / 16)));
|
|
580
1159
|
let prev = a;
|
|
581
|
-
for (let i = 1; i <= n; i++) {
|
|
1160
|
+
for (let i = 1; i <= n; i++) {
|
|
1161
|
+
const t = t0 + (sweep * i) / n,
|
|
1162
|
+
q = i === n ? b : { x: cx + r * Math.cos(t), y: cy + r * Math.sin(t) };
|
|
1163
|
+
pieces.push({ a: prev, b: q });
|
|
1164
|
+
prev = q;
|
|
1165
|
+
}
|
|
582
1166
|
};
|
|
583
1167
|
for (const g of root) if (Array.isArray(g) && ['gr_line', 'gr_arc'].includes(g[0])) edge(g, (x, y) => ({ x, y }));
|
|
584
|
-
for (const g of kidsOf(root, 'gr_rect'))
|
|
585
|
-
|
|
586
|
-
|
|
587
|
-
|
|
1168
|
+
for (const g of kidsOf(root, 'gr_rect'))
|
|
1169
|
+
if (kidOf(g, 'layer')?.[1] === 'Edge.Cuts') {
|
|
1170
|
+
const s = kidOf(g, 'start'),
|
|
1171
|
+
e = kidOf(g, 'end'),
|
|
1172
|
+
[x0, y0, x1, y1] = [s[1], s[2], e[1], e[2]].map(num);
|
|
1173
|
+
pieces.push(
|
|
1174
|
+
{ a: { x: x0, y: y0 }, b: { x: x1, y: y0 } },
|
|
1175
|
+
{ a: { x: x1, y: y0 }, b: { x: x1, y: y1 } },
|
|
1176
|
+
{ a: { x: x1, y: y1 }, b: { x: x0, y: y1 } },
|
|
1177
|
+
{ a: { x: x0, y: y1 }, b: { x: x0, y: y0 } },
|
|
1178
|
+
);
|
|
1179
|
+
}
|
|
588
1180
|
for (const f of kidsOf(root, 'footprint')) {
|
|
589
|
-
const at = kidOf(f, 'at'),
|
|
590
|
-
|
|
1181
|
+
const at = kidOf(f, 'at'),
|
|
1182
|
+
fx = num(at[1]),
|
|
1183
|
+
fy = num(at[2]),
|
|
1184
|
+
deg = num(at[3] || 0),
|
|
1185
|
+
t = (deg * Math.PI) / 180,
|
|
1186
|
+
c = Math.cos(t),
|
|
1187
|
+
s = Math.sin(t);
|
|
1188
|
+
const bottom = kidOf(f, 'layer')?.[1] === 'B.Cu';
|
|
591
1189
|
const place = (x, y) => ({ x: fx + x * c + y * s, y: fy - x * s + y * c }); // KiCad's frame: y down, angles counter-clockwise on screen
|
|
592
1190
|
for (const l of [...kidsOf(f, 'fp_line'), ...kidsOf(f, 'fp_arc')]) edge(l, place);
|
|
593
1191
|
const props = Object.fromEntries(kidsOf(f, 'property').map((p) => [String(p[1]).trim(), p[2]]));
|
|
594
1192
|
const ref = props.Reference ?? kidsOf(f, 'fp_text').find((x) => x[1] === 'reference')?.[2];
|
|
595
|
-
const pads = [],
|
|
1193
|
+
const pads = [],
|
|
1194
|
+
own = []; // own: the part's unplated holes (a socket's locating pegs), in its frame
|
|
596
1195
|
for (const p of kidsOf(f, 'pad')) {
|
|
597
|
-
const [, name, kind, shape] = p,
|
|
598
|
-
|
|
1196
|
+
const [, name, kind, shape] = p,
|
|
1197
|
+
pa = kidOf(p, 'at'),
|
|
1198
|
+
sz = kidOf(p, 'size'),
|
|
1199
|
+
drill = kidOf(p, 'drill');
|
|
1200
|
+
if (kind === 'np_thru_hole') {
|
|
1201
|
+
own.push({
|
|
1202
|
+
x: r4(bottom ? -num(pa[1]) : num(pa[1])),
|
|
1203
|
+
y: r4(-num(pa[2])),
|
|
1204
|
+
d: num(drill[1]),
|
|
1205
|
+
at: place(num(pa[1]), num(pa[2])),
|
|
1206
|
+
});
|
|
1207
|
+
continue;
|
|
1208
|
+
}
|
|
599
1209
|
if (!name) continue; // unnamed pads are mechanical: no net
|
|
600
1210
|
// A pad's place in the part's frame, y up, seen from the side the part is on: (x, -y) on top; a part on the back
|
|
601
1211
|
// is stored mirrored by KiCad, and turned the other way, so (-x, -y) with the turn negated (see rotation below)
|
|
602
|
-
const px = num(pa[1]),
|
|
603
|
-
|
|
1212
|
+
const px = num(pa[1]),
|
|
1213
|
+
py = num(pa[2]),
|
|
1214
|
+
angle = turnOf((num(pa[3] || 0) - deg) * (bottom ? -1 : 1));
|
|
1215
|
+
const pad = {
|
|
1216
|
+
pin: name,
|
|
1217
|
+
x: r4(bottom ? -px : px),
|
|
1218
|
+
y: r4(-py),
|
|
1219
|
+
w: num(sz[1]),
|
|
1220
|
+
h: num(sz[2]),
|
|
1221
|
+
angle,
|
|
1222
|
+
smd: kind === 'smd',
|
|
1223
|
+
shape,
|
|
1224
|
+
net: kidOf(p, 'net')?.[2] || null,
|
|
1225
|
+
};
|
|
604
1226
|
const ratio = kidOf(p, 'roundrect_rratio'); // rounded corners, as a share of the shorter side
|
|
605
1227
|
if (shape === 'roundrect' && ratio) pad.corner = r4(num(ratio[1]) * Math.min(pad.w, pad.h));
|
|
606
1228
|
if (shape === 'oval' && pad.w !== pad.h) pad.corner = r4(Math.min(pad.w, pad.h) / 2); // an oval: round ends, a rectangle's corners rounded all the way
|
|
607
1229
|
if (drill) {
|
|
608
|
-
const d = drill.slice(1),
|
|
1230
|
+
const d = drill.slice(1),
|
|
1231
|
+
oval = d[0] === 'oval',
|
|
1232
|
+
ds = d.filter((x) => !Array.isArray(x) && x !== 'oval').map(num),
|
|
1233
|
+
off = kidOf(drill, 'offset');
|
|
609
1234
|
pad.hole = Math.min(...ds);
|
|
610
1235
|
if (oval && ds.length > 1 && ds[0] !== ds[1]) pad.hole_size = [ds[0], ds[1]];
|
|
611
|
-
if (off && (num(off[1]) || num(off[2]))) {
|
|
612
|
-
|
|
1236
|
+
if (off && (num(off[1]) || num(off[2]))) {
|
|
1237
|
+
// KiCad drills at the pad's position and moves its copper by the offset (turned with the pad)
|
|
1238
|
+
const t = ((num(pa[3] || 0) - deg) * Math.PI) / 180,
|
|
1239
|
+
ox = num(off[1]),
|
|
1240
|
+
oy = -num(off[2]); // y up
|
|
613
1241
|
const o = [(ox * Math.cos(t) - oy * Math.sin(t)) * (bottom ? -1 : 1), ox * Math.sin(t) + oy * Math.cos(t)];
|
|
614
|
-
pad.x = r4(pad.x + o[0]);
|
|
1242
|
+
pad.x = r4(pad.x + o[0]);
|
|
1243
|
+
pad.y = r4(pad.y + o[1]);
|
|
1244
|
+
pad.hole_offset = [r4(-o[0]), r4(-o[1])]; // the copper's centre, and the hole from it
|
|
615
1245
|
}
|
|
616
1246
|
}
|
|
617
|
-
if (p.some((x) => Array.isArray(x) && x[0] === 'property' && x[1] === 'pad_prop_castellated'))
|
|
1247
|
+
if (p.some((x) => Array.isArray(x) && x[0] === 'property' && x[1] === 'pad_prop_castellated'))
|
|
1248
|
+
pad.castellated = true;
|
|
618
1249
|
pads.push(pad);
|
|
619
1250
|
}
|
|
620
|
-
if (!pads.length) {
|
|
1251
|
+
if (!pads.length) {
|
|
1252
|
+
holes.push(...own.map((h) => ({ ...h.at, d: h.d })));
|
|
1253
|
+
continue;
|
|
1254
|
+
} // a mounting hole (a board's), a logo: nothing to connect
|
|
621
1255
|
const attr = kidOf(f, 'attr') || []; // parts the source keeps off its BOM and placement files (edge pads, test points)
|
|
622
|
-
const m3 = kidOf(f, 'model'),
|
|
623
|
-
|
|
624
|
-
|
|
625
|
-
|
|
626
|
-
|
|
1256
|
+
const m3 = kidOf(f, 'model'),
|
|
1257
|
+
xyz = (k) => {
|
|
1258
|
+
const v = kidOf(kidOf(m3, k) || [], 'xyz');
|
|
1259
|
+
return v ? v.slice(1).map(Number) : null;
|
|
1260
|
+
};
|
|
1261
|
+
const model = m3 && {
|
|
1262
|
+
path: m3[1],
|
|
1263
|
+
offset: xyz('offset') || [0, 0, 0],
|
|
1264
|
+
scale: xyz('scale') || [1, 1, 1],
|
|
1265
|
+
rotate: xyz('rotate') || [0, 0, 0],
|
|
1266
|
+
}; // its 3D model, as KiCad finds it
|
|
1267
|
+
raw.push({
|
|
1268
|
+
ref,
|
|
1269
|
+
footprint: f[1],
|
|
1270
|
+
value: props.Value,
|
|
1271
|
+
mpn: props.MPN ?? props['Manufacturer Part Number'],
|
|
1272
|
+
lcsc: props.LCSC,
|
|
1273
|
+
x: fx,
|
|
1274
|
+
y: fy,
|
|
1275
|
+
rotation: turnOf(bottom ? -deg : deg),
|
|
1276
|
+
layer: bottom ? 'bottom' : 'top',
|
|
1277
|
+
pads,
|
|
1278
|
+
...(model ? { model } : {}),
|
|
1279
|
+
...(attr.includes('exclude_from_bom') ? { bom: false } : {}),
|
|
1280
|
+
...(attr.includes('exclude_from_pos_files') ? { place: false } : {}),
|
|
1281
|
+
...(own.length ? { holes: own.map(({ at, ...h }) => h) } : {}),
|
|
1282
|
+
});
|
|
627
1283
|
}
|
|
628
1284
|
// The outline: the loops on Edge.Cuts, the biggest outside (counter-clockwise, y up); without one closed loop, its bounds
|
|
629
1285
|
const found = loops(pieces);
|
|
630
1286
|
const all = pieces.flatMap((p) => [p.a, p.b]);
|
|
631
1287
|
if (!all.length) throw new Error('no board outline: nothing is drawn on Edge.Cuts');
|
|
632
|
-
const xs = all.map((p) => p.x),
|
|
1288
|
+
const xs = all.map((p) => p.x),
|
|
1289
|
+
ys = all.map((p) => p.y),
|
|
1290
|
+
cx = (Math.min(...xs) + Math.max(...xs)) / 2,
|
|
1291
|
+
cy = (Math.min(...ys) + Math.max(...ys)) / 2;
|
|
633
1292
|
const to = (p) => ({ x: r4(p.x - cx), y: r4(cy - p.y) }); // into the circuit's frame: centred, y up
|
|
634
|
-
let outline = null,
|
|
1293
|
+
let outline = null,
|
|
1294
|
+
cutouts = [];
|
|
635
1295
|
if (found) {
|
|
636
|
-
const shapes = found
|
|
1296
|
+
const shapes = found
|
|
1297
|
+
.map((l) => l.map(to))
|
|
1298
|
+
.map((l) => (area(l) < 0 ? l.reverse() : l))
|
|
1299
|
+
.sort((a, b) => area(b) - area(a));
|
|
637
1300
|
[outline, ...cutouts] = shapes;
|
|
638
1301
|
}
|
|
639
1302
|
const parts = raw.map((p) => ({ ...p, ...to(p) }));
|
|
@@ -641,18 +1304,34 @@ export function fromKicadPcb(text) {
|
|
|
641
1304
|
for (const p of parts) for (const q of p.pads) if (q.net) (nets[q.net] ||= new Set()).add(`${p.ref}.${q.pin}`);
|
|
642
1305
|
const planes = {};
|
|
643
1306
|
for (const z of kidsOf(root, 'zone')) {
|
|
644
|
-
const net = kidOf(z, 'net_name')?.[1],
|
|
1307
|
+
const net = kidOf(z, 'net_name')?.[1],
|
|
1308
|
+
on = [...(kidOf(z, 'layers')?.slice(1) || []), ...(kidOf(z, 'layer') ? [kidOf(z, 'layer')[1]] : [])];
|
|
645
1309
|
if (net) planes[net] = [...new Set([...(planes[net] || []), ...on])];
|
|
646
1310
|
}
|
|
647
1311
|
return {
|
|
648
|
-
layers: layers.length,
|
|
1312
|
+
layers: layers.length,
|
|
1313
|
+
copper: layers,
|
|
1314
|
+
width: r4(Math.max(...xs) - Math.min(...xs)),
|
|
1315
|
+
height: r4(Math.max(...ys) - Math.min(...ys)),
|
|
649
1316
|
thickness: num(kidOf(kidOf(root, 'general') || [], 'thickness')?.[1]) || null,
|
|
650
|
-
outline,
|
|
651
|
-
|
|
652
|
-
|
|
1317
|
+
outline,
|
|
1318
|
+
cutouts,
|
|
1319
|
+
parts,
|
|
1320
|
+
nets: Object.fromEntries(
|
|
1321
|
+
Object.entries(nets)
|
|
1322
|
+
.filter(([, s]) => s.size > 1)
|
|
1323
|
+
.map(([k, s]) => [k, [...s]]),
|
|
1324
|
+
),
|
|
1325
|
+
planes,
|
|
1326
|
+
holes: holes.map((h) => ({ ...to(h), d: h.d })),
|
|
653
1327
|
routing: sourceCopper(root, to),
|
|
654
|
-
source: {
|
|
655
|
-
|
|
1328
|
+
source: {
|
|
1329
|
+
generator: kidOf(root, 'generator')?.[1],
|
|
1330
|
+
version: kidOf(root, 'version')?.[1],
|
|
1331
|
+
tracks: kidsOf(root, 'segment').length + kidsOf(root, 'arc').length,
|
|
1332
|
+
vias: kidsOf(root, 'via').length,
|
|
1333
|
+
...commonest(root),
|
|
1334
|
+
},
|
|
656
1335
|
};
|
|
657
1336
|
}
|
|
658
1337
|
|
|
@@ -665,66 +1344,206 @@ export function fromKicadPcb(text) {
|
|
|
665
1344
|
* @param {object} circuit @param {{ planes?: string[], layers?: number }} [o]
|
|
666
1345
|
*/
|
|
667
1346
|
export function clone(circuit, o = {}) {
|
|
668
|
-
const inner = (l) => /^In\d+\.Cu$/.test(l),
|
|
669
|
-
|
|
670
|
-
const
|
|
671
|
-
|
|
672
|
-
|
|
673
|
-
|
|
674
|
-
|
|
675
|
-
|
|
676
|
-
|
|
677
|
-
|
|
678
|
-
|
|
679
|
-
|
|
680
|
-
|
|
681
|
-
|
|
682
|
-
|
|
683
|
-
const
|
|
684
|
-
|
|
685
|
-
|
|
686
|
-
|
|
687
|
-
|
|
688
|
-
|
|
689
|
-
|
|
690
|
-
|
|
691
|
-
|
|
692
|
-
|
|
693
|
-
|
|
694
|
-
|
|
695
|
-
|
|
696
|
-
|
|
697
|
-
|
|
698
|
-
|
|
699
|
-
|
|
1347
|
+
const inner = (l) => /^In\d+\.Cu$/.test(l),
|
|
1348
|
+
layers = o.layers ?? circuit.layers ?? 2;
|
|
1349
|
+
const planes =
|
|
1350
|
+
o.planes ??
|
|
1351
|
+
Object.entries(circuit.planes || {})
|
|
1352
|
+
.filter(([, ls]) => ls.some(inner))
|
|
1353
|
+
.map(([n]) => n);
|
|
1354
|
+
const notes = [],
|
|
1355
|
+
castellated = new Set();
|
|
1356
|
+
const parts = circuit.parts
|
|
1357
|
+
.map((p) => {
|
|
1358
|
+
const quarterTurn = p.rotation % 90 === 0,
|
|
1359
|
+
t = (p.rotation * Math.PI) / 180,
|
|
1360
|
+
c = Math.cos(t),
|
|
1361
|
+
s = Math.sin(t);
|
|
1362
|
+
const pads = p.pads.map((q) => {
|
|
1363
|
+
const pin = `pin${q.pin}`;
|
|
1364
|
+
if (!q.smd) {
|
|
1365
|
+
const at = quarterTurn ? { x: q.x, y: q.y } : { x: q.x * c - q.y * s, y: q.x * s + q.y * c };
|
|
1366
|
+
if (q.castellated) {
|
|
1367
|
+
castellated.add(p.ref);
|
|
1368
|
+
return { pin, hint: q.pin, ...at, hole: q.hole, outer: Math.min(q.w, q.h), castellated: true };
|
|
1369
|
+
}
|
|
1370
|
+
if (q.w === q.h && !q.hole_offset) return { pin, hint: q.pin, ...at, hole: q.hole, outer: q.w };
|
|
1371
|
+
// an oval pad, or a hole off its centre: a rounded rectangle round the hole, turned with the part (quarter turns)
|
|
1372
|
+
const sw = (q.angle + (quarterTurn ? 0 : p.rotation)) % 180 === 90,
|
|
1373
|
+
w = sw ? q.h : q.w,
|
|
1374
|
+
h = sw ? q.w : q.h;
|
|
1375
|
+
return {
|
|
1376
|
+
pin,
|
|
1377
|
+
hint: q.pin,
|
|
1378
|
+
...at,
|
|
1379
|
+
hole: q.hole,
|
|
1380
|
+
outer: Math.min(w, h),
|
|
1381
|
+
rect: {
|
|
1382
|
+
w,
|
|
1383
|
+
h,
|
|
1384
|
+
offset: q.hole_offset || [0, 0],
|
|
1385
|
+
...(q.hole_size ? { slot: sw ? [q.hole_size[1], q.hole_size[0]] : q.hole_size } : {}),
|
|
1386
|
+
},
|
|
1387
|
+
}; // (slot: a slotted hole's width and height)
|
|
1388
|
+
}
|
|
1389
|
+
const turn = q.angle + (quarterTurn ? 0 : p.rotation);
|
|
1390
|
+
if (turn % 90 === 0) {
|
|
1391
|
+
// a rectangle, its sides swapped by a quarter turn of its own
|
|
1392
|
+
const sw = turn % 180 !== 0,
|
|
1393
|
+
at = quarterTurn ? { x: q.x, y: q.y } : { x: q.x * c - q.y * s, y: q.x * s + q.y * c };
|
|
1394
|
+
return {
|
|
1395
|
+
pin,
|
|
1396
|
+
smd: true,
|
|
1397
|
+
hint: q.pin,
|
|
1398
|
+
...at,
|
|
1399
|
+
w: sw ? q.h : q.w,
|
|
1400
|
+
h: sw ? q.w : q.h,
|
|
1401
|
+
...(q.shape === 'circle' && q.w === q.h ? { circle: true } : {}),
|
|
1402
|
+
...(q.corner ? { corner: q.corner } : {}),
|
|
1403
|
+
};
|
|
1404
|
+
}
|
|
1405
|
+
const a = (turn * Math.PI) / 180,
|
|
1406
|
+
ca = Math.cos(a),
|
|
1407
|
+
sa = Math.sin(a),
|
|
1408
|
+
at = quarterTurn ? { x: q.x, y: q.y } : { x: q.x * c - q.y * s, y: q.x * s + q.y * c };
|
|
1409
|
+
const pts = [
|
|
1410
|
+
[-1, -1],
|
|
1411
|
+
[1, -1],
|
|
1412
|
+
[1, 1],
|
|
1413
|
+
[-1, 1],
|
|
1414
|
+
].map(([u, v]) => [
|
|
1415
|
+
r4(at.x + ((u * q.w) / 2) * ca - ((v * q.h) / 2) * sa),
|
|
1416
|
+
r4(at.y + ((u * q.w) / 2) * sa + ((v * q.h) / 2) * ca),
|
|
1417
|
+
]);
|
|
1418
|
+
return { pin, smd: true, hint: q.pin, ...at, points: pts }; // corners relative to the part, as circuit.mjs takes them
|
|
1419
|
+
});
|
|
1420
|
+
const holes = (p.holes || []).map((h) =>
|
|
1421
|
+
quarterTurn ? h : { ...h, x: h.x * c - h.y * s, y: h.x * s + h.y * c },
|
|
1422
|
+
);
|
|
1423
|
+
return {
|
|
1424
|
+
name: p.ref,
|
|
1425
|
+
ftype: 'simple_chip',
|
|
1426
|
+
x: p.x,
|
|
1427
|
+
y: p.y,
|
|
1428
|
+
layer: p.layer,
|
|
1429
|
+
rotation: quarterTurn ? p.rotation : 0,
|
|
1430
|
+
mpn: p.mpn,
|
|
1431
|
+
lcsc: p.lcsc,
|
|
1432
|
+
value: p.value,
|
|
1433
|
+
...(p.bom === false ? { bom: false } : {}),
|
|
1434
|
+
...(p.place === false ? { place: false } : {}),
|
|
1435
|
+
...(holes.length ? { holes } : {}),
|
|
1436
|
+
...(p.model && circuit.models?.[p.model.path]
|
|
1437
|
+
? { model: { ...p.model, ...circuit.models[p.model.path], turn: quarterTurn ? 0 : p.rotation } }
|
|
1438
|
+
: {}),
|
|
1439
|
+
courtyard: null,
|
|
1440
|
+
pads,
|
|
1441
|
+
}; // no sch: laid out on the schematic in rows, each pin labelled with its net
|
|
1442
|
+
})
|
|
1443
|
+
.filter((p) => p.pads.length);
|
|
1444
|
+
const have = new Set(parts.flatMap((p) => p.pads.map((q) => `${p.name}.${q.pin}`))),
|
|
1445
|
+
dropped = new Set();
|
|
1446
|
+
const nets = Object.fromEntries(
|
|
1447
|
+
Object.entries(circuit.nets)
|
|
1448
|
+
.filter(([n]) => !planes.includes(n))
|
|
1449
|
+
.map(([n, pins]) => [
|
|
1450
|
+
n,
|
|
1451
|
+
pins
|
|
1452
|
+
.map((x) => {
|
|
1453
|
+
const i = x.indexOf('.');
|
|
1454
|
+
return `${x.slice(0, i)}.pin${x.slice(i + 1)}`;
|
|
1455
|
+
})
|
|
1456
|
+
.filter((x) => have.has(x) || !dropped.add(x)),
|
|
1457
|
+
])
|
|
1458
|
+
.filter(([, pins]) => pins.length > 1),
|
|
1459
|
+
);
|
|
700
1460
|
const plural = (set, one, many) => `${set.size} ${set.size === 1 ? one : many} (${[...set].join(', ')})`;
|
|
701
1461
|
// On 4 layers or more, each plane net fills the inner layer the source gives it (the first, if several), or the next free one
|
|
702
|
-
const onPlanes = {},
|
|
703
|
-
|
|
704
|
-
|
|
705
|
-
const
|
|
706
|
-
|
|
707
|
-
|
|
708
|
-
|
|
709
|
-
|
|
710
|
-
|
|
711
|
-
|
|
712
|
-
|
|
713
|
-
|
|
1462
|
+
const onPlanes = {},
|
|
1463
|
+
free = Array.from({ length: Math.max(0, layers - 2) }, (_, i) => `inner${i + 1}`);
|
|
1464
|
+
if (layers >= 4)
|
|
1465
|
+
for (const n of planes) {
|
|
1466
|
+
const own = (circuit.planes?.[n] || []).find(inner),
|
|
1467
|
+
want = own ? `inner${own.match(/\d+/)[0]}` : null;
|
|
1468
|
+
const layer = want && free.includes(want) ? want : free[0];
|
|
1469
|
+
if (!layer) {
|
|
1470
|
+
notes.push(`${n}: no inner layer left for its plane`);
|
|
1471
|
+
continue;
|
|
1472
|
+
}
|
|
1473
|
+
free.splice(free.indexOf(layer), 1);
|
|
1474
|
+
onPlanes[n] = {
|
|
1475
|
+
layer,
|
|
1476
|
+
pins: (circuit.nets[n] || [])
|
|
1477
|
+
.map((x) => {
|
|
1478
|
+
const i = x.indexOf('.');
|
|
1479
|
+
return `${x.slice(0, i)}.pin${x.slice(i + 1)}`;
|
|
1480
|
+
})
|
|
1481
|
+
.filter((x) => have.has(x)),
|
|
1482
|
+
};
|
|
1483
|
+
}
|
|
1484
|
+
if (layers >= 4 && Object.keys(onPlanes).length)
|
|
1485
|
+
notes.push(
|
|
1486
|
+
`planes on inner layers: ${Object.entries(onPlanes)
|
|
1487
|
+
.map(([n, q]) => `${n} on ${q.layer} (${q.pins.length} pads)`)
|
|
1488
|
+
.join(', ')}`,
|
|
1489
|
+
);
|
|
1490
|
+
else if (planes.length)
|
|
1491
|
+
notes.push(
|
|
1492
|
+
`left to planes, not routed: ${planes.map((n) => `${n} (${circuit.nets[n]?.length ?? 0} pads)`).join(', ')}. On 2 layers these nets need a pour joined to every pad: build the board with 4 layers ({ layers: 4 }) to give them planes`,
|
|
1493
|
+
);
|
|
1494
|
+
if (castellated.size)
|
|
1495
|
+
notes.push(
|
|
1496
|
+
`castellated pads on ${plural(castellated, 'part', 'parts')}: half holes on the board's edge, which the fab cuts through (an option when ordering)`,
|
|
1497
|
+
);
|
|
1498
|
+
if (dropped.size)
|
|
1499
|
+
notes.push(
|
|
1500
|
+
`${dropped.size} pins with no pad left on this board are out of their nets: ${[...dropped].slice(0, 5).join(', ')}`,
|
|
1501
|
+
);
|
|
714
1502
|
const src = circuit.source || {}; // the source's via and clearance, which its layout was made to
|
|
715
|
-
const sizes = {
|
|
1503
|
+
const sizes = {
|
|
1504
|
+
...(src.via ? { via_pad: src.via.pad, via_hole: src.via.hole } : {}),
|
|
1505
|
+
...(src.clearance ? { plane_clearance: src.clearance } : {}),
|
|
1506
|
+
};
|
|
716
1507
|
// The source's own copper kept with a moved block, its pins named as the board names them
|
|
717
|
-
const named = (x) => {
|
|
718
|
-
|
|
719
|
-
|
|
720
|
-
|
|
721
|
-
|
|
1508
|
+
const named = (x) => {
|
|
1509
|
+
const i = x.indexOf('.');
|
|
1510
|
+
return `${x.slice(0, i)}.pin${x.slice(i + 1)}`;
|
|
1511
|
+
};
|
|
1512
|
+
const copper = circuit.kept?.islands.length
|
|
1513
|
+
? {
|
|
1514
|
+
...circuit.kept,
|
|
1515
|
+
islands: circuit.kept.islands.map((k) => ({ ...k, pins: k.pins.map(named) })),
|
|
1516
|
+
stubs: (circuit.kept.stubs || []).map((b) => ({ ...b, pin: named(b.pin) })),
|
|
1517
|
+
}
|
|
1518
|
+
: null;
|
|
1519
|
+
if (copper)
|
|
1520
|
+
notes.push(
|
|
1521
|
+
`the source's own routing kept: ${copper.tracks.length} tracks and ${copper.vias.length} vias in ${copper.islands.length} pieces, and ${copper.stubs.length} escapes routed on from where they leave`,
|
|
1522
|
+
);
|
|
1523
|
+
return {
|
|
1524
|
+
parts,
|
|
1525
|
+
nets,
|
|
1526
|
+
holes: circuit.holes,
|
|
1527
|
+
outline: circuit.outline,
|
|
1528
|
+
layers,
|
|
1529
|
+
...(Object.keys(onPlanes).length ? { planes: onPlanes } : {}),
|
|
1530
|
+
...(copper ? { copper } : {}),
|
|
1531
|
+
...sizes,
|
|
1532
|
+
notes,
|
|
1533
|
+
};
|
|
722
1534
|
}
|
|
723
1535
|
|
|
724
1536
|
// A part's pads on the board (the circuit's frame), as render places them: turned, and mirrored in x on the back
|
|
725
1537
|
export function padsOnBoard(part) {
|
|
726
|
-
const m = part.layer === 'bottom' ? -1 : 1,
|
|
727
|
-
|
|
1538
|
+
const m = part.layer === 'bottom' ? -1 : 1,
|
|
1539
|
+
t = (part.rotation * Math.PI) / 180,
|
|
1540
|
+
c = Math.cos(t),
|
|
1541
|
+
s = Math.sin(t);
|
|
1542
|
+
return part.pads.map((q) => ({
|
|
1543
|
+
...q,
|
|
1544
|
+
bx: r4(part.x + m * (c * q.x - s * q.y)),
|
|
1545
|
+
by: r4(part.y + (s * q.x + c * q.y)),
|
|
1546
|
+
}));
|
|
728
1547
|
}
|
|
729
1548
|
|
|
730
1549
|
/**
|
|
@@ -736,10 +1555,26 @@ export function padsOnBoard(part) {
|
|
|
736
1555
|
export function withFootprint(circuit, ref, pads) {
|
|
737
1556
|
const part = circuit.parts.find((p) => p.ref === ref);
|
|
738
1557
|
if (!part) throw new Error(`withFootprint: no part ${ref} in the circuit`);
|
|
739
|
-
const had = new Map(part.pads.map((q) => [q.pin, q.net])),
|
|
740
|
-
|
|
741
|
-
|
|
742
|
-
|
|
1558
|
+
const had = new Map(part.pads.map((q) => [q.pin, q.net])),
|
|
1559
|
+
given = new Set(pads.map((q) => q.pin));
|
|
1560
|
+
const missing = [...had.keys()].filter((n) => !given.has(n)),
|
|
1561
|
+
extra = [...given].filter((n) => !had.has(n));
|
|
1562
|
+
if (missing.length || extra.length)
|
|
1563
|
+
throw new Error(
|
|
1564
|
+
`withFootprint: ${ref}'s new pads must have the same pins as before${missing.length ? `; missing ${missing.join(', ')}` : ''}${extra.length ? `; not on ${ref}: ${extra.join(', ')}` : ''}`,
|
|
1565
|
+
);
|
|
1566
|
+
return {
|
|
1567
|
+
...circuit,
|
|
1568
|
+
parts: circuit.parts.map((p) =>
|
|
1569
|
+
p.ref === ref
|
|
1570
|
+
? {
|
|
1571
|
+
...p,
|
|
1572
|
+
footprint: `${p.footprint} (reshaped)`,
|
|
1573
|
+
pads: pads.map((q) => ({ angle: 0, smd: false, shape: 'circle', ...q, net: had.get(q.pin) })),
|
|
1574
|
+
}
|
|
1575
|
+
: p,
|
|
1576
|
+
),
|
|
1577
|
+
};
|
|
743
1578
|
}
|
|
744
1579
|
|
|
745
1580
|
/**
|
|
@@ -751,16 +1586,28 @@ export function withFootprint(circuit, ref, pads) {
|
|
|
751
1586
|
export function addPins(circuit, ref, pads) {
|
|
752
1587
|
const part = circuit.parts.find((p) => p.ref === ref);
|
|
753
1588
|
if (!part) throw new Error(`addPins: no part ${ref} in the circuit`);
|
|
754
|
-
const have = new Set(part.pads.map((q) => q.pin)),
|
|
1589
|
+
const have = new Set(part.pads.map((q) => q.pin)),
|
|
1590
|
+
nets = { ...circuit.nets },
|
|
1591
|
+
added = [...(circuit.added || [])];
|
|
755
1592
|
for (const q of pads) {
|
|
756
1593
|
if (have.has(q.pin)) throw new Error(`addPins: ${ref} already has a pin ${q.pin}`);
|
|
757
|
-
if (!q.joins && !nets[q.net])
|
|
758
|
-
|
|
1594
|
+
if (!q.joins && !nets[q.net])
|
|
1595
|
+
throw new Error(`addPins: no net ${q.net} in the source (give joins: [...] for a new net)`);
|
|
1596
|
+
if (q.joins)
|
|
1597
|
+
for (const x of q.joins) {
|
|
1598
|
+
const owner = Object.entries(nets).find(([, n]) => n.includes(x));
|
|
1599
|
+
if (owner) throw new Error(`addPins: ${x} is already on ${owner[0]}`);
|
|
1600
|
+
}
|
|
759
1601
|
nets[q.net] = [...(nets[q.net] || q.joins), `${ref}.${q.pin}`];
|
|
760
1602
|
added.push({ pin: `${ref}.${q.pin}`, net: q.net, ...(q.joins ? { joins: q.joins } : {}) });
|
|
761
1603
|
}
|
|
762
1604
|
const extra = pads.map(({ joins, ...q }) => ({ angle: 0, smd: false, shape: 'circle', ...q }));
|
|
763
|
-
return {
|
|
1605
|
+
return {
|
|
1606
|
+
...circuit,
|
|
1607
|
+
nets,
|
|
1608
|
+
added,
|
|
1609
|
+
parts: circuit.parts.map((p) => (p.ref === ref ? { ...p, pads: [...p.pads, ...extra] } : p)),
|
|
1610
|
+
};
|
|
764
1611
|
}
|
|
765
1612
|
|
|
766
1613
|
/**
|
|
@@ -774,15 +1621,36 @@ export function addPins(circuit, ref, pads) {
|
|
|
774
1621
|
* o: { reach = 1.5, step = 0.1, gap = 0.15, char = 0.75 (a character's width over its height), area, near = 6 }.
|
|
775
1622
|
* @param {object[]} silk { text, x, y, size, rotation, to } @param {object} circuit @param {object} [o]
|
|
776
1623
|
*/
|
|
777
|
-
export function clearLabels(
|
|
778
|
-
|
|
779
|
-
|
|
780
|
-
|
|
1624
|
+
export function clearLabels(
|
|
1625
|
+
silk,
|
|
1626
|
+
circuit,
|
|
1627
|
+
{ reach = 1.5, step = 0.1, gap = 0.15, char = 0.75, area = null, near = 6 } = {},
|
|
1628
|
+
) {
|
|
1629
|
+
const padBoxes = (p) =>
|
|
1630
|
+
padsOnBoard(p).map((q) => {
|
|
1631
|
+
const t = turnOf(p.rotation + q.angle) % 180 === 90;
|
|
1632
|
+
return { x: q.bx, y: q.by, w: t ? q.h : q.w, h: t ? q.w : q.h };
|
|
1633
|
+
});
|
|
1634
|
+
const copper = circuit.parts.flatMap((p) => [
|
|
1635
|
+
...padBoxes(p),
|
|
1636
|
+
...padsOnBoard({ ...p, pads: (p.holes || []).map((h) => ({ ...h, w: h.d, h: h.d, angle: 0 })) }).map((h) => ({
|
|
1637
|
+
x: h.bx,
|
|
1638
|
+
y: h.by,
|
|
1639
|
+
w: h.w,
|
|
1640
|
+
h: h.h,
|
|
1641
|
+
})),
|
|
1642
|
+
]);
|
|
781
1643
|
// A surface-mount part's body spans its pads: a label with an arrow keeps off it (the part would hide it)
|
|
782
|
-
const bodies = circuit.parts
|
|
783
|
-
|
|
784
|
-
|
|
785
|
-
|
|
1644
|
+
const bodies = circuit.parts
|
|
1645
|
+
.filter((p) => p.pads.length > 1 && p.pads.every((q) => q.smd))
|
|
1646
|
+
.map((p) => {
|
|
1647
|
+
const b = padBoxes(p),
|
|
1648
|
+
x0 = Math.min(...b.map((q) => q.x - q.w / 2)),
|
|
1649
|
+
x1 = Math.max(...b.map((q) => q.x + q.w / 2)),
|
|
1650
|
+
y0 = Math.min(...b.map((q) => q.y - q.h / 2)),
|
|
1651
|
+
y1 = Math.max(...b.map((q) => q.y + q.h / 2));
|
|
1652
|
+
return { x: (x0 + x1) / 2, y: (y0 + y1) / 2, w: x1 - x0, h: y1 - y0 };
|
|
1653
|
+
});
|
|
786
1654
|
return slideClear(silk, copper, { reach, step, gap, char, bodies, area, near });
|
|
787
1655
|
}
|
|
788
1656
|
|
|
@@ -795,16 +1663,32 @@ export function clearLabels(silk, circuit, { reach = 1.5, step = 0.1, gap = 0.15
|
|
|
795
1663
|
* @param {object} circuit @param {{ anchor?: number }} [o] @returns {object[]}
|
|
796
1664
|
*/
|
|
797
1665
|
export function learnPlacement(circuit, o = {}) {
|
|
798
|
-
const min = o.anchor ?? 4,
|
|
799
|
-
|
|
1666
|
+
const min = o.anchor ?? 4,
|
|
1667
|
+
anchors = circuit.parts.filter((p) => p.pads.length >= min),
|
|
1668
|
+
rules = [];
|
|
1669
|
+
const anchorPads = anchors.flatMap((a) =>
|
|
1670
|
+
padsOnBoard(a)
|
|
1671
|
+
.filter((q) => q.net)
|
|
1672
|
+
.map((q) => ({ ...q, ref: a.ref })),
|
|
1673
|
+
);
|
|
800
1674
|
for (const p of circuit.parts.filter((x) => x.pads.length < min)) {
|
|
801
1675
|
let best = null; // on its most particular net (the fewest pins: a crystal's pin before GND), then the nearest pad
|
|
802
|
-
for (const q of padsOnBoard(p))
|
|
803
|
-
|
|
804
|
-
|
|
805
|
-
|
|
806
|
-
|
|
807
|
-
|
|
1676
|
+
for (const q of padsOnBoard(p))
|
|
1677
|
+
for (const a of anchorPads) {
|
|
1678
|
+
if (!q.net || a.net !== q.net) continue;
|
|
1679
|
+
const d = Math.hypot(a.bx - q.bx, a.by - q.by),
|
|
1680
|
+
n = circuit.nets[q.net]?.length ?? Infinity;
|
|
1681
|
+
if (!best || n < best.n || (n === best.n && d < best.d)) best = { d, n, q, a };
|
|
1682
|
+
}
|
|
1683
|
+
if (best)
|
|
1684
|
+
rules.push({
|
|
1685
|
+
part: p.ref,
|
|
1686
|
+
anchor: best.a.ref,
|
|
1687
|
+
pin: best.a.pin,
|
|
1688
|
+
net: best.q.net,
|
|
1689
|
+
source: r4(best.d),
|
|
1690
|
+
max: r4(Math.max(best.d * 1.25, best.d + 0.5)),
|
|
1691
|
+
});
|
|
808
1692
|
}
|
|
809
1693
|
return rules;
|
|
810
1694
|
}
|
|
@@ -816,24 +1700,49 @@ export function learnPlacement(circuit, o = {}) {
|
|
|
816
1700
|
* @param {object} circuit @param {Record<string, { x?: number, y?: number, rotation?: number }>} moves @param {object[]} [rules]
|
|
817
1701
|
*/
|
|
818
1702
|
export function arrange(circuit, moves, rules = circuit.placement || learnPlacement(circuit)) {
|
|
819
|
-
const byRef = new Map(circuit.parts.map((p) => [p.ref, p])),
|
|
1703
|
+
const byRef = new Map(circuit.parts.map((p) => [p.ref, p])),
|
|
1704
|
+
follow = new Map(rules.map((r) => [r.part, r.anchor]));
|
|
820
1705
|
for (const ref of Object.keys(moves)) if (!byRef.has(ref)) throw new Error(`arrange: no part ${ref} in the circuit`);
|
|
821
1706
|
const moved = (p) => {
|
|
822
1707
|
const to = moves[p.ref];
|
|
823
|
-
if (to) {
|
|
824
|
-
|
|
1708
|
+
if (to) {
|
|
1709
|
+
const dr = ((to.rotation ?? p.rotation) - p.rotation + 360) % 360;
|
|
1710
|
+
return { ...p, x: to.x ?? p.x, y: to.y ?? p.y, rotation: (to.rotation ?? p.rotation) % 360, dr };
|
|
1711
|
+
}
|
|
1712
|
+
const a = follow.has(p.ref) && !moves[p.ref] ? byRef.get(follow.get(p.ref)) : null,
|
|
1713
|
+
at = a && moves[a.ref];
|
|
825
1714
|
if (!at) return p;
|
|
826
|
-
const turn = ((at.rotation ?? a.rotation) - a.rotation + 360) % 360,
|
|
827
|
-
|
|
828
|
-
|
|
1715
|
+
const turn = ((at.rotation ?? a.rotation) - a.rotation + 360) % 360,
|
|
1716
|
+
t = (turn * Math.PI) / 180,
|
|
1717
|
+
c = Math.cos(t),
|
|
1718
|
+
s = Math.sin(t);
|
|
1719
|
+
const dx = p.x - a.x,
|
|
1720
|
+
dy = p.y - a.y,
|
|
1721
|
+
own = p.layer === a.layer ? turn : -turn; // a part on the other side turns the other way, seen from its side
|
|
1722
|
+
return {
|
|
1723
|
+
...p,
|
|
1724
|
+
x: r4((at.x ?? a.x) + c * dx - s * dy),
|
|
1725
|
+
y: r4((at.y ?? a.y) + s * dx + c * dy),
|
|
1726
|
+
rotation: turnOf(p.rotation + own),
|
|
1727
|
+
};
|
|
829
1728
|
};
|
|
830
1729
|
const parts = circuit.parts.map(moved).map(({ dr, ...p }) => p);
|
|
831
|
-
const shifted = new Set(
|
|
832
|
-
|
|
1730
|
+
const shifted = new Set(
|
|
1731
|
+
parts
|
|
1732
|
+
.filter(
|
|
1733
|
+
(p, i) => p.x !== circuit.parts[i].x || p.y !== circuit.parts[i].y || p.rotation !== circuit.parts[i].rotation,
|
|
1734
|
+
)
|
|
1735
|
+
.map((p) => p.ref),
|
|
1736
|
+
); // a kept island to a part that moved apart is left to routing
|
|
1737
|
+
const kept = circuit.kept && {
|
|
1738
|
+
...circuit.kept,
|
|
1739
|
+
islands: circuit.kept.islands.filter((k) => !k.pins.some((x) => shifted.has(x.split('.')[0]))),
|
|
1740
|
+
};
|
|
833
1741
|
if (kept) {
|
|
834
1742
|
kept.stubs = (kept.stubs || []).filter((b) => !shifted.has(b.pin.split('.')[0]));
|
|
835
1743
|
const ids = new Set([...kept.islands.map((k) => k.id), ...kept.stubs.map((b) => b.id)]);
|
|
836
|
-
kept.tracks = kept.tracks.filter((g) => ids.has(g.island ?? g.stub));
|
|
1744
|
+
kept.tracks = kept.tracks.filter((g) => ids.has(g.island ?? g.stub));
|
|
1745
|
+
kept.vias = kept.vias.filter((v) => ids.has(v.island ?? v.stub));
|
|
837
1746
|
}
|
|
838
1747
|
return { ...circuit, ...(kept ? { kept } : {}), parts };
|
|
839
1748
|
}
|
|
@@ -847,105 +1756,248 @@ export function arrange(circuit, moves, rules = circuit.placement || learnPlacem
|
|
|
847
1756
|
* @param {object} circuit @param {string[]} refs @param {{ turn?: number, dx?: number, dy?: number }} move @param {{ keep?: boolean }} [o]
|
|
848
1757
|
*/
|
|
849
1758
|
export function moveGroup(circuit, refs, { turn = 0, dx = 0, dy = 0 } = {}, { keep = false } = {}) {
|
|
850
|
-
const set = new Set(refs),
|
|
1759
|
+
const set = new Set(refs),
|
|
1760
|
+
missing = refs.filter((r) => !circuit.parts.some((p) => p.ref === r));
|
|
851
1761
|
if (missing.length) throw new Error(`moveGroup: no part ${missing.join(', ')} in the circuit`);
|
|
852
1762
|
if (turn % 90) throw new Error(`moveGroup: turn in quarter turns (0, 90, 180, 270), not ${turn}`);
|
|
853
|
-
const t = (turn * Math.PI) / 180,
|
|
1763
|
+
const t = (turn * Math.PI) / 180,
|
|
1764
|
+
c = Math.round(Math.cos(t)),
|
|
1765
|
+
s = Math.round(Math.sin(t));
|
|
854
1766
|
const at = ({ x, y }) => ({ x: r4(c * x - s * y + dx), y: r4(s * x + c * y + dy) });
|
|
855
1767
|
let kept = circuit.kept;
|
|
856
|
-
if (keep) {
|
|
857
|
-
|
|
1768
|
+
if (keep) {
|
|
1769
|
+
// the source's copper wholly within the group, moved with it
|
|
1770
|
+
if (!circuit.routing)
|
|
1771
|
+
throw new Error("moveGroup: keep needs the source's tracks (circuit.routing, from fromKicadPcb)");
|
|
858
1772
|
const k = islands(circuit, set);
|
|
859
|
-
kept = {
|
|
860
|
-
|
|
861
|
-
|
|
1773
|
+
kept = {
|
|
1774
|
+
tracks: [...(kept?.tracks || []), ...k.tracks.map((g) => ({ ...g, a: at(g.a), b: at(g.b) }))],
|
|
1775
|
+
vias: [...(kept?.vias || []), ...k.vias.map((v) => ({ ...v, ...at(v) }))],
|
|
1776
|
+
islands: [...(kept?.islands || []), ...k.islands],
|
|
1777
|
+
stubs: [...(kept?.stubs || []), ...k.stubs.map((b) => ({ ...b, end: { ...b.end, ...at(b.end) } }))],
|
|
1778
|
+
};
|
|
862
1779
|
}
|
|
863
|
-
return {
|
|
864
|
-
...
|
|
865
|
-
|
|
1780
|
+
return {
|
|
1781
|
+
...circuit,
|
|
1782
|
+
...(kept ? { kept } : {}),
|
|
1783
|
+
parts: circuit.parts.map((p) =>
|
|
1784
|
+
!set.has(p.ref)
|
|
1785
|
+
? p
|
|
1786
|
+
: {
|
|
1787
|
+
...p,
|
|
1788
|
+
...at(p),
|
|
1789
|
+
rotation: turnOf(p.rotation + (p.layer === 'bottom' ? -turn : turn)),
|
|
1790
|
+
},
|
|
1791
|
+
),
|
|
1792
|
+
};
|
|
866
1793
|
}
|
|
867
1794
|
|
|
868
1795
|
// The source's copper in islands: tracks and vias joined end to end, through a via, or by touching a pad of their net.
|
|
869
1796
|
// Returns the islands that touch only pads of the given parts (at least one): { tracks, vias, islands: [{ id, net,
|
|
870
1797
|
// pins, via }] }, each track and via carrying its island's id. Islands touching any other part, or no pad, are left.
|
|
871
1798
|
function islands(circuit, refs) {
|
|
872
|
-
const { tracks, vias } = circuit.routing,
|
|
873
|
-
|
|
874
|
-
|
|
875
|
-
|
|
876
|
-
|
|
877
|
-
|
|
1799
|
+
const { tracks, vias } = circuit.routing,
|
|
1800
|
+
near = 0.01;
|
|
1801
|
+
const pads = circuit.parts.flatMap((p) =>
|
|
1802
|
+
padsOnBoard(p).map((q) => {
|
|
1803
|
+
const turned = turnOf(p.rotation + q.angle) % 180 === 90;
|
|
1804
|
+
return {
|
|
1805
|
+
ref: p.ref,
|
|
1806
|
+
pin: q.pin,
|
|
1807
|
+
net: q.net,
|
|
1808
|
+
x: q.bx,
|
|
1809
|
+
y: q.by,
|
|
1810
|
+
w: turned ? q.h : q.w,
|
|
1811
|
+
h: turned ? q.w : q.h,
|
|
1812
|
+
layer: q.smd ? p.layer : null,
|
|
1813
|
+
};
|
|
1814
|
+
}),
|
|
1815
|
+
);
|
|
1816
|
+
const onSeg = (pt, g) => {
|
|
1817
|
+
const dx = g.b.x - g.a.x,
|
|
1818
|
+
dy = g.b.y - g.a.y,
|
|
1819
|
+
l = dx * dx + dy * dy,
|
|
1820
|
+
u = l ? Math.max(0, Math.min(1, ((pt.x - g.a.x) * dx + (pt.y - g.a.y) * dy) / l)) : 0;
|
|
1821
|
+
return Math.hypot(pt.x - g.a.x - u * dx, pt.y - g.a.y - u * dy) <= near;
|
|
1822
|
+
};
|
|
878
1823
|
// copper touching copper: a track's end within half its width of the pad (as KiCad joins them), a via within its radius
|
|
879
|
-
const inPad = (pt, q, layer, reach = 0) =>
|
|
880
|
-
|
|
881
|
-
|
|
882
|
-
|
|
883
|
-
|
|
884
|
-
|
|
885
|
-
|
|
886
|
-
|
|
887
|
-
|
|
888
|
-
|
|
889
|
-
|
|
1824
|
+
const inPad = (pt, q, layer, reach = 0) =>
|
|
1825
|
+
(!q.layer || !layer || q.layer === layer) &&
|
|
1826
|
+
Math.abs(pt.x - q.x) <= q.w / 2 + reach + near &&
|
|
1827
|
+
Math.abs(pt.y - q.y) <= q.h / 2 + reach + near;
|
|
1828
|
+
const nodes = [
|
|
1829
|
+
...tracks.map((g, i) => ({ kind: 't', i, g, net: g.net })),
|
|
1830
|
+
...vias.map((v, i) => ({ kind: 'v', i, v, net: v.net })),
|
|
1831
|
+
];
|
|
1832
|
+
const adj = nodes.map(() => []),
|
|
1833
|
+
up = nodes.map((_, i) => i),
|
|
1834
|
+
find = (i) => {
|
|
1835
|
+
while (up[i] !== i) i = up[i] = up[up[i]];
|
|
1836
|
+
return i;
|
|
1837
|
+
},
|
|
1838
|
+
join = (i, j) => {
|
|
1839
|
+
up[find(i)] = find(j);
|
|
1840
|
+
};
|
|
1841
|
+
const byNet = new Map();
|
|
1842
|
+
nodes.forEach((n, i) => byNet.set(n.net, [...(byNet.get(n.net) || []), i]));
|
|
1843
|
+
for (const list of byNet.values())
|
|
1844
|
+
for (let x = 0; x < list.length; x++)
|
|
1845
|
+
for (let y = x + 1; y < list.length; y++) {
|
|
1846
|
+
const A = nodes[list[x]],
|
|
1847
|
+
B = nodes[list[y]];
|
|
1848
|
+
const touch =
|
|
1849
|
+
A.kind === 't' && B.kind === 't'
|
|
1850
|
+
? A.g.layer === B.g.layer &&
|
|
1851
|
+
(onSeg(A.g.a, B.g) || onSeg(A.g.b, B.g) || onSeg(B.g.a, A.g) || onSeg(B.g.b, A.g))
|
|
1852
|
+
: A.kind === 'v' && B.kind === 'v'
|
|
1853
|
+
? Math.hypot(A.v.x - B.v.x, A.v.y - B.v.y) <= (A.v.pad + B.v.pad) / 2
|
|
1854
|
+
: (() => {
|
|
1855
|
+
const [t, v] = A.kind === 't' ? [A.g, B.v] : [B.g, A.v];
|
|
1856
|
+
return (
|
|
1857
|
+
Math.hypot(t.a.x - v.x, t.a.y - v.y) <= v.pad / 2 + near ||
|
|
1858
|
+
Math.hypot(t.b.x - v.x, t.b.y - v.y) <= v.pad / 2 + near
|
|
1859
|
+
);
|
|
1860
|
+
})();
|
|
1861
|
+
if (touch) {
|
|
1862
|
+
join(list[x], list[y]);
|
|
1863
|
+
adj[list[x]].push(list[y]);
|
|
1864
|
+
adj[list[y]].push(list[x]);
|
|
1865
|
+
}
|
|
1866
|
+
}
|
|
890
1867
|
const touched = new Map(); // island root -> pads it touches
|
|
891
1868
|
nodes.forEach((n, i) => {
|
|
892
|
-
const hit = pads.filter(
|
|
893
|
-
|
|
1869
|
+
const hit = pads.filter(
|
|
1870
|
+
(q) =>
|
|
1871
|
+
q.net === n.net &&
|
|
1872
|
+
(n.kind === 't'
|
|
1873
|
+
? inPad(n.g.a, q, n.g.layer, n.g.width / 2) || inPad(n.g.b, q, n.g.layer, n.g.width / 2)
|
|
1874
|
+
: inPad(n.v, q, null, n.v.pad / 2)),
|
|
1875
|
+
);
|
|
1876
|
+
const r = find(i);
|
|
1877
|
+
touched.set(r, [...(touched.get(r) || []), ...hit]);
|
|
894
1878
|
});
|
|
895
1879
|
const keep = new Map(); // root -> island
|
|
896
|
-
for (const [r, hit] of touched)
|
|
897
|
-
|
|
1880
|
+
for (const [r, hit] of touched)
|
|
1881
|
+
if (hit.length && hit.every((q) => refs.has(q.ref)))
|
|
1882
|
+
keep.set(r, {
|
|
1883
|
+
id: `island${keep.size + 1}`,
|
|
1884
|
+
net: nodes[r].net,
|
|
1885
|
+
pins: [...new Set(hit.map((q) => `${q.ref}.${q.pin}`))],
|
|
1886
|
+
via: false,
|
|
1887
|
+
});
|
|
898
1888
|
// A kept piece's dead ends (a branch that led somewhere left behind): trimmed, track by track
|
|
899
|
-
const dead = new Set(),
|
|
1889
|
+
const dead = new Set(),
|
|
1890
|
+
ends = (i) => {
|
|
1891
|
+
const g = nodes[i].g;
|
|
1892
|
+
return [g.a, g.b];
|
|
1893
|
+
};
|
|
900
1894
|
for (let again = true; again;) {
|
|
901
1895
|
again = false;
|
|
902
1896
|
nodes.forEach((n, i) => {
|
|
903
1897
|
if (n.kind !== 't' || dead.has(i) || !keep.has(find(i))) return;
|
|
904
|
-
const free = ends(i).some(
|
|
905
|
-
|
|
906
|
-
|
|
1898
|
+
const free = ends(i).some(
|
|
1899
|
+
(pt) =>
|
|
1900
|
+
!pads.some((q) => q.net === n.net && inPad(pt, q, n.g.layer, n.g.width / 2)) &&
|
|
1901
|
+
!adj[i].some(
|
|
1902
|
+
(j) =>
|
|
1903
|
+
!dead.has(j) &&
|
|
1904
|
+
(nodes[j].kind === 'v'
|
|
1905
|
+
? Math.hypot(pt.x - nodes[j].v.x, pt.y - nodes[j].v.y) <= nodes[j].v.pad / 2 + near
|
|
1906
|
+
: onSeg(pt, nodes[j].g) ||
|
|
1907
|
+
[nodes[j].g.a, nodes[j].g.b].some((e) => Math.hypot(e.x - pt.x, e.y - pt.y) <= near)),
|
|
1908
|
+
),
|
|
1909
|
+
);
|
|
1910
|
+
if (free) {
|
|
1911
|
+
dead.add(i);
|
|
1912
|
+
again = true;
|
|
1913
|
+
}
|
|
907
1914
|
});
|
|
908
1915
|
}
|
|
909
1916
|
// A track's end that stops just short of its pad (its copper overlapping it, as KiCad joins them) is moved onto the pad
|
|
910
|
-
const onto = (pt, net, layer, reach) => {
|
|
911
|
-
|
|
912
|
-
|
|
1917
|
+
const onto = (pt, net, layer, reach) => {
|
|
1918
|
+
const q = pads.find((d) => d.net === net && inPad(pt, d, layer, reach) && !inPad(pt, d, layer));
|
|
1919
|
+
return q
|
|
1920
|
+
? {
|
|
1921
|
+
x: r4(Math.min(Math.max(pt.x, q.x - q.w / 2 + 0.01), q.x + q.w / 2 - 0.01)),
|
|
1922
|
+
y: r4(Math.min(Math.max(pt.y, q.y - q.h / 2 + 0.01), q.y + q.h / 2 - 0.01)),
|
|
1923
|
+
}
|
|
1924
|
+
: pt;
|
|
1925
|
+
};
|
|
1926
|
+
const snapped = (g) => ({
|
|
1927
|
+
...g,
|
|
1928
|
+
a: onto(g.a, g.net, g.layer, g.width / 2),
|
|
1929
|
+
b: onto(g.b, g.net, g.layer, g.width / 2),
|
|
1930
|
+
});
|
|
913
1931
|
const out = { tracks: [], vias: [], islands: [], stubs: [] };
|
|
914
|
-
nodes.forEach((n, i) => {
|
|
1932
|
+
nodes.forEach((n, i) => {
|
|
1933
|
+
const k = keep.get(find(i));
|
|
1934
|
+
if (!k || dead.has(i)) return;
|
|
1935
|
+
if (n.kind === 't') out.tracks.push({ ...snapped(n.g), island: k.id });
|
|
1936
|
+
else {
|
|
1937
|
+
k.via = true;
|
|
1938
|
+
out.vias.push({ ...n.v, island: k.id });
|
|
1939
|
+
}
|
|
1940
|
+
});
|
|
915
1941
|
out.islands = [...keep.values()];
|
|
916
1942
|
// Breakouts: an island from one of the block's pins out to other parts keeps its stretch within the block's bounds,
|
|
917
1943
|
// from the pin to where it leaves (a fine-pitch chip's escape, proven); the rest is routed from the stub's end
|
|
918
1944
|
const own = pads.filter((q) => refs.has(q.ref));
|
|
919
1945
|
if (!own.length) return out;
|
|
920
|
-
const box = {
|
|
1946
|
+
const box = {
|
|
1947
|
+
x0: Math.min(...own.map((q) => q.x - q.w / 2)) - 0.3,
|
|
1948
|
+
x1: Math.max(...own.map((q) => q.x + q.w / 2)) + 0.3,
|
|
1949
|
+
y0: Math.min(...own.map((q) => q.y - q.h / 2)) - 0.3,
|
|
1950
|
+
y1: Math.max(...own.map((q) => q.y + q.h / 2)) + 0.3,
|
|
1951
|
+
};
|
|
921
1952
|
const inBox = (pt) => pt.x >= box.x0 && pt.x <= box.x1 && pt.y >= box.y0 && pt.y <= box.y1;
|
|
922
1953
|
const inside = (n) => (n.kind === 't' ? inBox(n.g.a) && inBox(n.g.b) : inBox(n.v));
|
|
923
1954
|
for (const [r, hit] of touched) {
|
|
924
1955
|
const mine = [...new Set(hit.filter((q) => refs.has(q.ref)).map((q) => `${q.ref}.${q.pin}`))];
|
|
925
1956
|
if (keep.has(r) || mine.length !== 1 || hit.every((q) => refs.has(q.ref))) continue;
|
|
926
1957
|
const pin = own.find((q) => `${q.ref}.${q.pin}` === mine[0]);
|
|
927
|
-
const touches = (n) =>
|
|
1958
|
+
const touches = (n) =>
|
|
1959
|
+
n.kind === 't'
|
|
1960
|
+
? inPad(n.g.a, pin, n.g.layer, n.g.width / 2) || inPad(n.g.b, pin, n.g.layer, n.g.width / 2)
|
|
1961
|
+
: inPad(n.v, pin, null, n.v.pad / 2);
|
|
928
1962
|
const start = nodes.map((n, i) => i).filter((i) => find(i) === r && touches(nodes[i]));
|
|
929
1963
|
// From the pin outward: whole pieces within the bounds, and the one track that crosses them cut where it does
|
|
930
|
-
const seen = new Set(),
|
|
931
|
-
|
|
1964
|
+
const seen = new Set(),
|
|
1965
|
+
cut = [],
|
|
1966
|
+
queue = [];
|
|
1967
|
+
const visit = (j) => {
|
|
932
1968
|
if (seen.has(j)) return;
|
|
933
1969
|
const n = nodes[j];
|
|
934
|
-
if (inside(n)) {
|
|
1970
|
+
if (inside(n)) {
|
|
1971
|
+
seen.add(j);
|
|
1972
|
+
queue.push(j);
|
|
1973
|
+
return;
|
|
1974
|
+
}
|
|
935
1975
|
if (n.kind !== 't') return cut.push(null); // a via outside: give up on a stub
|
|
936
1976
|
const [p, q] = inBox(n.g.a) ? [n.g.a, n.g.b] : inBox(n.g.b) ? [n.g.b, n.g.a] : [null, null];
|
|
937
1977
|
if (!p) return cut.push(null);
|
|
938
1978
|
let t = 1; // where p -> q leaves the box
|
|
939
|
-
for (const [d, lo, hi, o] of [
|
|
1979
|
+
for (const [d, lo, hi, o] of [
|
|
1980
|
+
[q.x - p.x, box.x0, box.x1, p.x],
|
|
1981
|
+
[q.y - p.y, box.y0, box.y1, p.y],
|
|
1982
|
+
])
|
|
1983
|
+
if (d) t = Math.min(t, ((d > 0 ? hi : lo) - o) / d);
|
|
940
1984
|
cut.push({ g: { ...n.g, a: p, b: { x: r4(p.x + (q.x - p.x) * t), y: r4(p.y + (q.y - p.y) * t) } } });
|
|
941
1985
|
};
|
|
942
1986
|
for (const i of start) visit(i);
|
|
943
|
-
while (queue.length) {
|
|
1987
|
+
while (queue.length) {
|
|
1988
|
+
const i = queue.shift();
|
|
1989
|
+
for (const j of adj[i]) visit(j);
|
|
1990
|
+
}
|
|
944
1991
|
if (cut.length !== 1 || !cut[0]) continue; // no way out, more than one, or not a plain track: routed whole
|
|
945
|
-
const id = `stub${out.stubs.length + 1}`,
|
|
1992
|
+
const id = `stub${out.stubs.length + 1}`,
|
|
1993
|
+
g = cut[0].g;
|
|
946
1994
|
out.stubs.push({ id, net: g.net, pin: mine[0], end: { x: g.b.x, y: g.b.y, layer: g.layer } });
|
|
947
1995
|
out.tracks.push({ ...snapped(g), stub: id });
|
|
948
|
-
for (const i of seen) {
|
|
1996
|
+
for (const i of seen) {
|
|
1997
|
+
const n = nodes[i];
|
|
1998
|
+
if (n.kind === 't') out.tracks.push({ ...snapped(n.g), stub: id });
|
|
1999
|
+
else out.vias.push({ ...n.v, stub: id });
|
|
2000
|
+
}
|
|
949
2001
|
}
|
|
950
2002
|
return out;
|
|
951
2003
|
}
|
|
@@ -956,15 +2008,29 @@ function islands(circuit, refs) {
|
|
|
956
2008
|
* @param {object} circuit @param {object[]} [rules]
|
|
957
2009
|
*/
|
|
958
2010
|
export function placementChecks(circuit, rules = circuit.placement || learnPlacement(circuit)) {
|
|
959
|
-
const byRef = new Map(circuit.parts.map((p) => [p.ref, p])),
|
|
2011
|
+
const byRef = new Map(circuit.parts.map((p) => [p.ref, p])),
|
|
2012
|
+
out = [];
|
|
960
2013
|
for (const r of rules) {
|
|
961
|
-
const p = byRef.get(r.part),
|
|
962
|
-
|
|
963
|
-
|
|
2014
|
+
const p = byRef.get(r.part),
|
|
2015
|
+
a = byRef.get(r.anchor);
|
|
2016
|
+
if (!p || !a) {
|
|
2017
|
+
out.push({ level: 'fail', text: `placement: ${!p ? r.part : r.anchor} isn't on the board` });
|
|
2018
|
+
continue;
|
|
2019
|
+
}
|
|
2020
|
+
const pin = padsOnBoard(a).filter((q) => q.pin === r.pin),
|
|
2021
|
+
mine = padsOnBoard(p).filter((q) => q.net === r.net);
|
|
964
2022
|
const d = Math.min(...mine.flatMap((q) => pin.map((x) => Math.hypot(x.bx - q.bx, x.by - q.by))));
|
|
965
|
-
if (!(d <= r.max + 1e-6))
|
|
2023
|
+
if (!(d <= r.max + 1e-6))
|
|
2024
|
+
out.push({
|
|
2025
|
+
level: 'fail',
|
|
2026
|
+
text: `placement: ${r.part} is ${mm(d)} mm from ${r.anchor} pin ${r.pin} (${r.net}): at most ${mm(r.max)} (${mm(r.source)} on the source)`,
|
|
2027
|
+
});
|
|
966
2028
|
}
|
|
967
|
-
if (!out.length)
|
|
2029
|
+
if (!out.length)
|
|
2030
|
+
out.push({
|
|
2031
|
+
level: 'pass',
|
|
2032
|
+
text: `placement: all ${rules.length} small parts within reach of their anchors, as the source has them`,
|
|
2033
|
+
});
|
|
968
2034
|
return out;
|
|
969
2035
|
}
|
|
970
2036
|
|
|
@@ -975,39 +2041,98 @@ export function placementChecks(circuit, rules = circuit.placement || learnPlace
|
|
|
975
2041
|
*/
|
|
976
2042
|
export function sameCircuit(json, circuit, o = {}, added = []) {
|
|
977
2043
|
const onBoard = new Set(json.filter((e) => e.type === 'source_net').map((e) => e.name)); // nets the board has planes for
|
|
978
|
-
const left = { ...clone(circuit, o).nets },
|
|
979
|
-
|
|
980
|
-
const
|
|
981
|
-
|
|
982
|
-
|
|
983
|
-
|
|
2044
|
+
const left = { ...clone(circuit, o).nets },
|
|
2045
|
+
all = { ...circuit.nets };
|
|
2046
|
+
for (const a of added) {
|
|
2047
|
+
if (!all[a.net]) left[a.net] = true;
|
|
2048
|
+
all[a.net] = [...(all[a.net] || a.joins), a.pin];
|
|
2049
|
+
} // declared new pins: expected too
|
|
2050
|
+
const nets = Object.fromEntries(
|
|
2051
|
+
Object.entries(all)
|
|
2052
|
+
.filter(([n]) => left[n] || onBoard.has(n))
|
|
2053
|
+
.map(([n, pins]) => [
|
|
2054
|
+
n,
|
|
2055
|
+
pins.map((x) => {
|
|
2056
|
+
const i = x.indexOf('.');
|
|
2057
|
+
return `${x.slice(0, i)}.pin${x.slice(i + 1)}`;
|
|
2058
|
+
}),
|
|
2059
|
+
]),
|
|
2060
|
+
);
|
|
2061
|
+
const up = new Map(),
|
|
2062
|
+
find = (a) => {
|
|
2063
|
+
while (up.get(a) !== a) a = up.get(a);
|
|
2064
|
+
return a;
|
|
2065
|
+
};
|
|
2066
|
+
const join = (a, b) => {
|
|
2067
|
+
up.set(find(a), find(b));
|
|
2068
|
+
};
|
|
984
2069
|
const comp = new Map(json.filter((e) => e.type === 'source_component').map((e) => [e.source_component_id, e]));
|
|
985
|
-
const name = new Map(
|
|
2070
|
+
const name = new Map(
|
|
2071
|
+
json
|
|
2072
|
+
.filter((e) => e.type === 'source_port')
|
|
2073
|
+
.map((e) => [e.source_port_id, `${comp.get(e.source_component_id)?.name}.${e.name}`]),
|
|
2074
|
+
);
|
|
986
2075
|
for (const id of name.keys()) up.set(id, id);
|
|
987
|
-
for (const c of comp.values())
|
|
2076
|
+
for (const c of comp.values())
|
|
2077
|
+
for (const g of c.internally_connected_source_port_ids || []) g.forEach((id) => join(id, g[0]));
|
|
988
2078
|
for (const t of json.filter((e) => e.type === 'source_trace')) {
|
|
989
2079
|
t.connected_source_port_ids.forEach((id) => join(id, t.connected_source_port_ids[0]));
|
|
990
|
-
for (const n of t.connected_source_net_ids || []) {
|
|
2080
|
+
for (const n of t.connected_source_net_ids || []) {
|
|
2081
|
+
if (!up.has(n)) up.set(n, n);
|
|
2082
|
+
join(t.connected_source_port_ids[0], n);
|
|
2083
|
+
} // a pad joined to a plane
|
|
991
2084
|
}
|
|
992
2085
|
const group = new Map(); // pin name -> group
|
|
993
2086
|
for (const [id, n] of name) group.set(n, find(id));
|
|
994
2087
|
for (const [n, pins] of Object.entries(nets)) if (!left[n]) nets[n] = pins.filter((p) => group.has(p)); // a pin with no pad here (castellated): out of its plane too
|
|
995
|
-
const out = [],
|
|
2088
|
+
const out = [],
|
|
2089
|
+
missing = [],
|
|
2090
|
+
split = [],
|
|
2091
|
+
shorted = [];
|
|
996
2092
|
const owner = new Map(); // group -> net
|
|
997
2093
|
for (const [net, pins] of Object.entries(nets)) {
|
|
998
2094
|
const gs = new Set(pins.map((p) => group.get(p)));
|
|
999
|
-
if (gs.has(undefined)) {
|
|
2095
|
+
if (gs.has(undefined)) {
|
|
2096
|
+
missing.push(`${net}: ${pins.filter((p) => !group.has(p)).join(', ')}`);
|
|
2097
|
+
continue;
|
|
2098
|
+
}
|
|
1000
2099
|
if (gs.size > 1) split.push(net);
|
|
1001
|
-
for (const g of gs) {
|
|
2100
|
+
for (const g of gs) {
|
|
2101
|
+
if (owner.has(g) && owner.get(g) !== net) shorted.push(`${owner.get(g)} and ${net}`);
|
|
2102
|
+
owner.set(g, net);
|
|
2103
|
+
}
|
|
1002
2104
|
}
|
|
1003
2105
|
const extra = []; // board pins in a net's group that the source doesn't put in that net
|
|
1004
|
-
for (const [pin, g] of group) {
|
|
1005
|
-
|
|
2106
|
+
for (const [pin, g] of group) {
|
|
2107
|
+
const net = owner.get(g);
|
|
2108
|
+
if (net && !nets[net].includes(pin)) extra.push(`${pin} in ${net}`);
|
|
2109
|
+
}
|
|
2110
|
+
if (extra.length)
|
|
2111
|
+
out.push({
|
|
2112
|
+
level: 'fail',
|
|
2113
|
+
text: `${extra.length} pins joined to nets the source leaves them out of: ${extra.slice(0, 5).join(', ')}`,
|
|
2114
|
+
});
|
|
1006
2115
|
const n = Object.keys(nets).length;
|
|
1007
|
-
if (missing.length)
|
|
1008
|
-
|
|
1009
|
-
|
|
1010
|
-
|
|
2116
|
+
if (missing.length)
|
|
2117
|
+
out.push({
|
|
2118
|
+
level: 'fail',
|
|
2119
|
+
text: `${missing.length} nets name pins the board doesn't have: ${missing.slice(0, 3).join('; ')}`,
|
|
2120
|
+
});
|
|
2121
|
+
if (split.length)
|
|
2122
|
+
out.push({
|
|
2123
|
+
level: 'fail',
|
|
2124
|
+
text: `${split.length} nets are split in two or more on the board: ${split.slice(0, 5).join(', ')}`,
|
|
2125
|
+
});
|
|
2126
|
+
if (shorted.length)
|
|
2127
|
+
out.push({
|
|
2128
|
+
level: 'fail',
|
|
2129
|
+
text: `nets joined that the source keeps apart: ${[...new Set(shorted)].slice(0, 5).join('; ')}`,
|
|
2130
|
+
});
|
|
2131
|
+
if (!out.length)
|
|
2132
|
+
out.push({
|
|
2133
|
+
level: 'pass',
|
|
2134
|
+
text: `same circuit as the source: all ${n} nets join the same pins, and no others${Object.keys(all).length > n ? ` (${Object.keys(all).length - n} left to planes)` : ''}${added.length ? `, plus ${added.length} pins added: ${added.map((a) => `${a.pin} (${a.net.replace(/^\//, '')})`).join(', ')}` : ''}`,
|
|
2135
|
+
});
|
|
1011
2136
|
return out;
|
|
1012
2137
|
}
|
|
1013
2138
|
|
|
@@ -1020,11 +2145,21 @@ export function sameCircuit(json, circuit, o = {}, added = []) {
|
|
|
1020
2145
|
export function wrlMesh(text, unit = 2.54) {
|
|
1021
2146
|
const out = [];
|
|
1022
2147
|
for (const m of text.matchAll(/coordIndex\s*\[([^\]]*)\][\s\S]*?point\s*\[([^\]]*)\]/g)) {
|
|
1023
|
-
const pts = m[2]
|
|
2148
|
+
const pts = m[2]
|
|
2149
|
+
.split(',')
|
|
2150
|
+
.map((p) =>
|
|
2151
|
+
p
|
|
2152
|
+
.trim()
|
|
2153
|
+
.split(/\s+/)
|
|
2154
|
+
.map((n) => Number(n) * unit),
|
|
2155
|
+
)
|
|
2156
|
+
.filter((p) => p.length === 3 && p.every(Number.isFinite));
|
|
1024
2157
|
let face = [];
|
|
1025
2158
|
for (const n of m[1].split(',').map((x) => Number(x.trim()))) {
|
|
1026
|
-
if (n === -1) {
|
|
1027
|
-
|
|
2159
|
+
if (n === -1) {
|
|
2160
|
+
for (let i = 1; i + 1 < face.length; i++) out.push([pts[face[0]], pts[face[i]], pts[face[i + 1]]]);
|
|
2161
|
+
face = [];
|
|
2162
|
+
} else if (Number.isInteger(n) && pts[n]) face.push(n);
|
|
1028
2163
|
}
|
|
1029
2164
|
}
|
|
1030
2165
|
return out;
|
|
@@ -1036,10 +2171,23 @@ export function wrlMesh(text, unit = 2.54) {
|
|
|
1036
2171
|
* @param {string} text @returns {{ min: number[], max: number[] } | null}
|
|
1037
2172
|
*/
|
|
1038
2173
|
export function stepBounds(text) {
|
|
1039
|
-
const k = /SI_UNIT\s*\(\s*\.MILLI\.\s*,\s*\.METRE\.\s*\)/i.test(text)
|
|
1040
|
-
|
|
1041
|
-
|
|
1042
|
-
|
|
2174
|
+
const k = /SI_UNIT\s*\(\s*\.MILLI\.\s*,\s*\.METRE\.\s*\)/i.test(text)
|
|
2175
|
+
? 1
|
|
2176
|
+
: /INCH/i.test(text)
|
|
2177
|
+
? 25.4
|
|
2178
|
+
: /SI_UNIT\s*\(\s*\$\s*,\s*\.METRE\./i.test(text)
|
|
2179
|
+
? 1000
|
|
2180
|
+
: 1;
|
|
2181
|
+
const min = [Infinity, Infinity, Infinity],
|
|
2182
|
+
max = [-Infinity, -Infinity, -Infinity];
|
|
2183
|
+
for (const m of text.matchAll(
|
|
2184
|
+
/CARTESIAN_POINT\s*\(\s*'[^']*'\s*,\s*\(\s*([-\d.Ee+]+)\s*,\s*([-\d.Ee+]+)\s*,\s*([-\d.Ee+]+)\s*\)/g,
|
|
2185
|
+
))
|
|
2186
|
+
for (let i = 0; i < 3; i++) {
|
|
2187
|
+
const v = Number(m[i + 1]) * k;
|
|
2188
|
+
min[i] = Math.min(min[i], v);
|
|
2189
|
+
max[i] = Math.max(max[i], v);
|
|
2190
|
+
}
|
|
1043
2191
|
return Number.isFinite(min[0]) ? { min: min.map(r4), max: max.map(r4) } : null;
|
|
1044
2192
|
}
|
|
1045
2193
|
|
|
@@ -1050,16 +2198,44 @@ export function stepBounds(text) {
|
|
|
1050
2198
|
* below it, 3 mm above). Give the result as a part's `model`: { boxes } in the part's frame, z from the board's top.
|
|
1051
2199
|
* @param {{ x, y }[]} holes in the part's frame @param {object} [o] { thickness = 1.6, pitch = 2.54, pin = 0.64, spacer = 2.5, below = 6, above = 3 }
|
|
1052
2200
|
*/
|
|
1053
|
-
export function pinHeaders(
|
|
2201
|
+
export function pinHeaders(
|
|
2202
|
+
holes,
|
|
2203
|
+
{ thickness = 1.6, pitch = 2.54, pin = 0.64, spacer = 2.5, below = 6, above = 3 } = {},
|
|
2204
|
+
) {
|
|
1054
2205
|
const bottom = -thickness - spacer; // the spacer's underside, from the board's top
|
|
1055
|
-
return {
|
|
1056
|
-
{
|
|
1057
|
-
|
|
2206
|
+
return {
|
|
2207
|
+
boxes: holes.flatMap(({ x, y }) => [
|
|
2208
|
+
{ min: [x - pitch / 2, y - pitch / 2, bottom], max: [x + pitch / 2, y + pitch / 2, -thickness] },
|
|
2209
|
+
{ min: [x - pin / 2, y - pin / 2, bottom - below], max: [x + pin / 2, y + pin / 2, -thickness + above] },
|
|
2210
|
+
]),
|
|
2211
|
+
};
|
|
1058
2212
|
}
|
|
1059
2213
|
|
|
1060
2214
|
function boxMesh({ min: [x0, y0, z0], max: [x1, y1, z1] }) {
|
|
1061
|
-
const v = [
|
|
1062
|
-
|
|
2215
|
+
const v = [
|
|
2216
|
+
[x0, y0, z0],
|
|
2217
|
+
[x1, y0, z0],
|
|
2218
|
+
[x1, y1, z0],
|
|
2219
|
+
[x0, y1, z0],
|
|
2220
|
+
[x0, y0, z1],
|
|
2221
|
+
[x1, y0, z1],
|
|
2222
|
+
[x1, y1, z1],
|
|
2223
|
+
[x0, y1, z1],
|
|
2224
|
+
];
|
|
2225
|
+
return [
|
|
2226
|
+
[0, 2, 1],
|
|
2227
|
+
[0, 3, 2],
|
|
2228
|
+
[4, 5, 6],
|
|
2229
|
+
[4, 6, 7],
|
|
2230
|
+
[0, 1, 5],
|
|
2231
|
+
[0, 5, 4],
|
|
2232
|
+
[1, 2, 6],
|
|
2233
|
+
[1, 6, 5],
|
|
2234
|
+
[2, 3, 7],
|
|
2235
|
+
[2, 7, 6],
|
|
2236
|
+
[3, 0, 4],
|
|
2237
|
+
[3, 4, 7],
|
|
2238
|
+
].map((f) => f.map((i) => v[i]));
|
|
1063
2239
|
}
|
|
1064
2240
|
|
|
1065
2241
|
/**
|
|
@@ -1070,24 +2246,38 @@ function boxMesh({ min: [x0, y0, z0], max: [x1, y1, z1] }) {
|
|
|
1070
2246
|
* @param {object[]} json render's @param {{ thickness: number, meshes?: object }} o @returns {number[][][]}
|
|
1071
2247
|
*/
|
|
1072
2248
|
export function partModels(json, { thickness, meshes = {} }) {
|
|
1073
|
-
const rad = Math.PI / 180,
|
|
2249
|
+
const rad = Math.PI / 180,
|
|
2250
|
+
out = [];
|
|
1074
2251
|
for (const c of json.filter((e) => e.type === 'cad_component' && e.rulecad_model)) {
|
|
1075
|
-
const m = c.rulecad_model,
|
|
2252
|
+
const m = c.rulecad_model,
|
|
2253
|
+
tris = m.mesh ? meshes[m.mesh] : m.box ? boxMesh(m.box) : m.boxes ? m.boxes.flatMap(boxMesh) : null;
|
|
1076
2254
|
if (!tris) continue;
|
|
1077
|
-
const [sx, sy, sz] = m.scale ?? [1, 1, 1],
|
|
1078
|
-
|
|
2255
|
+
const [sx, sy, sz] = m.scale ?? [1, 1, 1],
|
|
2256
|
+
[rx, ry, rz] = (m.rotate ?? [0, 0, 0]).map((a) => -a * rad),
|
|
2257
|
+
[ox, oy, oz] = m.offset ?? [0, 0, 0];
|
|
2258
|
+
const turn = (v) => {
|
|
2259
|
+
// KiCad's model turn: about x, then y, then z
|
|
1079
2260
|
let [x, y, z] = v;
|
|
1080
2261
|
[y, z] = [y * Math.cos(rx) - z * Math.sin(rx), y * Math.sin(rx) + z * Math.cos(rx)];
|
|
1081
2262
|
[x, z] = [x * Math.cos(ry) + z * Math.sin(ry), -x * Math.sin(ry) + z * Math.cos(ry)];
|
|
1082
2263
|
[x, y] = [x * Math.cos(rz) - y * Math.sin(rz), x * Math.sin(rz) + y * Math.cos(rz)];
|
|
1083
2264
|
return [x, y, z];
|
|
1084
2265
|
};
|
|
1085
|
-
const back = m.layer === 'bottom',
|
|
2266
|
+
const back = m.layer === 'bottom',
|
|
2267
|
+
t = (m.rotation * Math.PI) / 180,
|
|
2268
|
+
ct = Math.cos(t),
|
|
2269
|
+
st = Math.sin(t),
|
|
2270
|
+
tt = (m.turn * Math.PI) / 180;
|
|
1086
2271
|
const place = (v) => {
|
|
1087
2272
|
let [x, y, z] = turn([v[0] * sx, v[1] * sy, v[2] * sz]);
|
|
1088
|
-
x += ox;
|
|
2273
|
+
x += ox;
|
|
2274
|
+
y += oy;
|
|
2275
|
+
z += oz;
|
|
1089
2276
|
if (m.turn) [x, y] = [x * Math.cos(tt) - y * Math.sin(tt), x * Math.sin(tt) + y * Math.cos(tt)]; // a part at an angle that isn't a quarter turn
|
|
1090
|
-
if (back) {
|
|
2277
|
+
if (back) {
|
|
2278
|
+
x = -x;
|
|
2279
|
+
y = -y;
|
|
2280
|
+
} // the part's own frame on the back is the footprint's turned half round (as its pads are)
|
|
1091
2281
|
const m1 = back ? -1 : 1;
|
|
1092
2282
|
return [r4(m.x + m1 * (ct * x - st * y)), r4(m.y + (st * x + ct * y)), r4(back ? -z : thickness + z)];
|
|
1093
2283
|
};
|
|
@@ -1099,33 +2289,80 @@ export function partModels(json, { thickness, meshes = {} }) {
|
|
|
1099
2289
|
// ---------- board shapes ----------
|
|
1100
2290
|
// Outlines for board.outline: closed polygons, counter-clockwise, centred on at (default the origin). Curves are cut
|
|
1101
2291
|
// into segments (default 8 per quarter circle: fine for a router and a fab, which mills them as arcs anyway).
|
|
1102
|
-
const arc = (cx, cy, r, a0, n) =>
|
|
2292
|
+
const arc = (cx, cy, r, a0, n) =>
|
|
2293
|
+
Array.from({ length: n + 1 }, (_, i) => {
|
|
2294
|
+
const a = a0 + (Math.PI / 2) * (i / n);
|
|
2295
|
+
return { x: cx + r * Math.cos(a), y: cy + r * Math.sin(a) };
|
|
2296
|
+
});
|
|
1103
2297
|
export const shape = {
|
|
1104
|
-
rect: (w, h, { at = [0, 0] } = {}) =>
|
|
2298
|
+
rect: (w, h, { at = [0, 0] } = {}) =>
|
|
2299
|
+
shape.polygon(
|
|
2300
|
+
[
|
|
2301
|
+
[-w / 2, -h / 2],
|
|
2302
|
+
[w / 2, -h / 2],
|
|
2303
|
+
[w / 2, h / 2],
|
|
2304
|
+
[-w / 2, h / 2],
|
|
2305
|
+
],
|
|
2306
|
+
{ at },
|
|
2307
|
+
),
|
|
1105
2308
|
// corners rounded to radius r
|
|
1106
2309
|
rounded: (w, h, r, { at = [0, 0], segments = 8 } = {}) => {
|
|
2310
|
+
if (r > Math.min(w, h) / 2)
|
|
2311
|
+
throw new Error(
|
|
2312
|
+
`shape.rounded: a corner radius of ${r} mm is more than half the shorter side (${Math.min(w, h) / 2} mm of ${w} x ${h}), so the outline would cross itself: make it ${Math.min(w, h) / 2} or less`,
|
|
2313
|
+
);
|
|
1107
2314
|
if (r <= 0) return shape.rect(w, h, { at });
|
|
1108
|
-
const x = w / 2 - r,
|
|
1109
|
-
|
|
1110
|
-
|
|
2315
|
+
const x = w / 2 - r,
|
|
2316
|
+
y = h / 2 - r;
|
|
2317
|
+
return [
|
|
2318
|
+
...arc(x, -y, r, -Math.PI / 2, segments),
|
|
2319
|
+
...arc(x, y, r, 0, segments),
|
|
2320
|
+
...arc(-x, y, r, Math.PI / 2, segments),
|
|
2321
|
+
...arc(-x, -y, r, Math.PI, segments),
|
|
2322
|
+
].map((p) => ({ x: p.x + at[0], y: p.y + at[1] }));
|
|
1111
2323
|
},
|
|
1112
2324
|
// corners cut at 45 degrees, b along each side
|
|
1113
|
-
bevelled: (w, h, b, { at = [0, 0] } = {}) =>
|
|
2325
|
+
bevelled: (w, h, b, { at = [0, 0] } = {}) =>
|
|
2326
|
+
shape.polygon(
|
|
2327
|
+
[
|
|
2328
|
+
[-w / 2 + b, -h / 2],
|
|
2329
|
+
[w / 2 - b, -h / 2],
|
|
2330
|
+
[w / 2, -h / 2 + b],
|
|
2331
|
+
[w / 2, h / 2 - b],
|
|
2332
|
+
[w / 2 - b, h / 2],
|
|
2333
|
+
[-w / 2 + b, h / 2],
|
|
2334
|
+
[-w / 2, h / 2 - b],
|
|
2335
|
+
[-w / 2, -h / 2 + b],
|
|
2336
|
+
],
|
|
2337
|
+
{ at },
|
|
2338
|
+
),
|
|
1114
2339
|
// a ring from radius r0 to r1, open by gap at angle (radians) so it is one outline: for a contact ring's copper
|
|
1115
2340
|
ring: (r0, r1, { gap = 0.3, angle = 0, segments = 48, at = [0, 0] } = {}) => {
|
|
1116
|
-
const a0 = angle + gap / r1 / 2,
|
|
1117
|
-
|
|
2341
|
+
const a0 = angle + gap / r1 / 2,
|
|
2342
|
+
a1 = angle + Math.PI * 2 - gap / r1 / 2,
|
|
2343
|
+
b0 = angle + gap / r0 / 2,
|
|
2344
|
+
b1 = angle + Math.PI * 2 - gap / r0 / 2;
|
|
2345
|
+
const arcAt = (r, s, e) =>
|
|
2346
|
+
Array.from({ length: segments + 1 }, (_, i) => {
|
|
2347
|
+
const a = s + ((e - s) * i) / segments;
|
|
2348
|
+
return [at[0] + r * Math.cos(a), at[1] + r * Math.sin(a)];
|
|
2349
|
+
});
|
|
1118
2350
|
return [...arcAt(r1, a0, a1), ...arcAt(r0, b1, b0)];
|
|
1119
2351
|
},
|
|
1120
|
-
circle: (d, { at = [0, 0], segments = 32 } = {}) =>
|
|
1121
|
-
|
|
2352
|
+
circle: (d, { at = [0, 0], segments = 32 } = {}) =>
|
|
2353
|
+
Array.from({ length: segments }, (_, i) => ({
|
|
2354
|
+
x: at[0] + (d / 2) * Math.cos((Math.PI * 2 * i) / segments),
|
|
2355
|
+
y: at[1] + (d / 2) * Math.sin((Math.PI * 2 * i) / segments),
|
|
2356
|
+
})),
|
|
2357
|
+
polygon: (points, { at = [0, 0] } = {}) => points.map(([x, y]) => ({ x: x + at[0], y: y + at[1] })),
|
|
1122
2358
|
};
|
|
1123
2359
|
// Is the point inside the polygon? (even-odd rule)
|
|
1124
2360
|
export function inside(points, x, y) {
|
|
1125
2361
|
let hit = false;
|
|
1126
2362
|
for (let i = 0, j = points.length - 1; i < points.length; j = i++) {
|
|
1127
|
-
const a = points[i],
|
|
1128
|
-
|
|
2363
|
+
const a = points[i],
|
|
2364
|
+
b = points[j];
|
|
2365
|
+
if (a.y > y !== b.y > y && x < ((b.x - a.x) * (y - a.y)) / (b.y - a.y) + a.x) hit = !hit;
|
|
1129
2366
|
}
|
|
1130
2367
|
return hit;
|
|
1131
2368
|
}
|
|
@@ -1133,12 +2370,117 @@ export function inside(points, x, y) {
|
|
|
1133
2370
|
function toEdge(points, x, y) {
|
|
1134
2371
|
let d = Infinity;
|
|
1135
2372
|
for (let i = 0; i < points.length; i++) {
|
|
1136
|
-
const a = points[i],
|
|
2373
|
+
const a = points[i],
|
|
2374
|
+
b = points[(i + 1) % points.length],
|
|
2375
|
+
dx = b.x - a.x,
|
|
2376
|
+
dy = b.y - a.y,
|
|
2377
|
+
l = dx * dx + dy * dy;
|
|
1137
2378
|
const t = l ? Math.max(0, Math.min(1, ((x - a.x) * dx + (y - a.y) * dy) / l)) : 0;
|
|
1138
2379
|
d = Math.min(d, Math.hypot(x - a.x - t * dx, y - a.y - t * dy));
|
|
1139
2380
|
}
|
|
1140
2381
|
return d;
|
|
1141
2382
|
}
|
|
2383
|
+
// Do two line segments (a-b and c-d) cross, each passing through the other (not where they only touch)?
|
|
2384
|
+
function segmentsCross(a, b, c, d) {
|
|
2385
|
+
const side = (p, q, r) => Math.sign((q.x - p.x) * (r.y - p.y) - (q.y - p.y) * (r.x - p.x));
|
|
2386
|
+
return side(a, b, c) * side(a, b, d) < 0 && side(c, d, a) * side(c, d, b) < 0;
|
|
2387
|
+
}
|
|
2388
|
+
// How near two line segments (a-b and c-d) come, in mm: 0 where they cross or touch
|
|
2389
|
+
function segmentGap(a, b, c, d) {
|
|
2390
|
+
if (segmentsCross(a, b, c, d)) return 0;
|
|
2391
|
+
return Math.min(
|
|
2392
|
+
toEdge([c, d], a.x, a.y),
|
|
2393
|
+
toEdge([c, d], b.x, b.y),
|
|
2394
|
+
toEdge([a, b], c.x, c.y),
|
|
2395
|
+
toEdge([a, b], d.x, d.y),
|
|
2396
|
+
);
|
|
2397
|
+
}
|
|
2398
|
+
// A pad's or a hole's whole shape, as the edge test takes it: a core (one point, the two ends of a slot's middle line,
|
|
2399
|
+
// or a rectangle's or polygon's corners), in the board's frame, and how far the shape reaches round it (r: a circle's
|
|
2400
|
+
// or a slot's radius, a rounded rectangle's corner radius). deg turns it counter-clockwise about its centre (cx, cy)
|
|
2401
|
+
function coreShape(cx, cy, corners, r, deg = 0) {
|
|
2402
|
+
const a = (Number(deg || 0) * Math.PI) / 180,
|
|
2403
|
+
c = Math.cos(a),
|
|
2404
|
+
s = Math.sin(a);
|
|
2405
|
+
return { pts: corners.map(([x, y]) => ({ x: cx + x * c - y * s, y: cy + x * s + y * c })), r };
|
|
2406
|
+
}
|
|
2407
|
+
// a slot, a pill or an oval (taken as a slot: the oval's ellipse lies inside it): two circles at its ends and the band
|
|
2408
|
+
const slotShape = (cx, cy, w, h, deg) => {
|
|
2409
|
+
const r = Math.min(w, h) / 2,
|
|
2410
|
+
l = Math.abs(w - h) / 2;
|
|
2411
|
+
return coreShape(cx, cy, w >= h ? [[-l, 0], [l, 0]] : [[0, -l], [0, l]], r, deg); // prettier-ignore
|
|
2412
|
+
};
|
|
2413
|
+
// a rectangle, its corners rounded to br (none: square corners)
|
|
2414
|
+
const rectShape = (cx, cy, w, h, br, deg) => {
|
|
2415
|
+
const r = Math.max(0, Math.min(br ?? 0, w / 2, h / 2)),
|
|
2416
|
+
x = w / 2 - r,
|
|
2417
|
+
y = h / 2 - r;
|
|
2418
|
+
return coreShape(cx, cy, [[-x, -y], [x, -y], [x, y], [-x, y]], r, deg); // prettier-ignore
|
|
2419
|
+
};
|
|
2420
|
+
// A hole as the fab drills it (a plated hole's drill, off its pad's centre where it's set off): a circle, a slot or a
|
|
2421
|
+
// rectangle. kind says which, w and h its size before any turn
|
|
2422
|
+
function holeShape(e) {
|
|
2423
|
+
const x = e.x + (e.hole_offset_x ?? 0),
|
|
2424
|
+
y = e.y + (e.hole_offset_y ?? 0),
|
|
2425
|
+
deg = e.hole_ccw_rotation ?? e.ccw_rotation ?? 0;
|
|
2426
|
+
if (e.hole_width != null && e.hole_height != null && e.hole_shape !== 'circle') {
|
|
2427
|
+
const [w, h] = [e.hole_width, e.hole_height];
|
|
2428
|
+
return e.hole_shape === 'rect'
|
|
2429
|
+
? { ...rectShape(x, y, w, h, 0, deg), kind: 'rect', w, h }
|
|
2430
|
+
: { ...slotShape(x, y, w, h, deg), kind: 'slot', w, h };
|
|
2431
|
+
}
|
|
2432
|
+
const d = e.hole_diameter ?? e.hole_width ?? 0;
|
|
2433
|
+
return e.hole_shape === 'square'
|
|
2434
|
+
? { ...rectShape(x, y, d, d, 0, 0), kind: 'rect', w: d, h: d }
|
|
2435
|
+
: { ...coreShape(x, y, [[0, 0]], d / 2), kind: 'circle', w: d, h: d };
|
|
2436
|
+
}
|
|
2437
|
+
// A pad's copper (a surface pad, or the copper round a plated hole; an unplated hole, its hole), its whole shape
|
|
2438
|
+
function copperShape(e) {
|
|
2439
|
+
if (e.type === 'pcb_hole') return holeShape(e);
|
|
2440
|
+
if (e.type === 'pcb_smtpad') {
|
|
2441
|
+
if (e.shape === 'circle') return coreShape(e.x, e.y, [[0, 0]], e.radius);
|
|
2442
|
+
if (e.shape === 'polygon') return { pts: e.points.map((q) => ({ x: q.x, y: q.y })), r: 0 };
|
|
2443
|
+
if (e.shape === 'pill' || e.shape === 'rotated_pill') return slotShape(e.x, e.y, e.width, e.height, e.ccw_rotation);
|
|
2444
|
+
return rectShape(e.x, e.y, e.width, e.height, e.corner_radius ?? e.rect_border_radius, e.ccw_rotation);
|
|
2445
|
+
}
|
|
2446
|
+
if (e.shape === 'circle') return coreShape(e.x, e.y, [[0, 0]], e.outer_diameter / 2);
|
|
2447
|
+
if (e.shape === 'oval' || e.shape === 'pill')
|
|
2448
|
+
return slotShape(e.x, e.y, e.outer_width, e.outer_height, e.ccw_rotation);
|
|
2449
|
+
if (e.shape === 'hole_with_polygon_pad')
|
|
2450
|
+
return coreShape(
|
|
2451
|
+
e.x,
|
|
2452
|
+
e.y,
|
|
2453
|
+
e.pad_outline.map((q) => [q.x, q.y]),
|
|
2454
|
+
0,
|
|
2455
|
+
e.ccw_rotation,
|
|
2456
|
+
);
|
|
2457
|
+
if (e.rect_pad_width != null)
|
|
2458
|
+
return rectShape(e.x, e.y, e.rect_pad_width, e.rect_pad_height, e.rect_border_radius, e.rect_ccw_rotation);
|
|
2459
|
+
return coreShape(e.x, e.y, [[0, 0]], 0); // (a shape this doesn't know: its centre, as before)
|
|
2460
|
+
}
|
|
2461
|
+
// How far a shape (coreShape's) reaches past the edge of an outline (a closed list of points), in mm: above 0, it
|
|
2462
|
+
// crosses the edge by that much; 0 or below, it is inside, that far clear of the edge
|
|
2463
|
+
function reachPast(outline, s) {
|
|
2464
|
+
const from = s.pts.map((q) => (inside(outline, q.x, q.y) ? 1 : -1) * toEdge(outline, q.x, q.y)); // inward
|
|
2465
|
+
if (from.some((f) => f < 0)) return s.r - Math.min(...from); // a corner outside: the farthest out, and its rounding
|
|
2466
|
+
let near = Infinity, // every corner inside: how near the outline's sides come to the core's (0 where they cross)
|
|
2467
|
+
crossed = false;
|
|
2468
|
+
const n = s.pts.length,
|
|
2469
|
+
sides = n < 3 ? [[0, n - 1]] : s.pts.map((_, i) => [i, (i + 1) % n]);
|
|
2470
|
+
for (const [i, k] of sides)
|
|
2471
|
+
for (let j = 0; j < outline.length; j++) {
|
|
2472
|
+
const c = outline[j],
|
|
2473
|
+
d = outline[(j + 1) % outline.length];
|
|
2474
|
+
crossed ||= segmentsCross(s.pts[i], s.pts[k], c, d);
|
|
2475
|
+
near = Math.min(near, segmentGap(s.pts[i], s.pts[k], c, d));
|
|
2476
|
+
}
|
|
2477
|
+
// The outline cuts into the core (a notch in the board poking into a pad between its corners): the shape crosses the
|
|
2478
|
+
// edge even with square corners (r 0), by as deep as the outline's corners reach into it
|
|
2479
|
+
const deep =
|
|
2480
|
+
n < 3 ? 0 : Math.max(0, ...outline.filter((q) => inside(s.pts, q.x, q.y)).map((q) => toEdge(s.pts, q.x, q.y)));
|
|
2481
|
+
if (crossed || deep > 1e-9) return s.r + Math.max(deep, 1e-3);
|
|
2482
|
+
return s.r - near;
|
|
2483
|
+
}
|
|
1142
2484
|
|
|
1143
2485
|
// ---------- building ----------
|
|
1144
2486
|
// render(board) -> Circuit JSON (circuit.mjs)
|
|
@@ -1147,12 +2489,24 @@ export const render = (board, options) => circuitJson(board, options); // option
|
|
|
1147
2489
|
// The board as a solid (previews, fits, the on-screen copy, the model page): the bare board, drilled, bottom at z = 0. Its
|
|
1148
2490
|
// copper is drawn in the 2D views (views), not in 3D. The board is a 2D outline with its holes, extruded: its faces
|
|
1149
2491
|
// triangulate cleanly (cylinders subtracted from a block leave long slivers).
|
|
1150
|
-
export function solids(json, { thickness, smooth = 16, models }) {
|
|
1151
|
-
|
|
2492
|
+
export function solids(json, { thickness, smooth = 16, models }) {
|
|
2493
|
+
// models: { file: triangles }, the parts' meshes (cad loads them) // smooth: segments per hole (a board without the variable gets 16)
|
|
2494
|
+
const { rectangle, circle, polygon } = jscad.primitives,
|
|
2495
|
+
{ subtract } = jscad.booleans,
|
|
2496
|
+
{ extrudeLinear } = jscad.extrusions;
|
|
1152
2497
|
const b = json.find((e) => e.type === 'pcb_board');
|
|
1153
|
-
const drills = json
|
|
1154
|
-
.
|
|
1155
|
-
|
|
2498
|
+
const drills = json
|
|
2499
|
+
.filter((e) => e.type === 'pcb_hole' || e.type === 'pcb_plated_hole' || e.type === 'pcb_via')
|
|
2500
|
+
.map((e) =>
|
|
2501
|
+
circle({
|
|
2502
|
+
center: [e.x + (e.hole_offset_x ?? 0), e.y + (e.hole_offset_y ?? 0)],
|
|
2503
|
+
radius: (e.hole_diameter ?? e.hole_width) / 2,
|
|
2504
|
+
segments: smooth,
|
|
2505
|
+
}),
|
|
2506
|
+
); // a hole off-centre in its pad, where the fab drills it
|
|
2507
|
+
const outline = b.outline
|
|
2508
|
+
? polygon({ points: b.outline.map((p) => [p.x, p.y]) })
|
|
2509
|
+
: rectangle({ center: [b.center.x, b.center.y], size: [b.width, b.height] });
|
|
1156
2510
|
const board = extrudeLinear({ height: thickness }, drills.length ? subtract(outline, ...drills) : outline);
|
|
1157
2511
|
const parts = models ? partModels(json, { thickness, meshes: models }) : [];
|
|
1158
2512
|
return { board, ...(parts.length ? { components: jscad.geometries.geom3.fromPoints(parts) } : {}) }; // the parts' 3D models, where there are any
|
|
@@ -1162,8 +2516,15 @@ export function solids(json, { thickness, smooth = 16, models }) { // models: {
|
|
|
1162
2516
|
// size, mm, in the layout's frame) and, with the Pico under it, the Pico's centre
|
|
1163
2517
|
export function outputs(json, matrix) {
|
|
1164
2518
|
const b = json.find((e) => e.type === 'pcb_board');
|
|
1165
|
-
return {
|
|
1166
|
-
|
|
2519
|
+
return {
|
|
2520
|
+
board_x: b.center.x,
|
|
2521
|
+
board_y: b.center.y,
|
|
2522
|
+
board_w: b.width,
|
|
2523
|
+
board_d: b.height,
|
|
2524
|
+
...(b.outline ? { board_outline: b.outline } : {}),
|
|
2525
|
+
...(matrix?.pico ? { pico_x: matrix.pico.x, pico_y: matrix.pico.y } : {}),
|
|
2526
|
+
...Object.fromEntries(Object.entries(matrix?.place || {}).filter(([, n]) => typeof n === 'number')),
|
|
2527
|
+
}; // (where a board puts what an assembly mounts on it: matrix.place, numbers by name)
|
|
1167
2528
|
}
|
|
1168
2529
|
|
|
1169
2530
|
/**
|
|
@@ -1175,11 +2536,21 @@ export function outputs(json, matrix) {
|
|
|
1175
2536
|
* so a turned part's are swapped). A case reads them to put openings over a USB socket, a light or a button.
|
|
1176
2537
|
*/
|
|
1177
2538
|
export function parts(json) {
|
|
1178
|
-
const names = Object.fromEntries(
|
|
1179
|
-
|
|
2539
|
+
const names = Object.fromEntries(
|
|
2540
|
+
json.filter((e) => e.type === 'source_component').map((e) => [e.source_component_id, e.name]),
|
|
2541
|
+
);
|
|
2542
|
+
return Object.fromEntries(
|
|
2543
|
+
json
|
|
2544
|
+
.filter((e) => e.type === 'pcb_component')
|
|
2545
|
+
.map((e) => [
|
|
2546
|
+
names[e.source_component_id],
|
|
2547
|
+
{ x: e.center.x, y: e.center.y, w: e.width, h: e.height, layer: e.layer, rotation: e.rotation ?? 0 },
|
|
2548
|
+
]),
|
|
2549
|
+
);
|
|
1180
2550
|
}
|
|
1181
2551
|
|
|
1182
|
-
export const holes = (json) =>
|
|
2552
|
+
export const holes = (json) =>
|
|
2553
|
+
json.filter((e) => e.type === 'pcb_hole' && !e.pcb_component_id).map((e) => ({ x: e.x, y: e.y, d: e.hole_diameter }));
|
|
1183
2554
|
|
|
1184
2555
|
// ---------- checks ----------
|
|
1185
2556
|
const mm = (x) => String(Number(x.toFixed(3))); // 0.30000000000000004 reads as 0.3
|
|
@@ -1189,247 +2560,670 @@ export { viaHoleGaps }; // (in circuit.mjs, which repairs by it)
|
|
|
1189
2560
|
|
|
1190
2561
|
// A source board's nearest track to its edge, copper to edge (mm): what its own layout allows there
|
|
1191
2562
|
export function sourceEdgeGap(circuit) {
|
|
1192
|
-
const edges = [circuit.outline, ...(circuit.cutouts || [])]
|
|
1193
|
-
|
|
1194
|
-
|
|
2563
|
+
const edges = [circuit.outline, ...(circuit.cutouts || [])]
|
|
2564
|
+
.filter((o) => o?.length)
|
|
2565
|
+
.flatMap((o) => o.map((p, i) => [p, o[(i + 1) % o.length]]));
|
|
2566
|
+
const ps = (p, a, b) => {
|
|
2567
|
+
const dx = b.x - a.x,
|
|
2568
|
+
dy = b.y - a.y,
|
|
2569
|
+
l = dx * dx + dy * dy,
|
|
2570
|
+
t = l ? Math.max(0, Math.min(1, ((p.x - a.x) * dx + (p.y - a.y) * dy) / l)) : 0;
|
|
2571
|
+
return Math.hypot(p.x - a.x - t * dx, p.y - a.y - t * dy);
|
|
2572
|
+
};
|
|
2573
|
+
const gaps = (circuit.routing?.tracks || []).map(
|
|
2574
|
+
(g) =>
|
|
2575
|
+
Math.min(...edges.map(([a, b]) => Math.min(ps(g.a, a, b), ps(g.b, a, b), ps(a, g.a, g.b), ps(b, g.a, g.b)))) -
|
|
2576
|
+
g.width / 2,
|
|
2577
|
+
);
|
|
1195
2578
|
return gaps.length && edges.length ? Math.min(...gaps) : null;
|
|
1196
2579
|
}
|
|
1197
2580
|
|
|
1198
2581
|
// The rules KiCad checks a board by: its own clearance, and a clone's pads by the edge where the source has them
|
|
1199
2582
|
// (inherited: the design-rule errors already said to be the source's)
|
|
1200
2583
|
function kicadRules(json, inherited) {
|
|
1201
|
-
const edgeExempt = [...new Set(inherited.map((e) => e.message?.match(/^SMT pad (\w+)\./)?.[1]).filter(Boolean))].map(
|
|
2584
|
+
const edgeExempt = [...new Set(inherited.map((e) => e.message?.match(/^SMT pad (\w+)\./)?.[1]).filter(Boolean))].map(
|
|
2585
|
+
(ref) => ({ ref, edge: 0 }),
|
|
2586
|
+
);
|
|
1202
2587
|
return { clearance: json.find((e) => e.type === 'pcb_board')?.min_trace_to_pad_edge_clearance, edgeExempt };
|
|
1203
2588
|
}
|
|
1204
2589
|
// A KiCad finding that is the source's own: a kept track by the edge no nearer than the source's nearest (KiCad's place
|
|
1205
2590
|
// is 100 mm in, y down)
|
|
1206
2591
|
function kicadSourceEdge(json, source) {
|
|
1207
2592
|
const srcEdge = source?.circuit ? sourceEdgeGap(source.circuit) : null;
|
|
1208
|
-
const keptSegs = json
|
|
1209
|
-
|
|
1210
|
-
|
|
2593
|
+
const keptSegs = json
|
|
2594
|
+
.filter((e) => e.type === 'pcb_trace' && e.rulecad_kept)
|
|
2595
|
+
.flatMap((t) => t.route.slice(1).map((q, i) => [t.route[i], q]));
|
|
2596
|
+
const onKept = (pos) =>
|
|
2597
|
+
keptSegs.some(([a, b]) => {
|
|
2598
|
+
const p = { x: pos.x - 100, y: 100 - pos.y },
|
|
2599
|
+
dx = b.x - a.x,
|
|
2600
|
+
dy = b.y - a.y,
|
|
2601
|
+
l = dx * dx + dy * dy,
|
|
2602
|
+
t = l ? Math.max(0, Math.min(1, ((p.x - a.x) * dx + (p.y - a.y) * dy) / l)) : 0;
|
|
2603
|
+
return Math.hypot(p.x - a.x - t * dx, p.y - a.y - t * dy) < 0.02;
|
|
2604
|
+
});
|
|
2605
|
+
return (x) =>
|
|
2606
|
+
x.type === 'copper_edge_clearance' &&
|
|
2607
|
+
srcEdge != null &&
|
|
2608
|
+
x.items.some((i) => /^Track /.test(i.description) && onKept(i.pos)) &&
|
|
2609
|
+
Number(x.description.match(/actual ([\d.]+) mm/)?.[1]) >= srcEdge - 1e-3;
|
|
1211
2610
|
}
|
|
1212
2611
|
// The design-rule errors a clone has where its source has them, for kicadRules
|
|
1213
2612
|
async function sourceErrors(json, source) {
|
|
1214
2613
|
if (!source?.circuit) return [];
|
|
1215
|
-
const { runAllChecks } = await import('@tscircuit/checks'),
|
|
2614
|
+
const { runAllChecks } = await import('@tscircuit/checks'),
|
|
2615
|
+
same = asSource(json, source.circuit, source.arranged?.kept);
|
|
1216
2616
|
return (await runAllChecks(structuredClone(json))).filter((e) => same(e));
|
|
1217
2617
|
}
|
|
1218
2618
|
|
|
1219
|
-
export async function checks(json, v, matrix, source) {
|
|
2619
|
+
export async function checks(json, v, matrix, source) {
|
|
2620
|
+
// source: a clone's { circuit, arranged } (its own checks join these)
|
|
1220
2621
|
const { runAllChecks } = await import('@tscircuit/checks');
|
|
1221
|
-
const out = [],
|
|
2622
|
+
const out = [],
|
|
2623
|
+
j = v.jlcpcb;
|
|
1222
2624
|
const board = json.find((e) => e.type === 'pcb_board');
|
|
1223
2625
|
// On a shaped board, a part's box can reach past a curved edge when its copper doesn't (a ring on a round disc): that
|
|
1224
2626
|
// part is checked here pad by pad against the outline instead (below)
|
|
1225
2627
|
// Castellated pads sit on the edge by design: half holes the fab cuts through. They're checked against its rules for them below
|
|
1226
2628
|
// (with the other pads of their pins: a header pad beside a half hole runs into it, as on a Pico)
|
|
1227
|
-
const b = board,
|
|
1228
|
-
|
|
1229
|
-
const
|
|
1230
|
-
|
|
1231
|
-
const
|
|
1232
|
-
|
|
2629
|
+
const b = board,
|
|
2630
|
+
castellated = json.filter((e) => e.type === 'pcb_plated_hole' && e.port_hints?.includes('castellated'));
|
|
2631
|
+
const pinOf = (e) => `${e.pcb_component_id}:${e.port_hints?.[1]}`,
|
|
2632
|
+
edgePins = new Set(castellated.map(pinOf));
|
|
2633
|
+
const halves = new Set(
|
|
2634
|
+
json.filter((e) => e.type === 'pcb_plated_hole' && edgePins.has(pinOf(e))).map((e) => e.pcb_plated_hole_id),
|
|
2635
|
+
);
|
|
2636
|
+
const padsOf = (id) =>
|
|
2637
|
+
json.filter(
|
|
2638
|
+
(e) =>
|
|
2639
|
+
e.pcb_component_id === id &&
|
|
2640
|
+
['pcb_smtpad', 'pcb_plated_hole'].includes(e.type) &&
|
|
2641
|
+
!halves.has(e.pcb_plated_hole_id),
|
|
2642
|
+
);
|
|
2643
|
+
const fits = (id) =>
|
|
2644
|
+
board.outline && padsOf(id).every((e) => (e.points || [e]).every((q) => inside(board.outline, q.x, q.y)));
|
|
2645
|
+
const onEdge = (e) => {
|
|
2646
|
+
const t = JSON.stringify(e);
|
|
2647
|
+
return [...halves].some((id) => new RegExp(`${id}(?!\\d)`).test(t));
|
|
2648
|
+
};
|
|
1233
2649
|
// A clone's pads as close to the edge as the source has them, and parts that reach past it as they do there, are the
|
|
1234
2650
|
// source's design (a mid-mount socket in its notch): said, not failed. Anything else near the edge fails as usual
|
|
1235
|
-
const inherited = [],
|
|
2651
|
+
const inherited = [],
|
|
2652
|
+
same = source?.circuit ? asSource(json, source.circuit, source.arranged?.kept) : null,
|
|
2653
|
+
planeNames = new Set(json.filter((e) => e.type === 'source_net').map((e) => e.name));
|
|
1236
2654
|
// A clone's own kept tracks as near the edge as the source's own come (its tracks by its USB-C notch): the source's
|
|
1237
2655
|
// nearest track to its edge, copper to edge, measured on the source
|
|
1238
|
-
const srcEdge = source?.circuit ? sourceEdgeGap(source.circuit) : null,
|
|
1239
|
-
|
|
2656
|
+
const srcEdge = source?.circuit ? sourceEdgeGap(source.circuit) : null,
|
|
2657
|
+
keptIds = new Set(json.filter((e) => e.type === 'pcb_trace' && e.rulecad_kept).map((e) => e.pcb_trace_id));
|
|
2658
|
+
const keptByEdge = (e) => {
|
|
2659
|
+
const m = e.message?.match(/^Trace too close to board edge \(([\d.]+)mm/),
|
|
2660
|
+
id = JSON.stringify(e).match(/pcb_trace_\d+/)?.[0];
|
|
1240
2661
|
if (!m || srcEdge == null || !keptIds.has(id)) return false;
|
|
1241
|
-
const t = json.find((x) => x.pcb_trace_id === id),
|
|
1242
|
-
|
|
1243
|
-
|
|
2662
|
+
const t = json.find((x) => x.pcb_trace_id === id),
|
|
2663
|
+
w = Math.max(...t.route.map((q) => q.width ?? 0));
|
|
2664
|
+
return Number(m[1]) - w / 2 >= srcEdge - 1e-3;
|
|
2665
|
+
};
|
|
2666
|
+
const drc = (await runAllChecks(json))
|
|
2667
|
+
.filter((e) => !(e.type === 'pcb_component_outside_board_error' && fits(e.pcb_component_id)) && !onEdge(e))
|
|
1244
2668
|
.filter((e) => !((same?.(e) || keptByEdge(e)) && inherited.push(e)))
|
|
1245
|
-
.filter((e) => !
|
|
2669
|
+
.filter((e) => !planeNames.has(e.message?.match(/is not connected to net \[(.+)\] by a PCB trace/)?.[1])); // planes join these: checked below, pad by pad
|
|
1246
2670
|
const problems = [...json, ...drc].filter((e) => /_error$/.test(e.type));
|
|
1247
|
-
const seen = new Set(),
|
|
1248
|
-
|
|
2671
|
+
const seen = new Set(),
|
|
2672
|
+
errors = problems.filter((e) => !seen.has(e.message) && seen.add(e.message));
|
|
2673
|
+
out.push(
|
|
2674
|
+
errors.length
|
|
2675
|
+
? {
|
|
2676
|
+
level: 'fail',
|
|
2677
|
+
text: `${errors.length} design-rule errors: ${errors
|
|
2678
|
+
.slice(0, 3)
|
|
2679
|
+
.map((e) => e.message)
|
|
2680
|
+
.join('; ')}`,
|
|
2681
|
+
}
|
|
2682
|
+
: { level: 'pass', text: "tscircuit's design checks: no errors (traces, clearances, holes, board edge)" },
|
|
2683
|
+
);
|
|
1249
2684
|
// Connections between pads: as many tracks as connections (the router names a net's pieces after its connections). To
|
|
1250
2685
|
// a plane: a track to a via, or the pad's own hole
|
|
1251
|
-
const traces = json.filter((e) => e.type === 'pcb_trace'),
|
|
1252
|
-
|
|
1253
|
-
const
|
|
1254
|
-
|
|
1255
|
-
|
|
1256
|
-
|
|
2686
|
+
const traces = json.filter((e) => e.type === 'pcb_trace'),
|
|
2687
|
+
toPlane = json.filter((e) => e.type === 'source_trace' && e.connected_source_net_ids?.length);
|
|
2688
|
+
const planeIds = new Set(toPlane.map((t) => t.source_trace_id)),
|
|
2689
|
+
tracked = new Set(traces.map((t) => t.source_trace_id));
|
|
2690
|
+
const holePorts = new Set(
|
|
2691
|
+
json
|
|
2692
|
+
.filter((e) => e.type === 'pcb_plated_hole')
|
|
2693
|
+
.map((e) => json.find((p) => p.type === 'pcb_port' && p.pcb_port_id === e.pcb_port_id)?.source_port_id),
|
|
2694
|
+
);
|
|
2695
|
+
const unrouted =
|
|
2696
|
+
json.filter((e) => e.type === 'source_trace').length -
|
|
2697
|
+
planeIds.size -
|
|
2698
|
+
traces.filter((t) => !planeIds.has(t.source_trace_id)).length +
|
|
2699
|
+
toPlane.filter((t) => !tracked.has(t.source_trace_id) && !holePorts.has(t.connected_source_port_ids[0])).length;
|
|
2700
|
+
out.push(
|
|
2701
|
+
unrouted > 0
|
|
2702
|
+
? { level: 'fail', text: `${unrouted} connections have no track` }
|
|
2703
|
+
: {
|
|
2704
|
+
level: 'pass',
|
|
2705
|
+
text: `every connection is routed (${traces.length} tracks, ${json.filter((e) => e.type === 'pcb_via').length} vias)`,
|
|
2706
|
+
},
|
|
2707
|
+
);
|
|
1257
2708
|
out.push(...planeChecks(json));
|
|
1258
2709
|
// A clone's own routing, kept: every track and via of it on the board exactly as the source has it (smoothing and
|
|
1259
2710
|
// repair move only the router's tracks), but for escapes cut back where a routed track turned straight back on them:
|
|
1260
2711
|
// each of those a piece of the source's own track, named with how much went
|
|
1261
2712
|
const keptCu = source?.arranged?.kept;
|
|
1262
2713
|
if (keptCu?.tracks?.length) {
|
|
1263
|
-
const key = (x, y) => `${x.toFixed(4)},${y.toFixed(4)}`,
|
|
1264
|
-
|
|
2714
|
+
const key = (x, y) => `${x.toFixed(4)},${y.toFixed(4)}`,
|
|
2715
|
+
seg = (layer, width, a, b) => `${layer} ${width} ${key(a.x, a.y)} ${key(b.x, b.y)}`;
|
|
2716
|
+
const tracksAt = new Set(
|
|
2717
|
+
keptCu.tracks.flatMap((g) => [seg(g.layer, g.width, g.a, g.b), seg(g.layer, g.width, g.b, g.a)]),
|
|
2718
|
+
),
|
|
2719
|
+
viasAt = new Set(keptCu.vias.map((q) => key(q.x, q.y)));
|
|
1265
2720
|
const theirs = (layer, width, a, b) => tracksAt.has(seg(layer, width, a, b));
|
|
1266
|
-
const laid = traces.filter((t) => t.rulecad_kept),
|
|
1267
|
-
|
|
2721
|
+
const laid = traces.filter((t) => t.rulecad_kept),
|
|
2722
|
+
isVia = (t) => t.route[1]?.route_type === 'via';
|
|
2723
|
+
const along = (o, p) => {
|
|
2724
|
+
const dx = o.b.x - o.a.x,
|
|
2725
|
+
dy = o.b.y - o.a.y,
|
|
2726
|
+
l = Math.hypot(dx, dy);
|
|
2727
|
+
return (
|
|
2728
|
+
Math.abs((p.x - o.a.x) * dy - (p.y - o.a.y) * dx) / l < 1e-4 &&
|
|
2729
|
+
((p.x - o.a.x) * dx + (p.y - o.a.y) * dy) / l > -1e-4 &&
|
|
2730
|
+
((p.x - o.a.x) * dx + (p.y - o.a.y) * dy) / l < l + 1e-4
|
|
2731
|
+
);
|
|
2732
|
+
};
|
|
1268
2733
|
let squared = 0;
|
|
1269
|
-
const cutBy = [],
|
|
1270
|
-
|
|
1271
|
-
|
|
1272
|
-
|
|
1273
|
-
|
|
1274
|
-
|
|
1275
|
-
|
|
1276
|
-
|
|
1277
|
-
|
|
1278
|
-
|
|
1279
|
-
|
|
1280
|
-
|
|
2734
|
+
const cutBy = [],
|
|
2735
|
+
moved = laid.filter((t) => {
|
|
2736
|
+
if (isVia(t)) return !viasAt.has(key(t.route[0].x, t.route[0].y));
|
|
2737
|
+
const [p, q] = t.route,
|
|
2738
|
+
w = p.width,
|
|
2739
|
+
layer = p.layer;
|
|
2740
|
+
if (t.route.length === 2 && theirs(layer, w, p, q)) return false;
|
|
2741
|
+
const sq = t.rulecad_squared; // the source's segment, redrawn to leave its pad square: the same ends
|
|
2742
|
+
if (sq && theirs(sq.a.layer ?? layer, sq.a.width ?? w, sq.a, sq.b)) {
|
|
2743
|
+
squared++;
|
|
2744
|
+
return false;
|
|
2745
|
+
} // (its pad end left square, or joined to the next square, by the finish)
|
|
2746
|
+
const o = t.rulecad_shortened; // a piece of the source's segment, from one of its ends
|
|
2747
|
+
if (
|
|
2748
|
+
o &&
|
|
2749
|
+
t.route.length === 2 &&
|
|
2750
|
+
theirs(layer, w, o.a, o.b) &&
|
|
2751
|
+
along(o, p) &&
|
|
2752
|
+
along(o, q) &&
|
|
2753
|
+
[p, q].some((r) => [o.a, o.b].some((e) => key(e.x, e.y) === key(r.x, r.y)))
|
|
2754
|
+
) {
|
|
2755
|
+
cutBy.push(Math.hypot(o.b.x - o.a.x, o.b.y - o.a.y) - Math.hypot(q.x - p.x, q.y - p.y));
|
|
2756
|
+
return false;
|
|
2757
|
+
}
|
|
2758
|
+
return true;
|
|
2759
|
+
});
|
|
1281
2760
|
const gone = traces.flatMap((t) => (t.rulecad_trimmed || []).map((g) => ({ ...g, track: t })));
|
|
1282
2761
|
const strays = gone.filter((g) => !theirs(g.a.layer, g.a.width, g.a, g.b));
|
|
1283
2762
|
cutBy.push(...gone.map((g) => Math.hypot(g.b.x - g.a.x, g.b.y - g.a.y)));
|
|
1284
2763
|
const escapes = traces.reduce((n, t) => n + (t.rulecad_cut || 0), 0);
|
|
1285
|
-
const vias = laid.filter(isVia).length,
|
|
1286
|
-
|
|
1287
|
-
|
|
2764
|
+
const vias = laid.filter(isVia).length,
|
|
2765
|
+
short = laid.filter((t) => t.rulecad_shortened).length,
|
|
2766
|
+
total = cutBy.reduce((n, d) => n + d, 0);
|
|
2767
|
+
out.push(
|
|
2768
|
+
moved.length || strays.length
|
|
2769
|
+
? {
|
|
2770
|
+
level: 'fail',
|
|
2771
|
+
text: `${moved.length + strays.length} of the source's own tracks and vias aren't where the source has them`,
|
|
2772
|
+
}
|
|
2773
|
+
: {
|
|
2774
|
+
level: 'pass',
|
|
2775
|
+
text: `the source's own routing as it was: ${laid.length - vias - short} tracks and ${vias} vias exactly where the source has them${cutBy.length ? `, but for ${escapes} escapes cut back where a routed track turned straight back on them (${gone.length} segments gone, ${short} shortened: ${mm(total)} mm of track in all)` : ''} ${squared ? `; ${squared} of them redrawn by the finish (to leave a pad square, or rejoined)` : ''} (only the router's tracks are tidied)`,
|
|
2776
|
+
},
|
|
2777
|
+
);
|
|
1288
2778
|
}
|
|
1289
2779
|
// What a fab's engineer flags in tracks: one leaving a surface-mount pad at an angle (a small part can tombstone, drawn
|
|
1290
2780
|
// up on one end as its solder melts) and acute corners between tracks of a net (acid traps). A board that asks for
|
|
1291
2781
|
// finishing (finish: true) fails on any left; others are told
|
|
1292
2782
|
{
|
|
1293
2783
|
const { unfinished } = await import('@rulecad/smooth');
|
|
1294
|
-
const u = unfinished(json),
|
|
1295
|
-
|
|
1296
|
-
|
|
1297
|
-
|
|
1298
|
-
|
|
1299
|
-
|
|
2784
|
+
const u = unfinished(json),
|
|
2785
|
+
asked = !!json.find((e) => e.type === 'pcb_board')?.rulecad_finish,
|
|
2786
|
+
at = (l) =>
|
|
2787
|
+
l
|
|
2788
|
+
.slice(0, 4)
|
|
2789
|
+
.map((x) => `${mm(x.at.x)}, ${mm(x.at.y)}`)
|
|
2790
|
+
.join('; ');
|
|
2791
|
+
const ours = { exits: u.exits.filter((l) => !l.kept), acute: u.acute.filter((l) => !l.kept) },
|
|
2792
|
+
theirs = { exits: u.exits.filter((l) => l.kept), acute: u.acute.filter((l) => l.kept) };
|
|
2793
|
+
const say = (x) =>
|
|
2794
|
+
[
|
|
2795
|
+
x.exits.length && `${x.exits.length} tracks leave an SMD pad at an angle (${at(x.exits)})`,
|
|
2796
|
+
x.acute.length && `${x.acute.length} acute corners between tracks (${at(x.acute)})`,
|
|
2797
|
+
]
|
|
2798
|
+
.filter(Boolean)
|
|
2799
|
+
.join('; ');
|
|
2800
|
+
out.push(
|
|
2801
|
+
!ours.exits.length && !ours.acute.length
|
|
2802
|
+
? {
|
|
2803
|
+
level: 'pass',
|
|
2804
|
+
text: `finish: every track leaves its SMD pad square to the pad's edge, and no tracks meet at an acute angle${theirs.exits.length || theirs.acute.length ? ", but where the source's own routing has them" : ''}`,
|
|
2805
|
+
}
|
|
2806
|
+
: {
|
|
2807
|
+
level: asked ? 'fail' : 'warn',
|
|
2808
|
+
text: `finish: ${say(ours)}${asked ? '' : ' (finish: true on the board squares and fills them)'}`,
|
|
2809
|
+
},
|
|
2810
|
+
);
|
|
2811
|
+
if (theirs.exits.length || theirs.acute.length)
|
|
2812
|
+
out.push({
|
|
2813
|
+
level: 'warn',
|
|
2814
|
+
text: `finish, as the source's own routing has them (no room to change without moving other copper): ${say(theirs)}`,
|
|
2815
|
+
});
|
|
1300
2816
|
}
|
|
1301
2817
|
// Tracks and the gaps between them, measured from the board as drawn (not the design's variables): the narrowest
|
|
1302
2818
|
// track, and the nearest two tracks of different connections come on one layer, edge to edge
|
|
1303
|
-
const segs = traces
|
|
2819
|
+
const segs = traces
|
|
2820
|
+
.flatMap((t) =>
|
|
2821
|
+
t.route.slice(1).map((q, i) => ({
|
|
2822
|
+
a: t.route[i],
|
|
2823
|
+
b: q,
|
|
2824
|
+
id: t.source_trace_id ?? t.pcb_trace_id,
|
|
2825
|
+
w: Math.max(t.route[i].width ?? 0, q.width ?? 0),
|
|
2826
|
+
layer: q.layer ?? t.route[i].layer,
|
|
2827
|
+
})),
|
|
2828
|
+
)
|
|
1304
2829
|
.filter((g) => g.a.route_type !== 'via' && g.b.route_type !== 'via' && g.a.layer === g.b.layer);
|
|
1305
|
-
const widths = segs.map((g) => g.w).filter((w) => w > 0),
|
|
2830
|
+
const widths = segs.map((g) => g.w).filter((w) => w > 0),
|
|
2831
|
+
narrow = widths.length ? Math.min(...widths) : null;
|
|
1306
2832
|
let tight = null;
|
|
1307
|
-
const segGap = (g, h) => {
|
|
1308
|
-
|
|
2833
|
+
const segGap = (g, h) => {
|
|
2834
|
+
const pts = [
|
|
2835
|
+
[g.a, h],
|
|
2836
|
+
[g.b, h],
|
|
2837
|
+
[h.a, g],
|
|
2838
|
+
[h.b, g],
|
|
2839
|
+
].map(([p, o]) => {
|
|
2840
|
+
const dx = o.b.x - o.a.x,
|
|
2841
|
+
dy = o.b.y - o.a.y,
|
|
2842
|
+
l = dx * dx + dy * dy,
|
|
2843
|
+
t = l ? Math.max(0, Math.min(1, ((p.x - o.a.x) * dx + (p.y - o.a.y) * dy) / l)) : 0;
|
|
2844
|
+
return Math.hypot(p.x - o.a.x - t * dx, p.y - o.a.y - t * dy);
|
|
2845
|
+
});
|
|
2846
|
+
return Math.min(...pts) - (g.w + h.w) / 2;
|
|
2847
|
+
};
|
|
2848
|
+
const crosses = (g, h) => {
|
|
2849
|
+
const o = (p, q, r) => Math.sign((q.x - p.x) * (r.y - p.y) - (q.y - p.y) * (r.x - p.x));
|
|
2850
|
+
return o(g.a, g.b, h.a) * o(g.a, g.b, h.b) < 0 && o(h.a, h.b, g.a) * o(h.a, h.b, g.b) < 0;
|
|
2851
|
+
};
|
|
1309
2852
|
// (tracks of one net may run close or meet: connections are grouped into nets by the ports and nets they share)
|
|
1310
|
-
const parent = new Map(),
|
|
2853
|
+
const parent = new Map(),
|
|
2854
|
+
root = (x) => {
|
|
2855
|
+
while (parent.get(x) !== x) x = parent.get(x);
|
|
2856
|
+
return x;
|
|
2857
|
+
},
|
|
2858
|
+
join = (x, y) => {
|
|
2859
|
+
parent.set(root(x), root(y));
|
|
2860
|
+
};
|
|
1311
2861
|
for (const t of json.filter((e) => e.type === 'source_trace')) {
|
|
1312
2862
|
const ends = [t.source_trace_id, ...(t.connected_source_port_ids || []), ...(t.connected_source_net_ids || [])];
|
|
1313
2863
|
for (const e of ends) if (!parent.has(e)) parent.set(e, e);
|
|
1314
2864
|
for (const e of ends.slice(1)) join(ends[0], e);
|
|
1315
2865
|
}
|
|
1316
2866
|
const netOf = (id) => (parent.has(id) ? root(id) : id);
|
|
1317
|
-
const byLayer = new Map();
|
|
1318
|
-
for (const
|
|
1319
|
-
|
|
1320
|
-
|
|
1321
|
-
|
|
1322
|
-
|
|
1323
|
-
|
|
1324
|
-
|
|
1325
|
-
|
|
1326
|
-
|
|
1327
|
-
|
|
1328
|
-
|
|
2867
|
+
const byLayer = new Map();
|
|
2868
|
+
for (const g of segs) byLayer.set(g.layer, [...(byLayer.get(g.layer) || []), g]);
|
|
2869
|
+
for (const list of byLayer.values())
|
|
2870
|
+
for (let x = 0; x < list.length; x++)
|
|
2871
|
+
for (let y = x + 1; y < list.length; y++) {
|
|
2872
|
+
const g = list[x],
|
|
2873
|
+
h = list[y];
|
|
2874
|
+
if (g.id === h.id || netOf(g.id) === netOf(h.id)) continue;
|
|
2875
|
+
const d = crosses(g, h) ? -1 : segGap(g, h);
|
|
2876
|
+
if (d <= 1e-6) continue; // touching: two pieces of one net meeting at a pad (the design checks catch real shorts)
|
|
2877
|
+
if (!tight || d < tight.d) tight = { d, at: [(g.a.x + g.b.x) / 2, (g.a.y + g.b.y) / 2] };
|
|
2878
|
+
}
|
|
2879
|
+
const thinTrack = narrow != null && narrow < j.track_min - 1e-9,
|
|
2880
|
+
closeGap = tight && tight.d < j.gap_min - 1e-9;
|
|
2881
|
+
if (narrow != null)
|
|
2882
|
+
out.push(
|
|
2883
|
+
thinTrack || closeGap
|
|
2884
|
+
? {
|
|
2885
|
+
level: 'fail',
|
|
2886
|
+
text: [
|
|
2887
|
+
thinTrack && `a track ${mm(narrow)} mm wide, under JLCPCB's ${j.track_min} mm`,
|
|
2888
|
+
closeGap &&
|
|
2889
|
+
`two tracks ${mm(tight.d)} mm apart near (${mm(tight.at[0])}, ${mm(tight.at[1])}), under JLCPCB's ${j.gap_min} mm`,
|
|
2890
|
+
]
|
|
2891
|
+
.filter(Boolean)
|
|
2892
|
+
.join('; '),
|
|
2893
|
+
}
|
|
2894
|
+
: {
|
|
2895
|
+
level: 'pass',
|
|
2896
|
+
text: `tracks ${mm(narrow)} mm or wider${tight ? `, ${mm(tight.d)} mm or more apart` : ''}, measured on the board: over JLCPCB's ${j.track_min} / ${j.gap_min} mm`,
|
|
2897
|
+
},
|
|
2898
|
+
);
|
|
1329
2899
|
// A board that can't be made: no size, a hole through its edge, two parts of one name, a pin in two nets
|
|
1330
|
-
const named = json.filter((e) => e.type === 'source_component').map((e) => e.name),
|
|
1331
|
-
|
|
1332
|
-
//
|
|
1333
|
-
//
|
|
2900
|
+
const named = json.filter((e) => e.type === 'source_component').map((e) => e.name),
|
|
2901
|
+
twice = named.filter((n, i) => named.indexOf(n) !== i);
|
|
2902
|
+
// A hole through the edge: every hole, and the copper round a round plated one, tested by its whole shape against the
|
|
2903
|
+
// board's outline (a rectangular board's is its four corners), so a shaped board and a rectangular one are held to one
|
|
2904
|
+
// test: a round hole as a circle, a slot as its two end circles and the band between them, turned as it is, a square
|
|
2905
|
+
// or rectangular hole by its corners (holeShape, reachPast). Half holes and parts that reach past the edge as
|
|
1334
2906
|
// a clone's source has them are on the edge by design (checked above and below)
|
|
1335
2907
|
const reaching = same && b.outline ? same.reaching : new Set(); // (on a shaped board only, as before: a rectangle has no notch to reach into)
|
|
1336
|
-
const edge =
|
|
1337
|
-
|
|
2908
|
+
const edge =
|
|
2909
|
+
b.outline ||
|
|
2910
|
+
[
|
|
2911
|
+
[-1, -1],
|
|
2912
|
+
[1, -1],
|
|
2913
|
+
[1, 1],
|
|
2914
|
+
[-1, 1],
|
|
2915
|
+
].map(([sx, sy]) => ({ x: b.center.x + (sx * b.width) / 2, y: b.center.y + (sy * b.height) / 2 }));
|
|
2916
|
+
const refOf = new Map(
|
|
2917
|
+
json
|
|
2918
|
+
.filter((e) => e.type === 'pcb_component')
|
|
2919
|
+
.map((e) => [
|
|
2920
|
+
e.pcb_component_id,
|
|
2921
|
+
json.find((c) => c.type === 'source_component' && c.source_component_id === e.source_component_id)?.name,
|
|
2922
|
+
]),
|
|
2923
|
+
);
|
|
1338
2924
|
const boardHoles = json.filter((e) => e.type === 'pcb_hole' && !e.pcb_component_id);
|
|
1339
|
-
const holeName = (e) =>
|
|
1340
|
-
|
|
1341
|
-
|
|
1342
|
-
|
|
1343
|
-
|
|
1344
|
-
|
|
1345
|
-
|
|
1346
|
-
|
|
1347
|
-
|
|
1348
|
-
|
|
2925
|
+
const holeName = (e) =>
|
|
2926
|
+
e.type === 'pcb_plated_hole'
|
|
2927
|
+
? `${refOf.get(e.pcb_component_id) ?? 'a part'}.${e.port_hints?.[1] ?? 'pin'}'s hole`
|
|
2928
|
+
: e.pcb_component_id
|
|
2929
|
+
? `${refOf.get(e.pcb_component_id) ?? 'a part'}'s hole`
|
|
2930
|
+
: `mounting hole ${boardHoles.indexOf(e) + 1}`;
|
|
2931
|
+
const edgeHoles = json
|
|
2932
|
+
.filter(
|
|
2933
|
+
(e) =>
|
|
2934
|
+
(e.type === 'pcb_hole' || e.type === 'pcb_plated_hole') &&
|
|
2935
|
+
!halves.has(e.pcb_plated_hole_id) &&
|
|
2936
|
+
!reaching.has(e.pcb_component_id),
|
|
2937
|
+
)
|
|
2938
|
+
.map((e) => {
|
|
2939
|
+
const copper = e.shape === 'circle' && e.outer_diameter != null,
|
|
2940
|
+
s = copper ? { ...copperShape(e), kind: 'circle', w: e.outer_diameter } : holeShape(e);
|
|
2941
|
+
// outside: every part of it beyond the edge (each point of its core at least its radius out)
|
|
2942
|
+
const outside = s.pts.every((q) => !inside(edge, q.x, q.y) && toEdge(edge, q.x, q.y) >= s.r - 1e-6);
|
|
2943
|
+
return {
|
|
2944
|
+
e,
|
|
2945
|
+
s,
|
|
2946
|
+
x: e.x + (copper ? 0 : (e.hole_offset_x ?? 0)),
|
|
2947
|
+
y: e.y + (copper ? 0 : (e.hole_offset_y ?? 0)),
|
|
2948
|
+
copper,
|
|
2949
|
+
outside,
|
|
2950
|
+
past: reachPast(edge, s), // how far it reaches beyond the edge
|
|
2951
|
+
};
|
|
2952
|
+
})
|
|
2953
|
+
.filter((h) => h.past > 1e-6);
|
|
2954
|
+
const holeSize = ({ s, copper }) =>
|
|
2955
|
+
s.kind === 'slot'
|
|
2956
|
+
? `a ${mm(s.w)} × ${mm(s.h)} mm slot`
|
|
2957
|
+
: s.kind === 'rect'
|
|
2958
|
+
? `${mm(s.w)} × ${mm(s.h)} mm`
|
|
2959
|
+
: `${mm(s.w)} mm${copper ? ' across its copper' : ''}`;
|
|
2960
|
+
const holeText = (h) =>
|
|
2961
|
+
`${holeName(h.e)} (${holeSize(h)}) ${h.outside ? "is outside the board's edge" : `breaks through the board's edge by ${mm(h.past)} mm`} at (${mm(h.x)}, ${mm(h.y)})`;
|
|
2962
|
+
const broken = [
|
|
2963
|
+
!(b.width > 0 && b.height > 0) && `the board is ${mm(b.width)} × ${mm(b.height)} mm`,
|
|
2964
|
+
edgeHoles.length &&
|
|
2965
|
+
(edgeHoles.length === 1
|
|
2966
|
+
? holeText(edgeHoles[0])
|
|
2967
|
+
: `${edgeHoles.length} holes break through the board's edge: ${edgeHoles.slice(0, 3).map(holeText).join(', ')}${edgeHoles.length > 3 ? ', …' : ''}`),
|
|
2968
|
+
twice.length && `two parts named ${[...new Set(twice)].join(', ')}`,
|
|
2969
|
+
].filter(Boolean); // (a pin in two nets is refused as the board is built)
|
|
1349
2970
|
if (broken.length) out.push({ level: 'fail', text: `the board can't be made as drawn: ${broken.join('; ')}` });
|
|
1350
2971
|
// Vias and plated holes against the fab's sizes, each measured from the board: the hole, the pad, and the ring
|
|
1351
2972
|
// between them (under the recommended ring a warning, under the least a failure). A via's ring and a plated hole's
|
|
1352
2973
|
// have their own figures (JLCPCB asks a via's pad only 0.1 mm wider than its hole). A clone's vias as its source
|
|
1353
2974
|
// has them are the source's design: said, not failed
|
|
1354
|
-
const srcVia = source?.circuit?.via,
|
|
2975
|
+
const srcVia = source?.circuit?.via,
|
|
2976
|
+
asSrc = (e) =>
|
|
2977
|
+
srcVia && Math.abs(e.hole_diameter - srcVia.hole) < 1e-6 && Math.abs(e.outer_diameter - srcVia.pad) < 1e-6;
|
|
1355
2978
|
// (a plated hole sharing its pin with a surface pad of its part is a via in that pad, such as a chip's thermal vias
|
|
1356
2979
|
// under its exposed pad: a via's figures)
|
|
1357
|
-
const padPins = new Set(
|
|
1358
|
-
|
|
1359
|
-
|
|
1360
|
-
const
|
|
1361
|
-
|
|
1362
|
-
|
|
1363
|
-
const
|
|
2980
|
+
const padPins = new Set(
|
|
2981
|
+
json.filter((e) => e.type === 'pcb_smtpad').map((e) => `${e.pcb_component_id}:${e.port_hints?.[0]}`),
|
|
2982
|
+
);
|
|
2983
|
+
const inPad = (e) =>
|
|
2984
|
+
e.type === 'pcb_plated_hole' &&
|
|
2985
|
+
e.port_hints?.slice(1).some((h) => padPins.has(`${e.pcb_component_id}:${String(h).replace(/^pin/, '')}`));
|
|
2986
|
+
const rings = json
|
|
2987
|
+
.filter(
|
|
2988
|
+
(e) =>
|
|
2989
|
+
e.type === 'pcb_via' || (e.type === 'pcb_plated_hole' && e.outer_diameter != null && e.hole_diameter != null),
|
|
2990
|
+
)
|
|
2991
|
+
.map((e) => ({ e, ring: (e.outer_diameter - e.hole_diameter) / 2, via: e.type === 'pcb_via' || inPad(e) }));
|
|
2992
|
+
const leastOf = (r) => (r.via ? (j.via_annular_min ?? j.annular_min ?? 0.18) : (j.annular_min ?? 0.18)),
|
|
2993
|
+
wantOf = (r) => (r.via ? (j.via_annular ?? j.annular) : j.annular);
|
|
2994
|
+
const badVias = rings.filter(
|
|
2995
|
+
(r) => r.via && !asSrc(r.e) && (r.e.hole_diameter < j.via_hole || r.e.outer_diameter < j.via_pad),
|
|
2996
|
+
),
|
|
2997
|
+
thinRings = rings.filter((r) => !asSrc(r.e) && r.ring < leastOf(r) - 1e-9),
|
|
2998
|
+
smallRings = rings.filter((r) => !asSrc(r.e) && r.ring >= leastOf(r) - 1e-9 && r.ring < wantOf(r) - 1e-9);
|
|
2999
|
+
const inherited_ = rings.filter((r) => asSrc(r.e) && r.ring < wantOf(r)).length,
|
|
3000
|
+
kind = (list) =>
|
|
3001
|
+
list.every((r) => r.via) ? 'vias' : list.every((r) => !r.via) ? 'plated holes' : 'vias and plated holes';
|
|
3002
|
+
const least = (list) => mm(Math.min(...list.map((r) => r.ring))),
|
|
3003
|
+
figures = (list) =>
|
|
3004
|
+
[...new Set(list.map((r) => (r.via ? 'vias' : 'plated holes')))]
|
|
3005
|
+
.map((k) =>
|
|
3006
|
+
k === 'vias' ? `${j.via_annular_min ?? j.annular_min} mm for vias` : `${j.annular_min} mm for plated holes`,
|
|
3007
|
+
)
|
|
3008
|
+
.join(', ');
|
|
1364
3009
|
if (rings.length) {
|
|
1365
|
-
out.push(
|
|
1366
|
-
|
|
1367
|
-
|
|
1368
|
-
|
|
3010
|
+
out.push(
|
|
3011
|
+
badVias.length
|
|
3012
|
+
? {
|
|
3013
|
+
level: 'fail',
|
|
3014
|
+
text: `${badVias.length} vias under JLCPCB's ${j.via_hole} mm hole in a ${j.via_pad} mm pad (${mm(badVias[0].e.hole_diameter)} in ${mm(badVias[0].e.outer_diameter)})`,
|
|
3015
|
+
}
|
|
3016
|
+
: thinRings.length
|
|
3017
|
+
? {
|
|
3018
|
+
level: 'fail',
|
|
3019
|
+
text: `${thinRings.length} ${kind(thinRings)} with a ${least(thinRings)} mm ring, under JLCPCB's least (${figures(thinRings)})`,
|
|
3020
|
+
}
|
|
3021
|
+
: smallRings.length
|
|
3022
|
+
? {
|
|
3023
|
+
level: 'warn',
|
|
3024
|
+
text: `${smallRings.length} ${kind(smallRings)} with a ${least(smallRings)} mm ring: above JLCPCB's least, under what it recommends (${[...new Set(smallRings.map((r) => (r.via ? `${j.via_annular ?? j.annular} mm for vias` : `${j.annular} mm for plated holes`)))].join(', ')})`,
|
|
3025
|
+
}
|
|
3026
|
+
: {
|
|
3027
|
+
level: 'pass',
|
|
3028
|
+
text: `${rings.filter((r) => r.via).length} vias (rings ${rings.some((r) => r.via) ? least(rings.filter((r) => r.via)) : '-'} mm or more) and ${rings.filter((r) => !r.via).length} plated holes (${rings.some((r) => !r.via) ? least(rings.filter((r) => !r.via)) : '-'} mm or more): JLCPCB recommends ${j.via_annular ?? j.annular} and ${j.annular}${inherited_ ? `; ${inherited_} as the source has them` : ''}`,
|
|
3029
|
+
},
|
|
3030
|
+
);
|
|
1369
3031
|
}
|
|
1370
3032
|
// A via's hole to a track of another net (JLCPCB measures it from the hole's edge, not the via's pad: a small via's
|
|
1371
3033
|
// thin ring leaves less room than the copper clearance suggests)
|
|
1372
3034
|
if (j.via_hole_track && json.some((e) => e.type === 'pcb_via')) {
|
|
1373
3035
|
const close = viaHoleGaps(json).filter((g) => g.gap < j.via_hole_track - 1e-6);
|
|
1374
3036
|
const own = close.filter((g) => !(g.kept && asSrc(g.via)));
|
|
1375
|
-
out.push(
|
|
1376
|
-
|
|
3037
|
+
out.push(
|
|
3038
|
+
own.length
|
|
3039
|
+
? {
|
|
3040
|
+
level: 'fail',
|
|
3041
|
+
text: `${own.length} tracks closer than JLCPCB's ${j.via_hole_track} mm to a via's hole (${mm(Math.min(...own.map((g) => g.gap)))} mm at ${mm(own[0].at.x)}, ${mm(own[0].at.y)})`,
|
|
3042
|
+
}
|
|
3043
|
+
: {
|
|
3044
|
+
level: 'pass',
|
|
3045
|
+
text: `every via's hole ${j.via_hole_track} mm or more from tracks of other nets${close.length ? `, but ${close.length} as the source has them` : ''}`,
|
|
3046
|
+
},
|
|
3047
|
+
);
|
|
1377
3048
|
}
|
|
1378
3049
|
// Silkscreen the fab can print: lines no thinner than silk_line, text no smaller than silk_text
|
|
1379
|
-
const silkLines = json.filter(
|
|
1380
|
-
|
|
1381
|
-
|
|
1382
|
-
|
|
1383
|
-
|
|
1384
|
-
|
|
1385
|
-
|
|
1386
|
-
|
|
1387
|
-
|
|
3050
|
+
const silkLines = json.filter(
|
|
3051
|
+
(e) =>
|
|
3052
|
+
(e.type === 'pcb_silkscreen_path' ||
|
|
3053
|
+
e.type === 'pcb_silkscreen_rect' ||
|
|
3054
|
+
e.type === 'pcb_silkscreen_line' ||
|
|
3055
|
+
e.type === 'pcb_silkscreen_circle') &&
|
|
3056
|
+
e.stroke_width != null &&
|
|
3057
|
+
e.stroke_width < j.silk_line,
|
|
3058
|
+
);
|
|
3059
|
+
const silkTexts = json.filter(
|
|
3060
|
+
(e) => e.type === 'pcb_silkscreen_text' && e.font_size != null && e.font_size < j.silk_text,
|
|
3061
|
+
);
|
|
3062
|
+
if (json.some((e) => /^pcb_silkscreen_/.test(e.type)))
|
|
3063
|
+
out.push(
|
|
3064
|
+
silkLines.length || silkTexts.length
|
|
3065
|
+
? {
|
|
3066
|
+
level: 'fail',
|
|
3067
|
+
text: `silkscreen the fab can't print: ${[silkLines.length && `${silkLines.length} lines under ${j.silk_line} mm (${mm(Math.min(...silkLines.map((e) => e.stroke_width)))})`, silkTexts.length && `${silkTexts.length} texts under ${j.silk_text} mm high (${mm(Math.min(...silkTexts.map((e) => e.font_size)))})`].filter(Boolean).join(', ')}`,
|
|
3068
|
+
}
|
|
3069
|
+
: {
|
|
3070
|
+
level: 'pass',
|
|
3071
|
+
text: `silkscreen: lines ${j.silk_line} mm or wider, text ${j.silk_text} mm or taller (JLCPCB's least)`,
|
|
3072
|
+
},
|
|
3073
|
+
);
|
|
3074
|
+
const unplated = json.filter((e) => e.type === 'pcb_hole').map((e) => e.hole_diameter ?? e.hole_width),
|
|
3075
|
+
npth = j.npth_min ?? 0.5;
|
|
3076
|
+
if (unplated.length && Math.min(...unplated) < npth - 1e-9)
|
|
3077
|
+
out.push({
|
|
3078
|
+
level: 'fail',
|
|
3079
|
+
text: `an unplated hole of ${mm(Math.min(...unplated))} mm, under JLCPCB's ${npth} mm for unplated holes`,
|
|
3080
|
+
});
|
|
3081
|
+
const drills = json
|
|
3082
|
+
.filter((e) => e.type === 'pcb_hole' || e.type === 'pcb_plated_hole' || e.type === 'pcb_via')
|
|
3083
|
+
.map((e) => e.hole_diameter ?? e.hole_width);
|
|
3084
|
+
if (drills.length)
|
|
3085
|
+
out.push(
|
|
3086
|
+
Math.min(...drills) < j.drill_min
|
|
3087
|
+
? { level: 'fail', text: `a hole under JLCPCB's ${j.drill_min} mm` }
|
|
3088
|
+
: {
|
|
3089
|
+
level: 'pass',
|
|
3090
|
+
text: `${drills.length} holes, smallest ${Math.min(...drills)} mm (JLCPCB: ${j.drill_min} mm)`,
|
|
3091
|
+
},
|
|
3092
|
+
);
|
|
1388
3093
|
const size = `${b.width.toFixed(1)} × ${b.height.toFixed(1)} mm`;
|
|
1389
|
-
if (b.outline) {
|
|
1390
|
-
|
|
1391
|
-
const
|
|
1392
|
-
|
|
1393
|
-
|
|
1394
|
-
|
|
3094
|
+
if (b.outline) {
|
|
3095
|
+
// a shaped board: every pad and hole inside it, by its whole shape (its holes and round plated pads tested above)
|
|
3096
|
+
const pads = json.filter(
|
|
3097
|
+
(e) =>
|
|
3098
|
+
['pcb_smtpad', 'pcb_plated_hole', 'pcb_hole'].includes(e.type) &&
|
|
3099
|
+
!halves.has(e.pcb_plated_hole_id) &&
|
|
3100
|
+
!reaching.has(e.pcb_component_id),
|
|
3101
|
+
);
|
|
3102
|
+
const circles = new Set(
|
|
3103
|
+
json.filter(
|
|
3104
|
+
(e) =>
|
|
3105
|
+
e.type === 'pcb_hole' || (e.type === 'pcb_plated_hole' && e.shape === 'circle' && e.outer_diameter != null),
|
|
3106
|
+
),
|
|
3107
|
+
); // (said above when they cross)
|
|
3108
|
+
// each pad by its whole copper (copperShape): a round pad as a circle, a rectangular one by its corners, turned as it
|
|
3109
|
+
// is, its rounded corners as rounded, a pill as a slot, a polygon by its corners and sides; the copper of a plated
|
|
3110
|
+
// hole in a rectangular or pill pad the same (its hole is tested above)
|
|
3111
|
+
const out_ = pads.filter((e) => !circles.has(e) && reachPast(b.outline, copperShape(e)) > 1e-6);
|
|
3112
|
+
out.push(
|
|
3113
|
+
out_.length
|
|
3114
|
+
? {
|
|
3115
|
+
level: 'fail',
|
|
3116
|
+
text: `${out_.length} pads or holes outside the board's outline (first at ${mm(out_[0].x ?? out_[0].points[0].x)}, ${mm(out_[0].y ?? out_[0].points[0].y)} mm)`,
|
|
3117
|
+
}
|
|
3118
|
+
: edgeHoles.length
|
|
3119
|
+
? {
|
|
3120
|
+
level: 'info',
|
|
3121
|
+
text: `shaped board (${b.outline.length} points): its pads are inside it, but not its holes (above)`,
|
|
3122
|
+
}
|
|
3123
|
+
: {
|
|
3124
|
+
level: 'pass',
|
|
3125
|
+
text: `shaped board (${b.outline.length} points): all ${pads.length} pads and holes inside it`,
|
|
3126
|
+
},
|
|
3127
|
+
);
|
|
1395
3128
|
}
|
|
1396
|
-
if (castellated.length) {
|
|
3129
|
+
if (castellated.length) {
|
|
3130
|
+
// JLCPCB's rules for half holes: big enough, far enough apart
|
|
1397
3131
|
const small = castellated.filter((e) => e.hole_diameter < (j.castellated_drill_min ?? 0.6));
|
|
1398
3132
|
let gap = Infinity;
|
|
1399
|
-
for (const a of castellated)
|
|
1400
|
-
|
|
1401
|
-
|
|
1402
|
-
|
|
3133
|
+
for (const a of castellated)
|
|
3134
|
+
for (const c of castellated)
|
|
3135
|
+
if (a !== c) gap = Math.min(gap, Math.hypot(a.x - c.x, a.y - c.y) - (a.hole_diameter + c.hole_diameter) / 2);
|
|
3136
|
+
out.push(
|
|
3137
|
+
small.length || gap < (j.castellated_gap_min ?? 0.6)
|
|
3138
|
+
? {
|
|
3139
|
+
level: 'fail',
|
|
3140
|
+
text: `castellated holes: ${small.length ? `${small.length} under JLCPCB's ${j.castellated_drill_min ?? 0.6} mm` : `${mm(gap)} mm apart, under JLCPCB's ${j.castellated_gap_min ?? 0.6} mm`}`,
|
|
3141
|
+
}
|
|
3142
|
+
: {
|
|
3143
|
+
level: 'pass',
|
|
3144
|
+
text: `${castellated.length} castellated holes on the edge, ${mm(Math.min(...castellated.map((e) => e.hole_diameter)))} mm or more, ${mm(gap)} mm apart (JLCPCB: ${j.castellated_drill_min ?? 0.6} / ${j.castellated_gap_min ?? 0.6} mm). Order with castellated holes`,
|
|
3145
|
+
},
|
|
3146
|
+
);
|
|
1403
3147
|
}
|
|
1404
|
-
out.push(
|
|
1405
|
-
|
|
3148
|
+
out.push(
|
|
3149
|
+
Math.max(b.width, b.height) <= j.cheap_size
|
|
3150
|
+
? { level: 'pass', text: `${size}: within JLCPCB's lowest price (${j.cheap_size} × ${j.cheap_size} mm)` }
|
|
3151
|
+
: { level: 'info', text: `${size}: over ${j.cheap_size} × ${j.cheap_size} mm, priced by quote` },
|
|
3152
|
+
);
|
|
3153
|
+
if (matrix?.direct) {
|
|
3154
|
+
// keys wired straight to a GPIO each, no matrix: every key its own pin
|
|
1406
3155
|
const gpio = Object.values(matrix.direct);
|
|
1407
|
-
out.push(
|
|
1408
|
-
|
|
1409
|
-
|
|
3156
|
+
out.push(
|
|
3157
|
+
new Set(gpio).size === gpio.length
|
|
3158
|
+
? {
|
|
3159
|
+
level: 'pass',
|
|
3160
|
+
text: `direct wiring: ${gpio.length} keys, each on a GPIO of its own (${Object.entries(matrix.direct)
|
|
3161
|
+
.map(([k, g]) => `${k} ${g}`)
|
|
3162
|
+
.join(', ')})`,
|
|
3163
|
+
}
|
|
3164
|
+
: { level: 'fail', text: 'direct wiring: two keys share a GPIO' },
|
|
3165
|
+
);
|
|
1410
3166
|
} else if (matrix) {
|
|
1411
|
-
const cells = new Set(matrix.keys.map((k) => `${k.row},${k.col}`)),
|
|
1412
|
-
|
|
1413
|
-
|
|
1414
|
-
|
|
3167
|
+
const cells = new Set(matrix.keys.map((k) => `${k.row},${k.col}`)),
|
|
3168
|
+
gpio = [...Object.values(matrix.rows), ...Object.values(matrix.cols)];
|
|
3169
|
+
out.push(
|
|
3170
|
+
cells.size === matrix.keys.length && new Set(gpio).size === gpio.length
|
|
3171
|
+
? {
|
|
3172
|
+
level: 'pass',
|
|
3173
|
+
text: `matrix: ${matrix.keys.length} keys on ${Object.keys(matrix.rows).length} rows × ${Object.keys(matrix.cols).length} columns, ${gpio.length} GPIO (rows ${Object.values(matrix.rows).join(' ')}; columns ${Object.values(matrix.cols).join(' ')})`,
|
|
3174
|
+
}
|
|
3175
|
+
: { level: 'fail', text: 'matrix: two keys share a row and column, or a GPIO is used twice' },
|
|
3176
|
+
);
|
|
1415
3177
|
}
|
|
1416
3178
|
// KiCad's own design-rule check, when KiCad is installed: the board as KiCad reads it, its planes poured by KiCad. A
|
|
1417
3179
|
// clone's pads by the edge where the source has them are allowed there, as in our checks
|
|
1418
3180
|
const { kicadDrc } = await import('./kicad.mjs');
|
|
1419
3181
|
const kicad = await kicadDrc(json, kicadRules(json, inherited)).catch((e) => ({ failed: e }));
|
|
1420
|
-
if (!kicad)
|
|
1421
|
-
|
|
3182
|
+
if (!kicad)
|
|
3183
|
+
out.push({ level: 'info', text: "KiCad isn't installed: its design-rule check, a second opinion, skipped" });
|
|
3184
|
+
else if (kicad.failed)
|
|
3185
|
+
out.push({
|
|
3186
|
+
level: 'warn',
|
|
3187
|
+
text: `KiCad's design-rule check didn't run: ${String(kicad.failed.message || kicad.failed).split('\n')[0]}`,
|
|
3188
|
+
});
|
|
1422
3189
|
else {
|
|
1423
|
-
const asSrcEdge = kicadSourceEdge(json, source),
|
|
3190
|
+
const asSrcEdge = kicadSourceEdge(json, source),
|
|
3191
|
+
srcEdgeHits = kicad.errors.filter(asSrcEdge);
|
|
1424
3192
|
kicad.errors = kicad.errors.filter((x) => !asSrcEdge(x));
|
|
1425
3193
|
if (srcEdgeHits.length) inherited.push(...srcEdgeHits.map((x) => ({ message: `KiCad: ${x.description}` })));
|
|
1426
|
-
const by = (list) =>
|
|
1427
|
-
|
|
1428
|
-
|
|
3194
|
+
const by = (list) =>
|
|
3195
|
+
Object.entries(
|
|
3196
|
+
list.reduce((m, x) => ((m[x.type.replace(/_/g, ' ')] = (m[x.type.replace(/_/g, ' ')] || 0) + 1), m), {}),
|
|
3197
|
+
)
|
|
3198
|
+
.map(([t, n]) => `${n} ${t}`)
|
|
3199
|
+
.join(', ');
|
|
3200
|
+
out.push(
|
|
3201
|
+
kicad.errors.length
|
|
3202
|
+
? {
|
|
3203
|
+
level: 'fail',
|
|
3204
|
+
text: `KiCad ${kicad.version}'s design-rule check: ${kicad.errors.length} errors (${by(kicad.errors)}); first: ${kicad.errors[0].description}`,
|
|
3205
|
+
}
|
|
3206
|
+
: {
|
|
3207
|
+
level: 'pass',
|
|
3208
|
+
text: `KiCad ${kicad.version}'s design-rule check, its own planes poured: no errors${kicad.warnings.length ? ` (warnings: ${by(kicad.warnings)})` : ''}`,
|
|
3209
|
+
},
|
|
3210
|
+
);
|
|
1429
3211
|
}
|
|
1430
|
-
if (inherited.length)
|
|
1431
|
-
|
|
1432
|
-
|
|
3212
|
+
if (inherited.length)
|
|
3213
|
+
out.push({
|
|
3214
|
+
level: 'info',
|
|
3215
|
+
text: `as the source has them, so not failed: ${[...new Set(inherited.map((e) => e.message.replace(/ \(.*$/, '').replace(/\. Try moving.*$/, '')))].slice(0, 4).join('; ')}${inherited.length > 4 ? ` (${inherited.length} in all)` : ''}`,
|
|
3216
|
+
});
|
|
3217
|
+
if (source?.circuit)
|
|
3218
|
+
out.push(
|
|
3219
|
+
...sameCircuit(json, source.circuit, {}, source.arranged?.added || []),
|
|
3220
|
+
...placementChecks(source.arranged || source.circuit, source.circuit.placement || learnPlacement(source.circuit)),
|
|
3221
|
+
);
|
|
3222
|
+
const notes = new Set(
|
|
3223
|
+
[...json, ...drc]
|
|
3224
|
+
.filter((e) => /_warning$/.test(e.type))
|
|
3225
|
+
.map((e) => e.type.replace(/^(source|pcb)_|_warning$/g, '').replace(/_/g, ' ')),
|
|
3226
|
+
);
|
|
1433
3227
|
if (notes.size) out.push({ level: 'info', text: `tscircuit notes, none about the copper: ${[...notes].join(', ')}` });
|
|
1434
3228
|
return out;
|
|
1435
3229
|
}
|
|
@@ -1438,24 +3232,43 @@ export async function checks(json, v, matrix, source) { // source: a clone's { c
|
|
|
1438
3232
|
// a part that reaches past the outline there too, and the source's own vias, kept, where they touch its pads. Returns a test for a design-rule error, with .reaching:
|
|
1439
3233
|
// the board's components that reach past it as on the source.
|
|
1440
3234
|
function asSource(json, circuit, kept) {
|
|
1441
|
-
const src = new Map(),
|
|
3235
|
+
const src = new Map(),
|
|
3236
|
+
past = new Set(),
|
|
3237
|
+
so = circuit.outline;
|
|
1442
3238
|
if (!so) return null;
|
|
1443
3239
|
for (const p of circuit.parts) {
|
|
1444
|
-
for (const q of padsOnBoard(p)) {
|
|
3240
|
+
for (const q of padsOnBoard(p)) {
|
|
3241
|
+
src.set(`${p.ref}.pin${q.pin}`, toEdge(so, q.bx, q.by));
|
|
3242
|
+
if (!inside(so, q.bx, q.by)) past.add(p.ref);
|
|
3243
|
+
}
|
|
1445
3244
|
for (const h of padsOnBoard({ ...p, pads: p.holes || [] })) if (!inside(so, h.bx, h.by)) past.add(p.ref); // its unplated holes too
|
|
1446
3245
|
}
|
|
1447
|
-
const b = json.find((e) => e.type === 'pcb_board'),
|
|
1448
|
-
|
|
3246
|
+
const b = json.find((e) => e.type === 'pcb_board'),
|
|
3247
|
+
bo = b.outline;
|
|
3248
|
+
const comp = new Map(
|
|
3249
|
+
json
|
|
3250
|
+
.filter((e) => e.type === 'pcb_component')
|
|
3251
|
+
.map((e) => [
|
|
3252
|
+
e.pcb_component_id,
|
|
3253
|
+
json.find((c) => c.source_component_id === e.source_component_id && c.type === 'source_component')?.name,
|
|
3254
|
+
]),
|
|
3255
|
+
);
|
|
1449
3256
|
const reaching = new Set([...comp].filter(([, n]) => past.has(n)).map(([id]) => id));
|
|
1450
3257
|
const sp = new Map(json.filter((e) => e.type === 'source_port').map((e) => [e.source_port_id, e]));
|
|
1451
3258
|
const at = new Map();
|
|
1452
3259
|
for (const e of json.filter((x) => (x.type === 'pcb_smtpad' || x.type === 'pcb_plated_hole') && x.pcb_port_id)) {
|
|
1453
|
-
const port = json.find((x) => x.type === 'pcb_port' && x.pcb_port_id === e.pcb_port_id),
|
|
1454
|
-
|
|
3260
|
+
const port = json.find((x) => x.type === 'pcb_port' && x.pcb_port_id === e.pcb_port_id),
|
|
3261
|
+
name = `${comp.get(e.pcb_component_id)}.${sp.get(port?.source_port_id)?.name}`;
|
|
3262
|
+
const c = e.type === 'pcb_smtpad' ? smtBounds(e) : e;
|
|
3263
|
+
if (!at.has(name)) at.set(name, c);
|
|
1455
3264
|
}
|
|
1456
3265
|
const test = (e) => {
|
|
1457
3266
|
const m = e.message?.match(/^(?:SMT pad|Plated hole) (\S+) violates copper-to-board-edge/);
|
|
1458
|
-
if (m) {
|
|
3267
|
+
if (m) {
|
|
3268
|
+
const c = at.get(m[1]),
|
|
3269
|
+
d = src.get(m[1]);
|
|
3270
|
+
return c != null && d != null && bo && Math.abs(toEdge(bo, c.x, c.y) - d) <= 0.02;
|
|
3271
|
+
}
|
|
1459
3272
|
const k = e.message?.match(/^Component (\S+) extends outside board/);
|
|
1460
3273
|
if (k) return past.has(k[1]);
|
|
1461
3274
|
const v = e.message?.match(/^Via hole at \(([-\d.]+)mm, ([-\d.]+)mm\)/); // the source's own via, kept where it was
|
|
@@ -1467,48 +3280,96 @@ function asSource(json, circuit, kept) {
|
|
|
1467
3280
|
|
|
1468
3281
|
// Each plane net's vias and holes inside its plane's copper (the pour leaves a clear ring round the others)
|
|
1469
3282
|
function planeChecks(json) {
|
|
1470
|
-
const nets = json.filter((e) => e.type === 'source_net'),
|
|
3283
|
+
const nets = json.filter((e) => e.type === 'source_net'),
|
|
3284
|
+
out = [];
|
|
1471
3285
|
if (!nets.length) return out;
|
|
1472
3286
|
const inRing = (ring, p) => inside(ring.vertices, p.x, p.y);
|
|
1473
|
-
const covered = (pours, p) =>
|
|
3287
|
+
const covered = (pours, p) =>
|
|
3288
|
+
pours.some((q) => inRing(q.brep_shape.outer_ring, p) && !q.brep_shape.inner_rings.some((r) => inRing(r, p)));
|
|
1474
3289
|
const port = new Map(json.filter((e) => e.type === 'pcb_port').map((e) => [e.source_port_id, e.pcb_port_id]));
|
|
1475
3290
|
for (const n of nets) {
|
|
1476
3291
|
const pours = json.filter((e) => e.type === 'pcb_copper_pour' && e.source_net_id === n.source_net_id);
|
|
1477
3292
|
const st = json.filter((e) => e.type === 'source_trace' && e.connected_source_net_ids?.includes(n.source_net_id));
|
|
1478
|
-
const ids = new Set(st.map((t) => t.source_trace_id)),
|
|
1479
|
-
|
|
1480
|
-
for (const t of
|
|
1481
|
-
const
|
|
3293
|
+
const ids = new Set(st.map((t) => t.source_trace_id)),
|
|
3294
|
+
pts = [];
|
|
3295
|
+
for (const t of json.filter((e) => e.type === 'pcb_trace' && ids.has(e.source_trace_id)))
|
|
3296
|
+
for (const v of json.filter((e) => e.type === 'pcb_via' && e.pcb_trace_id === t.pcb_trace_id)) pts.push(v);
|
|
3297
|
+
for (const t of st) {
|
|
3298
|
+
// a pin's hole (a castellated pin's header pad, not its half hole on the edge)
|
|
3299
|
+
const h = json.find(
|
|
3300
|
+
(e) =>
|
|
3301
|
+
e.type === 'pcb_plated_hole' &&
|
|
3302
|
+
e.pcb_port_id === port.get(t.connected_source_port_ids[0]) &&
|
|
3303
|
+
!e.port_hints?.includes('castellated'),
|
|
3304
|
+
);
|
|
1482
3305
|
if (h) pts.push(h);
|
|
1483
3306
|
}
|
|
1484
3307
|
const miss = pts.filter((p) => !covered(pours, p));
|
|
1485
|
-
out.push(
|
|
1486
|
-
|
|
1487
|
-
|
|
3308
|
+
out.push(
|
|
3309
|
+
!pours.length
|
|
3310
|
+
? { level: 'fail', text: `plane ${n.name}: no copper drawn` }
|
|
3311
|
+
: miss.length
|
|
3312
|
+
? {
|
|
3313
|
+
level: 'fail',
|
|
3314
|
+
text: `plane ${n.name}: ${miss.length} of its vias and holes are outside its copper (first at ${mm(miss[0].x)}, ${mm(miss[0].y)} mm)`,
|
|
3315
|
+
}
|
|
3316
|
+
: {
|
|
3317
|
+
level: 'pass',
|
|
3318
|
+
text: `plane ${n.name} on ${pours[0].layer}: all ${st.length} pads reach it (${pts.length} vias and holes inside its copper)`,
|
|
3319
|
+
},
|
|
3320
|
+
);
|
|
1488
3321
|
}
|
|
1489
3322
|
return out;
|
|
1490
3323
|
}
|
|
1491
3324
|
|
|
1492
3325
|
// ---------- files ----------
|
|
1493
3326
|
// The fab files: Gerbers (KiCad's Protel names, which JLCPCB reads), drill files, BOM and placement -> { name: text }
|
|
1494
|
-
const PROTEL = {
|
|
3327
|
+
const PROTEL = {
|
|
3328
|
+
F_Cu: 'GTL',
|
|
3329
|
+
B_Cu: 'GBL',
|
|
3330
|
+
F_Mask: 'GTS',
|
|
3331
|
+
B_Mask: 'GBS',
|
|
3332
|
+
F_SilkScreen: 'GTO',
|
|
3333
|
+
B_SilkScreen: 'GBO',
|
|
3334
|
+
F_Paste: 'GTP',
|
|
3335
|
+
B_Paste: 'GBP',
|
|
3336
|
+
Edge_Cuts: 'GKO',
|
|
3337
|
+
};
|
|
1495
3338
|
export async function fabFiles(json, name, { source } = {}) {
|
|
1496
3339
|
// Rounded pads and slots are more than the Gerber writer draws: it plots a rounded pad square, so its corners reach
|
|
1497
3340
|
// into a plane cut round the true shape, and it can't drill a slot. KiCad plots those boards, and checks the very copper
|
|
1498
3341
|
// it plots first; without KiCad they aren't made at all
|
|
1499
3342
|
const { kicadFab, needsKicadFab } = await import('./kicad.mjs');
|
|
1500
3343
|
if (needsKicadFab(json)) {
|
|
1501
|
-
const made = await kicadFab(json, name, {
|
|
1502
|
-
|
|
3344
|
+
const made = await kicadFab(json, name, {
|
|
3345
|
+
...kicadRules(json, await sourceErrors(json, source)),
|
|
3346
|
+
allow: kicadSourceEdge(json, source),
|
|
3347
|
+
});
|
|
3348
|
+
if (!made)
|
|
3349
|
+
throw new Error(
|
|
3350
|
+
'this board has slotted holes, or rounded pads beside a copper plane: its fab files need KiCad (install it, or name kicad-cli in KICAD_CLI)',
|
|
3351
|
+
);
|
|
1503
3352
|
const { convertCircuitJsonToPickAndPlaceCsv } = await import('circuit-json-to-pnp-csv');
|
|
1504
3353
|
return { ...made, [`${name}-bom.csv`]: bom(json), [`${name}-cpl.csv`]: convertCircuitJsonToPickAndPlaceCsv(json) };
|
|
1505
3354
|
}
|
|
1506
|
-
const {
|
|
3355
|
+
const {
|
|
3356
|
+
convertSoupToGerberCommands,
|
|
3357
|
+
stringifyGerberCommandLayers,
|
|
3358
|
+
convertSoupToExcellonDrillCommands,
|
|
3359
|
+
stringifyExcellonDrill,
|
|
3360
|
+
} = await import('circuit-json-to-gerber');
|
|
1507
3361
|
const { convertCircuitJsonToPickAndPlaceCsv } = await import('circuit-json-to-pnp-csv');
|
|
1508
3362
|
const out = {};
|
|
1509
|
-
for (const [layer, text] of Object.entries(stringifyGerberCommandLayers(convertSoupToGerberCommands(json)))) {
|
|
1510
|
-
|
|
1511
|
-
|
|
3363
|
+
for (const [layer, text] of Object.entries(stringifyGerberCommandLayers(convertSoupToGerberCommands(json)))) {
|
|
3364
|
+
const ext = PROTEL[layer] ?? (layer.match(/^In(\d+)_Cu$/) ? `G${layer.match(/\d+/)[0]}` : null);
|
|
3365
|
+
if (ext) out[`${name}.${ext}`] = text;
|
|
3366
|
+
} // fab notes (B_Fab) stay out
|
|
3367
|
+
out[`${name}-PTH.DRL`] = stringifyExcellonDrill(
|
|
3368
|
+
convertSoupToExcellonDrillCommands({ circuitJson: json, is_plated: true }),
|
|
3369
|
+
);
|
|
3370
|
+
out[`${name}-NPTH.DRL`] = stringifyExcellonDrill(
|
|
3371
|
+
convertSoupToExcellonDrillCommands({ circuitJson: json, is_plated: false }),
|
|
3372
|
+
);
|
|
1512
3373
|
out[`${name}-bom.csv`] = bom(json);
|
|
1513
3374
|
out[`${name}-cpl.csv`] = convertCircuitJsonToPickAndPlaceCsv(json);
|
|
1514
3375
|
return out;
|
|
@@ -1518,15 +3379,22 @@ export async function fabFiles(json, name, { source } = {}) {
|
|
|
1518
3379
|
// number comes with it when it has one (a clone's parts keep the source's); otherwise it's blank until parts are chosen
|
|
1519
3380
|
// for assembly, and a hand-soldered board doesn't need them.
|
|
1520
3381
|
function bom(json) {
|
|
1521
|
-
const lines = new Map(),
|
|
3382
|
+
const lines = new Map(),
|
|
3383
|
+
q = (x) => `"${String(x).replace(/"/g, '""')}"`;
|
|
1522
3384
|
for (const c of json.filter((e) => e.type === 'source_component' && !e.exclude_from_bom)) {
|
|
1523
|
-
const lcsc = c.supplier_part_numbers?.jlcpcb?.[0] ?? '',
|
|
3385
|
+
const lcsc = c.supplier_part_numbers?.jlcpcb?.[0] ?? '',
|
|
3386
|
+
comment = c.display_value || c.manufacturer_part_number || c.name;
|
|
1524
3387
|
const footprint = lcsc ? '' : c.rulecad_package || ''; // the part's own package (a part with an LCSC number is known by that)
|
|
1525
3388
|
const key = `${comment}|${footprint}|${lcsc}`;
|
|
1526
3389
|
if (!lines.has(key)) lines.set(key, { comment, footprint, lcsc, refs: [] });
|
|
1527
3390
|
lines.get(key).refs.push(c.name);
|
|
1528
3391
|
}
|
|
1529
|
-
return
|
|
3392
|
+
return (
|
|
3393
|
+
[
|
|
3394
|
+
'Comment,Designator,Footprint,LCSC Part #',
|
|
3395
|
+
...[...lines.values()].map((l) => [l.comment, l.refs.join(','), l.footprint, l.lcsc].map(q).join(',')),
|
|
3396
|
+
].join('\n') + '\n'
|
|
3397
|
+
);
|
|
1530
3398
|
}
|
|
1531
3399
|
|
|
1532
3400
|
// KiCad's own files, to check with kicad-cli or finish by hand: { 'name.kicad_pcb': text, 'name.kicad_sch': text }
|
|
@@ -1535,10 +3403,17 @@ export async function kicadFiles(json, name, { clearance, track, edgeExempt: exe
|
|
|
1535
3403
|
const { CircuitJsonToKicadPcbConverter, CircuitJsonToKicadSchConverter } = await import('circuit-json-to-kicad');
|
|
1536
3404
|
const { kicadNets, patchKicadPcb, kicadProject } = await import('./kicad.mjs');
|
|
1537
3405
|
const netted = kicadNets(json); // (see kicad.mjs: what the converter leaves out, made up)
|
|
1538
|
-
const pcb = new CircuitJsonToKicadPcbConverter(netted);
|
|
1539
|
-
|
|
3406
|
+
const pcb = new CircuitJsonToKicadPcbConverter(netted);
|
|
3407
|
+
pcb.runUntilFinished();
|
|
3408
|
+
const sch = new CircuitJsonToKicadSchConverter(json);
|
|
3409
|
+
sch.runUntilFinished();
|
|
1540
3410
|
const { pro, dru } = kicadProject(netted, { clearance, track, edgeExempt });
|
|
1541
|
-
return {
|
|
3411
|
+
return {
|
|
3412
|
+
[`${name}.kicad_pcb`]: patchKicadPcb(pcb.getOutputString(), netted),
|
|
3413
|
+
[`${name}.kicad_sch`]: sch.getOutputString(),
|
|
3414
|
+
[`${name}.kicad_pro`]: pro,
|
|
3415
|
+
[`${name}.kicad_dru`]: dru,
|
|
3416
|
+
};
|
|
1542
3417
|
}
|
|
1543
3418
|
|
|
1544
3419
|
// The 2D views for the model page, as SVG drawings: [[name, svg]]. "Group: view" names group into one tab with a
|
|
@@ -1560,22 +3435,32 @@ export async function views(json) {
|
|
|
1560
3435
|
*/
|
|
1561
3436
|
export function light(svg) {
|
|
1562
3437
|
const round = (v) => v.replace(/-?\d+\.\d{3,}/g, (n) => String(Math.round(Number(n) * 100) / 100));
|
|
1563
|
-
return svg
|
|
3438
|
+
return svg
|
|
3439
|
+
.replace(/ data-(?!pcb-layer=)[\w-]+="[^"]*"/g, '')
|
|
3440
|
+
.replace(/<style><\/style>/g, '')
|
|
1564
3441
|
.replace(/(<[^>]+>)/g, (tag) => tag.replace(/="([^"]*)"/g, (_, v) => `="${round(v)}"`));
|
|
1565
3442
|
}
|
|
1566
3443
|
|
|
1567
3444
|
// The schematic as a PNG
|
|
1568
3445
|
export async function schematicPng(json, out, width = 1600) {
|
|
1569
|
-
const { convertCircuitJsonToSchematicSvg } = await import('circuit-to-svg'),
|
|
3446
|
+
const { convertCircuitJsonToSchematicSvg } = await import('circuit-to-svg'),
|
|
3447
|
+
{ Resvg } = await import('@resvg/resvg-js');
|
|
1570
3448
|
fs.mkdirSync(path.dirname(out), { recursive: true });
|
|
1571
|
-
fs.writeFileSync(
|
|
3449
|
+
fs.writeFileSync(
|
|
3450
|
+
out,
|
|
3451
|
+
new Resvg(convertCircuitJsonToSchematicSvg(json), { fitTo: { mode: 'width', value: width } }).render().asPng(),
|
|
3452
|
+
);
|
|
1572
3453
|
return out;
|
|
1573
3454
|
}
|
|
1574
3455
|
|
|
1575
3456
|
// The board drawn from above as a PNG (front copper, back copper, silkscreen, holes)
|
|
1576
3457
|
export async function png(json, out, width = 1600) {
|
|
1577
|
-
const { convertCircuitJsonToPcbSvg } = await import('circuit-to-svg'),
|
|
3458
|
+
const { convertCircuitJsonToPcbSvg } = await import('circuit-to-svg'),
|
|
3459
|
+
{ Resvg } = await import('@resvg/resvg-js');
|
|
1578
3460
|
fs.mkdirSync(path.dirname(out), { recursive: true });
|
|
1579
|
-
fs.writeFileSync(
|
|
3461
|
+
fs.writeFileSync(
|
|
3462
|
+
out,
|
|
3463
|
+
new Resvg(convertCircuitJsonToPcbSvg(json), { fitTo: { mode: 'width', value: width } }).render().asPng(),
|
|
3464
|
+
);
|
|
1580
3465
|
return out;
|
|
1581
3466
|
}
|