@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/kicad.mjs
CHANGED
|
@@ -9,6 +9,7 @@
|
|
|
9
9
|
// the hole lands off by the offset: patchKicadPcb() moves each such pad to its hole
|
|
10
10
|
// - castellated pads (a half hole on the edge) marked as KiCad's castellated pads, which may cross the board's edge
|
|
11
11
|
// - a via laid twice at one place (a kept via and the track that names it) written once
|
|
12
|
+
// - text on a back layer mirrored (KiCad plots back text as written: unmirrored, it reads backwards from below)
|
|
12
13
|
// - the rules: kicadProject() writes the project file KiCad reads them from, with the board's own minimums (pcb_board's
|
|
13
14
|
// min_* values, which our checks use), and a custom rule file for exceptions the source has (pads by its edge)
|
|
14
15
|
// - kicadDrc(): KiCad's own design-rule check on all of that, when KiCad is installed
|
|
@@ -27,70 +28,179 @@ const KICAD_CENTRE = 100; // where the converter puts the design's (0, 0) on KiC
|
|
|
27
28
|
*/
|
|
28
29
|
export function kicadNets(json) {
|
|
29
30
|
const out = structuredClone(json);
|
|
30
|
-
const up = new Map(),
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
31
|
+
const up = new Map(),
|
|
32
|
+
find = (a) => {
|
|
33
|
+
while (up.get(a) !== a) {
|
|
34
|
+
up.set(a, up.get(up.get(a)));
|
|
35
|
+
a = up.get(a);
|
|
36
|
+
}
|
|
37
|
+
return a;
|
|
38
|
+
};
|
|
39
|
+
const join = (a, b) => {
|
|
40
|
+
for (const x of [a, b]) if (!up.has(x)) up.set(x, x);
|
|
41
|
+
up.set(find(a), find(b));
|
|
42
|
+
};
|
|
43
|
+
for (const e of out)
|
|
44
|
+
if (e.type === 'source_trace') {
|
|
45
|
+
const ids = [...(e.connected_source_port_ids || []), ...(e.connected_source_net_ids || [])];
|
|
46
|
+
join(e.source_trace_id, e.source_trace_id);
|
|
47
|
+
for (const id of ids) join(e.source_trace_id, id);
|
|
48
|
+
}
|
|
49
|
+
for (const e of out)
|
|
50
|
+
if (e.type === 'source_net' || e.type === 'source_port')
|
|
51
|
+
join(e.source_net_id || e.source_port_id, e.source_net_id || e.source_port_id);
|
|
38
52
|
// a pin with more than one pad (a half hole and a header hole) has a port for each: one net. (Pins sharing only a name,
|
|
39
53
|
// as a module's GND pins do, are joined only where the board joins them)
|
|
40
54
|
const pin = new Map();
|
|
41
|
-
for (const e of out)
|
|
55
|
+
for (const e of out)
|
|
56
|
+
if (e.type === 'source_port') {
|
|
57
|
+
const k = `${e.source_component_id}:${e.name}:${e.pin_number}`;
|
|
58
|
+
if (pin.has(k)) join(pin.get(k), e.source_port_id);
|
|
59
|
+
else pin.set(k, e.source_port_id);
|
|
60
|
+
}
|
|
42
61
|
const key = (id) => `net_${find(id)}`;
|
|
43
62
|
// each net's name: its source net's, the board's name for one of its traces, else after its first pad
|
|
44
63
|
const names = new Map();
|
|
45
64
|
for (const e of out) if (e.type === 'source_net') names.set(key(e.source_net_id), e.name);
|
|
46
|
-
for (const e of out)
|
|
65
|
+
for (const e of out)
|
|
66
|
+
if (e.type === 'source_trace' && e.rulecad_net && !names.has(key(e.source_trace_id)))
|
|
67
|
+
names.set(key(e.source_trace_id), e.rulecad_net);
|
|
47
68
|
const part = new Map(out.filter((e) => e.type === 'source_component').map((e) => [e.source_component_id, e.name]));
|
|
48
|
-
for (const e of out)
|
|
69
|
+
for (const e of out)
|
|
70
|
+
if (e.type === 'source_port' && !names.has(key(e.source_port_id)))
|
|
71
|
+
names.set(
|
|
72
|
+
key(e.source_port_id),
|
|
73
|
+
`Net-(${part.get(e.source_component_id) ?? '?'}-Pad${String(e.name ?? e.pin_number).replace(/^pin/, '')})`,
|
|
74
|
+
);
|
|
49
75
|
// one name, one net: KiCad joins nets that share a name (a USB-C socket's A5 and B5 are both its pin 5)
|
|
50
76
|
const taken = new Map();
|
|
51
|
-
for (const [k, n] of names) {
|
|
77
|
+
for (const [k, n] of names) {
|
|
78
|
+
const c = (taken.get(n) || 0) + 1;
|
|
79
|
+
taken.set(n, c);
|
|
80
|
+
if (c > 1) names.set(k, `${n}_${c}`);
|
|
81
|
+
}
|
|
52
82
|
// a net no trace joins is a pin on its own: no KiCad net (net 0), as KiCad leaves an unconnected pad
|
|
53
83
|
const joined = new Set(out.filter((e) => e.type === 'source_trace').map((e) => key(e.source_trace_id)));
|
|
54
|
-
for (const k of pin.values())
|
|
84
|
+
for (const k of pin.values())
|
|
85
|
+
if (
|
|
86
|
+
[...pin.values()].filter((x) => key(x) === key(k)).length > 1 ||
|
|
87
|
+
out.some((e) => e.type === 'source_port' && e.source_port_id !== k && key(e.source_port_id) === key(k))
|
|
88
|
+
)
|
|
89
|
+
joined.add(key(k)); // (two pads of one pin: a net of their own)
|
|
55
90
|
const nets = new Map(out.filter((e) => e.type === 'source_net').map((e) => [key(e.source_net_id), e]));
|
|
56
|
-
for (const k of joined)
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
91
|
+
for (const k of joined)
|
|
92
|
+
if (!nets.has(k)) {
|
|
93
|
+
const n = {
|
|
94
|
+
type: 'source_net',
|
|
95
|
+
source_net_id: `rulecad_${k}`,
|
|
96
|
+
name: names.get(k),
|
|
97
|
+
member_source_group_ids: [],
|
|
98
|
+
subcircuit_connectivity_map_key: k,
|
|
99
|
+
};
|
|
100
|
+
out.push(n);
|
|
101
|
+
nets.set(k, n);
|
|
102
|
+
}
|
|
60
103
|
for (const [k, n] of nets) n.subcircuit_connectivity_map_key = k;
|
|
61
104
|
const traceKey = new Map();
|
|
62
105
|
for (const e of out) {
|
|
63
|
-
if (e.type === 'source_trace') {
|
|
64
|
-
|
|
106
|
+
if (e.type === 'source_trace') {
|
|
107
|
+
e.subcircuit_connectivity_map_key = key(e.source_trace_id);
|
|
108
|
+
} else if (e.type === 'source_port' && joined.has(key(e.source_port_id)))
|
|
109
|
+
e.subcircuit_connectivity_map_key = key(e.source_port_id);
|
|
65
110
|
}
|
|
66
|
-
for (const e of out)
|
|
67
|
-
|
|
111
|
+
for (const e of out)
|
|
112
|
+
if (e.type === 'pcb_trace' && e.source_trace_id && up.has(e.source_trace_id)) {
|
|
113
|
+
e.subcircuit_connectivity_map_key = key(e.source_trace_id);
|
|
114
|
+
traceKey.set(e.pcb_trace_id, e.subcircuit_connectivity_map_key);
|
|
115
|
+
}
|
|
116
|
+
for (const e of out)
|
|
117
|
+
if (e.type === 'pcb_via' && traceKey.has(e.pcb_trace_id))
|
|
118
|
+
e.subcircuit_connectivity_map_key = traceKey.get(e.pcb_trace_id);
|
|
68
119
|
return out;
|
|
69
120
|
}
|
|
70
121
|
|
|
122
|
+
// Where the S-expression opened at text[start] closes (strings in quotes skipped, as a text may hold a bracket)
|
|
123
|
+
function closeOf(text, start) {
|
|
124
|
+
let depth = 0;
|
|
125
|
+
for (let i = start; i < text.length; i++) {
|
|
126
|
+
const c = text[i];
|
|
127
|
+
if (c === '"') {
|
|
128
|
+
for (i++; i < text.length && text[i] !== '"'; i++) if (text[i] === '\\') i++;
|
|
129
|
+
} else if (c === '(') depth++;
|
|
130
|
+
else if (c === ')' && --depth === 0) return i;
|
|
131
|
+
}
|
|
132
|
+
return -1;
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
/**
|
|
136
|
+
* Every text on a back layer (B.SilkS, B.Fab, ...) mirrored, as KiCad wants it: read from below, the right way round.
|
|
137
|
+
* A text already mirrored is left as it is. Without this, a back label the converter writes unmirrored plots reading
|
|
138
|
+
* backwards, and KiCad's check warns of "non-mirrored text on back layer".
|
|
139
|
+
* @param {string} text a .kicad_pcb @returns {string}
|
|
140
|
+
*/
|
|
141
|
+
export function mirrorBackText(text) {
|
|
142
|
+
const out = [];
|
|
143
|
+
let from = 0;
|
|
144
|
+
for (const m of text.matchAll(/\((?:gr_text|fp_text|property|gr_text_box|fp_text_box)\b/g)) {
|
|
145
|
+
const start = m.index,
|
|
146
|
+
end = start >= from ? closeOf(text, start) : -1;
|
|
147
|
+
if (end < 0) continue;
|
|
148
|
+
const item = text.slice(start, end + 1);
|
|
149
|
+
if (!/\(layer\s+"?B\.\w+"?[\s)]/.test(item) || /\(justify[^()]*\bmirror\b/.test(item)) continue;
|
|
150
|
+
let fixed;
|
|
151
|
+
const justify = item.match(/\(justify[^()]*\)/),
|
|
152
|
+
effects = item.indexOf('(effects');
|
|
153
|
+
if (justify) fixed = item.replace(justify[0], `${justify[0].slice(0, -1)} mirror)`);
|
|
154
|
+
else if (effects >= 0) {
|
|
155
|
+
const e = closeOf(item, effects);
|
|
156
|
+
fixed = `${item.slice(0, e)} (justify mirror)${item.slice(e)}`;
|
|
157
|
+
} else fixed = `${item.slice(0, -1)} (effects (justify mirror)))`;
|
|
158
|
+
out.push(text.slice(from, start), fixed);
|
|
159
|
+
from = end + 1;
|
|
160
|
+
}
|
|
161
|
+
return out.join('') + text.slice(from);
|
|
162
|
+
}
|
|
163
|
+
|
|
71
164
|
/**
|
|
72
165
|
* The converter's .kicad_pcb made right for KiCad (see the top of this file): pads with an off-centre hole moved to
|
|
73
|
-
* their hole, castellated pads marked, a via laid twice written once.
|
|
166
|
+
* their hole, castellated pads marked, a via laid twice written once, text on the back mirrored.
|
|
74
167
|
* @param {string} text @param {object[]} json @returns {string}
|
|
75
168
|
*/
|
|
76
169
|
export function patchKicadPcb(text, json) {
|
|
170
|
+
text = mirrorBackText(text);
|
|
77
171
|
const r4 = (n) => Math.round(n * 1e4) / 1e4;
|
|
78
172
|
// a pad with a drill offset: at its hole (the copper keeps its place: the offset is now from the hole to it)
|
|
79
|
-
text = text.replace(
|
|
80
|
-
(
|
|
173
|
+
text = text.replace(
|
|
174
|
+
/(\(pad "[^"]*" thru_hole \w+\s*\(at )(-?[\d.e-]+) (-?[\d.e-]+)((?: -?[\d.e-]+)?\)(?:(?!\(pad )[\s\S])*?\(drill [^()]*\(offset (-?[\d.e-]+) (-?[\d.e-]+)\))/g,
|
|
175
|
+
(all, head, x, y, rest, dx, dy) => `${head}${r4(Number(x) - Number(dx))} ${r4(Number(y) - Number(dy))}${rest}`,
|
|
176
|
+
);
|
|
81
177
|
// Pads found by where their footprint puts them (the hole, now), in footprint coordinates
|
|
82
178
|
const comp = new Map(json.filter((e) => e.type === 'pcb_component').map((e) => [e.pcb_component_id, e]));
|
|
83
|
-
const at = (e) => {
|
|
84
|
-
|
|
179
|
+
const at = (e) => {
|
|
180
|
+
const c = comp.get(e.pcb_component_id);
|
|
181
|
+
return c && { x: e.x + (e.hole_offset_x ?? 0) - c.center.x, y: -(e.y + (e.hole_offset_y ?? 0) - c.center.y), e };
|
|
182
|
+
};
|
|
183
|
+
const holes = json
|
|
184
|
+
.filter((e) => e.type === 'pcb_plated_hole')
|
|
185
|
+
.map(at)
|
|
186
|
+
.filter(Boolean);
|
|
85
187
|
const find = (x, y) => holes.find((p) => Math.abs(p.x - Number(x)) < 1e-3 && Math.abs(p.y - Number(y)) < 1e-3)?.e;
|
|
86
188
|
// castellated: the half hole and every other pad of its pin (a header pad joined to it reaches the edge with it), as
|
|
87
189
|
// KiCad's castellated pads, which may cross the board's edge
|
|
88
|
-
const edgePins = new Set(
|
|
190
|
+
const edgePins = new Set(
|
|
191
|
+
holes
|
|
192
|
+
.filter((p) => p.e.port_hints?.includes('castellated'))
|
|
193
|
+
.map((p) => `${p.e.pcb_component_id}:${p.e.port_hints?.[1]}`),
|
|
194
|
+
);
|
|
89
195
|
// a rectangular pad with rounded corners (rect_border_radius): KiCad's rounded rectangle, which the converter leaves square
|
|
90
196
|
text = text.replace(/\(pad "[^"]*" thru_hole (\w+)\s*\(at (-?[\d.e-]+) (-?[\d.e-]+)[^)]*\)/g, (all, shape, x, y) => {
|
|
91
|
-
const e = find(x, y);
|
|
197
|
+
const e = find(x, y);
|
|
198
|
+
if (!e) return all;
|
|
92
199
|
let out = all;
|
|
93
|
-
if (shape === 'rect' && e.rect_border_radius)
|
|
200
|
+
if (shape === 'rect' && e.rect_border_radius)
|
|
201
|
+
out =
|
|
202
|
+
out.replace(' thru_hole rect', ' thru_hole roundrect') +
|
|
203
|
+
`\n (roundrect_rratio ${r4(e.rect_border_radius / Math.min(e.rect_pad_width, e.rect_pad_height))})`;
|
|
94
204
|
if (edgePins.has(`${e.pcb_component_id}:${e.port_hints?.[1]}`)) out += '\n (property pad_prop_castellated)';
|
|
95
205
|
return out;
|
|
96
206
|
});
|
|
@@ -98,11 +208,15 @@ export function patchKicadPcb(text, json) {
|
|
|
98
208
|
text = text.replace(/\(setup\b/, `(setup\n\t\t(aux_axis_origin ${KICAD_CENTRE} ${KICAD_CENTRE})`);
|
|
99
209
|
// a via twice at one place, the same size, layers and net: once
|
|
100
210
|
const seen = new Set();
|
|
101
|
-
text = text.replace(
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
211
|
+
text = text.replace(
|
|
212
|
+
/\n \(via\s*\(at (-?[\d.e-]+) (-?[\d.e-]+)\)\s*\(size ([\d.]+)\)\s*\(drill ([\d.]+)\)\s*\(layers ([^)]*)\)\s*(\(net \d+\))?[\s\S]*?\n \)/g,
|
|
213
|
+
(all, x, y, size, drill, layers, net) => {
|
|
214
|
+
const k = [r4(Number(x)), r4(Number(y)), size, drill, layers, net].join(' ');
|
|
215
|
+
if (seen.has(k)) return '';
|
|
216
|
+
seen.add(k);
|
|
217
|
+
return all;
|
|
218
|
+
},
|
|
219
|
+
);
|
|
106
220
|
return text;
|
|
107
221
|
}
|
|
108
222
|
|
|
@@ -116,26 +230,92 @@ export function patchKicadPcb(text, json) {
|
|
|
116
230
|
export function kicadProject(json, { clearance, track, edgeExempt = [] } = {}) {
|
|
117
231
|
const b = json.find((e) => e.type === 'pcb_board') || {};
|
|
118
232
|
const via = json.find((e) => e.type === 'pcb_via');
|
|
119
|
-
const vias = json.filter((e) => e.type === 'pcb_via'),
|
|
120
|
-
|
|
233
|
+
const vias = json.filter((e) => e.type === 'pcb_via'),
|
|
234
|
+
holes = json
|
|
235
|
+
.filter((e) => e.type === 'pcb_plated_hole' || e.type === 'pcb_hole' || e.type === 'pcb_via')
|
|
236
|
+
.map((e) => e.hole_diameter ?? e.hole_width)
|
|
237
|
+
.filter(Boolean);
|
|
238
|
+
const viaPad = Math.min(b.min_via_pad_diameter ?? 0.3, ...vias.map((v) => v.outer_diameter)),
|
|
239
|
+
viaHole = Math.min(b.min_via_hole_diameter ?? 0.2, ...vias.map((v) => v.hole_diameter));
|
|
121
240
|
const gap = clearance ?? b.min_trace_to_pad_edge_clearance ?? 0.1;
|
|
122
241
|
const rules = {
|
|
123
|
-
min_clearance: gap,
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
242
|
+
min_clearance: gap,
|
|
243
|
+
min_track_width: Math.min(
|
|
244
|
+
b.min_trace_width ?? 0.1,
|
|
245
|
+
...json.filter((e) => e.type === 'pcb_trace').flatMap((t) => t.route.map((p) => p.width ?? Infinity)),
|
|
246
|
+
),
|
|
247
|
+
min_via_diameter: viaPad,
|
|
248
|
+
min_through_hole_diameter: Math.min(viaHole, ...holes),
|
|
249
|
+
min_via_annular_width: Math.min(
|
|
250
|
+
...vias.map((v) => (v.outer_diameter - v.hole_diameter) / 2),
|
|
251
|
+
(viaPad - viaHole) / 2,
|
|
252
|
+
),
|
|
253
|
+
min_copper_edge_clearance: b.min_board_edge_clearance ?? 0.2,
|
|
254
|
+
min_hole_clearance: b.min_trace_to_hole_edge_clearance ?? 0.2,
|
|
255
|
+
min_hole_to_hole: b.min_via_hole_edge_to_via_hole_edge_clearance ?? 0.1,
|
|
256
|
+
min_silk_clearance: 0,
|
|
257
|
+
min_microvia_diameter: 0.2,
|
|
258
|
+
min_microvia_drill: 0.1,
|
|
259
|
+
allow_blind_buried_vias: false,
|
|
260
|
+
allow_microvias: false,
|
|
261
|
+
max_error: 0.005,
|
|
262
|
+
use_height_for_length_calcs: true,
|
|
263
|
+
};
|
|
264
|
+
const pro = {
|
|
265
|
+
board: {
|
|
266
|
+
design_settings: {
|
|
267
|
+
defaults: {},
|
|
268
|
+
rules,
|
|
269
|
+
track_widths: [0],
|
|
270
|
+
via_dimensions: [{ diameter: 0, drill: 0 }],
|
|
271
|
+
rule_severities: {},
|
|
272
|
+
},
|
|
273
|
+
},
|
|
129
274
|
meta: { filename: 'board.kicad_pro', version: 3 },
|
|
130
|
-
net_settings: {
|
|
131
|
-
|
|
132
|
-
|
|
275
|
+
net_settings: {
|
|
276
|
+
classes: [
|
|
277
|
+
{
|
|
278
|
+
name: 'Default',
|
|
279
|
+
clearance: gap,
|
|
280
|
+
track_width: track ?? 0.15,
|
|
281
|
+
via_diameter: via?.outer_diameter ?? viaPad,
|
|
282
|
+
via_drill: via?.hole_diameter ?? viaHole,
|
|
283
|
+
microvia_diameter: 0.2,
|
|
284
|
+
microvia_drill: 0.1,
|
|
285
|
+
diff_pair_gap: 0.2,
|
|
286
|
+
diff_pair_width: 0.2,
|
|
287
|
+
diff_pair_via_gap: 0.25,
|
|
288
|
+
wire_width: 6,
|
|
289
|
+
bus_width: 12,
|
|
290
|
+
line_style: 0,
|
|
291
|
+
pcb_color: 'rgba(0, 0, 0, 0.000)',
|
|
292
|
+
schematic_color: 'rgba(0, 0, 0, 0.000)',
|
|
293
|
+
priority: 2147483647,
|
|
294
|
+
},
|
|
295
|
+
],
|
|
296
|
+
meta: { version: 3 },
|
|
297
|
+
},
|
|
298
|
+
};
|
|
299
|
+
const dru =
|
|
300
|
+
[
|
|
301
|
+
'(version 1)',
|
|
302
|
+
...edgeExempt.map(
|
|
303
|
+
(x) =>
|
|
304
|
+
`(rule "${x.ref}: its pads by the edge, as the source has them"\n (condition "A.Parent == '${x.ref}' && A.Type == 'Pad'")\n (constraint edge_clearance (min ${x.edge}mm)))`,
|
|
305
|
+
),
|
|
306
|
+
].join('\n') + '\n';
|
|
133
307
|
return { pro: JSON.stringify(pro, null, 2) + '\n', dru };
|
|
134
308
|
}
|
|
135
309
|
|
|
136
310
|
// kicad-cli, where KiCad installs it (KICAD_CLI names another), or null when KiCad isn't installed
|
|
137
311
|
export function kicadCli(env = process.env) {
|
|
138
|
-
const candidates = [
|
|
312
|
+
const candidates = [
|
|
313
|
+
env.KICAD_CLI,
|
|
314
|
+
'/Applications/KiCad/KiCad.app/Contents/MacOS/kicad-cli',
|
|
315
|
+
'/usr/bin/kicad-cli',
|
|
316
|
+
'/usr/local/bin/kicad-cli',
|
|
317
|
+
'C:\\Program Files\\KiCad\\bin\\kicad-cli.exe',
|
|
318
|
+
].filter(Boolean);
|
|
139
319
|
return candidates.find((p) => fs.existsSync(p)) ?? null;
|
|
140
320
|
}
|
|
141
321
|
|
|
@@ -146,21 +326,46 @@ async function onKicadBoard(json, o, fn) {
|
|
|
146
326
|
const { CircuitJsonToKicadPcbConverter } = await import('circuit-json-to-kicad');
|
|
147
327
|
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'rulecad-kicad-'));
|
|
148
328
|
try {
|
|
149
|
-
const netted = kicadNets(json),
|
|
150
|
-
|
|
329
|
+
const netted = kicadNets(json),
|
|
330
|
+
pcb = new CircuitJsonToKicadPcbConverter(netted);
|
|
331
|
+
pcb.runUntilFinished();
|
|
332
|
+
const { pro, dru } = kicadProject(netted, o),
|
|
333
|
+
board = path.join(dir, 'board.kicad_pcb');
|
|
151
334
|
fs.writeFileSync(board, patchKicadPcb(pcb.getOutputString(), netted));
|
|
152
|
-
fs.writeFileSync(path.join(dir, 'board.kicad_pro'), pro);
|
|
335
|
+
fs.writeFileSync(path.join(dir, 'board.kicad_pro'), pro);
|
|
336
|
+
fs.writeFileSync(path.join(dir, 'board.kicad_dru'), dru);
|
|
153
337
|
return await fn({ cli, dir, board });
|
|
154
|
-
} finally {
|
|
338
|
+
} finally {
|
|
339
|
+
fs.rmSync(dir, { recursive: true, force: true });
|
|
340
|
+
}
|
|
155
341
|
}
|
|
156
342
|
|
|
157
343
|
// kicad-cli's design-rule check, KiCad pouring the planes (extra: more arguments, as --save-board)
|
|
158
344
|
function runDrc(cli, dir, board, extra = []) {
|
|
159
345
|
const version = execFileSync(cli, ['version'], { encoding: 'utf8' }).trim();
|
|
160
|
-
execFileSync(
|
|
346
|
+
execFileSync(
|
|
347
|
+
cli,
|
|
348
|
+
[
|
|
349
|
+
'pcb',
|
|
350
|
+
'drc',
|
|
351
|
+
'--refill-zones',
|
|
352
|
+
...extra,
|
|
353
|
+
'--format',
|
|
354
|
+
'json',
|
|
355
|
+
'--severity-all',
|
|
356
|
+
'-o',
|
|
357
|
+
path.join(dir, 'drc.json'),
|
|
358
|
+
board,
|
|
359
|
+
],
|
|
360
|
+
{ stdio: 'pipe' },
|
|
361
|
+
);
|
|
161
362
|
const d = JSON.parse(fs.readFileSync(path.join(dir, 'drc.json'), 'utf8'));
|
|
162
363
|
const all = [...d.violations, ...d.unconnected_items].filter((x) => x.type !== 'lib_footprint_issues'); // (KiCad's library has no "tscircuit" footprints: nothing about the board)
|
|
163
|
-
return {
|
|
364
|
+
return {
|
|
365
|
+
version,
|
|
366
|
+
errors: all.filter((x) => x.severity === 'error'),
|
|
367
|
+
warnings: all.filter((x) => x.severity !== 'error'),
|
|
368
|
+
};
|
|
164
369
|
}
|
|
165
370
|
|
|
166
371
|
/**
|
|
@@ -180,7 +385,10 @@ export async function kicadDrc(json, o = {}) {
|
|
|
180
385
|
*/
|
|
181
386
|
export function needsKicadFab(json) {
|
|
182
387
|
const plated = json.filter((e) => e.type === 'pcb_plated_hole');
|
|
183
|
-
return
|
|
388
|
+
return (
|
|
389
|
+
plated.some((e) => e.hole_width != null && e.hole_height != null && e.hole_width !== e.hole_height) ||
|
|
390
|
+
(plated.some((e) => e.rect_border_radius) && json.some((e) => e.type === 'pcb_copper_pour'))
|
|
391
|
+
);
|
|
184
392
|
}
|
|
185
393
|
|
|
186
394
|
/**
|
|
@@ -190,60 +398,184 @@ export function needsKicadFab(json) {
|
|
|
190
398
|
*/
|
|
191
399
|
export function drillMismatches(json, pth, npth) {
|
|
192
400
|
const read = (text) => {
|
|
193
|
-
const tools = new Map(),
|
|
401
|
+
const tools = new Map(),
|
|
402
|
+
out = [];
|
|
403
|
+
let size = null;
|
|
194
404
|
for (const raw of text.split(/\r?\n/)) {
|
|
195
|
-
const line = raw.trim(),
|
|
196
|
-
|
|
197
|
-
|
|
405
|
+
const line = raw.trim(),
|
|
406
|
+
tool = line.match(/^T(\d+)(?:[A-Z]\S*?)?C([\d.]+)/),
|
|
407
|
+
pick = line.match(/^T(\d+)$/),
|
|
408
|
+
at = line.match(/^X(-?[\d.]+)Y(-?[\d.]+)(?:G85X(-?[\d.]+)Y(-?[\d.]+))?/);
|
|
409
|
+
if (tool) tools.set(tool[1], Number(tool[2]));
|
|
410
|
+
else if (pick) size = tools.get(pick[1]);
|
|
411
|
+
else if (at)
|
|
412
|
+
out.push({
|
|
413
|
+
x: (Number(at[1]) + (at[3] != null ? Number(at[3]) : Number(at[1]))) / 2,
|
|
414
|
+
y: (Number(at[2]) + (at[4] != null ? Number(at[4]) : Number(at[2]))) / 2,
|
|
415
|
+
d: size,
|
|
416
|
+
run: at[3] != null ? Math.hypot(Number(at[3]) - Number(at[1]), Number(at[4]) - Number(at[2])) : 0,
|
|
417
|
+
used: false,
|
|
418
|
+
});
|
|
198
419
|
}
|
|
199
420
|
return out;
|
|
200
421
|
};
|
|
201
|
-
const near = 0.011,
|
|
422
|
+
const near = 0.011,
|
|
423
|
+
wrong = [];
|
|
202
424
|
const compare = (text, all, kind) => {
|
|
203
|
-
const found = read(text),
|
|
425
|
+
const found = read(text),
|
|
426
|
+
seen = new Set(),
|
|
427
|
+
wanted = all.filter((h) => {
|
|
428
|
+
const k = [h.x.toFixed(3), h.y.toFixed(3), h.d, h.run].join();
|
|
429
|
+
return !seen.has(k) && seen.add(k);
|
|
430
|
+
}); // (a via laid twice is drilled once)
|
|
204
431
|
for (const h of wanted) {
|
|
205
432
|
const f = found.find((q) => !q.used && Math.hypot(q.x - h.x, q.y - h.y) < near);
|
|
206
|
-
if (!f) {
|
|
433
|
+
if (!f) {
|
|
434
|
+
wrong.push(`no ${kind} hole at (${h.x.toFixed(3)}, ${h.y.toFixed(3)})`);
|
|
435
|
+
continue;
|
|
436
|
+
}
|
|
207
437
|
f.used = true;
|
|
208
|
-
if (Math.abs(f.d - h.d) > near || Math.abs(f.run - h.run) > near)
|
|
438
|
+
if (Math.abs(f.d - h.d) > near || Math.abs(f.run - h.run) > near)
|
|
439
|
+
wrong.push(
|
|
440
|
+
`${kind} hole at (${h.x.toFixed(3)}, ${h.y.toFixed(3)}): ${f.d} mm${f.run ? ' slot' : ''} in the file, ${h.d} mm${h.run ? ` slot running ${h.run.toFixed(3)} mm` : ''} in the design`,
|
|
441
|
+
);
|
|
209
442
|
}
|
|
210
|
-
for (const f of found.filter((q) => !q.used))
|
|
443
|
+
for (const f of found.filter((q) => !q.used))
|
|
444
|
+
wrong.push(`a ${kind} hole at (${f.x.toFixed(3)}, ${f.y.toFixed(3)}) the design doesn't have`);
|
|
445
|
+
};
|
|
446
|
+
const hole = (e) => {
|
|
447
|
+
const w = e.hole_width,
|
|
448
|
+
h = e.hole_height,
|
|
449
|
+
slot = e.hole_diameter == null && w != null && h != null;
|
|
450
|
+
return {
|
|
451
|
+
x: e.x + (e.hole_offset_x ?? 0),
|
|
452
|
+
y: e.y + (e.hole_offset_y ?? 0),
|
|
453
|
+
d: slot ? Math.min(w, h) : (e.hole_diameter ?? w),
|
|
454
|
+
run: slot ? Math.abs(w - h) : 0,
|
|
455
|
+
};
|
|
211
456
|
};
|
|
212
|
-
const hole = (e) => { const w = e.hole_width, h = e.hole_height, slot = e.hole_diameter == null && w != null && h != null; return { x: e.x + (e.hole_offset_x ?? 0), y: e.y + (e.hole_offset_y ?? 0), d: slot ? Math.min(w, h) : e.hole_diameter ?? w, run: slot ? Math.abs(w - h) : 0 }; };
|
|
213
457
|
compare(pth, json.filter((e) => e.type === 'pcb_plated_hole' || e.type === 'pcb_via').map(hole), 'plated');
|
|
214
458
|
compare(npth, json.filter((e) => e.type === 'pcb_hole').map(hole), 'unplated');
|
|
215
459
|
return wrong;
|
|
216
460
|
}
|
|
217
461
|
|
|
462
|
+
/**
|
|
463
|
+
* Throws when KiCad's check found text on a back layer that isn't mirrored (KiCad counts it only a warning, but a
|
|
464
|
+
* back label plotted so reads backwards): patchKicadPcb mirrors them all, so one left is a fault to see, not to plot.
|
|
465
|
+
* @param {{ type: string, items?: { description?: string }[] }[]} warnings KiCad's design-rule check's warnings
|
|
466
|
+
*/
|
|
467
|
+
export function unmirroredBackText(warnings) {
|
|
468
|
+
const found = warnings.filter((x) => x.type === 'nonmirrored_text_on_back_layer');
|
|
469
|
+
if (found.length)
|
|
470
|
+
throw new Error(
|
|
471
|
+
`no fab files: ${found.length} texts on the back of the board aren't mirrored, so they would read backwards from below (first: ${found[0].items?.[0]?.description ?? found[0].description})`,
|
|
472
|
+
);
|
|
473
|
+
}
|
|
474
|
+
|
|
218
475
|
/**
|
|
219
476
|
* The Gerber and drill files, plotted by KiCad from the very board its design-rule check has just passed, planes poured,
|
|
220
477
|
* named as a fab expects: { 'name.GTL': text, ..., 'name-PTH.DRL': text, 'name-NPTH.DRL': text }. Throws if the check
|
|
221
|
-
* finds an error (allow(finding): one that's accepted, the source's own) or the
|
|
478
|
+
* finds an error (allow(finding): one that's accepted, the source's own) or text on the back that isn't mirrored, or
|
|
479
|
+
* the drill files aren't the design's holes;
|
|
222
480
|
* null when KiCad isn't installed.
|
|
223
481
|
* @param {object[]} json @param {string} name @param {{ clearance?: number, track?: number, edgeExempt?: object[], allow?: (x: any) => boolean }} [o]
|
|
224
482
|
*/
|
|
225
483
|
export async function kicadFab(json, name, o = {}) {
|
|
226
484
|
return onKicadBoard(json, o, ({ cli, dir, board }) => {
|
|
227
|
-
const drc = runDrc(cli, dir, board, ['--save-board']),
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
485
|
+
const drc = runDrc(cli, dir, board, ['--save-board']),
|
|
486
|
+
errors = drc.errors.filter((x) => !o.allow?.(x));
|
|
487
|
+
if (errors.length)
|
|
488
|
+
throw new Error(
|
|
489
|
+
`no fab files: KiCad's design-rule check found ${errors.length} errors on the board it would plot (first: ${errors[0].description})`,
|
|
490
|
+
);
|
|
491
|
+
unmirroredBackText(drc.warnings);
|
|
492
|
+
const copper = json.find((e) => e.type === 'pcb_board')?.num_layers ?? 2,
|
|
493
|
+
inner = Array.from({ length: copper - 2 }, (_, i) => `In${i + 1}.Cu`);
|
|
494
|
+
const layers = [
|
|
495
|
+
'F.Cu',
|
|
496
|
+
...inner,
|
|
497
|
+
'B.Cu',
|
|
498
|
+
'F.Paste',
|
|
499
|
+
'B.Paste',
|
|
500
|
+
'F.SilkS',
|
|
501
|
+
'B.SilkS',
|
|
502
|
+
'F.Mask',
|
|
503
|
+
'B.Mask',
|
|
504
|
+
'Edge.Cuts',
|
|
505
|
+
];
|
|
506
|
+
const plots = path.join(dir, 'plots'),
|
|
507
|
+
drills = path.join(dir, 'drills');
|
|
508
|
+
fs.mkdirSync(plots);
|
|
509
|
+
fs.mkdirSync(drills);
|
|
510
|
+
execFileSync(
|
|
511
|
+
cli,
|
|
512
|
+
[
|
|
513
|
+
'pcb',
|
|
514
|
+
'export',
|
|
515
|
+
'gerbers',
|
|
516
|
+
'--layers',
|
|
517
|
+
layers.join(','),
|
|
518
|
+
'--use-drill-file-origin',
|
|
519
|
+
'--no-x2',
|
|
520
|
+
'--no-netlist',
|
|
521
|
+
'-o',
|
|
522
|
+
`${plots}/`,
|
|
523
|
+
board,
|
|
524
|
+
],
|
|
525
|
+
{ stdio: 'pipe' },
|
|
526
|
+
);
|
|
527
|
+
execFileSync(
|
|
528
|
+
cli,
|
|
529
|
+
[
|
|
530
|
+
'pcb',
|
|
531
|
+
'export',
|
|
532
|
+
'drill',
|
|
533
|
+
'--format',
|
|
534
|
+
'excellon',
|
|
535
|
+
'--excellon-separate-th',
|
|
536
|
+
'--excellon-units',
|
|
537
|
+
'mm',
|
|
538
|
+
'--excellon-zeros-format',
|
|
539
|
+
'decimal',
|
|
540
|
+
'--excellon-oval-format',
|
|
541
|
+
'alternate',
|
|
542
|
+
'--drill-origin',
|
|
543
|
+
'plot',
|
|
544
|
+
'-o',
|
|
545
|
+
`${drills}/`,
|
|
546
|
+
board,
|
|
547
|
+
],
|
|
548
|
+
{ stdio: 'pipe' },
|
|
549
|
+
);
|
|
550
|
+
const ext = {
|
|
551
|
+
F_Cu: 'GTL',
|
|
552
|
+
B_Cu: 'GBL',
|
|
553
|
+
F_Paste: 'GTP',
|
|
554
|
+
B_Paste: 'GBP',
|
|
555
|
+
F_Silkscreen: 'GTO',
|
|
556
|
+
B_Silkscreen: 'GBO',
|
|
557
|
+
F_Mask: 'GTS',
|
|
558
|
+
B_Mask: 'GBS',
|
|
559
|
+
Edge_Cuts: 'GKO',
|
|
560
|
+
};
|
|
236
561
|
const out = {};
|
|
237
562
|
for (const f of fs.readdirSync(plots)) {
|
|
238
563
|
if (f.endsWith('.gbrjob')) continue;
|
|
239
|
-
const layer = f.replace(/^board-/, '').replace(/\.[^.]+$/, ''),
|
|
564
|
+
const layer = f.replace(/^board-/, '').replace(/\.[^.]+$/, ''),
|
|
565
|
+
inn = layer.match(/^In(\d+)_Cu$/),
|
|
566
|
+
e = inn ? `G${inn[1]}` : ext[layer];
|
|
240
567
|
if (!e) throw new Error(`no fab files: KiCad plotted a layer we can't name (${f})`);
|
|
241
568
|
out[`${name}.${e}`] = fs.readFileSync(path.join(plots, f), 'utf8');
|
|
242
569
|
}
|
|
243
|
-
if (Object.keys(out).length !== layers.length)
|
|
244
|
-
|
|
570
|
+
if (Object.keys(out).length !== layers.length)
|
|
571
|
+
throw new Error(`no fab files: KiCad plotted ${Object.keys(out).length} of ${layers.length} layers`);
|
|
572
|
+
const pth = fs.readFileSync(path.join(drills, 'board-PTH.drl'), 'utf8'),
|
|
573
|
+
npth = fs.readFileSync(path.join(drills, 'board-NPTH.drl'), 'utf8');
|
|
245
574
|
const wrong = drillMismatches(json, pth, npth);
|
|
246
|
-
if (wrong.length)
|
|
575
|
+
if (wrong.length)
|
|
576
|
+
throw new Error(
|
|
577
|
+
`no fab files: KiCad's drill files aren't the design's holes (${wrong.length}; first: ${wrong[0]})`,
|
|
578
|
+
);
|
|
247
579
|
return { ...out, [`${name}-PTH.DRL`]: pth, [`${name}-NPTH.DRL`]: npth };
|
|
248
580
|
});
|
|
249
581
|
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@rulecad/pcb",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.7.0",
|
|
4
4
|
"description": "Circuit boards from rules: parts from rule sets or any standard footprint, quarter-turn rotation, nets and autorouting; keyboards with every matrix track drawn by rule. Gerbers, KiCad files and a JLCPCB BOM. Circuit JSON written directly: no React.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"exports": "./pcb.mjs",
|
|
@@ -24,7 +24,7 @@
|
|
|
24
24
|
"autorouter"
|
|
25
25
|
],
|
|
26
26
|
"engines": {
|
|
27
|
-
"node": ">=
|
|
27
|
+
"node": ">=24"
|
|
28
28
|
},
|
|
29
29
|
"repository": {
|
|
30
30
|
"type": "git",
|
|
@@ -38,10 +38,10 @@
|
|
|
38
38
|
"dependencies": {
|
|
39
39
|
"@flatten-js/core": "1.6.14",
|
|
40
40
|
"@jscad/modeling": "^2.12.0",
|
|
41
|
-
"@rulecad/fixings": "^0.
|
|
42
|
-
"@rulecad/rules": "^0.
|
|
41
|
+
"@rulecad/fixings": "^0.2.0",
|
|
42
|
+
"@rulecad/rules": "^0.4.0",
|
|
43
43
|
"@resvg/resvg-js": "2.6.2",
|
|
44
|
-
"@rulecad/smooth": "^0.
|
|
44
|
+
"@rulecad/smooth": "^0.3.0",
|
|
45
45
|
"@tscircuit/capacity-autorouter": "0.0.982",
|
|
46
46
|
"@tscircuit/checks": "0.0.264",
|
|
47
47
|
"@tscircuit/circuit-json-util": "0.0.122",
|