multisim2kicad 0.0.0 → 0.1.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/LICENSE +15 -0
- package/README.md +126 -1
- package/dist/cli.js +3755 -0
- package/dist/db/ewdb.d.ts +19 -0
- package/dist/db/symbols.d.ts +33 -0
- package/dist/emit/footprint-lib.d.ts +35 -0
- package/dist/emit/kicad-pcb.d.ts +34 -0
- package/dist/emit/kicad-pro.d.ts +18 -0
- package/dist/emit/kicad-sch.d.ts +59 -0
- package/dist/emit/pcb-layers.d.ts +40 -0
- package/dist/index.d.ts +19 -0
- package/dist/index.js +3791 -0
- package/dist/ir/types.d.ts +391 -0
- package/dist/load.d.ts +18 -0
- package/dist/main.d.ts +38 -0
- package/dist/parse/doc.d.ts +18 -0
- package/dist/parse/ms-hierarchy.d.ts +75 -0
- package/dist/parse/pcb.d.ts +9 -0
- package/dist/parse/sch.d.ts +38 -0
- package/dist/parse/ub-geom.d.ts +38 -0
- package/dist/ref/ci-netlist.d.ts +71 -0
- package/package.json +58 -3
package/dist/cli.js
ADDED
|
@@ -0,0 +1,3755 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
|
|
3
|
+
// src/main.ts
|
|
4
|
+
import { mkdir, readdir, readFile as readFile2, stat, writeFile } from "node:fs/promises";
|
|
5
|
+
import { basename, dirname, join, resolve } from "node:path";
|
|
6
|
+
|
|
7
|
+
// src/load.ts
|
|
8
|
+
import { readFile } from "node:fs/promises";
|
|
9
|
+
import { decodeBuffer, detectFormatByHeader, MAX_HEADER_LENGTH } from "electronics-workbench-decoder";
|
|
10
|
+
async function loadDesign(path) {
|
|
11
|
+
const buf = await readFile(path);
|
|
12
|
+
const format = detectFormatByHeader(buf.subarray(0, MAX_HEADER_LENGTH));
|
|
13
|
+
let xml;
|
|
14
|
+
let via;
|
|
15
|
+
if (format) {
|
|
16
|
+
if (format.kind !== "compressed-xml") {
|
|
17
|
+
throw new Error(`${path}: ${format.label} files are component databases, not designs`);
|
|
18
|
+
}
|
|
19
|
+
xml = decodeBuffer(buf).xml.toString("utf8");
|
|
20
|
+
via = "binary";
|
|
21
|
+
} else {
|
|
22
|
+
xml = buf.toString("utf8");
|
|
23
|
+
via = "xml";
|
|
24
|
+
}
|
|
25
|
+
const head = xml.slice(0, 4096);
|
|
26
|
+
if (/<MSMElectronicsWorkbench[\s>]/.test(head))
|
|
27
|
+
return { kind: "schematic", xml, via };
|
|
28
|
+
if (/<ElectronicsWorkbench[\s>]/.test(head))
|
|
29
|
+
return { kind: "pcb", xml, via };
|
|
30
|
+
throw new Error(`${path}: not an Electronics Workbench design (no EW root element)`);
|
|
31
|
+
}
|
|
32
|
+
function designBaseName(file) {
|
|
33
|
+
return file.replace(/^.*[\\/]/, "").replace(/\.xml$/i, "").replace(/\.(ewprj|ms1\d)$/i, "");
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
// src/parse/doc.ts
|
|
37
|
+
import { parseEwXml } from "electronics-workbench-decoder";
|
|
38
|
+
import { decodeEwString } from "electronics-workbench-decoder";
|
|
39
|
+
var docOf = (input) => typeof input === "string" ? parseEwXml(input) : input;
|
|
40
|
+
var displayText = (s) => s.replace(/\r\n?/g, `
|
|
41
|
+
`).trim();
|
|
42
|
+
|
|
43
|
+
// src/parse/ub-geom.ts
|
|
44
|
+
function points(item) {
|
|
45
|
+
return (item?.child("Object")?.childrenNamed("Point") ?? []).map((p) => ({ x: Number(p.get("X") ?? 0), y: Number(p.get("Y") ?? 0) }));
|
|
46
|
+
}
|
|
47
|
+
var ARC_TOLERANCE_NM = 5000;
|
|
48
|
+
function segmentsFor(radius, sweep) {
|
|
49
|
+
if (radius <= 0)
|
|
50
|
+
return 1;
|
|
51
|
+
const step = 2 * Math.acos(Math.max(-1, 1 - ARC_TOLERANCE_NM / radius));
|
|
52
|
+
return Math.max(2, Math.ceil(Math.abs(sweep) / Math.max(step, 0.001)));
|
|
53
|
+
}
|
|
54
|
+
function ccwSweep(center, start, end) {
|
|
55
|
+
const a0 = Math.atan2(start.y - center.y, start.x - center.x);
|
|
56
|
+
const a1 = Math.atan2(end.y - center.y, end.x - center.x);
|
|
57
|
+
let s = a1 - a0;
|
|
58
|
+
while (s <= 0.000000000001)
|
|
59
|
+
s += 2 * Math.PI;
|
|
60
|
+
return s;
|
|
61
|
+
}
|
|
62
|
+
function arcPoints(center, radius, a0, sweep) {
|
|
63
|
+
const n = segmentsFor(radius, sweep);
|
|
64
|
+
const out = [];
|
|
65
|
+
for (let i = 0;i <= n; i++) {
|
|
66
|
+
const a = a0 + sweep * i / n;
|
|
67
|
+
out.push({ x: center.x + radius * Math.cos(a), y: center.y + radius * Math.sin(a) });
|
|
68
|
+
}
|
|
69
|
+
return out;
|
|
70
|
+
}
|
|
71
|
+
function roundedPolygon(corners, r) {
|
|
72
|
+
if (r <= 0)
|
|
73
|
+
return corners;
|
|
74
|
+
const out = [];
|
|
75
|
+
const n = corners.length;
|
|
76
|
+
let area = 0;
|
|
77
|
+
for (let i = 0;i < n; i++) {
|
|
78
|
+
const a = corners[i], b = corners[(i + 1) % n];
|
|
79
|
+
area += a.x * b.y - b.x * a.y;
|
|
80
|
+
}
|
|
81
|
+
const ccw = area > 0;
|
|
82
|
+
for (let i = 0;i < n; i++) {
|
|
83
|
+
const prev = corners[(i + n - 1) % n], cur = corners[i], next = corners[(i + 1) % n];
|
|
84
|
+
const u1 = unit(prev, cur), u2 = unit(cur, next);
|
|
85
|
+
const len = Math.min(r, dist(prev, cur) / 2, dist(cur, next) / 2);
|
|
86
|
+
const pIn = { x: cur.x - u1.x * len, y: cur.y - u1.y * len };
|
|
87
|
+
const pOut = { x: cur.x + u2.x * len, y: cur.y + u2.y * len };
|
|
88
|
+
const inward = ccw ? { x: -u1.y, y: u1.x } : { x: u1.y, y: -u1.x };
|
|
89
|
+
const c = { x: pIn.x + inward.x * len, y: pIn.y + inward.y * len };
|
|
90
|
+
const a0 = Math.atan2(pIn.y - c.y, pIn.x - c.x);
|
|
91
|
+
const a1 = Math.atan2(pOut.y - c.y, pOut.x - c.x);
|
|
92
|
+
let sweep = a1 - a0;
|
|
93
|
+
if (ccw)
|
|
94
|
+
while (sweep < 0)
|
|
95
|
+
sweep += 2 * Math.PI;
|
|
96
|
+
else
|
|
97
|
+
while (sweep > 0)
|
|
98
|
+
sweep -= 2 * Math.PI;
|
|
99
|
+
out.push(...arcPoints(c, len, a0, sweep));
|
|
100
|
+
}
|
|
101
|
+
return out;
|
|
102
|
+
}
|
|
103
|
+
var dist = (a, b) => Math.hypot(b.x - a.x, b.y - a.y);
|
|
104
|
+
function unit(a, b) {
|
|
105
|
+
const d = dist(a, b) || 1;
|
|
106
|
+
return { x: (b.x - a.x) / d, y: (b.y - a.y) / d };
|
|
107
|
+
}
|
|
108
|
+
function ubPrimitive(tag, item) {
|
|
109
|
+
const pts = points(item);
|
|
110
|
+
const radius = Number(item.get("Radius") ?? 0);
|
|
111
|
+
const width = Number(item.get("LineThickness") ?? 0);
|
|
112
|
+
switch (tag) {
|
|
113
|
+
case "UBPolygon":
|
|
114
|
+
return pts.length >= 3 ? { kind: "poly", points: pts } : undefined;
|
|
115
|
+
case "UBRectangle":
|
|
116
|
+
return pts.length >= 4 ? { kind: "poly", points: pts.slice(0, 4) } : undefined;
|
|
117
|
+
case "UBRoundedRectangle":
|
|
118
|
+
return pts.length >= 4 ? { kind: "poly", points: roundedPolygon(pts.slice(0, 4), radius) } : undefined;
|
|
119
|
+
case "UBPie": {
|
|
120
|
+
if (pts.length < 3)
|
|
121
|
+
return;
|
|
122
|
+
const [start, end, center] = pts;
|
|
123
|
+
const r = radius || dist(center, start);
|
|
124
|
+
const a0 = Math.atan2(start.y - center.y, start.x - center.x);
|
|
125
|
+
const sweep = ccwSweep(center, start, end);
|
|
126
|
+
if (sweep >= 2 * Math.PI - 0.000000001)
|
|
127
|
+
return { kind: "circle", center, radius: r, width: 0, fill: true };
|
|
128
|
+
return { kind: "poly", points: [center, ...arcPoints(center, r, a0, sweep)] };
|
|
129
|
+
}
|
|
130
|
+
case "UBArc": {
|
|
131
|
+
if (pts.length < 3)
|
|
132
|
+
return;
|
|
133
|
+
const [start, end, center] = pts;
|
|
134
|
+
const r = radius || dist(center, start);
|
|
135
|
+
if (dist(start, end) < 1)
|
|
136
|
+
return { kind: "circle", center, radius: r, width, fill: false };
|
|
137
|
+
return { kind: "arc", center, start, end, width };
|
|
138
|
+
}
|
|
139
|
+
case "UBEllipse": {
|
|
140
|
+
if (pts.length < 2)
|
|
141
|
+
return;
|
|
142
|
+
const [p0, p1] = pts;
|
|
143
|
+
const center = { x: (p0.x + p1.x) / 2, y: (p0.y + p1.y) / 2 };
|
|
144
|
+
return { kind: "circle", center, radius: dist(p0, p1) / 2, width, fill: true };
|
|
145
|
+
}
|
|
146
|
+
}
|
|
147
|
+
return;
|
|
148
|
+
}
|
|
149
|
+
var UB_PRIMITIVE_TAGS = ["UBPolygon", "UBRectangle", "UBRoundedRectangle", "UBPie", "UBArc", "UBEllipse"];
|
|
150
|
+
function primitiveOutline(p) {
|
|
151
|
+
if (p.kind === "poly")
|
|
152
|
+
return p.points;
|
|
153
|
+
if (p.kind === "circle" && p.fill)
|
|
154
|
+
return arcPoints(p.center, p.radius, 0, 2 * Math.PI).slice(0, -1);
|
|
155
|
+
return;
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
// src/parse/pcb.ts
|
|
159
|
+
var kids = (n, list, item) => n?.child(list)?.childrenNamed(item) ?? [];
|
|
160
|
+
var SHAPE_TAGS = new Set([
|
|
161
|
+
"Polyline",
|
|
162
|
+
"Rectangle",
|
|
163
|
+
"RoundedRectangle",
|
|
164
|
+
"Ellipse",
|
|
165
|
+
"Arc"
|
|
166
|
+
]);
|
|
167
|
+
var toPoints = points;
|
|
168
|
+
function toShape(tag, item) {
|
|
169
|
+
const layer = Number(item.get("Layer") ?? -1);
|
|
170
|
+
const thickness = Number(item.get("LineThickness") ?? 0);
|
|
171
|
+
const points = toPoints(item);
|
|
172
|
+
switch (tag) {
|
|
173
|
+
case "Polyline":
|
|
174
|
+
return { kind: "polyline", layer, thickness, points };
|
|
175
|
+
case "Rectangle":
|
|
176
|
+
return { kind: "rectangle", layer, thickness, points };
|
|
177
|
+
case "RoundedRectangle":
|
|
178
|
+
return {
|
|
179
|
+
kind: "roundRect",
|
|
180
|
+
layer,
|
|
181
|
+
thickness,
|
|
182
|
+
points,
|
|
183
|
+
radius: Number(item.get("Radius") ?? 0)
|
|
184
|
+
};
|
|
185
|
+
case "Ellipse":
|
|
186
|
+
return { kind: "ellipse", layer, thickness, points };
|
|
187
|
+
case "Arc": {
|
|
188
|
+
if (points.length < 3)
|
|
189
|
+
return;
|
|
190
|
+
const [start, end, center] = points;
|
|
191
|
+
return { kind: "arc", layer, thickness, start, end, center };
|
|
192
|
+
}
|
|
193
|
+
}
|
|
194
|
+
return;
|
|
195
|
+
}
|
|
196
|
+
function toTrack(item) {
|
|
197
|
+
const layer = Number(item.get("Layer") ?? -1);
|
|
198
|
+
const thickness = Number(item.get("LineThickness") ?? 0);
|
|
199
|
+
const pts = kids(item, "Object", "Point");
|
|
200
|
+
if (pts.length < 2)
|
|
201
|
+
return;
|
|
202
|
+
return {
|
|
203
|
+
layer,
|
|
204
|
+
thickness,
|
|
205
|
+
start: { x: Number(pts[0].get("X")), y: Number(pts[0].get("Y")) },
|
|
206
|
+
end: { x: Number(pts[1].get("X")), y: Number(pts[1].get("Y")) }
|
|
207
|
+
};
|
|
208
|
+
}
|
|
209
|
+
function ownAttributes(node) {
|
|
210
|
+
const m = new Map;
|
|
211
|
+
const container = node.at("ExtentableObject", "AttributeInterface", "Containers", "AttributeContainer");
|
|
212
|
+
for (const a of container?.at("Store", "DataTreeContainer")?.childrenNamed("Attribute") ?? []) {
|
|
213
|
+
const tag = a.str("Tag");
|
|
214
|
+
if (tag)
|
|
215
|
+
m.set(tag, displayText(a.str("Value")));
|
|
216
|
+
}
|
|
217
|
+
return m;
|
|
218
|
+
}
|
|
219
|
+
function collectByTag(node, tag) {
|
|
220
|
+
const out = [];
|
|
221
|
+
const rec = (n) => {
|
|
222
|
+
for (const c of n.children) {
|
|
223
|
+
if (c.name === tag)
|
|
224
|
+
out.push(c);
|
|
225
|
+
else
|
|
226
|
+
rec(c);
|
|
227
|
+
}
|
|
228
|
+
};
|
|
229
|
+
if (node)
|
|
230
|
+
rec(node);
|
|
231
|
+
return out;
|
|
232
|
+
}
|
|
233
|
+
var PAD_TAGS = [
|
|
234
|
+
"LayoutPadRound",
|
|
235
|
+
"LayoutPadSquare",
|
|
236
|
+
"LayoutPadRoundedSquare",
|
|
237
|
+
"LayoutPadRectangle",
|
|
238
|
+
"LayoutPadRoundedRectangle",
|
|
239
|
+
"LayoutPadCustom"
|
|
240
|
+
];
|
|
241
|
+
var TOP_BIT = 1n;
|
|
242
|
+
var ALL_LAYERS = 0xffffffffffffffffn;
|
|
243
|
+
var lamination = (v) => {
|
|
244
|
+
if (v == null)
|
|
245
|
+
return ALL_LAYERS;
|
|
246
|
+
try {
|
|
247
|
+
return BigInt(String(v));
|
|
248
|
+
} catch {
|
|
249
|
+
return ALL_LAYERS;
|
|
250
|
+
}
|
|
251
|
+
};
|
|
252
|
+
function parsePadElement(container) {
|
|
253
|
+
if (!container)
|
|
254
|
+
return;
|
|
255
|
+
for (const tag of PAD_TAGS) {
|
|
256
|
+
const p = container.child(tag);
|
|
257
|
+
if (!p)
|
|
258
|
+
continue;
|
|
259
|
+
const center = { x: Number(p.get("CenterX") ?? 0), y: Number(p.get("CenterY") ?? 0) };
|
|
260
|
+
const rotation = Number(p.get("Rotation") ?? 0);
|
|
261
|
+
const w = 2 * Number(p.get("HalfWidth") ?? 0);
|
|
262
|
+
const h = 2 * Number(p.get("HalfHeight") ?? p.get("HalfWidth") ?? 0);
|
|
263
|
+
const r = Number(p.get("Radius") ?? 0);
|
|
264
|
+
switch (tag) {
|
|
265
|
+
case "LayoutPadRound":
|
|
266
|
+
return { shape: { kind: "circle", diameter: 2 * r }, center, rotation };
|
|
267
|
+
case "LayoutPadSquare":
|
|
268
|
+
return { shape: { kind: "rect", width: w, height: w }, center, rotation };
|
|
269
|
+
case "LayoutPadRoundedSquare":
|
|
270
|
+
return { shape: { kind: "roundrect", width: w, height: w, cornerRadius: r }, center, rotation };
|
|
271
|
+
case "LayoutPadRectangle":
|
|
272
|
+
return { shape: { kind: "rect", width: w, height: h }, center, rotation };
|
|
273
|
+
case "LayoutPadRoundedRectangle":
|
|
274
|
+
return { shape: { kind: "roundrect", width: w, height: h, cornerRadius: r }, center, rotation };
|
|
275
|
+
case "LayoutPadCustom": {
|
|
276
|
+
const prims = [];
|
|
277
|
+
for (const ptag of UB_PRIMITIVE_TAGS) {
|
|
278
|
+
for (const it of collectByTag(p.child("Custom"), ptag)) {
|
|
279
|
+
const prim = ubPrimitive(ptag, it);
|
|
280
|
+
if (prim)
|
|
281
|
+
prims.push(prim);
|
|
282
|
+
}
|
|
283
|
+
}
|
|
284
|
+
if (prims.length === 0)
|
|
285
|
+
return;
|
|
286
|
+
return { shape: { kind: "custom", primitives: prims }, center, rotation: 0 };
|
|
287
|
+
}
|
|
288
|
+
}
|
|
289
|
+
}
|
|
290
|
+
return;
|
|
291
|
+
}
|
|
292
|
+
function pickLamPad(lamPads) {
|
|
293
|
+
return lamPads.find((lp) => (lamination(lp?.get("Lamination")) & TOP_BIT) !== 0n) ?? lamPads[0];
|
|
294
|
+
}
|
|
295
|
+
function parsePin(pin, bottom, tht) {
|
|
296
|
+
const container = tht ? pickLamPad(pin.childrenNamed("LamPad")) : pin.child("Pad");
|
|
297
|
+
const geom = parsePadElement(container);
|
|
298
|
+
if (!geom)
|
|
299
|
+
return;
|
|
300
|
+
const drill = pin.child("LayoutDrillObject");
|
|
301
|
+
return {
|
|
302
|
+
number: ownAttributes(pin).get("NUMBER") ?? "",
|
|
303
|
+
at: geom.center,
|
|
304
|
+
rotation: geom.rotation,
|
|
305
|
+
shape: geom.shape,
|
|
306
|
+
drillDiameter: tht && drill ? 2 * Number(drill.get("Drill-Radius") ?? 0) : 0,
|
|
307
|
+
side: tht ? "both" : bottom ? "bottom" : "top"
|
|
308
|
+
};
|
|
309
|
+
}
|
|
310
|
+
var PIN_TAGS = [
|
|
311
|
+
["Through-Board-Pin", true],
|
|
312
|
+
["SMT-Pin", false],
|
|
313
|
+
["NetBridge-Pin", false]
|
|
314
|
+
];
|
|
315
|
+
function ownAttributeElements(node) {
|
|
316
|
+
const container = node.at("ExtentableObject", "AttributeInterface", "Containers", "AttributeContainer");
|
|
317
|
+
return container?.at("Store", "DataTreeContainer")?.childrenNamed("Attribute") ?? [];
|
|
318
|
+
}
|
|
319
|
+
var INTERNAL_ATTRS = new Set([
|
|
320
|
+
"GUID",
|
|
321
|
+
"LIBRARYTREEID",
|
|
322
|
+
"SCHEMATICSECTIONS",
|
|
323
|
+
"SCHEMATICVARIANTS",
|
|
324
|
+
"DONOTANNOTATE",
|
|
325
|
+
"NETBRIDGE",
|
|
326
|
+
"SHAPE",
|
|
327
|
+
"PACKAGE",
|
|
328
|
+
"DEVICE"
|
|
329
|
+
]);
|
|
330
|
+
var shown = (attr) => attr.numOr("Visibility", 0) === 0;
|
|
331
|
+
function componentTexts(comp) {
|
|
332
|
+
const out = [];
|
|
333
|
+
for (const a of ownAttributeElements(comp)) {
|
|
334
|
+
const tag = a.str("Tag");
|
|
335
|
+
const keep = tag === "REFDES" || tag === "VALUE" || shown(a) && !INTERNAL_ATTRS.has(tag);
|
|
336
|
+
const t = keep ? toText(a) : undefined;
|
|
337
|
+
if (t)
|
|
338
|
+
out.push({ ...t, tag, visible: shown(a) });
|
|
339
|
+
}
|
|
340
|
+
return out;
|
|
341
|
+
}
|
|
342
|
+
function parseComponent(comp) {
|
|
343
|
+
const attrs = ownAttributes(comp);
|
|
344
|
+
const name = displayText(comp.str("Name"));
|
|
345
|
+
const bottom = Number(comp.get("Bottom") ?? 0) !== 0;
|
|
346
|
+
const pads = [];
|
|
347
|
+
for (const [tag, tht] of PIN_TAGS) {
|
|
348
|
+
for (const pin of collectByTag(comp.child("Group"), tag)) {
|
|
349
|
+
const pad = parsePin(pin, bottom, tht);
|
|
350
|
+
if (pad)
|
|
351
|
+
pads.push(pad);
|
|
352
|
+
}
|
|
353
|
+
}
|
|
354
|
+
const rp = comp.child("Group")?.child("RefPoint");
|
|
355
|
+
const origin = rp ? { x: Number(rp.get("X")), y: Number(rp.get("Y")) } : pads[0]?.at ?? { x: 0, y: 0 };
|
|
356
|
+
return {
|
|
357
|
+
reference: attrs.get("REFDES") || name || "REF**",
|
|
358
|
+
value: attrs.get("VALUE") || name || "",
|
|
359
|
+
name,
|
|
360
|
+
origin,
|
|
361
|
+
rotation: Number(comp.get("Rotation") ?? 0),
|
|
362
|
+
bottom,
|
|
363
|
+
pads,
|
|
364
|
+
graphics: [],
|
|
365
|
+
texts: componentTexts(comp)
|
|
366
|
+
};
|
|
367
|
+
}
|
|
368
|
+
var ruleValue = (e, attr) => {
|
|
369
|
+
const v = e.numOr(attr, -1);
|
|
370
|
+
return v > 0 && v < 2147483646 ? v : undefined;
|
|
371
|
+
};
|
|
372
|
+
function parseNets(node) {
|
|
373
|
+
const netList = node.find("UbNetList");
|
|
374
|
+
if (!netList)
|
|
375
|
+
return [];
|
|
376
|
+
return netList.childrenNamed("UBNet").map((n) => {
|
|
377
|
+
const net = {
|
|
378
|
+
name: n.str("Name"),
|
|
379
|
+
pins: kids(n, "Pins", "UBNetPin").map((p) => ({
|
|
380
|
+
refdes: p.str("Refdes"),
|
|
381
|
+
pin: p.str("Pin")
|
|
382
|
+
}))
|
|
383
|
+
};
|
|
384
|
+
const clearance = ruleValue(n, "TraceClearance");
|
|
385
|
+
const trackWidth = ruleValue(n, "Width");
|
|
386
|
+
if (clearance !== undefined)
|
|
387
|
+
net.clearance = clearance;
|
|
388
|
+
if (trackWidth !== undefined)
|
|
389
|
+
net.trackWidth = trackWidth;
|
|
390
|
+
return net;
|
|
391
|
+
});
|
|
392
|
+
}
|
|
393
|
+
function parseRules(designSheet) {
|
|
394
|
+
const bs = designSheet.find("BoardLayerSettings");
|
|
395
|
+
if (!bs)
|
|
396
|
+
return;
|
|
397
|
+
const via = designSheet.find((e) => e.cls === "CLayoutDesignRuleVia");
|
|
398
|
+
const v = (attr, dflt) => ruleValue(bs, attr) ?? dflt;
|
|
399
|
+
const trace = v("ClearancetoTrace", 200000);
|
|
400
|
+
return {
|
|
401
|
+
clearance: { trace, pad: v("ClearancetoPad", trace), via: v("ClearancetoVia", trace), area: v("ClearancetoArea", trace) },
|
|
402
|
+
trackWidth: v("NetTraceWidth", 250000),
|
|
403
|
+
minTrackWidth: v("MinimumNetTraceWidth", 0),
|
|
404
|
+
edgeClearance: v("BoardOutlineElectricalClearance", 0),
|
|
405
|
+
via: { diameter: 2 * (via ? ruleValue(via, "PadRadius") ?? 300000 : 300000), drill: 2 * (via ? ruleValue(via, "DrillRadius") ?? 150000 : 150000) }
|
|
406
|
+
};
|
|
407
|
+
}
|
|
408
|
+
var emptyCollected = () => ({
|
|
409
|
+
shapes: [],
|
|
410
|
+
tracks: [],
|
|
411
|
+
components: [],
|
|
412
|
+
holes: [],
|
|
413
|
+
vias: [],
|
|
414
|
+
zones: [],
|
|
415
|
+
texts: [],
|
|
416
|
+
ruleAreas: []
|
|
417
|
+
});
|
|
418
|
+
function toZone(kind, item, outline) {
|
|
419
|
+
const ext = item.child("UBExtension");
|
|
420
|
+
return {
|
|
421
|
+
kind,
|
|
422
|
+
layer: item.numOr("Layer", -1),
|
|
423
|
+
netName: item.str("NetName"),
|
|
424
|
+
outline,
|
|
425
|
+
clearance: ext?.num("Clearance") ?? 0,
|
|
426
|
+
minThickness: item.numOr("LineThickness", 0),
|
|
427
|
+
reliefSpokeWidth: item.numOr("ReliefSpokeWidth", 0),
|
|
428
|
+
thermalReliefStyle: item.numOr("ThermalReliefStyle", 0),
|
|
429
|
+
removeIslands: item.bool("RemoveSmallIslands") ?? false,
|
|
430
|
+
islandArea: item.numOr("RemoveIslandSize", 0),
|
|
431
|
+
removeNotEdgeConnected: item.bool("RemoveNotEdgeConnectedIslands") ?? false
|
|
432
|
+
};
|
|
433
|
+
}
|
|
434
|
+
var RULE_LAYER_WORDS = ["Zero", "One", "Two", "Three", "Four", "Five", "Size", "Seven"];
|
|
435
|
+
function toRuleArea(item) {
|
|
436
|
+
const outline = points(item);
|
|
437
|
+
if (outline.length < 3)
|
|
438
|
+
return;
|
|
439
|
+
const groups = item.child("NetGroups");
|
|
440
|
+
return {
|
|
441
|
+
type: item.numOr("RuleAreaType", 0),
|
|
442
|
+
outline,
|
|
443
|
+
activeLayers: RULE_LAYER_WORDS.map((w) => BigInt.asUintN(64, item.bigint(`ActiveLayers${w}`) ?? 0n)),
|
|
444
|
+
allNets: groups ? groups.bool("All") ?? false : true,
|
|
445
|
+
nets: groups?.childrenNamed("CompGroup").map((g) => g.str("Group")) ?? []
|
|
446
|
+
};
|
|
447
|
+
}
|
|
448
|
+
function toText(item) {
|
|
449
|
+
const text = displayText(item.str("Value"));
|
|
450
|
+
const fmt = item.child("TXTFormat");
|
|
451
|
+
if (!text || !fmt)
|
|
452
|
+
return;
|
|
453
|
+
const box = points(item);
|
|
454
|
+
const xs = box.map((p) => p.x);
|
|
455
|
+
const ys = box.map((p) => p.y);
|
|
456
|
+
const real = box.length >= 4 && Math.max(...xs) > Math.min(...xs) && Math.max(...ys) > Math.min(...ys);
|
|
457
|
+
const at = real ? { x: (Math.min(...xs) + Math.max(...xs)) / 2, y: (Math.min(...ys) + Math.max(...ys)) / 2 } : { x: fmt.numOr("RefPointX", 0), y: fmt.numOr("RefPointY", 0) };
|
|
458
|
+
return {
|
|
459
|
+
layer: item.numOr("Layer", -1),
|
|
460
|
+
text,
|
|
461
|
+
at,
|
|
462
|
+
angle: fmt.numOr("Angle", 0),
|
|
463
|
+
mirror: fmt.bool("Mirror") ?? false,
|
|
464
|
+
width: fmt.numOr("HorizontalSize", 0),
|
|
465
|
+
height: fmt.numOr("VerticalSize", 0),
|
|
466
|
+
strokeWidth: item.numOr("LineThickness", 0)
|
|
467
|
+
};
|
|
468
|
+
}
|
|
469
|
+
var UB_AREA_TAGS = new Set(UB_PRIMITIVE_TAGS);
|
|
470
|
+
function parseVia(item) {
|
|
471
|
+
const pt = kids(item, "Object", "Point")[0];
|
|
472
|
+
const drill = item.child("LayoutDrillObject");
|
|
473
|
+
if (!pt || !drill)
|
|
474
|
+
return;
|
|
475
|
+
const pad = parsePadElement(item.child("Pad"));
|
|
476
|
+
const drillDiameter = 2 * Number(drill.get("Drill-Radius") ?? 0);
|
|
477
|
+
const diameter = pad?.shape.kind === "circle" ? pad.shape.diameter : drillDiameter + 300000;
|
|
478
|
+
const netName = item.str("NetName");
|
|
479
|
+
return {
|
|
480
|
+
at: { x: Number(pt.get("X")), y: Number(pt.get("Y")) },
|
|
481
|
+
drillDiameter,
|
|
482
|
+
diameter,
|
|
483
|
+
netName: netName || undefined
|
|
484
|
+
};
|
|
485
|
+
}
|
|
486
|
+
function walkGeometry(node, out, inComponent = false) {
|
|
487
|
+
for (const item of node.children) {
|
|
488
|
+
const key = item.name;
|
|
489
|
+
if (SHAPE_TAGS.has(key)) {
|
|
490
|
+
const s = toShape(key, item);
|
|
491
|
+
if (s)
|
|
492
|
+
out.shapes.push(s);
|
|
493
|
+
walkGeometry(item, out, inComponent);
|
|
494
|
+
} else if (key === "UBPowerPlane") {
|
|
495
|
+
const outline = points(item);
|
|
496
|
+
if (outline.length >= 3)
|
|
497
|
+
out.zones.push(toZone("plane", item, outline));
|
|
498
|
+
} else if (UB_AREA_TAGS.has(key) && !inComponent) {
|
|
499
|
+
const prim = ubPrimitive(key, item);
|
|
500
|
+
const outline = prim && primitiveOutline(prim);
|
|
501
|
+
if (outline && outline.length >= 3)
|
|
502
|
+
out.zones.push(toZone("area", item, outline));
|
|
503
|
+
} else if (key === "LayoutRuleArea" && !inComponent) {
|
|
504
|
+
const r = toRuleArea(item);
|
|
505
|
+
if (r)
|
|
506
|
+
out.ruleAreas.push(r);
|
|
507
|
+
} else if (key === "UBAttribute" && !inComponent) {
|
|
508
|
+
if (item.str("Tag") === "TEXT") {
|
|
509
|
+
const t = toText(item);
|
|
510
|
+
if (t)
|
|
511
|
+
out.texts.push(t);
|
|
512
|
+
}
|
|
513
|
+
} else if (key === "UBTrack") {
|
|
514
|
+
const t = toTrack(item);
|
|
515
|
+
if (t)
|
|
516
|
+
out.tracks.push(t);
|
|
517
|
+
} else if (key === "UBComponent") {
|
|
518
|
+
const comp = parseComponent(item);
|
|
519
|
+
const inner = emptyCollected();
|
|
520
|
+
walkGeometry(item, inner, true);
|
|
521
|
+
comp.graphics = inner.shapes;
|
|
522
|
+
out.components.push(comp, ...inner.components);
|
|
523
|
+
out.tracks.push(...inner.tracks);
|
|
524
|
+
out.holes.push(...inner.holes);
|
|
525
|
+
out.vias.push(...inner.vias);
|
|
526
|
+
out.zones.push(...inner.zones);
|
|
527
|
+
} else if (key === "RegularVia") {
|
|
528
|
+
const v = parseVia(item);
|
|
529
|
+
if (v)
|
|
530
|
+
out.vias.push(v);
|
|
531
|
+
} else if (key === "LayoutDrillObject") {
|
|
532
|
+
if (String(item.get("Stand-Alone")) !== "1")
|
|
533
|
+
continue;
|
|
534
|
+
const pt = kids(item, "Object", "Point")[0];
|
|
535
|
+
if (!pt)
|
|
536
|
+
continue;
|
|
537
|
+
out.holes.push({
|
|
538
|
+
at: { x: Number(pt.get("X")), y: Number(pt.get("Y")) },
|
|
539
|
+
drillDiameter: 2 * Number(item.get("Drill-Radius") ?? 0),
|
|
540
|
+
plated: Number(item.get("Plated") ?? 0) !== 0
|
|
541
|
+
});
|
|
542
|
+
} else {
|
|
543
|
+
walkGeometry(item, out, inComponent);
|
|
544
|
+
}
|
|
545
|
+
}
|
|
546
|
+
}
|
|
547
|
+
function parseStackup(designSheet) {
|
|
548
|
+
const bs = designSheet.find("BoardLayerSettings");
|
|
549
|
+
const pairs = Math.max(1, bs?.numOr("LayerLaminationPairQuantity", 1) ?? 1);
|
|
550
|
+
const inner = Array.from({ length: Math.min(2 * pairs - 2, 62) }, (_, i) => i + 1);
|
|
551
|
+
return { copper: [0, ...inner, 63], thickness: bs?.numOr("BoardThickness", 1600000) ?? 1600000 };
|
|
552
|
+
}
|
|
553
|
+
function parseUbLibraryXml(input) {
|
|
554
|
+
const collected = emptyCollected();
|
|
555
|
+
walkGeometry(docOf(input).root, collected);
|
|
556
|
+
return collected.components[0];
|
|
557
|
+
}
|
|
558
|
+
function parsePcbXml(input) {
|
|
559
|
+
const doc = docOf(input);
|
|
560
|
+
if (doc.application === "multisim") {
|
|
561
|
+
throw new Error("input is a Multisim schematic; use the schematic converter (parseSchematicXml)");
|
|
562
|
+
}
|
|
563
|
+
if (doc.application !== "ultiboard")
|
|
564
|
+
throw new Error("not an Electronics Workbench XML file");
|
|
565
|
+
const root = doc.root;
|
|
566
|
+
const creator = root.at("history", "creator");
|
|
567
|
+
const project = root.child("Project");
|
|
568
|
+
const projectName = project?.str("Name") ?? "";
|
|
569
|
+
const sheetContainer = project?.at("UniqueSheets", "SheetInfos")?.child("SheetContainer");
|
|
570
|
+
const designSheet = sheetContainer?.at("Sheet", "Variable", "DesignSheet");
|
|
571
|
+
if (!designSheet)
|
|
572
|
+
throw new Error("no DesignSheet element found");
|
|
573
|
+
const sheetTitle = designSheet.str("Title");
|
|
574
|
+
const workArea = {
|
|
575
|
+
left: Number(designSheet.get("WorkAreaLeft") ?? 0),
|
|
576
|
+
bottom: Number(designSheet.get("WorkAreaBottom") ?? 0),
|
|
577
|
+
right: Number(designSheet.get("WorkAreaRight") ?? 0),
|
|
578
|
+
top: Number(designSheet.get("WorkAreaTop") ?? 0)
|
|
579
|
+
};
|
|
580
|
+
const layerDef = designSheet.find("LayoutLayerDefinition");
|
|
581
|
+
const layerNodes = layerDef?.childrenNamed("LayerInfo") ?? [];
|
|
582
|
+
const layers = layerNodes.map((node) => ({
|
|
583
|
+
number: Number(node.get("Number")),
|
|
584
|
+
name: node.str("Name"),
|
|
585
|
+
description: node.str("UserDescription") || undefined,
|
|
586
|
+
state: Number(node.get("State") ?? 0),
|
|
587
|
+
rgb: Number(node.get("RGB") ?? 0)
|
|
588
|
+
}));
|
|
589
|
+
const collected = emptyCollected();
|
|
590
|
+
walkGeometry(designSheet, collected);
|
|
591
|
+
return {
|
|
592
|
+
source: {
|
|
593
|
+
application: creator?.get("application") ?? "unknown",
|
|
594
|
+
versionMajor: Number(creator?.get("versionMajor") ?? 0),
|
|
595
|
+
versionMinor: Number(creator?.get("versionMinor") ?? 0),
|
|
596
|
+
schema: Number(root.get("Schema") ?? 0)
|
|
597
|
+
},
|
|
598
|
+
projectName,
|
|
599
|
+
sheetTitle,
|
|
600
|
+
workArea,
|
|
601
|
+
layers,
|
|
602
|
+
stackup: parseStackup(designSheet),
|
|
603
|
+
rules: parseRules(designSheet),
|
|
604
|
+
zones: collected.zones,
|
|
605
|
+
texts: collected.texts,
|
|
606
|
+
ruleAreas: collected.ruleAreas,
|
|
607
|
+
shapes: collected.shapes,
|
|
608
|
+
tracks: collected.tracks,
|
|
609
|
+
components: collected.components,
|
|
610
|
+
holes: collected.holes,
|
|
611
|
+
vias: collected.vias,
|
|
612
|
+
nets: parseNets(root)
|
|
613
|
+
};
|
|
614
|
+
}
|
|
615
|
+
|
|
616
|
+
// src/ref/ci-netlist.ts
|
|
617
|
+
function collectCiItems(root) {
|
|
618
|
+
const out = new Map;
|
|
619
|
+
for (const e of root.descendants()) {
|
|
620
|
+
const cls = e.cls;
|
|
621
|
+
if (!cls?.startsWith("Ci") || !e.has("CiID"))
|
|
622
|
+
continue;
|
|
623
|
+
const body = e.child(cls);
|
|
624
|
+
if (!body)
|
|
625
|
+
continue;
|
|
626
|
+
const list = out.get(cls) ?? [];
|
|
627
|
+
list.push({ id: e.get("CiID"), body });
|
|
628
|
+
out.set(cls, list);
|
|
629
|
+
}
|
|
630
|
+
return out;
|
|
631
|
+
}
|
|
632
|
+
function ciCollStrings(body) {
|
|
633
|
+
const attrs = body.child("Attributes");
|
|
634
|
+
if (!attrs)
|
|
635
|
+
return [];
|
|
636
|
+
return [
|
|
637
|
+
...attrs.childrenNamed("CiaCollString"),
|
|
638
|
+
...attrs.childrenNamed("Item").flatMap((it) => it.childrenNamed("CiaCollString"))
|
|
639
|
+
];
|
|
640
|
+
}
|
|
641
|
+
var collValues = (coll) => coll?.child("strings")?.childrenNamed("Item").map((s) => s.str("Value")) ?? [];
|
|
642
|
+
var attrStrings = (body) => ciCollStrings(body).flatMap(collValues);
|
|
643
|
+
function componentKind(body) {
|
|
644
|
+
const s = attrStrings(body).filter(Boolean);
|
|
645
|
+
if (s.length <= 1)
|
|
646
|
+
return "connector";
|
|
647
|
+
if (s[0] === "POWER_SOURCES")
|
|
648
|
+
return "power";
|
|
649
|
+
return "part";
|
|
650
|
+
}
|
|
651
|
+
function dbPartName(body) {
|
|
652
|
+
const s = attrStrings(body);
|
|
653
|
+
for (let i = 0;i + 2 < Math.min(s.length, 24); i++) {
|
|
654
|
+
if (/[A-Za-z]/.test(s[i]) && s[i] === s[i + 2] && s[i + 1] && s[i + 1].length < 64)
|
|
655
|
+
return s[i + 1];
|
|
656
|
+
}
|
|
657
|
+
return;
|
|
658
|
+
}
|
|
659
|
+
function portPinNumbers(port) {
|
|
660
|
+
const csv = collValues(ciCollStrings(port)[1])[6] ?? "";
|
|
661
|
+
return csv.split(",").map((s) => s.trim()).filter(Boolean);
|
|
662
|
+
}
|
|
663
|
+
function drawnPinNumbers(raw) {
|
|
664
|
+
return raw.split(",").map((s) => s.trim()).filter((s) => s && !/^#+$/.test(s));
|
|
665
|
+
}
|
|
666
|
+
function parseCiNetlist(input) {
|
|
667
|
+
const items = collectCiItems(docOf(input).root);
|
|
668
|
+
const components = new Map;
|
|
669
|
+
for (const { id, body } of items.get("CiComponent") ?? []) {
|
|
670
|
+
components.set(id, {
|
|
671
|
+
refdes: body.str("LocalName"),
|
|
672
|
+
circuit: body.get("Circuit") ?? "",
|
|
673
|
+
kind: componentKind(body),
|
|
674
|
+
part: dbPartName(body)
|
|
675
|
+
});
|
|
676
|
+
}
|
|
677
|
+
const instances = items.get("CiInstComponent") ?? [];
|
|
678
|
+
const ports = new Map;
|
|
679
|
+
for (const { id, body } of items.get("CiPort") ?? []) {
|
|
680
|
+
ports.set(id, { component: body.get("Component") ?? "", pins: portPinNumbers(body) });
|
|
681
|
+
}
|
|
682
|
+
const circuits = new Map;
|
|
683
|
+
const circuit = (id) => {
|
|
684
|
+
let c = circuits.get(id);
|
|
685
|
+
if (!c) {
|
|
686
|
+
c = { id, nets: new Map, components: [], kinds: new Map, instances: [] };
|
|
687
|
+
circuits.set(id, c);
|
|
688
|
+
}
|
|
689
|
+
return c;
|
|
690
|
+
};
|
|
691
|
+
for (const { id } of items.get("CiCircuit") ?? [])
|
|
692
|
+
circuit(id);
|
|
693
|
+
for (const comp of components.values()) {
|
|
694
|
+
const c = circuit(comp.circuit);
|
|
695
|
+
c.kinds.set(comp.refdes, comp.kind);
|
|
696
|
+
if (comp.kind === "part" && !c.components.includes(comp.refdes))
|
|
697
|
+
c.components.push(comp.refdes);
|
|
698
|
+
}
|
|
699
|
+
for (const { body } of instances)
|
|
700
|
+
circuit(body.get("Circuit") ?? "").instances.push(body.str("LocalName"));
|
|
701
|
+
for (const { body } of items.get("CiNode") ?? []) {
|
|
702
|
+
const c = circuit(body.get("Circuit") ?? "");
|
|
703
|
+
const name = body.str("LocalName");
|
|
704
|
+
const list = c.nets.get(name) ?? [];
|
|
705
|
+
for (const ref of body.child("Ports")?.childrenNamed("Item") ?? []) {
|
|
706
|
+
const port = ports.get(ref.get("CiID") ?? "");
|
|
707
|
+
const comp = port && components.get(port.component);
|
|
708
|
+
if (!port || !comp || comp.kind !== "part")
|
|
709
|
+
continue;
|
|
710
|
+
for (const pin of port.pins)
|
|
711
|
+
list.push({ refdes: comp.refdes, pin });
|
|
712
|
+
}
|
|
713
|
+
c.nets.set(name, list);
|
|
714
|
+
}
|
|
715
|
+
return {
|
|
716
|
+
circuits: [...circuits.values()],
|
|
717
|
+
hierarchical: instances.length > 0,
|
|
718
|
+
componentsById: new Map([...components].map(([id, c]) => [id, { refdes: c.refdes, kind: c.kind, part: c.part }]))
|
|
719
|
+
};
|
|
720
|
+
}
|
|
721
|
+
|
|
722
|
+
// src/parse/ms-hierarchy.ts
|
|
723
|
+
var modsOf = (o) => (o.at("ElectricalObject", "ModifierInfo")?.childrenNamed("Element") ?? []).flatMap((e) => e.childrenNamed("Item").map((i) => ({ mod: e.str("NetModifier"), value: i.str("Value") })));
|
|
724
|
+
var OWNER_CLASSES = new Set([
|
|
725
|
+
"CIITSymbolComp",
|
|
726
|
+
"CIITAnimationSymbolComp",
|
|
727
|
+
"CIITOffPageConnector",
|
|
728
|
+
"CBusOffpageConn",
|
|
729
|
+
"CIITBusHierConnector",
|
|
730
|
+
"CIITMacroComponent",
|
|
731
|
+
"CVirtualConnector",
|
|
732
|
+
"CIITHierConnector"
|
|
733
|
+
]);
|
|
734
|
+
function indexPage(ds, sheetComp, warnings) {
|
|
735
|
+
const pg = {
|
|
736
|
+
title: ds.str("Title"),
|
|
737
|
+
page: ds.str("PageName") || "1",
|
|
738
|
+
designSheet: ds,
|
|
739
|
+
edges: [],
|
|
740
|
+
pins: [],
|
|
741
|
+
symbols: new Map,
|
|
742
|
+
links: []
|
|
743
|
+
};
|
|
744
|
+
const visit = (node, owner) => {
|
|
745
|
+
if (node.name === "AnimationLayers")
|
|
746
|
+
return;
|
|
747
|
+
const cls = node.cls;
|
|
748
|
+
const sid = node.get("ID");
|
|
749
|
+
const o = cls ? node.child(cls) : undefined;
|
|
750
|
+
if (sid != null && cls && o && !cls.startsWith("Ci")) {
|
|
751
|
+
let next = owner;
|
|
752
|
+
if (cls === "CIITLinkComp") {
|
|
753
|
+
for (const c of [o.get("Connect1"), o.get("Connect2")])
|
|
754
|
+
if (c != null && c !== "0")
|
|
755
|
+
pg.edges.push([sid, c]);
|
|
756
|
+
pg.links.push({ id: sid, mods: modsOf(o) });
|
|
757
|
+
} else if (cls === "CODPinComp" || cls === "CIITPinConnectorComp") {
|
|
758
|
+
for (const c of o.child("ConnectList")?.childrenNamed("Item") ?? [])
|
|
759
|
+
pg.edges.push([sid, c.get("ID") ?? ""]);
|
|
760
|
+
if (cls === "CIITPinConnectorComp" && owner?.kind === "pin")
|
|
761
|
+
pg.edges.push([sid, owner.id]);
|
|
762
|
+
} else if (OWNER_CLASSES.has(cls)) {
|
|
763
|
+
pg.symbols.set(sid, { kind: cls, ciComp: o.get("CiComponent") ?? "", obj: o });
|
|
764
|
+
next = { id: sid, kind: cls };
|
|
765
|
+
} else if (cls === "CIITBusEntry") {
|
|
766
|
+
pg.links.push({ id: sid, mods: modsOf(o) });
|
|
767
|
+
next = { id: sid, kind: "pin" };
|
|
768
|
+
} else if (cls === "CIITPinSymbolComp") {
|
|
769
|
+
if (owner) {
|
|
770
|
+
pg.pins.push({
|
|
771
|
+
id: sid,
|
|
772
|
+
owner: owner.id,
|
|
773
|
+
ownerKind: owner.kind,
|
|
774
|
+
portId: o.get("PortID"),
|
|
775
|
+
pinNumber: o.str("PinNumber"),
|
|
776
|
+
pinName: o.str("PinName"),
|
|
777
|
+
mods: modsOf(o)
|
|
778
|
+
});
|
|
779
|
+
} else {
|
|
780
|
+
warnings.push(`orphan pin ${sid} on ${pg.title}/${pg.page}`);
|
|
781
|
+
}
|
|
782
|
+
next = { id: sid, kind: "pin" };
|
|
783
|
+
}
|
|
784
|
+
for (const c of o.children)
|
|
785
|
+
visit(c, next);
|
|
786
|
+
return;
|
|
787
|
+
}
|
|
788
|
+
if (cls === "CSheetComponentMSM" || cls === "CSheetComponent") {
|
|
789
|
+
sheetComp.set(node.get("ObjectID") ?? "", node.str("SheetName"));
|
|
790
|
+
}
|
|
791
|
+
for (const c of node.children)
|
|
792
|
+
visit(c, owner);
|
|
793
|
+
};
|
|
794
|
+
visit(ds, null);
|
|
795
|
+
return pg;
|
|
796
|
+
}
|
|
797
|
+
function indexCi(proj) {
|
|
798
|
+
const ci = new Map;
|
|
799
|
+
for (const o of proj.child("UniqueSheets")?.descendants() ?? []) {
|
|
800
|
+
const cls = o.cls;
|
|
801
|
+
if (!cls?.startsWith("Ci") || !o.has("CiID"))
|
|
802
|
+
continue;
|
|
803
|
+
const body = o.child(cls);
|
|
804
|
+
if (body)
|
|
805
|
+
ci.set(o.get("CiID"), { cls, body });
|
|
806
|
+
}
|
|
807
|
+
return ci;
|
|
808
|
+
}
|
|
809
|
+
function parseMultisimDesign(input) {
|
|
810
|
+
const warnings = [];
|
|
811
|
+
const { root: top } = docOf(input);
|
|
812
|
+
const proj = top.name === "MSMElectronicsWorkbench" ? top.child("Project") : undefined;
|
|
813
|
+
if (!proj)
|
|
814
|
+
throw new Error("not a Multisim design");
|
|
815
|
+
const ci = indexCi(proj);
|
|
816
|
+
const sheetComp = new Map;
|
|
817
|
+
const pages = (proj.at("UniqueSheets", "SheetInfos")?.childrenNamed("SheetContainer") ?? []).map((sc) => sc.at("Sheet", "Variable", "DesignSheet")).filter((ds) => ds != null).map((ds) => indexPage(ds, sheetComp, warnings));
|
|
818
|
+
const rootTitle = proj.child("DesignSheet")?.str("Title") || pages[0]?.title || "";
|
|
819
|
+
const irMap = new Map;
|
|
820
|
+
const unitMap = new Map;
|
|
821
|
+
const remaps = new Map;
|
|
822
|
+
for (const o of proj.child("Extensions")?.descendants() ?? []) {
|
|
823
|
+
if (o.name !== "RefDesInfoContainer" || !o.has("CIR"))
|
|
824
|
+
continue;
|
|
825
|
+
const cir = o.str("CIR");
|
|
826
|
+
const m = new Map;
|
|
827
|
+
for (const it of o.child("CIRToInfoMap")?.childrenNamed("CIRToInfoMapItem") ?? []) {
|
|
828
|
+
const ri = it.child("RefDesInfo");
|
|
829
|
+
const key = it.str("CIRKey");
|
|
830
|
+
const prefix = ri?.str("IRPrefix") ?? "";
|
|
831
|
+
const num = ri?.get("IRNumber");
|
|
832
|
+
m.set(key, num === "-1" ? prefix : `${prefix}${num ?? ""}`);
|
|
833
|
+
const sectionId = Number(ri?.get("IRSectionID") ?? -1);
|
|
834
|
+
if (ri?.str("IRSection") && sectionId >= 0)
|
|
835
|
+
unitMap.set(`${cir}|${key}`, sectionId + 1);
|
|
836
|
+
const a = ri?.child("PinNumbersCIR")?.childrenNamed("PinNumbersCIRItem").map((x) => x.str("PinNumberCIR")) ?? [];
|
|
837
|
+
const b = ri?.child("PinNumbersIR")?.childrenNamed("PinNumbersIRItem").map((x) => x.str("PinNumberIR")) ?? [];
|
|
838
|
+
if (a.length && a.length === b.length && a.some((x, i) => x !== b[i]))
|
|
839
|
+
remaps.set(`${cir}|${key}`, new Map(a.map((x, i) => [x, b[i]])));
|
|
840
|
+
}
|
|
841
|
+
irMap.set(cir, m);
|
|
842
|
+
}
|
|
843
|
+
const build = (sheet, path, name, cirOf, depth) => {
|
|
844
|
+
const inst = { path, sheet, name, finalName: name, cirOf, children: [] };
|
|
845
|
+
if (depth > 20) {
|
|
846
|
+
warnings.push(`hierarchy deeper than 20 at ${path}`);
|
|
847
|
+
return inst;
|
|
848
|
+
}
|
|
849
|
+
const pgs = pages.filter((p) => p.title === sheet);
|
|
850
|
+
if (!pgs.length)
|
|
851
|
+
warnings.push(`no pages for sheet "${sheet}" at ${path || "/"}`);
|
|
852
|
+
for (const pg of pgs) {
|
|
853
|
+
const cir = cirOf(pg.page);
|
|
854
|
+
for (const [sid, s] of pg.symbols) {
|
|
855
|
+
if (s.kind !== "CIITMacroComponent")
|
|
856
|
+
continue;
|
|
857
|
+
const iname = ci.get(s.ciComp)?.body.str("LocalName") ?? "";
|
|
858
|
+
const child = s.obj.at("HierBlock", "CHierBlock")?.str("FileName") || sheetComp.get(s.obj.get("SheetComponentObjectID") ?? "") || "";
|
|
859
|
+
if (!iname)
|
|
860
|
+
warnings.push(`macro ${sid} has no CiInstComponent`);
|
|
861
|
+
const c = build(child, `${path}/${iname}`, iname, (p) => `#${p}/${child}:${iname}${cir}`, depth + 1);
|
|
862
|
+
c.macroId = sid;
|
|
863
|
+
c.parentPath = path;
|
|
864
|
+
c.parentPage = pg.page;
|
|
865
|
+
c.finalName = irMap.get(cir)?.get(iname) ?? iname;
|
|
866
|
+
inst.children.push(c);
|
|
867
|
+
}
|
|
868
|
+
}
|
|
869
|
+
return inst;
|
|
870
|
+
};
|
|
871
|
+
const root = build(rootTitle, "", "", (p) => `#${p}/${rootTitle}:`, 0);
|
|
872
|
+
return {
|
|
873
|
+
rootTitle,
|
|
874
|
+
pages,
|
|
875
|
+
root,
|
|
876
|
+
ci,
|
|
877
|
+
warnings,
|
|
878
|
+
finalRefdes: (inst, page, key) => irMap.get(inst.cirOf(page))?.get(key),
|
|
879
|
+
pinRemap: (inst, page, key) => remaps.get(`${inst.cirOf(page)}|${key}`),
|
|
880
|
+
finalUnit: (inst, page, key) => unitMap.get(`${inst.cirOf(page)}|${key}`)
|
|
881
|
+
};
|
|
882
|
+
}
|
|
883
|
+
|
|
884
|
+
// src/parse/sch.ts
|
|
885
|
+
var items = (n, list, item = "Item") => n?.child(list)?.childrenNamed(item) ?? [];
|
|
886
|
+
var num = (v, d = 0) => {
|
|
887
|
+
const n = Number(v);
|
|
888
|
+
return Number.isFinite(n) ? n : d;
|
|
889
|
+
};
|
|
890
|
+
var snap = (v) => Math.abs(v - Math.round(v)) < 0.001 ? Math.round(v) : v;
|
|
891
|
+
var pt = (x, y) => ({ x: num(x), y: num(y) });
|
|
892
|
+
var IDENTITY = { m00: 1, m01: 0, m10: 0, m11: 1, m20: 0, m21: 0 };
|
|
893
|
+
function affineOf(node) {
|
|
894
|
+
if (!node || node.get("Transformer-M00") === undefined)
|
|
895
|
+
return IDENTITY;
|
|
896
|
+
return {
|
|
897
|
+
m00: num(node.get("Transformer-M00"), 1),
|
|
898
|
+
m01: num(node.get("Transformer-M01")),
|
|
899
|
+
m10: num(node.get("Transformer-M10")),
|
|
900
|
+
m11: num(node.get("Transformer-M11"), 1),
|
|
901
|
+
m20: num(node.get("Transformer-M20")),
|
|
902
|
+
m21: num(node.get("Transformer-M21"))
|
|
903
|
+
};
|
|
904
|
+
}
|
|
905
|
+
var apply = (t, p) => ({
|
|
906
|
+
x: snap(p.x * t.m00 + p.y * t.m10 + t.m20),
|
|
907
|
+
y: snap(p.x * t.m01 + p.y * t.m11 + t.m21)
|
|
908
|
+
});
|
|
909
|
+
var affineScale = (t) => Math.sqrt(Math.abs(t.m00 * t.m11 - t.m01 * t.m10)) || 1;
|
|
910
|
+
var D_ID = { a: 1, b: 0, c: 0, d: 1 };
|
|
911
|
+
var mul = (p, q) => ({
|
|
912
|
+
a: p.a * q.a + p.c * q.b,
|
|
913
|
+
b: p.b * q.a + p.d * q.b,
|
|
914
|
+
c: p.a * q.c + p.c * q.d,
|
|
915
|
+
d: p.b * q.c + p.d * q.d
|
|
916
|
+
});
|
|
917
|
+
var applyD = (t, p) => ({ x: t.a * p.x + t.c * p.y, y: t.b * p.x + t.d * p.y });
|
|
918
|
+
function flipToDihedral(flip) {
|
|
919
|
+
const rot = [
|
|
920
|
+
D_ID,
|
|
921
|
+
{ a: 0, b: 1, c: -1, d: 0 },
|
|
922
|
+
{ a: -1, b: 0, c: 0, d: -1 },
|
|
923
|
+
{ a: 0, b: -1, c: 1, d: 0 }
|
|
924
|
+
];
|
|
925
|
+
let m = D_ID;
|
|
926
|
+
if (flip & 256)
|
|
927
|
+
m = mul({ a: 1, b: 0, c: 0, d: -1 }, m);
|
|
928
|
+
if (flip & 4096)
|
|
929
|
+
m = mul({ a: -1, b: 0, c: 0, d: 1 }, m);
|
|
930
|
+
return mul(rot[flip & 3], m);
|
|
931
|
+
}
|
|
932
|
+
function collect(node, tag, skip) {
|
|
933
|
+
const out = [];
|
|
934
|
+
const rec = (n) => {
|
|
935
|
+
for (const c of n.children) {
|
|
936
|
+
if (c.name === tag)
|
|
937
|
+
out.push(c);
|
|
938
|
+
else if (!skip.has(c.name))
|
|
939
|
+
rec(c);
|
|
940
|
+
}
|
|
941
|
+
};
|
|
942
|
+
rec(node);
|
|
943
|
+
return out;
|
|
944
|
+
}
|
|
945
|
+
function wrapped(node, cls, skip) {
|
|
946
|
+
const out = [];
|
|
947
|
+
for (const it of collect(node, "Item", skip)) {
|
|
948
|
+
const body = it.cls === cls ? it.child(cls) : undefined;
|
|
949
|
+
if (body)
|
|
950
|
+
out.push([body, it.get("ID") ?? ""]);
|
|
951
|
+
}
|
|
952
|
+
return out;
|
|
953
|
+
}
|
|
954
|
+
function children(node) {
|
|
955
|
+
const out = [];
|
|
956
|
+
for (const item of items(node, "Objects")) {
|
|
957
|
+
for (const c of item.children)
|
|
958
|
+
out.push([c.name, c, item.get("ID") ?? ""]);
|
|
959
|
+
}
|
|
960
|
+
return out;
|
|
961
|
+
}
|
|
962
|
+
var penWidth = (n) => Math.max(0, num(n?.get("Pen-Width")));
|
|
963
|
+
var filled = (n) => String(n?.get("Brush-Style") ?? "1") === "0";
|
|
964
|
+
function ellipsePoints(c, rx, ry) {
|
|
965
|
+
const out = [];
|
|
966
|
+
for (let i = 0;i <= 32; i++) {
|
|
967
|
+
const a = 2 * Math.PI * i / 32;
|
|
968
|
+
out.push({ x: c.x + rx * Math.cos(a), y: c.y + ry * Math.sin(a) });
|
|
969
|
+
}
|
|
970
|
+
return out;
|
|
971
|
+
}
|
|
972
|
+
function graphicOf(cls, n, parent, raw = false) {
|
|
973
|
+
const t = raw ? parent : composeAffine(affineOf(n), parent);
|
|
974
|
+
if (String(n?.get("Hidden") ?? "0") === "1")
|
|
975
|
+
return;
|
|
976
|
+
const w = penWidth(n);
|
|
977
|
+
switch (cls) {
|
|
978
|
+
case "CODLineComp":
|
|
979
|
+
return { kind: "polyline", points: [apply(t, pt(n.get("pt0X"), n.get("pt0Y"))), apply(t, pt(n.get("pt1X"), n.get("pt1Y")))], width: w, fill: false };
|
|
980
|
+
case "CODMultiLineComp":
|
|
981
|
+
case "CODPolygonComp": {
|
|
982
|
+
const pts = items(n, "Points").map((p) => apply(t, pt(p.get("X"), p.get("Y"))));
|
|
983
|
+
if (pts.length < 2)
|
|
984
|
+
return;
|
|
985
|
+
if (cls === "CODPolygonComp")
|
|
986
|
+
pts.push(pts[0]);
|
|
987
|
+
return { kind: "polyline", points: pts, width: w, fill: cls === "CODPolygonComp" && filled(n) };
|
|
988
|
+
}
|
|
989
|
+
case "CODRectComp": {
|
|
990
|
+
const p0 = pt(n.get("pt0X"), n.get("pt0Y"));
|
|
991
|
+
const p1 = pt(n.get("pt1X"), n.get("pt1Y"));
|
|
992
|
+
const axisAligned = Math.abs(t.m01) < 0.000001 && Math.abs(t.m10) < 0.000001;
|
|
993
|
+
if (axisAligned)
|
|
994
|
+
return { kind: "rect", a: apply(t, p0), b: apply(t, p1), width: w, fill: filled(n) };
|
|
995
|
+
const corners = [p0, { x: p1.x, y: p0.y }, p1, { x: p0.x, y: p1.y }, p0].map((p) => apply(t, p));
|
|
996
|
+
return { kind: "polyline", points: corners, width: w, fill: filled(n) };
|
|
997
|
+
}
|
|
998
|
+
case "CODEllipseComp": {
|
|
999
|
+
const c = pt(n.get("CenterX"), n.get("CenterY"));
|
|
1000
|
+
const r1 = num(n.get("Radius1"));
|
|
1001
|
+
const r2 = num(n.get("Radius2"));
|
|
1002
|
+
if (Math.abs(r1 - r2) < 0.000001) {
|
|
1003
|
+
return { kind: "circle", center: apply(t, c), radius: r1 * affineScale(t), width: w, fill: filled(n) };
|
|
1004
|
+
}
|
|
1005
|
+
return { kind: "polyline", points: ellipsePoints(c, r1, r2).map((p) => apply(t, p)), width: w, fill: filled(n) };
|
|
1006
|
+
}
|
|
1007
|
+
case "CIITArcComp":
|
|
1008
|
+
return {
|
|
1009
|
+
kind: "arc",
|
|
1010
|
+
start: apply(t, pt(n.get("StartX"), n.get("StartY"))),
|
|
1011
|
+
mid: apply(t, pt(n.get("MiddleX"), n.get("MiddleY"))),
|
|
1012
|
+
end: apply(t, pt(n.get("EndX"), n.get("EndY"))),
|
|
1013
|
+
width: w
|
|
1014
|
+
};
|
|
1015
|
+
case "CODTextComp": {
|
|
1016
|
+
const text = displayText(n.str("Output"));
|
|
1017
|
+
if (!text)
|
|
1018
|
+
return;
|
|
1019
|
+
return { kind: "text", at: apply(t, { x: 0, y: 0 }), text, size: fontSize(n) };
|
|
1020
|
+
}
|
|
1021
|
+
}
|
|
1022
|
+
return;
|
|
1023
|
+
}
|
|
1024
|
+
function composeAffine(child, parent) {
|
|
1025
|
+
return {
|
|
1026
|
+
m00: child.m00 * parent.m00 + child.m01 * parent.m10,
|
|
1027
|
+
m01: child.m00 * parent.m01 + child.m01 * parent.m11,
|
|
1028
|
+
m10: child.m10 * parent.m00 + child.m11 * parent.m10,
|
|
1029
|
+
m11: child.m10 * parent.m01 + child.m11 * parent.m11,
|
|
1030
|
+
m20: child.m20 * parent.m00 + child.m21 * parent.m10 + parent.m20,
|
|
1031
|
+
m21: child.m20 * parent.m01 + child.m21 * parent.m11 + parent.m21
|
|
1032
|
+
};
|
|
1033
|
+
}
|
|
1034
|
+
var fontSize = (n) => Math.max(4, Math.min(12, Math.abs(num(n?.get("Font-Height"), -13)) * 0.4));
|
|
1035
|
+
var portPins = () => [];
|
|
1036
|
+
function parsePins(pinComp, parent, extraGraphics, raw = false, sourceId = "") {
|
|
1037
|
+
const child = (n, p) => raw ? p : composeAffine(affineOf(n), p);
|
|
1038
|
+
const t = child(pinComp, parent);
|
|
1039
|
+
let conn;
|
|
1040
|
+
let attachIds = [];
|
|
1041
|
+
const lines = [];
|
|
1042
|
+
let nameHidden = true;
|
|
1043
|
+
let numberHidden = true;
|
|
1044
|
+
for (const [cls, n] of children(pinComp)) {
|
|
1045
|
+
if (cls === "CIITPinConnectorComp") {
|
|
1046
|
+
conn = apply(child(n, t), pt(n.get("ptCenterX"), n.get("ptCenterY")));
|
|
1047
|
+
attachIds = items(n, "ConnectList").map((i) => String(i.get("ID")));
|
|
1048
|
+
} else if (cls === "CODLineComp") {
|
|
1049
|
+
const tt = child(n, t);
|
|
1050
|
+
lines.push([apply(tt, pt(n.get("pt0X"), n.get("pt0Y"))), apply(tt, pt(n.get("pt1X"), n.get("pt1Y")))]);
|
|
1051
|
+
} else if (cls === "CIITPinSymTextCompName") {
|
|
1052
|
+
if (String(n.get("Hidden") ?? "0") !== "1" && n.str("Output"))
|
|
1053
|
+
nameHidden = false;
|
|
1054
|
+
} else if (cls === "CIITPinSymTextCompNumber") {
|
|
1055
|
+
if (String(n.get("Hidden") ?? "0") !== "1" && n.str("Output"))
|
|
1056
|
+
numberHidden = false;
|
|
1057
|
+
} else {
|
|
1058
|
+
const g = graphicOf(cls, n, t, raw);
|
|
1059
|
+
if (g)
|
|
1060
|
+
extraGraphics.push(g);
|
|
1061
|
+
}
|
|
1062
|
+
}
|
|
1063
|
+
if (!conn)
|
|
1064
|
+
return { pins: [], nameHidden, numberHidden };
|
|
1065
|
+
let dir = { x: 0, y: 0 };
|
|
1066
|
+
let length = 0;
|
|
1067
|
+
for (const [a, b] of lines) {
|
|
1068
|
+
const near = (p) => Math.hypot(p.x - conn.x, p.y - conn.y) < 0.5;
|
|
1069
|
+
const far = near(a) ? b : near(b) ? a : undefined;
|
|
1070
|
+
if (far && length === 0) {
|
|
1071
|
+
length = Math.hypot(far.x - conn.x, far.y - conn.y);
|
|
1072
|
+
if (length > 0)
|
|
1073
|
+
dir = { x: (far.x - conn.x) / length, y: (far.y - conn.y) / length };
|
|
1074
|
+
} else {
|
|
1075
|
+
extraGraphics.push({ kind: "polyline", points: [a, b], width: 0, fill: false });
|
|
1076
|
+
}
|
|
1077
|
+
}
|
|
1078
|
+
const name = displayText(pinComp.str("PinName"));
|
|
1079
|
+
const fromNetlist = portPins(pinComp.get("PortID"));
|
|
1080
|
+
const numbers = fromNetlist.length ? fromNetlist : drawnPinNumbers(pinComp.str("PinNumber"));
|
|
1081
|
+
if (numbers.length === 0)
|
|
1082
|
+
numbers.push(name || "?");
|
|
1083
|
+
return {
|
|
1084
|
+
pins: numbers.map((number) => ({ pin: { name, number, at: conn, dir, length, netId: sourceId || undefined }, attachIds })),
|
|
1085
|
+
nameHidden,
|
|
1086
|
+
numberHidden
|
|
1087
|
+
};
|
|
1088
|
+
}
|
|
1089
|
+
function symbolText(n, raw) {
|
|
1090
|
+
if (!n)
|
|
1091
|
+
return;
|
|
1092
|
+
const text = displayText(n.str("Output"));
|
|
1093
|
+
const at = raw ? { x: 0, y: 0 } : apply(affineOf(n), { x: 0, y: 0 });
|
|
1094
|
+
return { text, at, hidden: String(n.get("Hidden") ?? "0") === "1" || !text };
|
|
1095
|
+
}
|
|
1096
|
+
function parseSymbolLike(comp, raw = false) {
|
|
1097
|
+
const graphics = [];
|
|
1098
|
+
const parsed = [];
|
|
1099
|
+
let anyNameShown = false;
|
|
1100
|
+
let anyNumberShown = false;
|
|
1101
|
+
let refText;
|
|
1102
|
+
let valueText;
|
|
1103
|
+
for (const [cls, n, id] of children(comp)) {
|
|
1104
|
+
switch (cls) {
|
|
1105
|
+
case "CIITPinSymbolComp": {
|
|
1106
|
+
const r = parsePins(n, IDENTITY, graphics, raw, id);
|
|
1107
|
+
parsed.push(...r.pins);
|
|
1108
|
+
anyNameShown ||= !r.nameHidden;
|
|
1109
|
+
anyNumberShown ||= !r.numberHidden;
|
|
1110
|
+
break;
|
|
1111
|
+
}
|
|
1112
|
+
case "CIITSymTextCompName":
|
|
1113
|
+
refText = symbolText(n, raw);
|
|
1114
|
+
break;
|
|
1115
|
+
case "CIITSymTextCompValue":
|
|
1116
|
+
valueText = symbolText(n, raw);
|
|
1117
|
+
break;
|
|
1118
|
+
case "CIITSymbolBorderRect":
|
|
1119
|
+
case "CIITSymTextCompLocation":
|
|
1120
|
+
break;
|
|
1121
|
+
default: {
|
|
1122
|
+
const g = graphicOf(cls, n, IDENTITY, raw);
|
|
1123
|
+
if (g)
|
|
1124
|
+
graphics.push(g);
|
|
1125
|
+
}
|
|
1126
|
+
}
|
|
1127
|
+
}
|
|
1128
|
+
const attach = new Map;
|
|
1129
|
+
for (const p of parsed)
|
|
1130
|
+
attach.set(p.pin, p.attachIds);
|
|
1131
|
+
return {
|
|
1132
|
+
symbol: {
|
|
1133
|
+
reference: refText?.text ?? "",
|
|
1134
|
+
value: valueText?.text ?? "",
|
|
1135
|
+
kind: "part",
|
|
1136
|
+
at: { x: 0, y: 0 },
|
|
1137
|
+
transform: flipToDihedral(num(comp.get("OrientationFlip"))),
|
|
1138
|
+
graphics,
|
|
1139
|
+
pins: parsed.map((p) => p.pin),
|
|
1140
|
+
refText,
|
|
1141
|
+
valueText,
|
|
1142
|
+
showPinNames: anyNameShown,
|
|
1143
|
+
showPinNumbers: anyNumberShown
|
|
1144
|
+
},
|
|
1145
|
+
attach,
|
|
1146
|
+
fallback: pt(comp.get("Transformer-M20"), comp.get("Transformer-M21"))
|
|
1147
|
+
};
|
|
1148
|
+
}
|
|
1149
|
+
var ALL_DIHEDRALS = [
|
|
1150
|
+
{ a: 1, b: 0, c: 0, d: 1 },
|
|
1151
|
+
{ a: 0, b: -1, c: 1, d: 0 },
|
|
1152
|
+
{ a: -1, b: 0, c: 0, d: -1 },
|
|
1153
|
+
{ a: 0, b: 1, c: -1, d: 0 },
|
|
1154
|
+
{ a: 1, b: 0, c: 0, d: -1 },
|
|
1155
|
+
{ a: 0, b: 1, c: 1, d: 0 },
|
|
1156
|
+
{ a: -1, b: 0, c: 0, d: 1 },
|
|
1157
|
+
{ a: 0, b: -1, c: -1, d: 0 }
|
|
1158
|
+
];
|
|
1159
|
+
var sameD = (p, q) => p.a === q.a && p.b === q.b && p.c === q.c && p.d === q.d;
|
|
1160
|
+
function fit(p, pinPts, preferred) {
|
|
1161
|
+
const pairs = [];
|
|
1162
|
+
for (const pin of p.symbol.pins) {
|
|
1163
|
+
const target = (p.attach.get(pin) ?? []).map((id) => pinPts.get(id)).find(Boolean);
|
|
1164
|
+
if (target)
|
|
1165
|
+
pairs.push([pin.at, target]);
|
|
1166
|
+
}
|
|
1167
|
+
if (pairs.length === 0)
|
|
1168
|
+
return;
|
|
1169
|
+
let best;
|
|
1170
|
+
const order = [preferred, ...ALL_DIHEDRALS.filter((d) => !sameD(d, preferred))];
|
|
1171
|
+
for (const d of order) {
|
|
1172
|
+
const votes = new Map;
|
|
1173
|
+
for (const [local, target] of pairs) {
|
|
1174
|
+
const l = applyD(d, local);
|
|
1175
|
+
const off = { x: snap(target.x - l.x), y: snap(target.y - l.y) };
|
|
1176
|
+
const k = `${off.x},${off.y}`;
|
|
1177
|
+
const v = votes.get(k);
|
|
1178
|
+
if (v)
|
|
1179
|
+
v.n++;
|
|
1180
|
+
else
|
|
1181
|
+
votes.set(k, { off, n: 1 });
|
|
1182
|
+
}
|
|
1183
|
+
const top = [...votes.values()].sort((x, y) => y.n - x.n)[0];
|
|
1184
|
+
if (!best || top.n > best.hits)
|
|
1185
|
+
best = { transform: d, at: top.off, hits: top.n, attached: pairs.length };
|
|
1186
|
+
}
|
|
1187
|
+
return best;
|
|
1188
|
+
}
|
|
1189
|
+
function applyFit(p, f, pinPts) {
|
|
1190
|
+
const { symbol } = p;
|
|
1191
|
+
if (f) {
|
|
1192
|
+
symbol.transform = f.transform;
|
|
1193
|
+
symbol.at = f.at;
|
|
1194
|
+
} else {
|
|
1195
|
+
symbol.at = p.fallback;
|
|
1196
|
+
}
|
|
1197
|
+
for (const pin of symbol.pins) {
|
|
1198
|
+
const target = (p.attach.get(pin) ?? []).map((id) => pinPts.get(id)).find(Boolean);
|
|
1199
|
+
if (!target)
|
|
1200
|
+
continue;
|
|
1201
|
+
const l = applyD(symbol.transform, pin.at);
|
|
1202
|
+
if (Math.abs(symbol.at.x + l.x - target.x) > 0.001 || Math.abs(symbol.at.y + l.y - target.y) > 0.001) {
|
|
1203
|
+
pin.attach = target;
|
|
1204
|
+
}
|
|
1205
|
+
}
|
|
1206
|
+
}
|
|
1207
|
+
var placementStats = { symbols: 0, pins: 0, pinsOnTarget: 0, raw: 0, composed: 0, unattached: 0 };
|
|
1208
|
+
function parsePlaced(comp, pinPts) {
|
|
1209
|
+
const flipD = flipToDihedral(num(comp.get("OrientationFlip")));
|
|
1210
|
+
const composed = parseSymbolLike(comp, false);
|
|
1211
|
+
const fc = fit(composed, pinPts, { a: 1, b: 0, c: 0, d: 1 });
|
|
1212
|
+
const raw = parseSymbolLike(comp, true);
|
|
1213
|
+
const fr = fit(raw, pinPts, flipD);
|
|
1214
|
+
const useRaw = !!fr && (!fc || fr.hits > fc.hits);
|
|
1215
|
+
const chosen = useRaw ? raw : composed;
|
|
1216
|
+
const f = useRaw ? fr : fc;
|
|
1217
|
+
if (!f)
|
|
1218
|
+
chosen.symbol.transform = { a: 1, b: 0, c: 0, d: 1 };
|
|
1219
|
+
applyFit(chosen, f, pinPts);
|
|
1220
|
+
placementStats.symbols++;
|
|
1221
|
+
if (f) {
|
|
1222
|
+
placementStats.pins += f.attached;
|
|
1223
|
+
placementStats.pinsOnTarget += f.hits;
|
|
1224
|
+
if (useRaw)
|
|
1225
|
+
placementStats.raw++;
|
|
1226
|
+
else
|
|
1227
|
+
placementStats.composed++;
|
|
1228
|
+
} else {
|
|
1229
|
+
placementStats.unattached++;
|
|
1230
|
+
}
|
|
1231
|
+
return chosen;
|
|
1232
|
+
}
|
|
1233
|
+
var SYMBOLISH = new Set([
|
|
1234
|
+
"CIITSymbolComp",
|
|
1235
|
+
"CIITAnimationSymbolComp",
|
|
1236
|
+
"CVirtualConnector",
|
|
1237
|
+
"CIITHierConnector",
|
|
1238
|
+
"CIITMacroComponent",
|
|
1239
|
+
"CIITOffPageConnector",
|
|
1240
|
+
"DesignSheet",
|
|
1241
|
+
"Background"
|
|
1242
|
+
]);
|
|
1243
|
+
var pinMods = (pinComp) => (pinComp.at("ElectricalObject", "ModifierInfo")?.childrenNamed("Element") ?? []).flatMap((e) => e.childrenNamed("Item").map((i) => ({ mod: e.str("NetModifier"), value: i.str("Value") })));
|
|
1244
|
+
function connectorModValue(comp, mod) {
|
|
1245
|
+
for (const [cls, n] of children(comp)) {
|
|
1246
|
+
if (cls !== "CIITPinSymbolComp")
|
|
1247
|
+
continue;
|
|
1248
|
+
const m = pinMods(n).find((x) => x.mod === mod);
|
|
1249
|
+
if (m?.value)
|
|
1250
|
+
return m.value;
|
|
1251
|
+
}
|
|
1252
|
+
return "";
|
|
1253
|
+
}
|
|
1254
|
+
function pageNets(edges, linkIds, pinIds) {
|
|
1255
|
+
const parent = new Map;
|
|
1256
|
+
const find = (x) => {
|
|
1257
|
+
if (!parent.has(x))
|
|
1258
|
+
parent.set(x, x);
|
|
1259
|
+
let r = x;
|
|
1260
|
+
while (parent.get(r) !== r)
|
|
1261
|
+
r = parent.get(r);
|
|
1262
|
+
let y = x;
|
|
1263
|
+
while (parent.get(y) !== r) {
|
|
1264
|
+
const n = parent.get(y);
|
|
1265
|
+
parent.set(y, r);
|
|
1266
|
+
y = n;
|
|
1267
|
+
}
|
|
1268
|
+
return r;
|
|
1269
|
+
};
|
|
1270
|
+
for (const [a, b] of edges) {
|
|
1271
|
+
const ra = find(a);
|
|
1272
|
+
const rb = find(b);
|
|
1273
|
+
if (ra !== rb)
|
|
1274
|
+
parent.set(ra, rb);
|
|
1275
|
+
}
|
|
1276
|
+
const links = new Map;
|
|
1277
|
+
const pins = new Map;
|
|
1278
|
+
for (const id of linkIds)
|
|
1279
|
+
links.set(find(id), (links.get(find(id)) ?? 0) + 1);
|
|
1280
|
+
for (const id of pinIds)
|
|
1281
|
+
pins.set(find(id), (pins.get(find(id)) ?? 0) + 1);
|
|
1282
|
+
const byId = (a, b) => a.length - b.length || (a < b ? -1 : a > b ? 1 : 0);
|
|
1283
|
+
const label = new Map;
|
|
1284
|
+
for (const id of [...parent.keys(), ...linkIds, ...pinIds]) {
|
|
1285
|
+
const r = find(id);
|
|
1286
|
+
const cur = label.get(r);
|
|
1287
|
+
if (cur === undefined || byId(id, cur) < 0)
|
|
1288
|
+
label.set(r, id);
|
|
1289
|
+
}
|
|
1290
|
+
return {
|
|
1291
|
+
netOf: (id) => id ? label.get(find(id)) ?? id : undefined,
|
|
1292
|
+
isolated: (id) => !!id && !links.get(find(id)) && (pins.get(find(id)) ?? 0) <= 1
|
|
1293
|
+
};
|
|
1294
|
+
}
|
|
1295
|
+
function parseSheet(designSheet, ci, pageIndex) {
|
|
1296
|
+
const nets = pageNets(pageIndex?.edges ?? [], pageIndex?.links.map((l) => l.id) ?? [], pageIndex?.pins.map((p) => p.id) ?? []);
|
|
1297
|
+
const pinPts = new Map;
|
|
1298
|
+
const pinSkip = new Set(["CIITSymbolComp", "CVirtualConnector", "DesignSheet"]);
|
|
1299
|
+
for (const [c, id] of wrapped(designSheet, "CODPinComp", pinSkip)) {
|
|
1300
|
+
pinPts.set(id, pt(c.get("CenterX"), c.get("CenterY")));
|
|
1301
|
+
}
|
|
1302
|
+
for (const [l] of wrapped(designSheet, "CIITLinkComp", pinSkip)) {
|
|
1303
|
+
const t = affineOf(l);
|
|
1304
|
+
const ptsL = items(l, "Points").map((q) => apply(t, pt(q.get("X"), q.get("Y"))));
|
|
1305
|
+
if (ptsL.length < 2)
|
|
1306
|
+
continue;
|
|
1307
|
+
for (const [attr, p] of [["Connect1", ptsL[0]], ["Connect2", ptsL[ptsL.length - 1]]]) {
|
|
1308
|
+
const id = l.get(attr) ?? "";
|
|
1309
|
+
if (id && id !== "0" && pinPts.has(id))
|
|
1310
|
+
pinPts.set(id, p);
|
|
1311
|
+
}
|
|
1312
|
+
}
|
|
1313
|
+
const symbols = [];
|
|
1314
|
+
const comps = [
|
|
1315
|
+
...collect(designSheet, "CIITSymbolComp", SYMBOLISH),
|
|
1316
|
+
...collect(designSheet, "CIITAnimationSymbolComp", SYMBOLISH)
|
|
1317
|
+
];
|
|
1318
|
+
for (const comp of comps) {
|
|
1319
|
+
const placed = parsePlaced(comp, pinPts);
|
|
1320
|
+
const ciComp = ci.componentsById.get(String(comp.get("CiComponent") ?? ""));
|
|
1321
|
+
if (ciComp?.kind === "power" && placed.symbol.pins.length === 1) {
|
|
1322
|
+
placed.symbol.kind = "power";
|
|
1323
|
+
placed.symbol.value = connectorModValue(comp, "NI_EWB_NET_GLOBAL_GROUND") || connectorModValue(comp, "NI_EWB_NET_GLOBAL") || ciComp.refdes;
|
|
1324
|
+
}
|
|
1325
|
+
if (!placed.symbol.reference && ciComp)
|
|
1326
|
+
placed.symbol.reference = ciComp.refdes;
|
|
1327
|
+
for (const pin of placed.symbol.pins) {
|
|
1328
|
+
pin.connected = !nets.isolated(pin.netId);
|
|
1329
|
+
pin.netId = nets.netOf(pin.netId);
|
|
1330
|
+
}
|
|
1331
|
+
if (placed.symbol.kind === "power" && placed.symbol.pins[0] && nets.isolated(placed.symbol.pins[0].netId)) {
|
|
1332
|
+
placed.symbol.floating = true;
|
|
1333
|
+
}
|
|
1334
|
+
if (ciComp)
|
|
1335
|
+
placed.symbol.drawnKey = ciComp.refdes + comp.str("DBComponentSectionName");
|
|
1336
|
+
if (ciComp?.part)
|
|
1337
|
+
placed.symbol.partName = ciComp.part;
|
|
1338
|
+
symbols.push(placed.symbol);
|
|
1339
|
+
}
|
|
1340
|
+
const labels = [];
|
|
1341
|
+
const connectors = [];
|
|
1342
|
+
for (const cls of ["CVirtualConnector", "CIITHierConnector", "CIITOffPageConnector"]) {
|
|
1343
|
+
for (const f of collect(designSheet, cls, SYMBOLISH))
|
|
1344
|
+
connectors.push([cls, f]);
|
|
1345
|
+
}
|
|
1346
|
+
for (const [cls, c] of connectors) {
|
|
1347
|
+
const placed = parsePlaced(c, pinPts);
|
|
1348
|
+
const s = placed.symbol;
|
|
1349
|
+
const pin = s.pins[0];
|
|
1350
|
+
const name = cls === "CIITHierConnector" ? connectorModValue(c, "NI_EWB_NET_HIERARCHY") || s.reference : cls === "CIITOffPageConnector" ? connectorModValue(c, "NI_EWB_NET_OFFPAGE") || s.reference : connectorModValue(c, "NI_EWB_NET_GLOBAL") || connectorModValue(c, "NI_EWB_NET_VIRTUAL") || s.reference || c.str("Name");
|
|
1351
|
+
if (!pin || !name)
|
|
1352
|
+
continue;
|
|
1353
|
+
const anchorLocal = applyD(s.transform, pin.at);
|
|
1354
|
+
const anchor = pin.attach ?? { x: s.at.x + anchorLocal.x, y: s.at.y + anchorLocal.y };
|
|
1355
|
+
const d = applyD(s.transform, pin.dir.x || pin.dir.y ? pin.dir : { x: 1, y: 0 });
|
|
1356
|
+
const dir = Math.abs(d.x) >= Math.abs(d.y) ? { x: Math.sign(d.x) || 1, y: 0 } : { x: 0, y: Math.sign(d.y) };
|
|
1357
|
+
const kind = cls === "CIITHierConnector" ? "hierarchical" : cls === "CIITOffPageConnector" || String(c.get("Global") ?? "1") === "1" || c.str("Type").includes("GLOBAL") ? "global" : "local";
|
|
1358
|
+
labels.push({ name, at: anchor, kind, dir, netId: nets.netOf(pin.netId), floating: nets.isolated(pin.netId) });
|
|
1359
|
+
}
|
|
1360
|
+
const blocks = [];
|
|
1361
|
+
for (const [m, macroId] of wrapped(designSheet, "CIITMacroComponent", SYMBOLISH)) {
|
|
1362
|
+
const placed = parsePlaced(m, pinPts);
|
|
1363
|
+
const s = placed.symbol;
|
|
1364
|
+
const toSheet = (q) => {
|
|
1365
|
+
const l = applyD(s.transform, q);
|
|
1366
|
+
return { x: s.at.x + l.x, y: s.at.y + l.y };
|
|
1367
|
+
};
|
|
1368
|
+
const pts = [];
|
|
1369
|
+
for (const g of s.graphics) {
|
|
1370
|
+
if (g.kind === "rect")
|
|
1371
|
+
pts.push(toSheet(g.a), toSheet(g.b));
|
|
1372
|
+
else if (g.kind === "polyline")
|
|
1373
|
+
pts.push(...g.points.map(toSheet));
|
|
1374
|
+
}
|
|
1375
|
+
const pinNames = new Map;
|
|
1376
|
+
const pinComps = children(m).filter(([cls]) => cls === "CIITPinSymbolComp").map(([, n]) => n);
|
|
1377
|
+
s.pins.forEach((pin, i) => {
|
|
1378
|
+
const n = pinComps[i];
|
|
1379
|
+
const nm = n && pinMods(n).find((x) => x.mod === "NI_EWB_NET_HIERARCHY_COMP")?.value || pin.name;
|
|
1380
|
+
pinNames.set(pin, nm);
|
|
1381
|
+
});
|
|
1382
|
+
const pinPos = s.pins.map((pin) => toSheet(pin.at));
|
|
1383
|
+
const all = [...pts, ...pinPos];
|
|
1384
|
+
if (all.length === 0)
|
|
1385
|
+
continue;
|
|
1386
|
+
const a = { x: Math.min(...all.map((q) => q.x)), y: Math.min(...all.map((q) => q.y)) };
|
|
1387
|
+
const b = { x: Math.max(...all.map((q) => q.x)), y: Math.max(...all.map((q) => q.y)) };
|
|
1388
|
+
blocks.push({
|
|
1389
|
+
id: macroId,
|
|
1390
|
+
childSheet: m.at("HierBlock", "CHierBlock")?.str("FileName") ?? "",
|
|
1391
|
+
a,
|
|
1392
|
+
b,
|
|
1393
|
+
pins: s.pins.map((pin, i) => ({ name: pinNames.get(pin) ?? pin.name, at: pinPos[i], attach: pin.attach }))
|
|
1394
|
+
});
|
|
1395
|
+
}
|
|
1396
|
+
const wires = [];
|
|
1397
|
+
for (const [l, linkId] of wrapped(designSheet, "CIITLinkComp", SYMBOLISH)) {
|
|
1398
|
+
const lt = affineOf(l);
|
|
1399
|
+
const points = items(l, "Points").map((p) => apply(lt, pt(p.get("X"), p.get("Y"))));
|
|
1400
|
+
if (points.length < 2)
|
|
1401
|
+
continue;
|
|
1402
|
+
wires.push({ points, netId: nets.netOf(linkId) });
|
|
1403
|
+
for (const el of l.at("ElectricalObject", "ModifierInfo")?.childrenNamed("Element") ?? []) {
|
|
1404
|
+
if (el.str("NetModifier") !== "NI_EWB_NET_NAME")
|
|
1405
|
+
continue;
|
|
1406
|
+
const name = el.child("Item")?.str("Value") ?? "";
|
|
1407
|
+
if (name)
|
|
1408
|
+
labels.push({ name, at: points[0], kind: "local", dir: { x: 1, y: 0 }, netId: nets.netOf(linkId) });
|
|
1409
|
+
}
|
|
1410
|
+
}
|
|
1411
|
+
const modValue = (n, mod) => pinMods(n).find((m) => m.mod === mod)?.value ?? "";
|
|
1412
|
+
const busKind = wrapped(designSheet, "CBusOffpageConn", SYMBOLISH).length ? "global" : "local";
|
|
1413
|
+
const taken = new Set([...labels.map((l) => l.name), ...symbols.filter((x) => x.kind === "power").map((x) => x.value)].map((n) => n.toUpperCase()));
|
|
1414
|
+
const lineLabel = (line) => busKind === "global" || taken.has(line.toUpperCase()) ? `${line}_BUS` : line;
|
|
1415
|
+
const buses = [];
|
|
1416
|
+
for (const [b] of wrapped(designSheet, "CIITBusCompV8", SYMBOLISH)) {
|
|
1417
|
+
const bt = affineOf(b);
|
|
1418
|
+
const points = items(b, "Points").map((p) => apply(bt, pt(p.get("X"), p.get("Y"))));
|
|
1419
|
+
if (points.length < 2)
|
|
1420
|
+
continue;
|
|
1421
|
+
const members = (b.child("MapBusLine2NetName")?.childrenNamed("Element") ?? []).map((e) => e.str("Key")).filter(Boolean);
|
|
1422
|
+
buses.push({ points, name: modValue(b, "NI_EWB_NET_VIRTUAL"), members: members.map(lineLabel) });
|
|
1423
|
+
}
|
|
1424
|
+
const busEntries = [];
|
|
1425
|
+
for (const [e, id] of wrapped(designSheet, "CIITBusEntry", SYMBOLISH)) {
|
|
1426
|
+
const et = affineOf(e);
|
|
1427
|
+
let conn;
|
|
1428
|
+
let line;
|
|
1429
|
+
for (const [cls, n] of children(e)) {
|
|
1430
|
+
const t = composeAffine(affineOf(n), et);
|
|
1431
|
+
if (cls === "CIITPinConnectorComp")
|
|
1432
|
+
conn = apply(t, pt(n.get("ptCenterX"), n.get("ptCenterY")));
|
|
1433
|
+
else if (cls === "CODLineComp")
|
|
1434
|
+
line = [apply(t, pt(n.get("pt0X"), n.get("pt0Y"))), apply(t, pt(n.get("pt1X"), n.get("pt1Y")))];
|
|
1435
|
+
}
|
|
1436
|
+
const member = modValue(e, "NI_EWB_NET_BUS_ENTRY");
|
|
1437
|
+
if (!line || !member)
|
|
1438
|
+
continue;
|
|
1439
|
+
const d = (p) => conn ? Math.hypot(p.x - conn.x, p.y - conn.y) : 0;
|
|
1440
|
+
const [wire, bus] = d(line[0]) <= d(line[1]) ? line : [line[1], line[0]];
|
|
1441
|
+
busEntries.push({ wire, bus, member: lineLabel(member) });
|
|
1442
|
+
labels.push({ name: lineLabel(member), at: wire, kind: busKind, dir: { x: wire.x < bus.x ? -1 : 1, y: 0 }, netId: nets.netOf(id) });
|
|
1443
|
+
}
|
|
1444
|
+
const texts = [];
|
|
1445
|
+
for (const t of collect(designSheet, "CODTextComp", SYMBOLISH)) {
|
|
1446
|
+
const text = displayText(t.str("Output"));
|
|
1447
|
+
if (text && String(t.get("Hidden") ?? "0") !== "1")
|
|
1448
|
+
texts.push({ text, at: apply(affineOf(t), { x: 0, y: 0 }), size: fontSize(t) });
|
|
1449
|
+
}
|
|
1450
|
+
const nmPerUnit = 250000;
|
|
1451
|
+
let width = (num(designSheet.get("WorkAreaRight")) - num(designSheet.get("WorkAreaLeft"))) / nmPerUnit;
|
|
1452
|
+
let height = (num(designSheet.get("WorkAreaTop")) - num(designSheet.get("WorkAreaBottom"))) / nmPerUnit;
|
|
1453
|
+
if (!(width > 0 && height > 0)) {
|
|
1454
|
+
const xs = wires.flatMap((w) => w.points.map((p) => p.x)).concat(symbols.map((s) => s.at.x));
|
|
1455
|
+
const ys = wires.flatMap((w) => w.points.map((p) => p.y)).concat(symbols.map((s) => s.at.y));
|
|
1456
|
+
width = Math.max(1188, ...xs.map((x) => x + 40));
|
|
1457
|
+
height = Math.max(840, ...ys.map((y) => y + 40));
|
|
1458
|
+
}
|
|
1459
|
+
const title = designSheet.str("Title");
|
|
1460
|
+
const page = designSheet.str("PageName") || "1";
|
|
1461
|
+
return {
|
|
1462
|
+
name: title,
|
|
1463
|
+
title,
|
|
1464
|
+
page,
|
|
1465
|
+
blocks,
|
|
1466
|
+
size: { width, height },
|
|
1467
|
+
symbols,
|
|
1468
|
+
wires,
|
|
1469
|
+
labels,
|
|
1470
|
+
texts,
|
|
1471
|
+
buses,
|
|
1472
|
+
busEntries
|
|
1473
|
+
};
|
|
1474
|
+
}
|
|
1475
|
+
function toSchInstance(inst, sheets, design) {
|
|
1476
|
+
const refdes = {};
|
|
1477
|
+
const pinRemaps = {};
|
|
1478
|
+
const units = {};
|
|
1479
|
+
for (const sh of sheets.filter((x) => x.title === inst.sheet)) {
|
|
1480
|
+
for (const sym of sh.symbols) {
|
|
1481
|
+
if (!sym.drawnKey)
|
|
1482
|
+
continue;
|
|
1483
|
+
const final = design.finalRefdes(inst, sh.page, sym.drawnKey);
|
|
1484
|
+
if (final)
|
|
1485
|
+
refdes[`${sh.page}|${sym.drawnKey}`] = final;
|
|
1486
|
+
const remap = design.pinRemap(inst, sh.page, sym.drawnKey);
|
|
1487
|
+
if (remap)
|
|
1488
|
+
pinRemaps[`${sh.page}|${sym.drawnKey}`] = Object.fromEntries(remap);
|
|
1489
|
+
const unit = design.finalUnit(inst, sh.page, sym.drawnKey);
|
|
1490
|
+
if (unit)
|
|
1491
|
+
units[`${sh.page}|${sym.drawnKey}`] = unit;
|
|
1492
|
+
}
|
|
1493
|
+
}
|
|
1494
|
+
return {
|
|
1495
|
+
sheet: inst.sheet,
|
|
1496
|
+
name: inst.finalName,
|
|
1497
|
+
blockId: inst.macroId,
|
|
1498
|
+
parentPage: inst.parentPage,
|
|
1499
|
+
refdes,
|
|
1500
|
+
pinRemaps,
|
|
1501
|
+
units,
|
|
1502
|
+
children: inst.children.map((c) => toSchInstance(c, sheets, design))
|
|
1503
|
+
};
|
|
1504
|
+
}
|
|
1505
|
+
function parseSchematicXml(input) {
|
|
1506
|
+
const doc = docOf(input);
|
|
1507
|
+
if (doc.application === "ultiboard") {
|
|
1508
|
+
throw new Error("input is an Ultiboard PCB; use the PCB converter (parsePcbXml)");
|
|
1509
|
+
}
|
|
1510
|
+
if (doc.application !== "multisim")
|
|
1511
|
+
throw new Error("not a Multisim schematic XML file");
|
|
1512
|
+
const root = doc.root;
|
|
1513
|
+
const creator = root.at("history", "creator");
|
|
1514
|
+
const project = root.child("Project");
|
|
1515
|
+
const designSheets = (project?.at("UniqueSheets", "SheetInfos")?.childrenNamed("SheetContainer") ?? []).map((sc) => sc.at("Sheet", "Variable", "DesignSheet")).filter((ds) => ds != null);
|
|
1516
|
+
if (designSheets.length === 0)
|
|
1517
|
+
throw new Error("no DesignSheet element found");
|
|
1518
|
+
const ci = parseCiNetlist(doc);
|
|
1519
|
+
const design = parseMultisimDesign(doc);
|
|
1520
|
+
portPins = (portId) => {
|
|
1521
|
+
const port = portId ? design.ci.get(portId) : undefined;
|
|
1522
|
+
return port ? portPinNumbers(port.body) : [];
|
|
1523
|
+
};
|
|
1524
|
+
const sheets = designSheets.map((ds) => {
|
|
1525
|
+
const title = ds.str("Title");
|
|
1526
|
+
const page = ds.str("PageName") || "1";
|
|
1527
|
+
return parseSheet(ds, ci, design.pages.find((p) => p.title === title && p.page === page));
|
|
1528
|
+
});
|
|
1529
|
+
const rootSheet = design.rootTitle || sheets[0].title;
|
|
1530
|
+
return {
|
|
1531
|
+
source: {
|
|
1532
|
+
application: creator?.get("application") ?? "unknown",
|
|
1533
|
+
versionMajor: num(creator?.get("versionMajor")),
|
|
1534
|
+
versionMinor: num(creator?.get("versionMinor")),
|
|
1535
|
+
schema: num(root.get("Schema"))
|
|
1536
|
+
},
|
|
1537
|
+
projectName: project?.str("Name") ?? "",
|
|
1538
|
+
rootSheet,
|
|
1539
|
+
sheets,
|
|
1540
|
+
root: toSchInstance(design.root, sheets, design)
|
|
1541
|
+
};
|
|
1542
|
+
}
|
|
1543
|
+
|
|
1544
|
+
// src/emit/pcb-layers.ts
|
|
1545
|
+
var TECHNICAL = [
|
|
1546
|
+
{ id: 32, name: "B.Adhes", type: "user", userName: "B.Adhesive" },
|
|
1547
|
+
{ id: 33, name: "F.Adhes", type: "user", userName: "F.Adhesive" },
|
|
1548
|
+
{ id: 34, name: "B.Paste", type: "user" },
|
|
1549
|
+
{ id: 35, name: "F.Paste", type: "user" },
|
|
1550
|
+
{ id: 36, name: "B.SilkS", type: "user", userName: "B.Silkscreen" },
|
|
1551
|
+
{ id: 37, name: "F.SilkS", type: "user", userName: "F.Silkscreen" },
|
|
1552
|
+
{ id: 38, name: "B.Mask", type: "user" },
|
|
1553
|
+
{ id: 39, name: "F.Mask", type: "user" },
|
|
1554
|
+
{ id: 40, name: "Dwgs.User", type: "user", userName: "User.Drawings" },
|
|
1555
|
+
{ id: 41, name: "Cmts.User", type: "user", userName: "User.Comments" },
|
|
1556
|
+
{ id: 42, name: "Eco1.User", type: "user", userName: "User.Eco1" },
|
|
1557
|
+
{ id: 43, name: "Eco2.User", type: "user", userName: "User.Eco2" },
|
|
1558
|
+
{ id: 44, name: "Edge.Cuts", type: "user" },
|
|
1559
|
+
{ id: 45, name: "Margin", type: "user" },
|
|
1560
|
+
{ id: 46, name: "B.CrtYd", type: "user", userName: "B.Courtyard" },
|
|
1561
|
+
{ id: 47, name: "F.CrtYd", type: "user", userName: "F.Courtyard" },
|
|
1562
|
+
{ id: 48, name: "B.Fab", type: "user" },
|
|
1563
|
+
{ id: 49, name: "F.Fab", type: "user" }
|
|
1564
|
+
];
|
|
1565
|
+
var USER_SLOTS = 9;
|
|
1566
|
+
var FIXED = {
|
|
1567
|
+
65: "Edge.Cuts",
|
|
1568
|
+
66: "F.SilkS",
|
|
1569
|
+
67: "B.SilkS",
|
|
1570
|
+
70: "F.Paste",
|
|
1571
|
+
71: "B.Paste",
|
|
1572
|
+
72: "F.Mask",
|
|
1573
|
+
73: "B.Mask",
|
|
1574
|
+
74: "F.Adhes",
|
|
1575
|
+
75: "B.Adhes",
|
|
1576
|
+
76: "F.Fab",
|
|
1577
|
+
77: "B.Fab",
|
|
1578
|
+
81: "Cmts.User",
|
|
1579
|
+
92: "F.CrtYd"
|
|
1580
|
+
};
|
|
1581
|
+
var COURTYARD = 92;
|
|
1582
|
+
var EW_3D_TOP = 68;
|
|
1583
|
+
var EW_3D_BOTTOM = 69;
|
|
1584
|
+
var TOP_TWIN = { 67: 66, 69: 68, 71: 70, 73: 72, 75: 74, 77: 76 };
|
|
1585
|
+
var DROPPED = new Set([64, 78, 79, 80, 511]);
|
|
1586
|
+
var copperName = (i, n) => i === 0 ? "F.Cu" : i === n - 1 ? "B.Cu" : `In${i}.Cu`;
|
|
1587
|
+
|
|
1588
|
+
class LayerMap {
|
|
1589
|
+
copper;
|
|
1590
|
+
table;
|
|
1591
|
+
dropped = new Map;
|
|
1592
|
+
map = new Map;
|
|
1593
|
+
constructor(board) {
|
|
1594
|
+
const n = board.stackup.copper.length;
|
|
1595
|
+
this.copper = board.stackup.copper.map((_, i) => copperName(i, n));
|
|
1596
|
+
board.stackup.copper.forEach((ew, i) => this.map.set(ew, this.copper[i]));
|
|
1597
|
+
const copperTable = this.copper.map((name, i) => ({
|
|
1598
|
+
id: i === n - 1 ? 31 : i,
|
|
1599
|
+
name,
|
|
1600
|
+
type: "signal"
|
|
1601
|
+
}));
|
|
1602
|
+
for (const [ew, name] of Object.entries(FIXED))
|
|
1603
|
+
this.map.set(Number(ew), name);
|
|
1604
|
+
const used = new Set([
|
|
1605
|
+
...board.shapes.map((s) => s.layer),
|
|
1606
|
+
...board.texts.map((t) => t.layer),
|
|
1607
|
+
...board.components.flatMap((c) => [...c.graphics.map((g) => g.layer), ...c.texts.map((t) => t.layer)]),
|
|
1608
|
+
...board.components.filter((c) => c.bottom).flatMap((c) => [...c.graphics, ...c.texts].map((g) => TOP_TWIN[g.layer] ?? g.layer))
|
|
1609
|
+
]);
|
|
1610
|
+
const ewName = new Map(board.layers.map((l) => [l.number, l.name]));
|
|
1611
|
+
const wanted = [...used].filter((l) => !this.map.has(l) && !DROPPED.has(l) && !(l >= 0 && l <= 63)).sort((a, b) => a - b);
|
|
1612
|
+
const user = [];
|
|
1613
|
+
for (const ew of wanted) {
|
|
1614
|
+
if (user.length < USER_SLOTS) {
|
|
1615
|
+
const name = `User.${user.length + 1}`;
|
|
1616
|
+
user.push({ id: 50 + user.length, name, type: "user", userName: ewName.get(ew) || `EW layer ${ew}` });
|
|
1617
|
+
this.map.set(ew, name);
|
|
1618
|
+
} else {
|
|
1619
|
+
this.map.set(ew, "Dwgs.User");
|
|
1620
|
+
}
|
|
1621
|
+
}
|
|
1622
|
+
this.table = [...copperTable, ...TECHNICAL, ...user];
|
|
1623
|
+
}
|
|
1624
|
+
kicad(ew) {
|
|
1625
|
+
const k = this.map.get(ew);
|
|
1626
|
+
if (k === undefined)
|
|
1627
|
+
this.dropped.set(ew, (this.dropped.get(ew) ?? 0) + 1);
|
|
1628
|
+
return k;
|
|
1629
|
+
}
|
|
1630
|
+
kicadInPart(ew, bottom) {
|
|
1631
|
+
if (bottom && ew === COURTYARD)
|
|
1632
|
+
return "B.CrtYd";
|
|
1633
|
+
if (ew === EW_3D_BOTTOM)
|
|
1634
|
+
return this.kicad(EW_3D_TOP) ?? this.kicad(ew);
|
|
1635
|
+
return this.kicad(ew);
|
|
1636
|
+
}
|
|
1637
|
+
isCopper(name) {
|
|
1638
|
+
return name !== undefined && this.copper.includes(name);
|
|
1639
|
+
}
|
|
1640
|
+
}
|
|
1641
|
+
|
|
1642
|
+
// src/emit/kicad-pcb.ts
|
|
1643
|
+
var KICAD_VERSION = 20240108;
|
|
1644
|
+
var NM_PER_MM = 1e6;
|
|
1645
|
+
var mm = (nm) => (nm / NM_PER_MM).toFixed(6);
|
|
1646
|
+
var fx = (nm) => mm(nm);
|
|
1647
|
+
var fy = (nm) => mm(-nm);
|
|
1648
|
+
var deg = (millionths) => millionths / 1e6;
|
|
1649
|
+
var normDeg = (d) => (d % 360 + 360) % 360;
|
|
1650
|
+
var EDGE_CUTS_WIDTH_NM = 50000;
|
|
1651
|
+
function q(s) {
|
|
1652
|
+
return `"${s.replace(/\\/g, "\\\\").replace(/"/g, "\\\"").replace(/\n/g, "\\n")}"`;
|
|
1653
|
+
}
|
|
1654
|
+
function uuid() {
|
|
1655
|
+
return crypto.randomUUID();
|
|
1656
|
+
}
|
|
1657
|
+
function strokeWidthFor(rawNm, layer) {
|
|
1658
|
+
if (layer === "Edge.Cuts")
|
|
1659
|
+
return EDGE_CUTS_WIDTH_NM;
|
|
1660
|
+
if (rawNm > 0)
|
|
1661
|
+
return rawNm;
|
|
1662
|
+
return 120000;
|
|
1663
|
+
}
|
|
1664
|
+
var BOARD = { kind: "gr", indent: "\t", xy: (x, y) => `${fx(x)} ${fy(y)}`, local: (x, y) => ({ x, y: -y }), angle: 0 };
|
|
1665
|
+
var stroke = (widthNm) => `(stroke (width ${mm(widthNm)}) (type default))`;
|
|
1666
|
+
function emitLine(f, x1, y1, x2, y2, widthNm, layer) {
|
|
1667
|
+
return `${f.indent}(${f.kind}_line (start ${f.xy(x1, y1)}) (end ${f.xy(x2, y2)}) ${stroke(widthNm)} (layer ${q(layer)}) (uuid ${q(uuid())}))`;
|
|
1668
|
+
}
|
|
1669
|
+
function emitArc(f, cx, cy, sx, sy, ex, ey, rNm, widthNm, layer) {
|
|
1670
|
+
const dx = (sx + ex) / 2 - cx;
|
|
1671
|
+
const dy = (sy + ey) / 2 - cy;
|
|
1672
|
+
const len = Math.hypot(dx, dy);
|
|
1673
|
+
const midX = len === 0 ? cx : cx + dx / len * rNm;
|
|
1674
|
+
const midY = len === 0 ? cy : cy + dy / len * rNm;
|
|
1675
|
+
return `${f.indent}(${f.kind}_arc (start ${f.xy(sx, sy)}) (mid ${f.xy(midX, midY)}) (end ${f.xy(ex, ey)}) ${stroke(widthNm)} (layer ${q(layer)}) (uuid ${q(uuid())}))`;
|
|
1676
|
+
}
|
|
1677
|
+
function emitCircle(f, cx, cy, rNm, widthNm, layer) {
|
|
1678
|
+
const c = f.local(cx, cy);
|
|
1679
|
+
return `${f.indent}(${f.kind}_circle (center ${mm(c.x)} ${mm(c.y)}) (end ${mm(c.x + rNm)} ${mm(c.y)}) ${stroke(widthNm)} (fill none) (layer ${q(layer)}) (uuid ${q(uuid())}))`;
|
|
1680
|
+
}
|
|
1681
|
+
function emitEllipse(f, s, layer) {
|
|
1682
|
+
if (s.points.length < 2)
|
|
1683
|
+
return [];
|
|
1684
|
+
const [p0, p1] = s.points;
|
|
1685
|
+
const cx = (p0.x + p1.x) / 2;
|
|
1686
|
+
const cy = (p0.y + p1.y) / 2;
|
|
1687
|
+
const r = Math.hypot(p1.x - p0.x, p1.y - p0.y) / 2;
|
|
1688
|
+
if (r <= 0)
|
|
1689
|
+
return [];
|
|
1690
|
+
return [emitCircle(f, cx, cy, r, strokeWidthFor(s.thickness, layer), layer)];
|
|
1691
|
+
}
|
|
1692
|
+
function bbox(points) {
|
|
1693
|
+
const xs = points.map((p) => p.x);
|
|
1694
|
+
const ys = points.map((p) => p.y);
|
|
1695
|
+
return {
|
|
1696
|
+
xMin: Math.min(...xs),
|
|
1697
|
+
xMax: Math.max(...xs),
|
|
1698
|
+
yMin: Math.min(...ys),
|
|
1699
|
+
yMax: Math.max(...ys)
|
|
1700
|
+
};
|
|
1701
|
+
}
|
|
1702
|
+
function emitRoundRect(f, s, layer) {
|
|
1703
|
+
if (s.points.length < 4)
|
|
1704
|
+
return [];
|
|
1705
|
+
const corners = s.points.slice(0, 4);
|
|
1706
|
+
const w = strokeWidthFor(s.thickness, layer);
|
|
1707
|
+
const unit = (a, b) => {
|
|
1708
|
+
const d = Math.hypot(b.x - a.x, b.y - a.y) || 1;
|
|
1709
|
+
return { x: (b.x - a.x) / d, y: (b.y - a.y) / d };
|
|
1710
|
+
};
|
|
1711
|
+
const shortest = Math.min(...corners.map((p, i) => Math.hypot(corners[(i + 1) % 4].x - p.x, corners[(i + 1) % 4].y - p.y)));
|
|
1712
|
+
const r = Math.max(0, Math.min(s.radius, shortest / 2));
|
|
1713
|
+
const ends = corners.map((p, i) => {
|
|
1714
|
+
const toPrev = unit(p, corners[(i + 3) % 4]);
|
|
1715
|
+
const toNext = unit(p, corners[(i + 1) % 4]);
|
|
1716
|
+
return {
|
|
1717
|
+
a: { x: p.x + toPrev.x * r, y: p.y + toPrev.y * r },
|
|
1718
|
+
b: { x: p.x + toNext.x * r, y: p.y + toNext.y * r },
|
|
1719
|
+
c: { x: p.x + (toPrev.x + toNext.x) * r, y: p.y + (toPrev.y + toNext.y) * r }
|
|
1720
|
+
};
|
|
1721
|
+
});
|
|
1722
|
+
const out = [];
|
|
1723
|
+
ends.forEach((e, i) => {
|
|
1724
|
+
const next = ends[(i + 1) % 4];
|
|
1725
|
+
out.push(emitLine(f, e.b.x, e.b.y, next.a.x, next.a.y, w, layer));
|
|
1726
|
+
});
|
|
1727
|
+
if (r > 0)
|
|
1728
|
+
for (const e of ends)
|
|
1729
|
+
out.push(emitArc(f, e.c.x, e.c.y, e.a.x, e.a.y, e.b.x, e.b.y, r, w, layer));
|
|
1730
|
+
return out;
|
|
1731
|
+
}
|
|
1732
|
+
function emitRectangle(f, s, layer) {
|
|
1733
|
+
if (s.points.length < 4)
|
|
1734
|
+
return [];
|
|
1735
|
+
const corners = s.points.slice(0, 4);
|
|
1736
|
+
const w = strokeWidthFor(s.thickness, layer);
|
|
1737
|
+
return corners.map((p, i) => {
|
|
1738
|
+
const q = corners[(i + 1) % 4];
|
|
1739
|
+
return emitLine(f, p.x, p.y, q.x, q.y, w, layer);
|
|
1740
|
+
});
|
|
1741
|
+
}
|
|
1742
|
+
function emitPolyline(f, s, layer) {
|
|
1743
|
+
if (s.points.length < 2)
|
|
1744
|
+
return [];
|
|
1745
|
+
const w = strokeWidthFor(s.thickness, layer);
|
|
1746
|
+
const out = [];
|
|
1747
|
+
for (let i = 0;i + 1 < s.points.length; i++) {
|
|
1748
|
+
const p1 = s.points[i];
|
|
1749
|
+
const p2 = s.points[i + 1];
|
|
1750
|
+
out.push(emitLine(f, p1.x, p1.y, p2.x, p2.y, w, layer));
|
|
1751
|
+
}
|
|
1752
|
+
return out;
|
|
1753
|
+
}
|
|
1754
|
+
function ccwMid(center, start, end) {
|
|
1755
|
+
const r = Math.hypot(start.x - center.x, start.y - center.y);
|
|
1756
|
+
const a0 = Math.atan2(start.y - center.y, start.x - center.x);
|
|
1757
|
+
let sweep = Math.atan2(end.y - center.y, end.x - center.x) - a0;
|
|
1758
|
+
while (sweep <= 0.000000000001)
|
|
1759
|
+
sweep += 2 * Math.PI;
|
|
1760
|
+
return { x: center.x + r * Math.cos(a0 + sweep / 2), y: center.y + r * Math.sin(a0 + sweep / 2) };
|
|
1761
|
+
}
|
|
1762
|
+
function emitArcShape(f, s, layer) {
|
|
1763
|
+
const r = Math.hypot(s.start.x - s.center.x, s.start.y - s.center.y);
|
|
1764
|
+
if (r <= 0)
|
|
1765
|
+
return [];
|
|
1766
|
+
const w = strokeWidthFor(s.thickness, layer);
|
|
1767
|
+
if (Math.hypot(s.end.x - s.start.x, s.end.y - s.start.y) < 1)
|
|
1768
|
+
return [emitCircle(f, s.center.x, s.center.y, r, w, layer)];
|
|
1769
|
+
const m = ccwMid(s.center, s.start, s.end);
|
|
1770
|
+
return [`${f.indent}(${f.kind}_arc (start ${f.xy(s.start.x, s.start.y)}) (mid ${f.xy(m.x, m.y)}) (end ${f.xy(s.end.x, s.end.y)}) ${stroke(w)} (layer ${q(layer)}) (uuid ${q(uuid())}))`];
|
|
1771
|
+
}
|
|
1772
|
+
function emitShape(shape, layer, f = BOARD) {
|
|
1773
|
+
if (!layer)
|
|
1774
|
+
return [];
|
|
1775
|
+
switch (shape.kind) {
|
|
1776
|
+
case "roundRect":
|
|
1777
|
+
return emitRoundRect(f, shape, layer);
|
|
1778
|
+
case "rectangle":
|
|
1779
|
+
return emitRectangle(f, shape, layer);
|
|
1780
|
+
case "polyline":
|
|
1781
|
+
return emitPolyline(f, shape, layer);
|
|
1782
|
+
case "ellipse":
|
|
1783
|
+
return emitEllipse(f, shape, layer);
|
|
1784
|
+
case "arc":
|
|
1785
|
+
return emitArcShape(f, shape, layer);
|
|
1786
|
+
}
|
|
1787
|
+
}
|
|
1788
|
+
var pts = (outline) => outline.map((p) => `(xy ${fx(p.x)} ${fy(p.y)})`).join(" ");
|
|
1789
|
+
function emitZone(z, lm, net, priority) {
|
|
1790
|
+
const layer = lm.kicad(z.layer);
|
|
1791
|
+
if (!lm.isCopper(layer))
|
|
1792
|
+
return;
|
|
1793
|
+
const mode = z.removeNotEdgeConnected ? 0 : z.removeIslands ? 2 : 1;
|
|
1794
|
+
const gap = z.clearance > 0 ? z.clearance : 254000;
|
|
1795
|
+
const spoke = z.reliefSpokeWidth > 0 ? z.reliefSpokeWidth : 254000;
|
|
1796
|
+
const minT = z.minThickness > 0 ? Math.min(z.minThickness, 1e6) : 254000;
|
|
1797
|
+
return [
|
|
1798
|
+
` (zone (net ${net?.idx ?? 0}) (net_name ${q(net?.name ?? "")}) (layer ${q(layer)}) (uuid ${q(uuid())})`,
|
|
1799
|
+
` (name ${q(`EW ${z.kind === "plane" ? "power plane" : "copper area"} ${z.netName}`)})`,
|
|
1800
|
+
` (hatch edge 0.5)`,
|
|
1801
|
+
` (priority ${priority})`,
|
|
1802
|
+
` (connect_pads (clearance ${mm(gap)}))`,
|
|
1803
|
+
` (min_thickness ${mm(minT)}) (filled_areas_thickness no)`,
|
|
1804
|
+
` (fill (thermal_gap ${mm(gap)}) (thermal_bridge_width ${mm(spoke)}) (island_removal_mode ${mode})${mode === 2 ? " (island_area_min 10)" : ""})`,
|
|
1805
|
+
` (polygon (pts ${pts(z.outline)}))`,
|
|
1806
|
+
` )`
|
|
1807
|
+
].join(`
|
|
1808
|
+
`);
|
|
1809
|
+
}
|
|
1810
|
+
function textParts(t, f) {
|
|
1811
|
+
const h = t.height > 0 ? t.height : 1e6;
|
|
1812
|
+
const w = t.width > 0 ? t.width : h;
|
|
1813
|
+
const thick = t.strokeWidth > 0 ? t.strokeWidth : Math.round(h * 0.15);
|
|
1814
|
+
const a = normDeg(deg(t.angle));
|
|
1815
|
+
return {
|
|
1816
|
+
at: `(at ${f.xy(t.at.x, t.at.y)}${a || f.kind === "fp" ? ` ${+a.toFixed(6)}` : ""})`,
|
|
1817
|
+
effects: `(effects (font (size ${mm(h)} ${mm(w)}) (thickness ${mm(thick)}))${t.mirror ? " (justify mirror)" : ""})`
|
|
1818
|
+
};
|
|
1819
|
+
}
|
|
1820
|
+
function emitText(t, lm) {
|
|
1821
|
+
const layer = lm.kicad(t.layer);
|
|
1822
|
+
if (!layer)
|
|
1823
|
+
return;
|
|
1824
|
+
const { at, effects } = textParts(t, BOARD);
|
|
1825
|
+
return ` (gr_text ${q(t.text)} ${at} (layer ${q(layer)}) (uuid ${q(uuid())}) ${effects})`;
|
|
1826
|
+
}
|
|
1827
|
+
function emitRuleArea(r, i, lm) {
|
|
1828
|
+
const nets = r.allNets ? "all nets" : `nets ${r.nets.join(", ") || "(none)"}`;
|
|
1829
|
+
return [
|
|
1830
|
+
` (zone (net 0) (net_name "") (layers ${lm.copper.map(q).join(" ")}) (uuid ${q(uuid())})`,
|
|
1831
|
+
` (name ${q(`EW rule area ${i + 1} (type ${r.type}, ${nets})`)})`,
|
|
1832
|
+
` (hatch edge 0.5)`,
|
|
1833
|
+
` (connect_pads (clearance 0))`,
|
|
1834
|
+
` (min_thickness 0.25) (filled_areas_thickness no)`,
|
|
1835
|
+
` (keepout (tracks allowed) (vias allowed) (pads allowed) (copperpour allowed) (footprints allowed))`,
|
|
1836
|
+
` (fill (thermal_gap 0.5) (thermal_bridge_width 0.5))`,
|
|
1837
|
+
` (polygon (pts ${pts(r.outline)}))`,
|
|
1838
|
+
` )`
|
|
1839
|
+
].join(`
|
|
1840
|
+
`);
|
|
1841
|
+
}
|
|
1842
|
+
var pinKey = (refdes, pin) => JSON.stringify([refdes, pin]);
|
|
1843
|
+
function buildNets(nets) {
|
|
1844
|
+
const table = [` (net 0 ${q("")})`];
|
|
1845
|
+
const byPin = new Map;
|
|
1846
|
+
const byName = new Map;
|
|
1847
|
+
nets.forEach((net, i) => {
|
|
1848
|
+
const ref = { idx: i + 1, name: net.name };
|
|
1849
|
+
table.push(` (net ${ref.idx} ${q(net.name)})`);
|
|
1850
|
+
byName.set(net.name.toUpperCase(), ref);
|
|
1851
|
+
for (const p of net.pins)
|
|
1852
|
+
byPin.set(pinKey(p.refdes, p.pin), ref);
|
|
1853
|
+
});
|
|
1854
|
+
return { table, resolve: (refdes, pin) => byPin.get(pinKey(refdes, pin)), byName };
|
|
1855
|
+
}
|
|
1856
|
+
var posKey = (p) => `${p.x},${p.y}`;
|
|
1857
|
+
function padContains(pad, p) {
|
|
1858
|
+
const dx = p.x - pad.at.x;
|
|
1859
|
+
const dy = p.y - pad.at.y;
|
|
1860
|
+
switch (pad.shape.kind) {
|
|
1861
|
+
case "circle":
|
|
1862
|
+
return Math.hypot(dx, dy) <= pad.shape.diameter / 2 + 1;
|
|
1863
|
+
case "rect":
|
|
1864
|
+
case "roundrect": {
|
|
1865
|
+
const a = -(deg(pad.rotation) * Math.PI) / 180;
|
|
1866
|
+
const lx = dx * Math.cos(a) - dy * Math.sin(a);
|
|
1867
|
+
const ly = dx * Math.sin(a) + dy * Math.cos(a);
|
|
1868
|
+
return Math.abs(lx) <= pad.shape.width / 2 + 1 && Math.abs(ly) <= pad.shape.height / 2 + 1;
|
|
1869
|
+
}
|
|
1870
|
+
case "custom": {
|
|
1871
|
+
const pts = pad.shape.primitives.flatMap((pr) => pr.kind === "poly" ? pr.points : [
|
|
1872
|
+
{ x: pr.center.x - (pr.kind === "circle" ? pr.radius : 0), y: pr.center.y },
|
|
1873
|
+
{ x: pr.center.x + (pr.kind === "circle" ? pr.radius : 0), y: pr.center.y }
|
|
1874
|
+
]);
|
|
1875
|
+
const b = bbox(pts);
|
|
1876
|
+
return p.x >= b.xMin && p.x <= b.xMax && p.y >= b.yMin && p.y <= b.yMax;
|
|
1877
|
+
}
|
|
1878
|
+
}
|
|
1879
|
+
}
|
|
1880
|
+
function computeNets(tracks, vias, pads, byName, lm) {
|
|
1881
|
+
const trackNets = new Array(tracks.length).fill(0);
|
|
1882
|
+
const viaNets = new Array(vias.length).fill(0);
|
|
1883
|
+
const T = tracks.length;
|
|
1884
|
+
const byPoint = new Map;
|
|
1885
|
+
const add = (p, id) => {
|
|
1886
|
+
const k = posKey(p);
|
|
1887
|
+
const l = byPoint.get(k);
|
|
1888
|
+
if (l)
|
|
1889
|
+
l.push(id);
|
|
1890
|
+
else
|
|
1891
|
+
byPoint.set(k, [id]);
|
|
1892
|
+
};
|
|
1893
|
+
tracks.forEach((t, i) => {
|
|
1894
|
+
add(t.start, i);
|
|
1895
|
+
add(t.end, i);
|
|
1896
|
+
});
|
|
1897
|
+
vias.forEach((v, i) => add(v.at, T + i));
|
|
1898
|
+
const get = (id) => id < T ? trackNets[id] : viaNets[id - T];
|
|
1899
|
+
const set = (id, n) => {
|
|
1900
|
+
if (id < T)
|
|
1901
|
+
trackNets[id] = n;
|
|
1902
|
+
else
|
|
1903
|
+
viaNets[id - T] = n;
|
|
1904
|
+
};
|
|
1905
|
+
const queue = [];
|
|
1906
|
+
const CELL = 2000000;
|
|
1907
|
+
const grid = new Map;
|
|
1908
|
+
for (const pp of pads) {
|
|
1909
|
+
const r = padReach(pp.pad);
|
|
1910
|
+
for (let gx = Math.floor((pp.pad.at.x - r) / CELL);gx <= Math.floor((pp.pad.at.x + r) / CELL); gx++) {
|
|
1911
|
+
for (let gy = Math.floor((pp.pad.at.y - r) / CELL);gy <= Math.floor((pp.pad.at.y + r) / CELL); gy++) {
|
|
1912
|
+
const k = `${gx},${gy}`;
|
|
1913
|
+
const l = grid.get(k);
|
|
1914
|
+
if (l)
|
|
1915
|
+
l.push(pp);
|
|
1916
|
+
else
|
|
1917
|
+
grid.set(k, [pp]);
|
|
1918
|
+
}
|
|
1919
|
+
}
|
|
1920
|
+
}
|
|
1921
|
+
const padAt = (p, layer) => {
|
|
1922
|
+
for (const pp of grid.get(`${Math.floor(p.x / CELL)},${Math.floor(p.y / CELL)}`) ?? []) {
|
|
1923
|
+
if (layer && !pp.copper.includes(layer))
|
|
1924
|
+
continue;
|
|
1925
|
+
if (padContains(pp.pad, p))
|
|
1926
|
+
return pp;
|
|
1927
|
+
}
|
|
1928
|
+
return;
|
|
1929
|
+
};
|
|
1930
|
+
tracks.forEach((t, i) => {
|
|
1931
|
+
const layer = lm.kicad(t.layer);
|
|
1932
|
+
const hit = padAt(t.start, layer) ?? padAt(t.end, layer);
|
|
1933
|
+
if (hit) {
|
|
1934
|
+
trackNets[i] = hit.net.idx;
|
|
1935
|
+
queue.push(i);
|
|
1936
|
+
}
|
|
1937
|
+
});
|
|
1938
|
+
vias.forEach((v, i) => {
|
|
1939
|
+
const named = v.netName ? byName.get(v.netName.toUpperCase()) : undefined;
|
|
1940
|
+
const hit = named ?? padAt(v.at, undefined)?.net;
|
|
1941
|
+
if (hit) {
|
|
1942
|
+
viaNets[i] = hit.idx;
|
|
1943
|
+
queue.push(T + i);
|
|
1944
|
+
}
|
|
1945
|
+
});
|
|
1946
|
+
while (queue.length > 0) {
|
|
1947
|
+
const id = queue.shift();
|
|
1948
|
+
const pts = id < T ? [tracks[id].start, tracks[id].end] : [vias[id - T].at];
|
|
1949
|
+
for (const p of pts) {
|
|
1950
|
+
for (const j of byPoint.get(posKey(p)) ?? []) {
|
|
1951
|
+
if (j !== id && get(j) === 0) {
|
|
1952
|
+
set(j, get(id));
|
|
1953
|
+
queue.push(j);
|
|
1954
|
+
}
|
|
1955
|
+
}
|
|
1956
|
+
}
|
|
1957
|
+
}
|
|
1958
|
+
return { trackNets, viaNets };
|
|
1959
|
+
}
|
|
1960
|
+
function padReach(pad) {
|
|
1961
|
+
switch (pad.shape.kind) {
|
|
1962
|
+
case "circle":
|
|
1963
|
+
return pad.shape.diameter / 2;
|
|
1964
|
+
case "rect":
|
|
1965
|
+
case "roundrect":
|
|
1966
|
+
return Math.hypot(pad.shape.width, pad.shape.height) / 2;
|
|
1967
|
+
case "custom": {
|
|
1968
|
+
let r = 0;
|
|
1969
|
+
for (const pr of pad.shape.primitives) {
|
|
1970
|
+
const pts = pr.kind === "poly" ? pr.points : [pr.center];
|
|
1971
|
+
const extra = pr.kind === "poly" ? 0 : pr.kind === "circle" ? pr.radius : Math.hypot(pr.start.x - pr.center.x, pr.start.y - pr.center.y);
|
|
1972
|
+
for (const p of pts)
|
|
1973
|
+
r = Math.max(r, Math.hypot(p.x - pad.at.x, p.y - pad.at.y) + extra);
|
|
1974
|
+
}
|
|
1975
|
+
return r;
|
|
1976
|
+
}
|
|
1977
|
+
}
|
|
1978
|
+
}
|
|
1979
|
+
function emitTrack(t, netIdx, lm) {
|
|
1980
|
+
const layer = lm.kicad(t.layer);
|
|
1981
|
+
if (!layer || !lm.isCopper(layer))
|
|
1982
|
+
return;
|
|
1983
|
+
return ` (segment (start ${fx(t.start.x)} ${fy(t.start.y)}) (end ${fx(t.end.x)} ${fy(t.end.y)}) (width ${mm(t.thickness)}) (layer ${q(layer)}) (net ${netIdx}) (uuid ${q(uuid())}))`;
|
|
1984
|
+
}
|
|
1985
|
+
function emitVia(v, netIdx) {
|
|
1986
|
+
return ` (via (at ${fx(v.at.x)} ${fy(v.at.y)}) (size ${mm(v.diameter)}) (drill ${mm(v.drillDiameter)}) (layers "F.Cu" "B.Cu") (net ${netIdx}) (uuid ${q(uuid())}))`;
|
|
1987
|
+
}
|
|
1988
|
+
function padCopper(pad, lm) {
|
|
1989
|
+
return pad.side === "both" ? lm.copper : pad.side === "bottom" ? ["B.Cu"] : ["F.Cu"];
|
|
1990
|
+
}
|
|
1991
|
+
function emitPrimitive(pr, at, f) {
|
|
1992
|
+
const o = f.local(at.x, at.y);
|
|
1993
|
+
const rel = (x, y) => {
|
|
1994
|
+
const p = f.local(x, y);
|
|
1995
|
+
return { x: p.x - o.x, y: p.y - o.y };
|
|
1996
|
+
};
|
|
1997
|
+
const xy = (x, y) => {
|
|
1998
|
+
const p = rel(x, y);
|
|
1999
|
+
return `${mm(p.x)} ${mm(p.y)}`;
|
|
2000
|
+
};
|
|
2001
|
+
const lx = (x, y) => mm(rel(x, y).x);
|
|
2002
|
+
const ly = (x, y) => mm(rel(x, y).y);
|
|
2003
|
+
switch (pr.kind) {
|
|
2004
|
+
case "poly":
|
|
2005
|
+
return `(gr_poly (pts ${pr.points.map((p) => `(xy ${xy(p.x, p.y)})`).join(" ")}) (width 0) (fill yes))`;
|
|
2006
|
+
case "circle": {
|
|
2007
|
+
const c = rel(pr.center.x, pr.center.y);
|
|
2008
|
+
return `(gr_circle (center ${mm(c.x)} ${mm(c.y)}) (end ${mm(c.x + pr.radius)} ${mm(c.y)}) (width ${mm(pr.fill ? 0 : pr.width)}) (fill ${pr.fill ? "yes" : "no"}))`;
|
|
2009
|
+
}
|
|
2010
|
+
case "arc": {
|
|
2011
|
+
const r = Math.hypot(pr.start.x - pr.center.x, pr.start.y - pr.center.y);
|
|
2012
|
+
const a0 = Math.atan2(pr.start.y - pr.center.y, pr.start.x - pr.center.x);
|
|
2013
|
+
let sweep = Math.atan2(pr.end.y - pr.center.y, pr.end.x - pr.center.x) - a0;
|
|
2014
|
+
while (sweep <= 0)
|
|
2015
|
+
sweep += 2 * Math.PI;
|
|
2016
|
+
const mid = { x: pr.center.x + r * Math.cos(a0 + sweep / 2), y: pr.center.y + r * Math.sin(a0 + sweep / 2) };
|
|
2017
|
+
return `(gr_arc (start ${lx(pr.start.x, pr.start.y)} ${ly(pr.start.x, pr.start.y)}) (mid ${lx(mid.x, mid.y)} ${ly(mid.x, mid.y)}) (end ${lx(pr.end.x, pr.end.y)} ${ly(pr.end.x, pr.end.y)}) (width ${mm(pr.width)}))`;
|
|
2018
|
+
}
|
|
2019
|
+
}
|
|
2020
|
+
}
|
|
2021
|
+
function hasCopper(pad) {
|
|
2022
|
+
if (pad.drillDiameter > 0)
|
|
2023
|
+
return true;
|
|
2024
|
+
const s = pad.shape;
|
|
2025
|
+
return s.kind === "custom" || (s.kind === "circle" ? s.diameter > 0 : s.width > 0 && s.height > 0);
|
|
2026
|
+
}
|
|
2027
|
+
function emitPad(pad, f, net) {
|
|
2028
|
+
const thru = pad.drillDiameter > 0;
|
|
2029
|
+
const type = thru ? "thru_hole" : "smd";
|
|
2030
|
+
const layers = thru ? `"*.Cu" "*.Mask"` : pad.side === "bottom" ? `"B.Cu" "B.Paste" "B.Mask"` : `"F.Cu" "F.Paste" "F.Mask"`;
|
|
2031
|
+
const drill = thru ? ` (drill ${mm(pad.drillDiameter)})` : "";
|
|
2032
|
+
let shapeTok = "circle";
|
|
2033
|
+
let size = "";
|
|
2034
|
+
let extra = "";
|
|
2035
|
+
switch (pad.shape.kind) {
|
|
2036
|
+
case "circle":
|
|
2037
|
+
size = `${mm(pad.shape.diameter)} ${mm(pad.shape.diameter)}`;
|
|
2038
|
+
break;
|
|
2039
|
+
case "rect":
|
|
2040
|
+
shapeTok = "rect";
|
|
2041
|
+
size = `${mm(pad.shape.width)} ${mm(pad.shape.height)}`;
|
|
2042
|
+
break;
|
|
2043
|
+
case "roundrect": {
|
|
2044
|
+
shapeTok = "roundrect";
|
|
2045
|
+
size = `${mm(pad.shape.width)} ${mm(pad.shape.height)}`;
|
|
2046
|
+
const minDim = Math.min(pad.shape.width, pad.shape.height);
|
|
2047
|
+
const ratio = minDim > 0 ? Math.min(0.5, pad.shape.cornerRadius / minDim) : 0;
|
|
2048
|
+
extra = ` (roundrect_rratio ${ratio.toFixed(6)})`;
|
|
2049
|
+
break;
|
|
2050
|
+
}
|
|
2051
|
+
case "custom": {
|
|
2052
|
+
shapeTok = "custom";
|
|
2053
|
+
const anchor = Math.max(1e4, Math.min(pad.drillDiameter, 1e5));
|
|
2054
|
+
size = `${mm(anchor)} ${mm(anchor)}`;
|
|
2055
|
+
extra = ` (options (clearance outline) (anchor circle)) (primitives ${pad.shape.primitives.map((p) => emitPrimitive(p, pad.at, f)).join(" ")})`;
|
|
2056
|
+
break;
|
|
2057
|
+
}
|
|
2058
|
+
}
|
|
2059
|
+
const rotDeg = pad.shape.kind === "circle" || pad.shape.kind === "custom" ? normDeg(f.angle) : normDeg(deg(pad.rotation));
|
|
2060
|
+
const at = `(at ${f.xy(pad.at.x, pad.at.y)}${rotDeg !== 0 ? ` ${+rotDeg.toFixed(6)}` : ""})`;
|
|
2061
|
+
const netTok = net ? ` (net ${net.idx} ${q(net.name)})` : "";
|
|
2062
|
+
return ` (pad ${q(pad.number)} ${type} ${shapeTok} ${at} (size ${size})${drill} (layers ${layers})${extra}${netTok} (uuid ${q(uuid())}))`;
|
|
2063
|
+
}
|
|
2064
|
+
function footprintFrame(c) {
|
|
2065
|
+
const r = deg(c.rotation);
|
|
2066
|
+
const phi = normDeg(+(c.bottom ? 180 - r : r).toFixed(6));
|
|
2067
|
+
const t = phi * Math.PI / 180;
|
|
2068
|
+
const cos = Math.cos(t);
|
|
2069
|
+
const sin = Math.sin(t);
|
|
2070
|
+
const ox = c.origin.x;
|
|
2071
|
+
const oy = -c.origin.y;
|
|
2072
|
+
const local = (x, y) => {
|
|
2073
|
+
const dx = x - ox;
|
|
2074
|
+
const dy = -y - oy;
|
|
2075
|
+
return { x: dx * cos - dy * sin, y: dx * sin + dy * cos };
|
|
2076
|
+
};
|
|
2077
|
+
const xy = (x, y) => {
|
|
2078
|
+
const p = local(x, y);
|
|
2079
|
+
return `${mm(p.x)} ${mm(p.y)}`;
|
|
2080
|
+
};
|
|
2081
|
+
return { phi, frame: { kind: "fp", indent: "\t\t", xy, local, angle: phi } };
|
|
2082
|
+
}
|
|
2083
|
+
function footprintName(c) {
|
|
2084
|
+
return (c.name || c.value || "UNKNOWN").replace(/[\\/:*?"<>|]+/g, "_");
|
|
2085
|
+
}
|
|
2086
|
+
function emitFootprint(c, resolve, lm, opts) {
|
|
2087
|
+
const cu = c.bottom ? "B.Cu" : "F.Cu";
|
|
2088
|
+
const silk = c.bottom ? "B.SilkS" : "F.SilkS";
|
|
2089
|
+
const fab = c.bottom ? "B.Fab" : "F.Fab";
|
|
2090
|
+
const { phi, frame } = footprintFrame(c);
|
|
2091
|
+
const link = opts.links?.get(c.reference);
|
|
2092
|
+
const lines = [
|
|
2093
|
+
` (footprint ${q(`${opts.footprintLib ?? "ew"}:${footprintName(c)}`)}`,
|
|
2094
|
+
` (layer ${q(cu)})`,
|
|
2095
|
+
...opts.library ? [] : [` (uuid ${q(uuid())})`, ` (at ${fx(c.origin.x)} ${fy(c.origin.y)}${phi ? ` ${+phi.toFixed(6)}` : ""})`],
|
|
2096
|
+
...link ? [` (path ${q(link.path)})`, ` (sheetname ${q(link.sheetname)})`, ` (sheetfile ${q(link.sheetfile)})`] : [],
|
|
2097
|
+
...opts.links && !link ? [` (attr board_only)`] : []
|
|
2098
|
+
];
|
|
2099
|
+
const value = link?.value || c.value;
|
|
2100
|
+
const field = (name, value, tag, fallbackLayer) => {
|
|
2101
|
+
const t = c.texts.find((x) => x.tag === tag);
|
|
2102
|
+
const layer = t && lm.kicadInPart(t.layer, c.bottom) || fallbackLayer;
|
|
2103
|
+
const parts = t ? textParts(t, frame) : { at: `(at 0 0 ${+phi.toFixed(6)})`, effects: `(effects (font (size 1 1) (thickness 0.15))${c.bottom ? " (justify mirror)" : ""})` };
|
|
2104
|
+
const hide = t && !t.visible ? " (hide yes)" : "";
|
|
2105
|
+
return ` (property ${q(name)} ${q(value)} ${parts.at} (layer ${q(layer)})${hide} (uuid ${q(uuid())}) ${parts.effects})`;
|
|
2106
|
+
};
|
|
2107
|
+
lines.push(field("Reference", c.reference, "REFDES", silk));
|
|
2108
|
+
lines.push(field("Value", value, "VALUE", fab));
|
|
2109
|
+
for (const t of c.texts) {
|
|
2110
|
+
if (t.tag === "REFDES" || t.tag === "VALUE" || !t.visible)
|
|
2111
|
+
continue;
|
|
2112
|
+
const layer = lm.kicadInPart(t.layer, c.bottom);
|
|
2113
|
+
if (!layer)
|
|
2114
|
+
continue;
|
|
2115
|
+
const { at, effects } = textParts(t, frame);
|
|
2116
|
+
lines.push(` (fp_text user ${q(t.text)} ${at} (layer ${q(layer)}) (uuid ${q(uuid())}) ${effects})`);
|
|
2117
|
+
}
|
|
2118
|
+
for (const g of c.graphics)
|
|
2119
|
+
lines.push(...emitShape(g, lm.kicadInPart(g.layer, c.bottom), frame));
|
|
2120
|
+
for (const pad of c.pads)
|
|
2121
|
+
if (hasCopper(pad))
|
|
2122
|
+
lines.push(emitPad(pad, frame, resolve(c.reference, pad.number)));
|
|
2123
|
+
lines.push(` )`);
|
|
2124
|
+
return lines.join(`
|
|
2125
|
+
`);
|
|
2126
|
+
}
|
|
2127
|
+
function emitFootprintFor(c, lm, opts = {}) {
|
|
2128
|
+
return emitFootprint(c, () => {
|
|
2129
|
+
return;
|
|
2130
|
+
}, lm, opts);
|
|
2131
|
+
}
|
|
2132
|
+
var mountingHoleName = (drillNm) => `MountingHole_${+(drillNm / NM_PER_MM).toFixed(4)}mm`;
|
|
2133
|
+
function mountingHoleFootprint(drillNm, lib, place) {
|
|
2134
|
+
const d = mm(drillNm);
|
|
2135
|
+
const name = mountingHoleName(drillNm);
|
|
2136
|
+
return [
|
|
2137
|
+
` (footprint ${q(place ? `${lib}:${name}` : name)}`,
|
|
2138
|
+
` (layer "F.Cu")`,
|
|
2139
|
+
...place ? [` (uuid ${q(uuid())})`, ` (at ${fx(place.at.x)} ${fy(place.at.y)})`] : [],
|
|
2140
|
+
` (property "Reference" ${q(place ? `MH${place.n}` : "MH**")} (at 0 0 0) (layer "F.Fab") (hide yes) (uuid ${q(uuid())}) (effects (font (size 1 1) (thickness 0.15))))`,
|
|
2141
|
+
` (property "Value" ${q(name)} (at 0 0 0) (layer "F.Fab") (hide yes) (uuid ${q(uuid())}) (effects (font (size 1 1) (thickness 0.15))))`,
|
|
2142
|
+
` (attr board_only exclude_from_pos_files exclude_from_bom)`,
|
|
2143
|
+
` (pad "" np_thru_hole circle (at 0 0) (size ${d} ${d}) (drill ${d}) (layers "*.Cu" "*.Mask") (uuid ${q(uuid())}))`,
|
|
2144
|
+
` )`
|
|
2145
|
+
].join(`
|
|
2146
|
+
`);
|
|
2147
|
+
}
|
|
2148
|
+
function emitHole(h, n, lib) {
|
|
2149
|
+
if (h.plated) {
|
|
2150
|
+
const size = h.drillDiameter + 500000;
|
|
2151
|
+
return ` (via (at ${fx(h.at.x)} ${fy(h.at.y)}) (size ${mm(size)}) (drill ${mm(h.drillDiameter)}) (layers "F.Cu" "B.Cu") (net 0) (uuid ${q(uuid())}))`;
|
|
2152
|
+
}
|
|
2153
|
+
return mountingHoleFootprint(h.drillDiameter, lib, { at: h.at, n });
|
|
2154
|
+
}
|
|
2155
|
+
function emitKicadPcb(board, opts = {}) {
|
|
2156
|
+
const lm = new LayerMap(board);
|
|
2157
|
+
const layerLines = lm.table.map((l) => l.userName ? ` (${l.id} ${q(l.name)} ${l.type} ${q(l.userName)})` : ` (${l.id} ${q(l.name)} ${l.type})`).join(`
|
|
2158
|
+
`);
|
|
2159
|
+
const { table: netTable, resolve, byName } = buildNets(board.nets);
|
|
2160
|
+
const shapeLines = board.shapes.flatMap((sh) => emitShape(sh, lm.kicad(sh.layer))).join(`
|
|
2161
|
+
`);
|
|
2162
|
+
const planeCount = board.zones.filter((z) => z.kind === "plane").length;
|
|
2163
|
+
let areaIdx = 0;
|
|
2164
|
+
let planeIdx = 0;
|
|
2165
|
+
const zoneLines = board.zones.map((z) => {
|
|
2166
|
+
const priority = z.kind === "plane" ? planeIdx++ : planeCount + areaIdx++;
|
|
2167
|
+
return emitZone(z, lm, byName.get(z.netName.toUpperCase()), priority);
|
|
2168
|
+
}).filter((x) => x !== undefined).join(`
|
|
2169
|
+
`);
|
|
2170
|
+
const textLines = board.texts.map((t) => emitText(t, lm)).filter((x) => x !== undefined).join(`
|
|
2171
|
+
`);
|
|
2172
|
+
const ruleLines = board.ruleAreas.map((r, i) => emitRuleArea(r, i, lm)).join(`
|
|
2173
|
+
`);
|
|
2174
|
+
const footprintLines = board.components.map((c) => emitFootprint(c, resolve, lm, opts)).join(`
|
|
2175
|
+
`);
|
|
2176
|
+
const holeLines = board.holes.map((h, i) => emitHole(h, i + 1, opts.footprintLib ?? "ew")).join(`
|
|
2177
|
+
`);
|
|
2178
|
+
const placed = [];
|
|
2179
|
+
for (const c of board.components) {
|
|
2180
|
+
for (const pad of c.pads) {
|
|
2181
|
+
const net = resolve(c.reference, pad.number);
|
|
2182
|
+
if (net)
|
|
2183
|
+
placed.push({ pad, net, copper: padCopper(pad, lm) });
|
|
2184
|
+
}
|
|
2185
|
+
}
|
|
2186
|
+
const { trackNets, viaNets } = computeNets(board.tracks, board.vias, placed, byName, lm);
|
|
2187
|
+
const trackLines = board.tracks.map((t, i) => emitTrack(t, trackNets[i], lm)).filter((s) => s !== undefined).join(`
|
|
2188
|
+
`);
|
|
2189
|
+
const viaLines = board.vias.map((v, i) => emitVia(v, viaNets[i])).join(`
|
|
2190
|
+
`);
|
|
2191
|
+
const importNote = `Imported from ${board.source.application} ` + `${board.source.versionMajor}.${board.source.versionMinor} via multisim2kicad`;
|
|
2192
|
+
return [
|
|
2193
|
+
`(kicad_pcb`,
|
|
2194
|
+
` (version ${KICAD_VERSION})`,
|
|
2195
|
+
` (generator ${q("multisim2kicad")})`,
|
|
2196
|
+
``,
|
|
2197
|
+
` (general`,
|
|
2198
|
+
` (thickness ${mm(board.stackup.thickness)})`,
|
|
2199
|
+
` )`,
|
|
2200
|
+
``,
|
|
2201
|
+
` (paper ${q("A4")})`,
|
|
2202
|
+
``,
|
|
2203
|
+
` (title_block`,
|
|
2204
|
+
` (title ${q(board.projectName)})`,
|
|
2205
|
+
` (comment 1 ${q(importNote)})`,
|
|
2206
|
+
` )`,
|
|
2207
|
+
``,
|
|
2208
|
+
` (layers`,
|
|
2209
|
+
layerLines,
|
|
2210
|
+
` )`,
|
|
2211
|
+
``,
|
|
2212
|
+
` (setup`,
|
|
2213
|
+
` (pad_to_mask_clearance 0)`,
|
|
2214
|
+
` )`,
|
|
2215
|
+
``,
|
|
2216
|
+
netTable.join(`
|
|
2217
|
+
`),
|
|
2218
|
+
``,
|
|
2219
|
+
footprintLines,
|
|
2220
|
+
``,
|
|
2221
|
+
holeLines,
|
|
2222
|
+
``,
|
|
2223
|
+
shapeLines,
|
|
2224
|
+
``,
|
|
2225
|
+
textLines,
|
|
2226
|
+
``,
|
|
2227
|
+
trackLines,
|
|
2228
|
+
``,
|
|
2229
|
+
viaLines,
|
|
2230
|
+
``,
|
|
2231
|
+
zoneLines,
|
|
2232
|
+
``,
|
|
2233
|
+
ruleLines,
|
|
2234
|
+
``,
|
|
2235
|
+
`)`,
|
|
2236
|
+
``
|
|
2237
|
+
].join(`
|
|
2238
|
+
`);
|
|
2239
|
+
}
|
|
2240
|
+
|
|
2241
|
+
// src/emit/kicad-sch.ts
|
|
2242
|
+
var KICAD_SCH_VERSION = 20250610;
|
|
2243
|
+
var KICAD_SYM_VERSION = 20250610;
|
|
2244
|
+
var MM_PER_UNIT = 0.254;
|
|
2245
|
+
var u = (v) => (v * MM_PER_UNIT).toFixed(4).replace(/\.?0+$/, "") || "0";
|
|
2246
|
+
function q2(s) {
|
|
2247
|
+
return `"${s.replace(/\\/g, "\\\\").replace(/"/g, "\\\"").replace(/\r\n|\r|\n/g, "\\n")}"`;
|
|
2248
|
+
}
|
|
2249
|
+
function uuid2() {
|
|
2250
|
+
return crypto.randomUUID();
|
|
2251
|
+
}
|
|
2252
|
+
var FONT = "(effects (font (size 1.27 1.27)))";
|
|
2253
|
+
var KICAD_ORIENT = [
|
|
2254
|
+
[{ a: 1, b: 0, c: 0, d: 1 }, 0, ""],
|
|
2255
|
+
[{ a: 0, b: -1, c: 1, d: 0 }, 90, ""],
|
|
2256
|
+
[{ a: -1, b: 0, c: 0, d: -1 }, 180, ""],
|
|
2257
|
+
[{ a: 0, b: 1, c: -1, d: 0 }, 270, ""],
|
|
2258
|
+
[{ a: 1, b: 0, c: 0, d: -1 }, 0, "x"],
|
|
2259
|
+
[{ a: 0, b: 1, c: 1, d: 0 }, 90, "x"],
|
|
2260
|
+
[{ a: -1, b: 0, c: 0, d: 1 }, 180, "x"],
|
|
2261
|
+
[{ a: 0, b: -1, c: -1, d: 0 }, 270, "x"]
|
|
2262
|
+
];
|
|
2263
|
+
function kicadOrient(t) {
|
|
2264
|
+
const hit = KICAD_ORIENT.find(([m]) => m.a === t.a && m.b === t.b && m.c === t.c && m.d === t.d);
|
|
2265
|
+
if (!hit)
|
|
2266
|
+
throw new Error(`not a dihedral transform: ${JSON.stringify(t)}`);
|
|
2267
|
+
return { angle: hit[1], mirror: hit[2] };
|
|
2268
|
+
}
|
|
2269
|
+
var applyD2 = (t, p) => ({ x: t.a * p.x + t.c * p.y, y: t.b * p.x + t.d * p.y });
|
|
2270
|
+
var add = (a, b) => ({ x: a.x + b.x, y: a.y + b.y });
|
|
2271
|
+
var sheetPinPos = (s, p) => add(s.at, applyD2(s.transform, p.at));
|
|
2272
|
+
var lib = (p) => `${u(p.x)} ${u(-p.y)}`;
|
|
2273
|
+
var stroke2 = (w) => `(stroke (width ${w > 1 ? u(w * 0.5) : "0"}) (type default))`;
|
|
2274
|
+
var fill = (f) => `(fill (type ${f ? "outline" : "none"}))`;
|
|
2275
|
+
function libGraphic(g) {
|
|
2276
|
+
switch (g.kind) {
|
|
2277
|
+
case "polyline":
|
|
2278
|
+
return ` (polyline (pts ${g.points.map((p) => `(xy ${lib(p)})`).join(" ")}) ${stroke2(g.width)} ${fill(g.fill)})`;
|
|
2279
|
+
case "rect":
|
|
2280
|
+
return ` (rectangle (start ${lib(g.a)}) (end ${lib(g.b)}) ${stroke2(g.width)} ${fill(g.fill)})`;
|
|
2281
|
+
case "circle":
|
|
2282
|
+
return ` (circle (center ${lib(g.center)}) (radius ${u(g.radius)}) ${stroke2(g.width)} ${fill(g.fill)})`;
|
|
2283
|
+
case "arc":
|
|
2284
|
+
return ` (arc (start ${lib(g.start)}) (mid ${lib(g.mid)}) (end ${lib(g.end)}) ${stroke2(g.width)} ${fill(false)})`;
|
|
2285
|
+
case "text":
|
|
2286
|
+
return ` (text ${q2(g.text)} (at ${lib(g.at)} 0) (effects (font (size ${u(g.size)} ${u(g.size)})) (justify left top)))`;
|
|
2287
|
+
}
|
|
2288
|
+
}
|
|
2289
|
+
function pinAngle(dir) {
|
|
2290
|
+
if (dir.x === 0 && dir.y === 0)
|
|
2291
|
+
return 0;
|
|
2292
|
+
const a = Math.atan2(-dir.y, dir.x) * 180 / Math.PI;
|
|
2293
|
+
return (Math.round(a / 90) * 90 % 360 + 360) % 360;
|
|
2294
|
+
}
|
|
2295
|
+
function uniquePins(pins) {
|
|
2296
|
+
const seen = new Set;
|
|
2297
|
+
return pins.filter((p) => p.number && !seen.has(p.number) && seen.add(p.number));
|
|
2298
|
+
}
|
|
2299
|
+
var pinStem = (p) => ({
|
|
2300
|
+
kind: "polyline",
|
|
2301
|
+
points: [p.at, { x: p.at.x + p.dir.x * p.length, y: p.at.y + p.dir.y * p.length }],
|
|
2302
|
+
width: 0,
|
|
2303
|
+
fill: false
|
|
2304
|
+
});
|
|
2305
|
+
var libLines = (gs) => gs.map(libGraphic).filter((x) => !!x);
|
|
2306
|
+
function libParts(s, refs, dropped) {
|
|
2307
|
+
const pins = uniquePins(s.pins).filter((p) => !dropped.has(p.number));
|
|
2308
|
+
const power = s.kind === "power";
|
|
2309
|
+
const pinLine = (p, number) => {
|
|
2310
|
+
const type = power ? "power_in" : p.electrical ?? "passive";
|
|
2311
|
+
const length = power ? 0 : p.length;
|
|
2312
|
+
return ` (pin ${type} line (at ${lib(p.at)} ${pinAngle(p.dir)}) (length ${u(length)})${power ? " (hide yes)" : ""} (name ${q2(p.name || "~")} ${FONT}) (number ${q2(number)} ${FONT}))`;
|
|
2313
|
+
};
|
|
2314
|
+
const stems = (keep) => libLines(s.pins.filter((p) => p.length > 0 && keep(p)).map(pinStem));
|
|
2315
|
+
const head = [
|
|
2316
|
+
power ? ` (power global)` : "",
|
|
2317
|
+
` (pin_numbers${s.showPinNumbers && !power ? "" : " (hide yes)"})`,
|
|
2318
|
+
` (pin_names (offset 0.254)${s.showPinNames && !power ? "" : " (hide yes)"})`,
|
|
2319
|
+
` (exclude_from_sim no)`,
|
|
2320
|
+
` (in_bom ${power ? "no" : "yes"})`,
|
|
2321
|
+
` (on_board ${power ? "no" : "yes"})`,
|
|
2322
|
+
` (duplicate_pin_numbers_are_jumpers no)`,
|
|
2323
|
+
` (property "Reference" ${q2(power ? "#PWR" : refPrefix(s))} (at 0 0 0) ${FONT})`
|
|
2324
|
+
].filter(Boolean);
|
|
2325
|
+
const units = new Map;
|
|
2326
|
+
const drawing = [...libLines(s.graphics), ...stems((p) => power || dropped.has(p.number))];
|
|
2327
|
+
for (const [unit, map] of unitsOf(refs))
|
|
2328
|
+
units.set(unit, [...drawing, ...pins.map((p) => pinLine(p, map?.[p.number] ?? p.number))]);
|
|
2329
|
+
return { value: s.value, head, body: [], units };
|
|
2330
|
+
}
|
|
2331
|
+
function centreSymbol(s) {
|
|
2332
|
+
const pts = s.pins.length ? s.pins.map((p) => p.at) : s.graphics.flatMap(graphicPoints);
|
|
2333
|
+
if (!pts.length)
|
|
2334
|
+
return s;
|
|
2335
|
+
const xs = pts.map((p) => p.x);
|
|
2336
|
+
const ys = pts.map((p) => p.y);
|
|
2337
|
+
const o = { x: Math.round((Math.min(...xs) + Math.max(...xs)) / 2), y: Math.round((Math.min(...ys) + Math.max(...ys)) / 2) };
|
|
2338
|
+
if (o.x === 0 && o.y === 0)
|
|
2339
|
+
return s;
|
|
2340
|
+
const m = (p) => ({ x: p.x - o.x, y: p.y - o.y });
|
|
2341
|
+
const text = (t) => t && { ...t, at: m(t.at) };
|
|
2342
|
+
return {
|
|
2343
|
+
...s,
|
|
2344
|
+
at: add(s.at, applyD2(s.transform, o)),
|
|
2345
|
+
graphics: s.graphics.map((g) => mapGraphic(g, m)),
|
|
2346
|
+
pins: s.pins.map((p) => ({ ...p, at: m(p.at) })),
|
|
2347
|
+
refText: text(s.refText),
|
|
2348
|
+
valueText: text(s.valueText)
|
|
2349
|
+
};
|
|
2350
|
+
}
|
|
2351
|
+
var IDENTITY_D = { a: 1, b: 0, c: 0, d: 1 };
|
|
2352
|
+
var composeD = (t, h) => ({
|
|
2353
|
+
a: t.a * h.a + t.c * h.b,
|
|
2354
|
+
b: t.b * h.a + t.d * h.b,
|
|
2355
|
+
c: t.a * h.c + t.c * h.d,
|
|
2356
|
+
d: t.b * h.c + t.d * h.d
|
|
2357
|
+
});
|
|
2358
|
+
var transposeD = (g) => ({ a: g.a, b: g.c, c: g.b, d: g.d });
|
|
2359
|
+
function reorient(s, g) {
|
|
2360
|
+
if (g.a === 1 && g.d === 1 && !g.b && !g.c)
|
|
2361
|
+
return s;
|
|
2362
|
+
const m = (p) => applyD2(g, p);
|
|
2363
|
+
const text = (t) => t && { ...t, at: m(t.at) };
|
|
2364
|
+
return {
|
|
2365
|
+
...s,
|
|
2366
|
+
transform: composeD(s.transform, transposeD(g)),
|
|
2367
|
+
graphics: s.graphics.map((x) => mapGraphic(x, m)),
|
|
2368
|
+
pins: s.pins.map((p) => ({ ...p, at: m(p.at), dir: m(p.dir) })),
|
|
2369
|
+
refText: text(s.refText),
|
|
2370
|
+
valueText: text(s.valueText)
|
|
2371
|
+
};
|
|
2372
|
+
}
|
|
2373
|
+
function mapGraphic(g, m) {
|
|
2374
|
+
switch (g.kind) {
|
|
2375
|
+
case "polyline":
|
|
2376
|
+
return { ...g, points: g.points.map(m) };
|
|
2377
|
+
case "rect":
|
|
2378
|
+
return { ...g, a: m(g.a), b: m(g.b) };
|
|
2379
|
+
case "circle":
|
|
2380
|
+
return { ...g, center: m(g.center) };
|
|
2381
|
+
case "arc":
|
|
2382
|
+
return { ...g, start: m(g.start), mid: m(g.mid), end: m(g.end) };
|
|
2383
|
+
case "text":
|
|
2384
|
+
return { ...g, at: m(g.at) };
|
|
2385
|
+
}
|
|
2386
|
+
}
|
|
2387
|
+
function graphicPoints(g) {
|
|
2388
|
+
switch (g.kind) {
|
|
2389
|
+
case "polyline":
|
|
2390
|
+
return g.points;
|
|
2391
|
+
case "rect":
|
|
2392
|
+
return [g.a, g.b];
|
|
2393
|
+
case "circle":
|
|
2394
|
+
return [g.center];
|
|
2395
|
+
case "arc":
|
|
2396
|
+
return [g.start, g.mid, g.end];
|
|
2397
|
+
case "text":
|
|
2398
|
+
return [g.at];
|
|
2399
|
+
}
|
|
2400
|
+
}
|
|
2401
|
+
var refPrefix = (s) => /^[A-Za-z_]*/.exec(s.reference)[0] || "U";
|
|
2402
|
+
function renderLibSymbol(e, fullName, indent) {
|
|
2403
|
+
const at = (p) => `(at ${p ? lib(p) : "0 0"} 0)`;
|
|
2404
|
+
const lines = [
|
|
2405
|
+
` (symbol ${q2(fullName)}`,
|
|
2406
|
+
...e.head.map((l) => e.refAt && l.includes(`(property "Reference"`) ? l.replace("(at 0 0 0)", at(e.refAt)) : l),
|
|
2407
|
+
` (property "Value" ${q2(e.value)} ${at(e.valueAt)} ${FONT})`,
|
|
2408
|
+
` (property "Footprint" ${q2(e.footprint ?? "")} (at 0 0 0) (hide yes) ${FONT})`,
|
|
2409
|
+
` (property "Datasheet" "" (at 0 0 0) (hide yes) ${FONT})`,
|
|
2410
|
+
...(e.fields ?? []).map(([k, v]) => ` (property ${q2(k)} ${q2(v)} (at 0 0 0) (hide yes) ${FONT})`),
|
|
2411
|
+
...e.body.length ? [` (symbol ${q2(`${e.name}_0_1`)}`, ...e.body, ` )`] : [],
|
|
2412
|
+
...[...e.units].sort((a, b) => a[0] - b[0]).flatMap(([unit, pins]) => [` (symbol ${q2(`${e.name}_${unit}_1`)}`, ...pins, ` )`]),
|
|
2413
|
+
` (embedded_fonts no)`,
|
|
2414
|
+
` )`
|
|
2415
|
+
];
|
|
2416
|
+
return indent === 2 ? lines.join(`
|
|
2417
|
+
`) : lines.map((l) => l.slice(1)).join(`
|
|
2418
|
+
`);
|
|
2419
|
+
}
|
|
2420
|
+
function librarySymbolsFile(specs) {
|
|
2421
|
+
const entries = specs.map((spec) => {
|
|
2422
|
+
const units = new Map;
|
|
2423
|
+
let head = [];
|
|
2424
|
+
let box;
|
|
2425
|
+
spec.units.forEach((unit, i) => {
|
|
2426
|
+
const stems = unit.stems ?? [];
|
|
2427
|
+
const centred = centreSymbol({
|
|
2428
|
+
reference: spec.reference,
|
|
2429
|
+
value: spec.value,
|
|
2430
|
+
kind: "part",
|
|
2431
|
+
at: { x: 0, y: 0 },
|
|
2432
|
+
transform: IDENTITY_D,
|
|
2433
|
+
graphics: [...unit.graphics, ...stems.filter((p) => p.length > 0).map(pinStem)],
|
|
2434
|
+
pins: unit.pins,
|
|
2435
|
+
showPinNames: spec.showPinNames,
|
|
2436
|
+
showPinNumbers: spec.showPinNumbers
|
|
2437
|
+
});
|
|
2438
|
+
if (i === 0) {
|
|
2439
|
+
const pts = [...centred.graphics.flatMap(graphicPoints), ...centred.pins.map((p) => p.at)];
|
|
2440
|
+
if (pts.length)
|
|
2441
|
+
box = { x0: Math.min(...pts.map((p) => p.x)), y0: Math.min(...pts.map((p) => p.y)), x1: Math.max(...pts.map((p) => p.x)), y1: Math.max(...pts.map((p) => p.y)) };
|
|
2442
|
+
}
|
|
2443
|
+
const parts = libParts(centred, [{ path: "", reference: spec.reference, unit: i + 1 }], new Set);
|
|
2444
|
+
head = parts.head;
|
|
2445
|
+
for (const [u, lines] of parts.units)
|
|
2446
|
+
units.set(u, lines);
|
|
2447
|
+
});
|
|
2448
|
+
const cx = box ? Math.round((box.x0 + box.x1) / 2) : 0;
|
|
2449
|
+
return {
|
|
2450
|
+
name: spec.name,
|
|
2451
|
+
key: spec.name,
|
|
2452
|
+
value: spec.value,
|
|
2453
|
+
head,
|
|
2454
|
+
body: [],
|
|
2455
|
+
units,
|
|
2456
|
+
footprint: spec.footprint,
|
|
2457
|
+
fields: spec.fields,
|
|
2458
|
+
refAt: box && { x: cx, y: box.y0 - 4 },
|
|
2459
|
+
valueAt: box && { x: cx, y: box.y1 + 4 }
|
|
2460
|
+
};
|
|
2461
|
+
});
|
|
2462
|
+
return libraryFileText(entries);
|
|
2463
|
+
}
|
|
2464
|
+
var libraryFileText = (entries) => [
|
|
2465
|
+
`(kicad_symbol_lib`,
|
|
2466
|
+
` (version ${KICAD_SYM_VERSION})`,
|
|
2467
|
+
` (generator "multisim2kicad")`,
|
|
2468
|
+
` (generator_version "0.1")`,
|
|
2469
|
+
...[...entries].sort((a, b) => a.name.localeCompare(b.name)).map((e) => renderLibSymbol(e, e.name, 1)),
|
|
2470
|
+
`)`,
|
|
2471
|
+
``
|
|
2472
|
+
].join(`
|
|
2473
|
+
`);
|
|
2474
|
+
|
|
2475
|
+
class SymbolLibrary {
|
|
2476
|
+
entries = [];
|
|
2477
|
+
names = new Set;
|
|
2478
|
+
add(s, refs, dropped) {
|
|
2479
|
+
const base = (s.kind === "power" ? `PWR_${s.value}` : s.partName || refPrefix(s)).replace(/[^A-Za-z0-9_.+-]+/g, "_") || "U";
|
|
2480
|
+
const keyOf = (parts) => JSON.stringify([base, parts.head, parts.body, s.kind === "power" ? s.value : ""]);
|
|
2481
|
+
const fits = (e, key, parts) => e.key === key && [...parts.units].every(([u, pins]) => !e.units.has(u) || e.units.get(u).join(`
|
|
2482
|
+
`) === pins.join(`
|
|
2483
|
+
`));
|
|
2484
|
+
const turns = s.graphics.some((g) => g.kind === "text") ? [IDENTITY_D] : KICAD_ORIENT.map(([m]) => m);
|
|
2485
|
+
for (const g of turns) {
|
|
2486
|
+
const t = centreSymbol(reorient(s, g));
|
|
2487
|
+
const parts = libParts(t, refs, dropped);
|
|
2488
|
+
const key = keyOf(parts);
|
|
2489
|
+
const found = this.entries.find((e) => fits(e, key, parts));
|
|
2490
|
+
if (found) {
|
|
2491
|
+
for (const [u, pins] of parts.units)
|
|
2492
|
+
if (!found.units.has(u))
|
|
2493
|
+
found.units.set(u, pins);
|
|
2494
|
+
return { entry: found, symbol: t };
|
|
2495
|
+
}
|
|
2496
|
+
}
|
|
2497
|
+
const parts = libParts(s, refs, dropped);
|
|
2498
|
+
const key = keyOf(parts);
|
|
2499
|
+
let name = base;
|
|
2500
|
+
for (let n = 2;this.names.has(name.toLowerCase()); n++)
|
|
2501
|
+
name = `${base}_${n}`;
|
|
2502
|
+
this.names.add(name.toLowerCase());
|
|
2503
|
+
const e = { ...parts, name, key };
|
|
2504
|
+
this.entries.push(e);
|
|
2505
|
+
return { entry: e, symbol: s };
|
|
2506
|
+
}
|
|
2507
|
+
file() {
|
|
2508
|
+
return libraryFileText(this.entries);
|
|
2509
|
+
}
|
|
2510
|
+
}
|
|
2511
|
+
function property(name, value, at, hide) {
|
|
2512
|
+
return ` (property ${q2(name)} ${q2(value)} (at ${u(at.x)} ${u(at.y)} 0)${hide ? " (hide yes)" : ""} (effects (font (size 1.27 1.27)) (justify left)))`;
|
|
2513
|
+
}
|
|
2514
|
+
function unitsOf(refs) {
|
|
2515
|
+
const m = new Map;
|
|
2516
|
+
for (const r of refs)
|
|
2517
|
+
if (!m.has(r.unit) || !m.get(r.unit) && r.pinMap)
|
|
2518
|
+
m.set(r.unit, r.pinMap);
|
|
2519
|
+
if (m.size === 0)
|
|
2520
|
+
m.set(1, undefined);
|
|
2521
|
+
return m;
|
|
2522
|
+
}
|
|
2523
|
+
function emitInstance(sym, libName, uuidStr, refs, projectName, dropped = new Set, footprint = "") {
|
|
2524
|
+
const s = sym.floating ? { ...sym, at: { x: sym.at.x + NUDGE, y: sym.at.y + NUDGE } } : sym;
|
|
2525
|
+
const reference = refs[0]?.reference ?? s.reference;
|
|
2526
|
+
const { angle, mirror } = kicadOrient(s.transform);
|
|
2527
|
+
const textAt = (t, dflt) => t ? add(s.at, applyD2(s.transform, t.at)) : dflt;
|
|
2528
|
+
const refAt = textAt(s.refText, s.at);
|
|
2529
|
+
const valAt = textAt(s.valueText, s.at);
|
|
2530
|
+
const power = s.kind === "power";
|
|
2531
|
+
return [
|
|
2532
|
+
` (symbol`,
|
|
2533
|
+
` (lib_id ${q2(libName)})`,
|
|
2534
|
+
` (at ${u(s.at.x)} ${u(s.at.y)} ${angle})${mirror ? ` (mirror ${mirror})` : ""}`,
|
|
2535
|
+
` (unit ${refs[0]?.unit ?? 1})`,
|
|
2536
|
+
` (exclude_from_sim no)`,
|
|
2537
|
+
` (in_bom ${power ? "no" : "yes"})`,
|
|
2538
|
+
` (on_board ${power ? "no" : "yes"})`,
|
|
2539
|
+
` (dnp no)`,
|
|
2540
|
+
` (uuid ${q2(uuidStr)})`,
|
|
2541
|
+
property("Reference", reference, refAt, power || !!s.refText?.hidden),
|
|
2542
|
+
property("Value", s.value, valAt, !power && !!s.valueText?.hidden),
|
|
2543
|
+
property("Footprint", footprint, s.at, true),
|
|
2544
|
+
property("Datasheet", "", s.at, true),
|
|
2545
|
+
...[...new Set(uniquePins(s.pins).filter((p) => !dropped.has(p.number)).flatMap((p) => [...unitsOf(refs).values()].map((m) => m?.[p.number] ?? p.number)))].map((n) => ` (pin ${q2(n)} (uuid ${q2(uuid2())}))`),
|
|
2546
|
+
` (instances (project ${q2(projectName)} ${refs.map((r) => `(path ${q2(r.path)} (reference ${q2(r.reference)}) (unit ${r.unit}))`).join(" ")}))`,
|
|
2547
|
+
` )`
|
|
2548
|
+
].join(`
|
|
2549
|
+
`);
|
|
2550
|
+
}
|
|
2551
|
+
var key = (p) => `${p.x},${p.y}`;
|
|
2552
|
+
function emitWire(a, b) {
|
|
2553
|
+
return ` (wire (pts (xy ${u(a.x)} ${u(a.y)}) (xy ${u(b.x)} ${u(b.y)})) (stroke (width 0) (type default)) (uuid ${q2(uuid2())}))`;
|
|
2554
|
+
}
|
|
2555
|
+
function labelAngle(dir) {
|
|
2556
|
+
if (dir.x < 0)
|
|
2557
|
+
return 180;
|
|
2558
|
+
if (dir.y < 0)
|
|
2559
|
+
return 90;
|
|
2560
|
+
if (dir.y > 0)
|
|
2561
|
+
return 270;
|
|
2562
|
+
return 0;
|
|
2563
|
+
}
|
|
2564
|
+
function emitBus(bus) {
|
|
2565
|
+
const out = [];
|
|
2566
|
+
for (let i = 0;i + 1 < bus.points.length; i++) {
|
|
2567
|
+
const [a, b] = [bus.points[i], bus.points[i + 1]];
|
|
2568
|
+
if (a.x === b.x && a.y === b.y)
|
|
2569
|
+
continue;
|
|
2570
|
+
out.push(` (bus (pts (xy ${u(a.x)} ${u(a.y)}) (xy ${u(b.x)} ${u(b.y)})) (stroke (width 0) (type default)) (uuid ${q2(uuid2())}))`);
|
|
2571
|
+
}
|
|
2572
|
+
const members = [...new Set(bus.members)];
|
|
2573
|
+
if (members.length && members.every((m) => /^[^\s{}\[\]]+$/.test(m))) {
|
|
2574
|
+
const at = bus.points[0];
|
|
2575
|
+
out.push(` (label ${q2(`{${members.join(" ")}}`)} (at ${u(at.x)} ${u(at.y)} 0) (effects (font (size 1.27 1.27)) (justify left bottom)) (uuid ${q2(uuid2())}))`);
|
|
2576
|
+
}
|
|
2577
|
+
return out;
|
|
2578
|
+
}
|
|
2579
|
+
function emitBusEntry(e) {
|
|
2580
|
+
return ` (bus_entry (at ${u(e.wire.x)} ${u(e.wire.y)}) (size ${u(e.bus.x - e.wire.x)} ${u(e.bus.y - e.wire.y)}) (stroke (width 0) (type default)) (uuid ${q2(uuid2())}))`;
|
|
2581
|
+
}
|
|
2582
|
+
var NUDGE = 0.5;
|
|
2583
|
+
function emitLabel(label) {
|
|
2584
|
+
const l = label.floating ? { ...label, at: { x: label.at.x + NUDGE, y: label.at.y + NUDGE } } : label;
|
|
2585
|
+
const angle = labelAngle(l.dir);
|
|
2586
|
+
const justify = angle === 180 || angle === 270 ? "right" : "left";
|
|
2587
|
+
if (l.kind === "hierarchical") {
|
|
2588
|
+
return ` (hierarchical_label ${q2(l.name)} (shape bidirectional) (at ${u(l.at.x)} ${u(l.at.y)} ${angle}) (effects (font (size 1.27 1.27)) (justify ${justify})) (uuid ${q2(uuid2())}))`;
|
|
2589
|
+
}
|
|
2590
|
+
if (l.kind === "global") {
|
|
2591
|
+
return ` (global_label ${q2(l.name)} (shape bidirectional) (at ${u(l.at.x)} ${u(l.at.y)} ${angle}) (fields_autoplaced yes) (effects (font (size 1.27 1.27)) (justify ${justify})) (uuid ${q2(uuid2())}) (property "Intersheetrefs" "\${INTERSHEET_REFS}" (at ${u(l.at.x)} ${u(l.at.y)} 0) (hide yes) (effects (font (size 1.27 1.27)))))`;
|
|
2592
|
+
}
|
|
2593
|
+
return ` (label ${q2(l.name)} (at ${u(l.at.x)} ${u(l.at.y)} ${angle}) (effects (font (size 1.27 1.27)) (justify ${justify} bottom)) (uuid ${q2(uuid2())}))`;
|
|
2594
|
+
}
|
|
2595
|
+
function junctions(segments, pinPoints) {
|
|
2596
|
+
const ends = new Map;
|
|
2597
|
+
const bump = (p, net, n = 1) => {
|
|
2598
|
+
const k = key(p);
|
|
2599
|
+
const e = ends.get(k);
|
|
2600
|
+
if (e) {
|
|
2601
|
+
e.n += n;
|
|
2602
|
+
e.nets.add(net);
|
|
2603
|
+
} else
|
|
2604
|
+
ends.set(k, { p, n, nets: new Set([net]) });
|
|
2605
|
+
};
|
|
2606
|
+
for (const [a, b, net] of segments) {
|
|
2607
|
+
bump(a, net);
|
|
2608
|
+
bump(b, net);
|
|
2609
|
+
}
|
|
2610
|
+
for (const [p, net] of pinPoints)
|
|
2611
|
+
if (ends.has(key(p)))
|
|
2612
|
+
bump(p, net);
|
|
2613
|
+
for (const e of ends.values()) {
|
|
2614
|
+
for (const [a, b, net] of segments) {
|
|
2615
|
+
if (onInterior(e.p, a, b)) {
|
|
2616
|
+
e.n += 2;
|
|
2617
|
+
e.nets.add(net);
|
|
2618
|
+
}
|
|
2619
|
+
}
|
|
2620
|
+
}
|
|
2621
|
+
const sameNet = (nets) => {
|
|
2622
|
+
const known = [...nets].filter((n) => n !== undefined);
|
|
2623
|
+
return new Set(known).size <= 1;
|
|
2624
|
+
};
|
|
2625
|
+
return [...ends.values()].filter((e) => e.n >= 3 && sameNet(e.nets)).map((e) => e.p);
|
|
2626
|
+
}
|
|
2627
|
+
function onInterior(p, a, b) {
|
|
2628
|
+
if (p.x === a.x && p.y === a.y || p.x === b.x && p.y === b.y)
|
|
2629
|
+
return false;
|
|
2630
|
+
const cross = (b.x - a.x) * (p.y - a.y) - (b.y - a.y) * (p.x - a.x);
|
|
2631
|
+
if (Math.abs(cross) > 0.000001)
|
|
2632
|
+
return false;
|
|
2633
|
+
return Math.min(a.x, b.x) <= p.x && p.x <= Math.max(a.x, b.x) && Math.min(a.y, b.y) <= p.y && p.y <= Math.max(a.y, b.y);
|
|
2634
|
+
}
|
|
2635
|
+
var slug = (s) => s.replace(/[^A-Za-z0-9_.+-]+/g, "_").replace(/^_+|_+$/g, "") || "sheet";
|
|
2636
|
+
function emitSheetSymbol(sub, at, size, pins, projectName) {
|
|
2637
|
+
return [
|
|
2638
|
+
` (sheet (at ${u(at.x)} ${u(at.y)}) (size ${u(size.w)} ${u(size.h)}) (exclude_from_sim no) (in_bom yes) (on_board yes) (dnp no)`,
|
|
2639
|
+
` (stroke (width 0.1524) (type solid)) (fill (color 0 0 0 0.0000)) (uuid ${q2(sub.uuid)})`,
|
|
2640
|
+
` (property "Sheetname" ${q2(sub.name)} (at ${u(at.x)} ${u(at.y - 2)} 0) (effects (font (size 1.27 1.27)) (justify left bottom)))`,
|
|
2641
|
+
` (property "Sheetfile" ${q2(sub.file)} (at ${u(at.x)} ${u(at.y + size.h + 2)} 0) (hide yes) (effects (font (size 1.27 1.27)) (justify left top)))`,
|
|
2642
|
+
...pins.map((p) => ` (pin ${q2(p.name)} bidirectional (at ${u(p.at.x)} ${u(p.at.y)} ${p.angle}) (uuid ${q2(uuid2())}) (effects (font (size 1.27 1.27)) (justify ${p.angle === 180 ? "left" : p.angle === 0 ? "right" : "left"})))`),
|
|
2643
|
+
` (instances (project ${q2(projectName)} ${sub.refs.map((r) => `(path ${q2(r.path)} (page ${q2(String(r.page))}))`).join(" ")}))`,
|
|
2644
|
+
` )`
|
|
2645
|
+
].join(`
|
|
2646
|
+
`);
|
|
2647
|
+
}
|
|
2648
|
+
function blockGeometry(b) {
|
|
2649
|
+
const w = Math.max(b.b.x - b.a.x, 9);
|
|
2650
|
+
const h = Math.max(b.b.y - b.a.y, 9);
|
|
2651
|
+
const stubs = [];
|
|
2652
|
+
const pins = b.pins.map((p) => {
|
|
2653
|
+
const d = [
|
|
2654
|
+
{ side: 180, dist: Math.abs(p.at.x - b.a.x), at: { x: b.a.x, y: p.at.y } },
|
|
2655
|
+
{ side: 0, dist: Math.abs(p.at.x - (b.a.x + w)), at: { x: b.a.x + w, y: p.at.y } },
|
|
2656
|
+
{ side: 90, dist: Math.abs(p.at.y - b.a.y), at: { x: p.at.x, y: b.a.y } },
|
|
2657
|
+
{ side: 270, dist: Math.abs(p.at.y - (b.a.y + h)), at: { x: p.at.x, y: b.a.y + h } }
|
|
2658
|
+
].sort((x, y) => x.dist - y.dist)[0];
|
|
2659
|
+
if (d.dist > 0)
|
|
2660
|
+
stubs.push([p.at, d.at]);
|
|
2661
|
+
if (p.attach)
|
|
2662
|
+
stubs.push([p.attach, p.at]);
|
|
2663
|
+
return { name: p.name, at: d.at, angle: d.side };
|
|
2664
|
+
});
|
|
2665
|
+
return { at: b.a, size: { w, h }, pins, stubs };
|
|
2666
|
+
}
|
|
2667
|
+
function resolveContacts(symbolsIn, segmentsIn, labelsIn) {
|
|
2668
|
+
const at = new Map;
|
|
2669
|
+
const put = (p, it) => {
|
|
2670
|
+
const k = key(p);
|
|
2671
|
+
at.set(k, [...at.get(k) ?? [], it]);
|
|
2672
|
+
};
|
|
2673
|
+
symbolsIn.forEach((s, i) => {
|
|
2674
|
+
for (const p of s.pins)
|
|
2675
|
+
put(p.attach ?? sheetPinPos(s, p), { net: p.netId, sym: i });
|
|
2676
|
+
});
|
|
2677
|
+
for (const [a, b, net] of segmentsIn) {
|
|
2678
|
+
put(a, { net });
|
|
2679
|
+
put(b, { net });
|
|
2680
|
+
}
|
|
2681
|
+
for (const l of labelsIn)
|
|
2682
|
+
if (!l.floating)
|
|
2683
|
+
put(l.at, { net: l.netId });
|
|
2684
|
+
const keeper = new Map;
|
|
2685
|
+
const rendezvous = new Map;
|
|
2686
|
+
for (const [k, items] of at) {
|
|
2687
|
+
const nets = [...new Set(items.map((i) => i.net).filter((n) => n !== undefined))];
|
|
2688
|
+
if (nets.length < 2)
|
|
2689
|
+
continue;
|
|
2690
|
+
const firstPin = items.find((i) => i.sym !== undefined && i.net !== undefined);
|
|
2691
|
+
const counts = new Map;
|
|
2692
|
+
for (const i of items)
|
|
2693
|
+
if (i.net !== undefined)
|
|
2694
|
+
counts.set(i.net, (counts.get(i.net) ?? 0) + 1);
|
|
2695
|
+
const keep = firstPin?.net ?? [...counts].sort((x, y) => y[1] - x[1])[0][0];
|
|
2696
|
+
keeper.set(k, keep);
|
|
2697
|
+
const [x, y] = k.split(",").map(Number);
|
|
2698
|
+
nets.filter((n) => n !== keep).forEach((n, j) => rendezvous.set(`${k}|${n}`, { x: x - NUDGE, y: y - NUDGE - j }));
|
|
2699
|
+
}
|
|
2700
|
+
if (keeper.size === 0)
|
|
2701
|
+
return { symbols: symbolsIn, segments: segmentsIn, labels: labelsIn };
|
|
2702
|
+
const relocate = (p, net) => {
|
|
2703
|
+
const k = key(p);
|
|
2704
|
+
const keep = keeper.get(k);
|
|
2705
|
+
if (keep === undefined || net === undefined || net === keep)
|
|
2706
|
+
return p;
|
|
2707
|
+
return rendezvous.get(`${k}|${net}`) ?? p;
|
|
2708
|
+
};
|
|
2709
|
+
const move = new Map;
|
|
2710
|
+
symbolsIn.forEach((s, i) => {
|
|
2711
|
+
const conflicted = s.pins.some((p) => {
|
|
2712
|
+
const keep = keeper.get(key(p.attach ?? sheetPinPos(s, p)));
|
|
2713
|
+
return keep !== undefined && p.netId !== undefined && p.netId !== keep;
|
|
2714
|
+
});
|
|
2715
|
+
if (conflicted)
|
|
2716
|
+
move.set(i, { x: NUDGE, y: NUDGE + move.size });
|
|
2717
|
+
});
|
|
2718
|
+
const segments = segmentsIn.map(([a, b, net]) => [relocate(a, net), relocate(b, net), net]);
|
|
2719
|
+
const symbols = symbolsIn.map((s, i) => {
|
|
2720
|
+
const d = move.get(i);
|
|
2721
|
+
if (!d)
|
|
2722
|
+
return s;
|
|
2723
|
+
const moved = { ...s, at: { x: s.at.x + d.x, y: s.at.y + d.y }, pins: s.pins.map((p) => ({ ...p, attach: undefined })) };
|
|
2724
|
+
s.pins.forEach((p, j) => {
|
|
2725
|
+
const orig = p.attach ?? sheetPinPos(s, p);
|
|
2726
|
+
const others = (at.get(key(orig)) ?? []).filter((it) => it.sym !== i && it.net === p.netId);
|
|
2727
|
+
if (others.length === 0 && !p.attach)
|
|
2728
|
+
return;
|
|
2729
|
+
segments.push([sheetPinPos(moved, moved.pins[j]), relocate(orig, p.netId), p.netId]);
|
|
2730
|
+
});
|
|
2731
|
+
return moved;
|
|
2732
|
+
});
|
|
2733
|
+
const labels = labelsIn.map((l) => l.floating ? l : { ...l, at: relocate(l.at, l.netId) });
|
|
2734
|
+
return { symbols, segments, labels };
|
|
2735
|
+
}
|
|
2736
|
+
function renderPage(f, sch, isRoot, footprints) {
|
|
2737
|
+
const importNote = `Imported from ${sch.source.application} ${sch.source.versionMajor}.${sch.source.versionMinor} via multisim2kicad`;
|
|
2738
|
+
const rawSegments = [];
|
|
2739
|
+
for (const w of f.sheet.wires)
|
|
2740
|
+
for (let i = 0;i + 1 < w.points.length; i++)
|
|
2741
|
+
rawSegments.push([w.points[i], w.points[i + 1], w.netId]);
|
|
2742
|
+
const resolved = resolveContacts(f.sheet.symbols, rawSegments, f.sheet.labels);
|
|
2743
|
+
const sheet = { ...f.sheet, symbols: resolved.symbols };
|
|
2744
|
+
const segments = [...resolved.segments];
|
|
2745
|
+
for (const s of sheet.symbols)
|
|
2746
|
+
for (const p of s.pins)
|
|
2747
|
+
if (p.attach)
|
|
2748
|
+
segments.push([p.attach, sheetPinPos(s, p), p.netId]);
|
|
2749
|
+
const sheetSymbols = [];
|
|
2750
|
+
const blockPinPoints = [];
|
|
2751
|
+
let stackY = 20;
|
|
2752
|
+
for (const sub of f.sub) {
|
|
2753
|
+
if (sub.block) {
|
|
2754
|
+
const g = blockGeometry(sub.block);
|
|
2755
|
+
segments.push(...g.stubs);
|
|
2756
|
+
blockPinPoints.push(...g.pins.map((p) => [p.at, undefined]));
|
|
2757
|
+
sheetSymbols.push(emitSheetSymbol(sub, g.at, g.size, g.pins, sch.projectName));
|
|
2758
|
+
} else {
|
|
2759
|
+
sheetSymbols.push(emitSheetSymbol(sub, { x: sheet.size.width + 40, y: stackY }, { w: 100, h: 30 }, [], sch.projectName));
|
|
2760
|
+
stackY += 50;
|
|
2761
|
+
}
|
|
2762
|
+
}
|
|
2763
|
+
const pinPoints = [
|
|
2764
|
+
...sheet.symbols.flatMap((s) => s.pins.map((p) => [sheetPinPos(s, p), p.netId])),
|
|
2765
|
+
...blockPinPoints
|
|
2766
|
+
];
|
|
2767
|
+
const labels = resolved.labels;
|
|
2768
|
+
return [
|
|
2769
|
+
`(kicad_sch`,
|
|
2770
|
+
` (version ${KICAD_SCH_VERSION})`,
|
|
2771
|
+
` (generator "multisim2kicad")`,
|
|
2772
|
+
` (generator_version "0.1")`,
|
|
2773
|
+
` (uuid ${q2(f.uuid)})`,
|
|
2774
|
+
` (paper "User" ${u(sheet.size.width)} ${u(sheet.size.height)})`,
|
|
2775
|
+
` (title_block`,
|
|
2776
|
+
` (title ${q2(sheet.page && sheet.page !== "1" ? `${sheet.title} — ${sheet.page}` : sheet.title || sch.projectName)})`,
|
|
2777
|
+
` (comment 1 ${q2(importNote)})`,
|
|
2778
|
+
` )`,
|
|
2779
|
+
` (lib_symbols`,
|
|
2780
|
+
...[...new Set(f.libEntries)].map((e) => renderLibSymbol(e, f.libNames[f.libEntries.indexOf(e)], 2)),
|
|
2781
|
+
` )`,
|
|
2782
|
+
...junctions(segments, pinPoints).map((p) => ` (junction (at ${u(p.x)} ${u(p.y)}) (diameter 0) (color 0 0 0 0) (uuid ${q2(uuid2())}))`),
|
|
2783
|
+
...segments.filter(([a, b]) => a.x !== b.x || a.y !== b.y).map(([a, b]) => emitWire(a, b)),
|
|
2784
|
+
...labels.map(emitLabel),
|
|
2785
|
+
...sheet.buses.flatMap(emitBus),
|
|
2786
|
+
...sheet.busEntries.map(emitBusEntry),
|
|
2787
|
+
...sheet.texts.map((t) => ` (text ${q2(t.text)} (exclude_from_sim no) (at ${u(t.at.x)} ${u(t.at.y)} 0) (effects (font (size ${u(t.size)} ${u(t.size)})) (justify left top)) (uuid ${q2(uuid2())}))`),
|
|
2788
|
+
...sheet.symbols.map((s, i) => emitInstance(s, f.libNames[i], f.symbolUuids[i], f.symbolRefs[i], sch.projectName, f.droppedPins[i], footprints?.get(f.symbolRefs[i][0]?.reference ?? ""))),
|
|
2789
|
+
...sheetSymbols,
|
|
2790
|
+
...isRoot ? [` (sheet_instances (path "/" (page "1")))`] : [],
|
|
2791
|
+
` (embedded_fonts no)`,
|
|
2792
|
+
`)`,
|
|
2793
|
+
``
|
|
2794
|
+
].join(`
|
|
2795
|
+
`);
|
|
2796
|
+
}
|
|
2797
|
+
function emitKicadSchProject(source, baseName, opts = {}) {
|
|
2798
|
+
const libNick = opts.library ?? "ew";
|
|
2799
|
+
const sch = { ...source, sheets: source.sheets.map((sh) => ({ ...sh, symbols: sh.symbols.map(centreSymbol) })) };
|
|
2800
|
+
const pagesOf = (title) => sch.sheets.filter((s) => s.title === title);
|
|
2801
|
+
const rootPages = pagesOf(sch.rootSheet);
|
|
2802
|
+
const rootFirst = rootPages[0] ?? sch.sheets[0];
|
|
2803
|
+
if (!rootFirst)
|
|
2804
|
+
throw new Error("schematic has no sheets");
|
|
2805
|
+
const files = new Map;
|
|
2806
|
+
const usedNames = new Set;
|
|
2807
|
+
for (const sheet of sch.sheets) {
|
|
2808
|
+
let fileName = sheet === rootFirst ? `${baseName}.kicad_sch` : `${baseName}-${slug(sheet.title)}${pagesOf(sheet.title).length > 1 ? `-${slug(sheet.page)}` : ""}.kicad_sch`;
|
|
2809
|
+
while (usedNames.has(fileName))
|
|
2810
|
+
fileName = fileName.replace(/\.kicad_sch$/, "_.kicad_sch");
|
|
2811
|
+
usedNames.add(fileName);
|
|
2812
|
+
files.set(sheet, {
|
|
2813
|
+
sheet,
|
|
2814
|
+
fileName,
|
|
2815
|
+
uuid: uuid2(),
|
|
2816
|
+
symbolUuids: sheet.symbols.map(() => uuid2()),
|
|
2817
|
+
libNames: [],
|
|
2818
|
+
libEntries: [],
|
|
2819
|
+
symbolRefs: sheet.symbols.map(() => []),
|
|
2820
|
+
droppedPins: sheet.symbols.map(() => new Set),
|
|
2821
|
+
sub: []
|
|
2822
|
+
});
|
|
2823
|
+
}
|
|
2824
|
+
for (const sheet of sch.sheets) {
|
|
2825
|
+
const f = files.get(sheet);
|
|
2826
|
+
const pages = pagesOf(sheet.title);
|
|
2827
|
+
if (pages[0] === sheet) {
|
|
2828
|
+
for (const other of pages.slice(1)) {
|
|
2829
|
+
f.sub.push({ key: `page:${other.page}`, uuid: uuid2(), name: other.page, file: files.get(other).fileName, refs: [] });
|
|
2830
|
+
}
|
|
2831
|
+
}
|
|
2832
|
+
for (const b of sheet.blocks) {
|
|
2833
|
+
const child = pagesOf(b.childSheet)[0];
|
|
2834
|
+
if (!child)
|
|
2835
|
+
continue;
|
|
2836
|
+
f.sub.push({ key: `block:${b.id}`, uuid: uuid2(), name: b.childSheet, file: files.get(child).fileName, block: b, refs: [] });
|
|
2837
|
+
}
|
|
2838
|
+
}
|
|
2839
|
+
let pageNo = 0;
|
|
2840
|
+
let pwr = 0;
|
|
2841
|
+
const placements = [];
|
|
2842
|
+
const visit = (inst, sheet, path, chain = []) => {
|
|
2843
|
+
const f = files.get(sheet);
|
|
2844
|
+
const myPage = ++pageNo;
|
|
2845
|
+
const seen = new Map;
|
|
2846
|
+
sheet.symbols.forEach((s, i) => {
|
|
2847
|
+
let ref;
|
|
2848
|
+
if (s.kind === "power")
|
|
2849
|
+
ref = `#PWR${String(++pwr).padStart(3, "0")}`;
|
|
2850
|
+
else {
|
|
2851
|
+
ref = s.drawnKey && inst.refdes[`${sheet.page}|${s.drawnKey}`] || s.reference || "U?";
|
|
2852
|
+
if (!(s.drawnKey && inst.refdes[`${sheet.page}|${s.drawnKey}`])) {
|
|
2853
|
+
const n = seen.get(ref) ?? 0;
|
|
2854
|
+
seen.set(ref, n + 1);
|
|
2855
|
+
if (n > 0)
|
|
2856
|
+
ref = `${ref}_${n}`;
|
|
2857
|
+
if (path.split("/").length > 2)
|
|
2858
|
+
ref = `${ref}_${inst.name || "X"}`;
|
|
2859
|
+
}
|
|
2860
|
+
}
|
|
2861
|
+
const k = s.drawnKey ? `${sheet.page}|${s.drawnKey}` : "";
|
|
2862
|
+
const r = { path, reference: ref, unit: k && inst.units[k] || 1, pinMap: k ? inst.pinRemaps[k] : undefined };
|
|
2863
|
+
f.symbolRefs[i].push(r);
|
|
2864
|
+
placements.push({ f, i, ref: r, chain });
|
|
2865
|
+
});
|
|
2866
|
+
for (const sub of f.sub) {
|
|
2867
|
+
if (sub.key.startsWith("page:")) {
|
|
2868
|
+
const other = pagesOf(sheet.title).find((p) => `page:${p.page}` === sub.key);
|
|
2869
|
+
sub.refs.push({ path, page: visit(inst, other, `${path}/${sub.uuid}`, [...chain, sub]) });
|
|
2870
|
+
} else {
|
|
2871
|
+
const child = inst.children.find((c) => c.parentPage === sheet.page && `block:${c.blockId}` === sub.key);
|
|
2872
|
+
if (!child)
|
|
2873
|
+
continue;
|
|
2874
|
+
if (child.name)
|
|
2875
|
+
sub.name = child.name;
|
|
2876
|
+
const childFirst = pagesOf(child.sheet)[0];
|
|
2877
|
+
sub.refs.push({ path, page: visit(child, childFirst, `${path}/${sub.uuid}`, [...chain, sub]) });
|
|
2878
|
+
}
|
|
2879
|
+
}
|
|
2880
|
+
return myPage;
|
|
2881
|
+
};
|
|
2882
|
+
const rootFile = files.get(rootFirst);
|
|
2883
|
+
visit(sch.root, rootFirst, `/${rootFile.uuid}`);
|
|
2884
|
+
for (const f of files.values()) {
|
|
2885
|
+
const count = new Map;
|
|
2886
|
+
for (const sub of f.sub) {
|
|
2887
|
+
const n = count.get(sub.name) ?? 0;
|
|
2888
|
+
count.set(sub.name, n + 1);
|
|
2889
|
+
if (n > 0)
|
|
2890
|
+
sub.name = `${sub.name}_${n}`;
|
|
2891
|
+
}
|
|
2892
|
+
}
|
|
2893
|
+
for (const f of files.values()) {
|
|
2894
|
+
if (f.symbolRefs.some((r) => r.length === 0) && f !== rootFile) {
|
|
2895
|
+
f.symbolRefs.forEach((r, i) => r.length || r.push({ path: `/${f.uuid}`, reference: f.sheet.symbols[i].reference || "U?", unit: 1 }));
|
|
2896
|
+
}
|
|
2897
|
+
}
|
|
2898
|
+
dropSharedPins([...files.values()]);
|
|
2899
|
+
const library = new SymbolLibrary;
|
|
2900
|
+
for (const f of files.values()) {
|
|
2901
|
+
f.libEntries = f.sheet.symbols.map((s, i) => {
|
|
2902
|
+
const r = library.add(s, f.symbolRefs[i], f.droppedPins[i]);
|
|
2903
|
+
f.sheet.symbols[i] = r.symbol;
|
|
2904
|
+
return r.entry;
|
|
2905
|
+
});
|
|
2906
|
+
f.libNames = f.libEntries.map((e) => `${libNick}:${e.name}`);
|
|
2907
|
+
}
|
|
2908
|
+
const links = new Map;
|
|
2909
|
+
for (const { f, i, ref, chain } of placements) {
|
|
2910
|
+
const s = f.sheet.symbols[i];
|
|
2911
|
+
if (s.kind === "power")
|
|
2912
|
+
continue;
|
|
2913
|
+
const cur = links.get(ref.reference);
|
|
2914
|
+
if (cur && cur.unit <= ref.unit)
|
|
2915
|
+
continue;
|
|
2916
|
+
links.set(ref.reference, {
|
|
2917
|
+
path: `${ref.path.split("/").slice(2).map((x) => `/${x}`).join("")}/${f.symbolUuids[i]}`,
|
|
2918
|
+
sheetname: `/${chain.map((c) => `${c.name}/`).join("")}`,
|
|
2919
|
+
sheetfile: f.fileName,
|
|
2920
|
+
value: s.value,
|
|
2921
|
+
unit: ref.unit
|
|
2922
|
+
});
|
|
2923
|
+
}
|
|
2924
|
+
const out = new Map;
|
|
2925
|
+
for (const f of files.values())
|
|
2926
|
+
out.set(f.fileName, renderPage(f, sch, f === rootFile, opts.footprints));
|
|
2927
|
+
return { files: out, links, symbolLibrary: library.file() };
|
|
2928
|
+
}
|
|
2929
|
+
function dropSharedPins(files) {
|
|
2930
|
+
const owners = new Map;
|
|
2931
|
+
for (const f of files) {
|
|
2932
|
+
f.sheet.symbols.forEach((s, i) => {
|
|
2933
|
+
const r = f.symbolRefs[i][0];
|
|
2934
|
+
if (s.kind === "power" || !r)
|
|
2935
|
+
return;
|
|
2936
|
+
for (const p of uniquePins(s.pins)) {
|
|
2937
|
+
const k = JSON.stringify([r.reference, r.pinMap?.[p.number] ?? p.number]);
|
|
2938
|
+
const list = owners.get(k) ?? [];
|
|
2939
|
+
list.push({ f, i, drawn: p.number, connected: !!p.connected });
|
|
2940
|
+
owners.set(k, list);
|
|
2941
|
+
}
|
|
2942
|
+
});
|
|
2943
|
+
}
|
|
2944
|
+
for (const list of owners.values()) {
|
|
2945
|
+
if (list.length < 2)
|
|
2946
|
+
continue;
|
|
2947
|
+
const keep = list.find((o) => o.connected) ?? list[0];
|
|
2948
|
+
for (const o of list)
|
|
2949
|
+
if (o !== keep)
|
|
2950
|
+
o.f.droppedPins[o.i].add(o.drawn);
|
|
2951
|
+
}
|
|
2952
|
+
}
|
|
2953
|
+
function kicadProSchematicSettings() {
|
|
2954
|
+
return { connection_grid_size: 10 };
|
|
2955
|
+
}
|
|
2956
|
+
|
|
2957
|
+
// src/db/symbols.ts
|
|
2958
|
+
import { decodeBuffer as decodeBuffer2, parseEwXml as parseEwXml2 } from "electronics-workbench-decoder";
|
|
2959
|
+
var rows = (db, table) => db.tables[table]?.rows ?? [];
|
|
2960
|
+
var lines = (v) => String(v ?? "").split(/\r?\n/).filter((l) => l !== "");
|
|
2961
|
+
function symbolPictureXml(image, size) {
|
|
2962
|
+
const body = image.subarray(5);
|
|
2963
|
+
const u32 = (n) => {
|
|
2964
|
+
const b = Buffer.alloc(4);
|
|
2965
|
+
b.writeUInt32LE(n);
|
|
2966
|
+
return b;
|
|
2967
|
+
};
|
|
2968
|
+
const file = Buffer.concat([Buffer.from("CompressedElectronicsWorkbenchXML", "latin1"), u32(size), u32(0), u32(size), u32(body.length), body]);
|
|
2969
|
+
return decodeBuffer2(file).xml.toString("latin1");
|
|
2970
|
+
}
|
|
2971
|
+
var pointsOf = (e) => (e.child("PtA")?.childrenNamed() ?? []).filter((p) => p.get("Type") === "Point").map((p) => ({ x: p.numOr("X", 0), y: p.numOr("Y", 0) }));
|
|
2972
|
+
var pointAt = (e) => e ? { x: e.numOr("X", 0), y: e.numOr("Y", 0) } : undefined;
|
|
2973
|
+
var objectsOf = (layer) => layer.child("DS")?.childrenNamed() ?? [];
|
|
2974
|
+
function ellipsePoints2(c, a, b, t0, t1, steps) {
|
|
2975
|
+
return Array.from({ length: steps + 1 }, (_, i) => {
|
|
2976
|
+
const t = t0 + (t1 - t0) * i / steps;
|
|
2977
|
+
return { x: c.x + a.x * Math.cos(t) + b.x * Math.sin(t), y: c.y + a.y * Math.cos(t) + b.y * Math.sin(t) };
|
|
2978
|
+
});
|
|
2979
|
+
}
|
|
2980
|
+
function graphicOf2(o) {
|
|
2981
|
+
const pts = pointsOf(o);
|
|
2982
|
+
const width = o.numOr("PW", 0);
|
|
2983
|
+
const fill = o.get("BS") === "0";
|
|
2984
|
+
switch (o.get("Type")) {
|
|
2985
|
+
case "Line":
|
|
2986
|
+
case "MultiLine":
|
|
2987
|
+
return pts.length >= 2 ? { kind: "polyline", points: pts, width, fill: false } : undefined;
|
|
2988
|
+
case "Polygon":
|
|
2989
|
+
return pts.length >= 3 ? { kind: "polyline", points: [...pts, pts[0]], width, fill } : undefined;
|
|
2990
|
+
case "Rectangle":
|
|
2991
|
+
return pts.length >= 2 ? { kind: "rect", a: pts[0], b: pts[1], width, fill } : undefined;
|
|
2992
|
+
case "Circle": {
|
|
2993
|
+
const [c, rim] = pts;
|
|
2994
|
+
return c && rim ? { kind: "circle", center: c, radius: Math.hypot(rim.x - c.x, rim.y - c.y), width, fill } : undefined;
|
|
2995
|
+
}
|
|
2996
|
+
case "Ellipse": {
|
|
2997
|
+
const [p, q] = pts;
|
|
2998
|
+
if (!p || !q)
|
|
2999
|
+
return;
|
|
3000
|
+
const c = { x: (p.x + q.x) / 2, y: (p.y + q.y) / 2 };
|
|
3001
|
+
const rx = Math.abs(q.x - p.x) / 2;
|
|
3002
|
+
const ry = Math.abs(q.y - p.y) / 2;
|
|
3003
|
+
if (rx === ry)
|
|
3004
|
+
return { kind: "circle", center: c, radius: rx, width, fill };
|
|
3005
|
+
return { kind: "polyline", points: ellipsePoints2(c, { x: rx, y: 0 }, { x: 0, y: ry }, 0, 2 * Math.PI, 48), width, fill };
|
|
3006
|
+
}
|
|
3007
|
+
case "HalfEllipseArc": {
|
|
3008
|
+
const [p0, p1, apex] = pts;
|
|
3009
|
+
if (!p0 || !p1 || !apex)
|
|
3010
|
+
return;
|
|
3011
|
+
const c = { x: (p0.x + p1.x) / 2, y: (p0.y + p1.y) / 2 };
|
|
3012
|
+
const a = { x: p0.x - c.x, y: p0.y - c.y };
|
|
3013
|
+
const b = { x: apex.x - c.x, y: apex.y - c.y };
|
|
3014
|
+
if (Math.abs(Math.hypot(a.x, a.y) - Math.hypot(b.x, b.y)) < 0.000000001 && Math.abs(a.x * b.x + a.y * b.y) < 0.000000001) {
|
|
3015
|
+
return { kind: "arc", start: p0, mid: apex, end: p1, width };
|
|
3016
|
+
}
|
|
3017
|
+
return { kind: "polyline", points: ellipsePoints2(c, a, b, 0, Math.PI, 24), width, fill: false };
|
|
3018
|
+
}
|
|
3019
|
+
case "SegmentArc": {
|
|
3020
|
+
const [c, s, e] = pts;
|
|
3021
|
+
if (!c || !s || !e)
|
|
3022
|
+
return;
|
|
3023
|
+
const r = Math.hypot(s.x - c.x, s.y - c.y);
|
|
3024
|
+
const a0 = Math.atan2(s.y - c.y, s.x - c.x);
|
|
3025
|
+
const a1 = Math.atan2(e.y - c.y, e.x - c.x);
|
|
3026
|
+
const sweep = ((a0 - a1) % (2 * Math.PI) + 2 * Math.PI) % (2 * Math.PI) || 2 * Math.PI;
|
|
3027
|
+
const am = a0 - sweep / 2;
|
|
3028
|
+
return { kind: "arc", start: s, mid: { x: c.x + r * Math.cos(am), y: c.y + r * Math.sin(am) }, end: e, width };
|
|
3029
|
+
}
|
|
3030
|
+
case "Text": {
|
|
3031
|
+
const at = pts[0];
|
|
3032
|
+
const text = o.str("Txt");
|
|
3033
|
+
return at && text ? { kind: "text", at, text, size: o.numOr("H", 10) } : undefined;
|
|
3034
|
+
}
|
|
3035
|
+
default:
|
|
3036
|
+
return;
|
|
3037
|
+
}
|
|
3038
|
+
}
|
|
3039
|
+
function parseSymbolPicture(xml) {
|
|
3040
|
+
const root = parseEwXml2(xml).root;
|
|
3041
|
+
const graphics = [];
|
|
3042
|
+
const pins = [];
|
|
3043
|
+
let showPinNames = false;
|
|
3044
|
+
for (const layer of root.child("LrsArr")?.childrenNamed() ?? []) {
|
|
3045
|
+
const name = layer.str("LN");
|
|
3046
|
+
const draw = /^(\d+) Draw layer$/i.exec(name);
|
|
3047
|
+
if (name === "Border" || draw && draw[1] !== "1")
|
|
3048
|
+
continue;
|
|
3049
|
+
for (const o of objectsOf(layer)) {
|
|
3050
|
+
if (o.get("Type") === "Pin") {
|
|
3051
|
+
const body = pointAt(o.child("CTSP"));
|
|
3052
|
+
const wire = pointAt(o.child("WCP"));
|
|
3053
|
+
const nameText = o.child("PNaT");
|
|
3054
|
+
const index = Number(nameText?.str("Txt"));
|
|
3055
|
+
if (!body || !wire || !Number.isInteger(index))
|
|
3056
|
+
continue;
|
|
3057
|
+
const length = Math.hypot(body.x - wire.x, body.y - wire.y);
|
|
3058
|
+
pins.push({ index, at: wire, dir: length ? { x: (body.x - wire.x) / length, y: (body.y - wire.y) / length } : { x: 0, y: 0 }, length });
|
|
3059
|
+
showPinNames ||= nameText?.get("Vis") !== "0";
|
|
3060
|
+
} else {
|
|
3061
|
+
const g = graphicOf2(o);
|
|
3062
|
+
if (g)
|
|
3063
|
+
graphics.push(g);
|
|
3064
|
+
}
|
|
3065
|
+
}
|
|
3066
|
+
}
|
|
3067
|
+
return { graphics, pins, showPinNames };
|
|
3068
|
+
}
|
|
3069
|
+
var ELECTRICAL = {
|
|
3070
|
+
INPUT: "input",
|
|
3071
|
+
OUTPUT: "output",
|
|
3072
|
+
"I/O": "bidirectional",
|
|
3073
|
+
PASSIVE: "passive",
|
|
3074
|
+
PWR: "power_in",
|
|
3075
|
+
GND: "power_in",
|
|
3076
|
+
VCC: "power_in",
|
|
3077
|
+
VEE: "power_in",
|
|
3078
|
+
VPP: "power_in",
|
|
3079
|
+
OPEN_COLLECTOR: "open_collector",
|
|
3080
|
+
OPEN_DRAIN: "open_collector",
|
|
3081
|
+
OPEN_EMITTER: "open_emitter",
|
|
3082
|
+
OPEN_SOURCE: "open_emitter",
|
|
3083
|
+
TRISTATE: "tri_state",
|
|
3084
|
+
NC: "no_connect"
|
|
3085
|
+
};
|
|
3086
|
+
function databaseSymbols(db, footprintFor) {
|
|
3087
|
+
const warnings = [];
|
|
3088
|
+
const pictures = new Map;
|
|
3089
|
+
for (const r of rows(db, "SYS_SYMBOL_PICTURE")) {
|
|
3090
|
+
const img = r.Image;
|
|
3091
|
+
if (!img?.value)
|
|
3092
|
+
continue;
|
|
3093
|
+
try {
|
|
3094
|
+
pictures.set(Number(r.Symbol_ID), parseSymbolPicture(symbolPictureXml(Buffer.from(img.value, "base64"), Number(r.Size))));
|
|
3095
|
+
} catch (e) {
|
|
3096
|
+
warnings.push(`symbol picture ${r.Symbol_ID}: ${e}`);
|
|
3097
|
+
}
|
|
3098
|
+
}
|
|
3099
|
+
const families = new Map(rows(db, "SYS_CONFIGURATION").map((r) => [r.Family_ID, r]));
|
|
3100
|
+
const packages = new Map(rows(db, "SYS_PCB_PACKAGE").map((r) => [r.Package_ID, String(r.Package_Type ?? "")]));
|
|
3101
|
+
const sectionsOf = groupBy(rows(db, "SYS_MAPPING_COMP_SYMBOL"), (r) => r.Component_ID);
|
|
3102
|
+
const packageOf = new Map(rows(db, "SYS_MAPPING_COMP_PACKAGE").map((r) => [r.Component_ID, r]));
|
|
3103
|
+
const used = new Set;
|
|
3104
|
+
const specs = [];
|
|
3105
|
+
for (const c of rows(db, "SYS_COMPONENT")) {
|
|
3106
|
+
const compName = String(c.Component_Name ?? "");
|
|
3107
|
+
const family = families.get(c.Family_ID);
|
|
3108
|
+
const familyName = String(family?.Family_Name ?? "");
|
|
3109
|
+
const pinNames = lines(c.Pinout);
|
|
3110
|
+
const pinTypes = lines(c.Pin_Type).map((t) => ELECTRICAL[t.split(":")[1] ?? ""] ?? "unspecified");
|
|
3111
|
+
const pkg = packageOf.get(c.Component_ID);
|
|
3112
|
+
const pkgName = pkg ? packages.get(pkg.Package_ID) ?? "" : "";
|
|
3113
|
+
const pads = pkg ? lines(pkg.Pinout).map((l) => l.split(",").map((s) => s.trim()).filter(Boolean)) : [];
|
|
3114
|
+
const sections = (sectionsOf.get(c.Component_ID) ?? []).sort((a, b) => Number(a.Sec_Order) - Number(b.Sec_Order));
|
|
3115
|
+
const units = [];
|
|
3116
|
+
const placedPads = new Set;
|
|
3117
|
+
const claimed = new Set;
|
|
3118
|
+
const pinIndex = (name, fallback) => {
|
|
3119
|
+
let first = -1;
|
|
3120
|
+
for (let i = 0;i < pinNames.length; i++) {
|
|
3121
|
+
if (pinNames[i] !== name)
|
|
3122
|
+
continue;
|
|
3123
|
+
if (!claimed.has(i))
|
|
3124
|
+
return i;
|
|
3125
|
+
if (first < 0)
|
|
3126
|
+
first = i;
|
|
3127
|
+
}
|
|
3128
|
+
return first >= 0 ? first : fallback;
|
|
3129
|
+
};
|
|
3130
|
+
let offset = 0;
|
|
3131
|
+
let showPinNames = false;
|
|
3132
|
+
for (const sec of sections) {
|
|
3133
|
+
const pic = pictures.get(Number(sec.Symbol_ID_ANSI));
|
|
3134
|
+
const secNames = lines(sec.Pinout_ANSI);
|
|
3135
|
+
if (!pic) {
|
|
3136
|
+
warnings.push(`${compName}: section ${sec.Sec_Order} has no symbol picture ${sec.Symbol_ID_ANSI}`);
|
|
3137
|
+
offset += secNames.length;
|
|
3138
|
+
continue;
|
|
3139
|
+
}
|
|
3140
|
+
showPinNames ||= pic.showPinNames;
|
|
3141
|
+
const pins = [];
|
|
3142
|
+
const stems = [];
|
|
3143
|
+
for (const p of [...pic.pins].sort((a, b) => a.index - b.index)) {
|
|
3144
|
+
const secName = secNames[p.index - 1];
|
|
3145
|
+
const k = secName === undefined ? offset + p.index - 1 : pinIndex(secName, offset + p.index - 1);
|
|
3146
|
+
claimed.add(k);
|
|
3147
|
+
const name = secName ?? pinNames[k] ?? String(p.index);
|
|
3148
|
+
if (secName !== undefined && pinNames.length && pinNames[k] !== secName)
|
|
3149
|
+
warnings.push(`${compName}: section ${sec.Sec_Order} pin ${secName} is not in the component's Pinout`);
|
|
3150
|
+
const numbers = pads[k]?.length ? pads[k] : [name];
|
|
3151
|
+
const base = { name, at: p.at, dir: p.dir, length: p.length, electrical: pinTypes[k] ?? "unspecified" };
|
|
3152
|
+
const fresh = numbers.filter((n) => !placedPads.has(n));
|
|
3153
|
+
if (fresh.length === 0)
|
|
3154
|
+
stems.push({ ...base, number: numbers[0] });
|
|
3155
|
+
for (const n of fresh) {
|
|
3156
|
+
placedPads.add(n);
|
|
3157
|
+
pins.push({ ...base, number: n });
|
|
3158
|
+
}
|
|
3159
|
+
}
|
|
3160
|
+
units.push({ graphics: pic.graphics, pins, stems });
|
|
3161
|
+
offset += secNames.length;
|
|
3162
|
+
}
|
|
3163
|
+
if (units.length) {
|
|
3164
|
+
const hidden = [];
|
|
3165
|
+
pinNames.forEach((name, k) => {
|
|
3166
|
+
if (claimed.has(k) || pkg && !pads[k]?.length)
|
|
3167
|
+
return;
|
|
3168
|
+
const numbers = ((pads[k]?.length) ? pads[k] : [name]).filter((n) => !placedPads.has(n));
|
|
3169
|
+
for (const n of numbers) {
|
|
3170
|
+
placedPads.add(n);
|
|
3171
|
+
hidden.push({ name, number: n, at: { x: 0, y: 0 }, dir: { x: 1, y: 0 }, length: PIN, electrical: pinTypes[k] ?? "power_in" });
|
|
3172
|
+
}
|
|
3173
|
+
});
|
|
3174
|
+
if (hidden.length)
|
|
3175
|
+
units.push(pinBlock(hidden));
|
|
3176
|
+
}
|
|
3177
|
+
if (units.length === 0) {
|
|
3178
|
+
warnings.push(`${compName}: no symbol`);
|
|
3179
|
+
continue;
|
|
3180
|
+
}
|
|
3181
|
+
let name = sanitize(compName) || "PART";
|
|
3182
|
+
if (used.has(name.toLowerCase()))
|
|
3183
|
+
name = sanitize(`${compName}_${familyName}`);
|
|
3184
|
+
for (let n = 2;used.has(name.toLowerCase()); n++)
|
|
3185
|
+
name = `${sanitize(compName)}_${n}`;
|
|
3186
|
+
used.add(name.toLowerCase());
|
|
3187
|
+
const footprint = pkgName ? footprintFor(pkgName) : undefined;
|
|
3188
|
+
const fields = [];
|
|
3189
|
+
const description = String(c.Function ?? "") || String(c.Description ?? "");
|
|
3190
|
+
if (description)
|
|
3191
|
+
fields.push(["Description", description]);
|
|
3192
|
+
if (c.Manufacturer)
|
|
3193
|
+
fields.push(["Manufacturer", String(c.Manufacturer)]);
|
|
3194
|
+
if (familyName)
|
|
3195
|
+
fields.push(["EW_Family", familyName]);
|
|
3196
|
+
if (pkgName && !footprint)
|
|
3197
|
+
fields.push(["EW_Package", pkgName]);
|
|
3198
|
+
specs.push({
|
|
3199
|
+
name,
|
|
3200
|
+
reference: /^[A-Za-z_#]*/.exec(String(family?.Template ?? ""))[0] || "U",
|
|
3201
|
+
value: compName,
|
|
3202
|
+
footprint,
|
|
3203
|
+
fields,
|
|
3204
|
+
showPinNames,
|
|
3205
|
+
showPinNumbers: true,
|
|
3206
|
+
units
|
|
3207
|
+
});
|
|
3208
|
+
}
|
|
3209
|
+
return { specs, warnings };
|
|
3210
|
+
}
|
|
3211
|
+
var PIN = 9;
|
|
3212
|
+
function pinBlock(pins) {
|
|
3213
|
+
const TEXT = 5;
|
|
3214
|
+
const longest = Math.max(...pins.map((p) => p.name.length));
|
|
3215
|
+
const width = Math.max(4, Math.ceil((longest * TEXT + 2 * TEXT) / PIN)) * PIN;
|
|
3216
|
+
const height = (pins.length + 1) * PIN;
|
|
3217
|
+
const y = (i) => (i + 1) * PIN;
|
|
3218
|
+
return {
|
|
3219
|
+
graphics: [
|
|
3220
|
+
{ kind: "rect", a: { x: PIN, y: 0 }, b: { x: PIN + width, y: height }, width: 1, fill: false },
|
|
3221
|
+
...pins.map((p, i) => ({ kind: "text", at: { x: PIN + 2, y: y(i) - 3 }, text: p.name, size: TEXT }))
|
|
3222
|
+
],
|
|
3223
|
+
pins: pins.map((p, i) => ({ ...p, at: { x: 0, y: y(i) }, dir: { x: 1, y: 0 }, length: PIN }))
|
|
3224
|
+
};
|
|
3225
|
+
}
|
|
3226
|
+
var sanitize = (s) => s.replace(/[^A-Za-z0-9_.+-]+/g, "_").replace(/^_+|_+$/g, "");
|
|
3227
|
+
function groupBy(xs, key) {
|
|
3228
|
+
const m = new Map;
|
|
3229
|
+
for (const x of xs) {
|
|
3230
|
+
const k = key(x);
|
|
3231
|
+
const list = m.get(k) ?? [];
|
|
3232
|
+
list.push(x);
|
|
3233
|
+
m.set(k, list);
|
|
3234
|
+
}
|
|
3235
|
+
return m;
|
|
3236
|
+
}
|
|
3237
|
+
|
|
3238
|
+
// src/emit/footprint-lib.ts
|
|
3239
|
+
var KICAD_MOD_VERSION = 20240108;
|
|
3240
|
+
var SAME_NM = 10;
|
|
3241
|
+
var QUARTER_TURNS = [0, 180, 90, 270];
|
|
3242
|
+
var deg2 = (millionths) => millionths / 1e6;
|
|
3243
|
+
var toMillionths = (d) => Math.round((d % 360 + 360) % 360 * 1e6);
|
|
3244
|
+
var BOTTOM_TWIN = Object.fromEntries(Object.entries(TOP_TWIN).map(([b, t]) => [t, Number(b)]));
|
|
3245
|
+
function toLibrary(c) {
|
|
3246
|
+
const r = deg2(c.rotation) * Math.PI / 180;
|
|
3247
|
+
const cos = Math.cos(r);
|
|
3248
|
+
const sin = Math.sin(r);
|
|
3249
|
+
return {
|
|
3250
|
+
point: (p) => {
|
|
3251
|
+
const dx = p.x - c.origin.x;
|
|
3252
|
+
const dy = p.y - c.origin.y;
|
|
3253
|
+
const l = c.bottom ? { x: -(dx * cos - dy * sin), y: dx * sin + dy * cos } : { x: dx * cos + dy * sin, y: -dx * sin + dy * cos };
|
|
3254
|
+
return { x: Math.round(l.x), y: Math.round(l.y) };
|
|
3255
|
+
},
|
|
3256
|
+
angle: (a) => toMillionths(c.bottom ? 180 - deg2(a) - deg2(c.rotation) : deg2(a) - deg2(c.rotation)),
|
|
3257
|
+
layer: (l) => c.bottom ? TOP_TWIN[l] ?? l : l,
|
|
3258
|
+
side: (s) => s === "both" ? "both" : "top",
|
|
3259
|
+
mirrors: c.bottom,
|
|
3260
|
+
textMirror: false
|
|
3261
|
+
};
|
|
3262
|
+
}
|
|
3263
|
+
function toPlaced(c) {
|
|
3264
|
+
const r = deg2(c.rotation) * Math.PI / 180;
|
|
3265
|
+
const cos = Math.cos(r);
|
|
3266
|
+
const sin = Math.sin(r);
|
|
3267
|
+
return {
|
|
3268
|
+
point: (l) => c.bottom ? { x: c.origin.x - l.x * cos + l.y * sin, y: c.origin.y + l.x * sin + l.y * cos } : { x: c.origin.x + l.x * cos - l.y * sin, y: c.origin.y + l.x * sin + l.y * cos },
|
|
3269
|
+
angle: (a) => toMillionths(c.bottom ? 180 - deg2(a) - deg2(c.rotation) : deg2(a) + deg2(c.rotation)),
|
|
3270
|
+
layer: (l) => c.bottom ? BOTTOM_TWIN[l] ?? l : l,
|
|
3271
|
+
side: (s) => s === "both" ? "both" : c.bottom ? "bottom" : "top",
|
|
3272
|
+
mirrors: c.bottom,
|
|
3273
|
+
textMirror: c.bottom
|
|
3274
|
+
};
|
|
3275
|
+
}
|
|
3276
|
+
function shape(s, m) {
|
|
3277
|
+
const layer = m.layer(s.layer);
|
|
3278
|
+
if (s.kind === "arc") {
|
|
3279
|
+
const [start, end] = m.mirrors ? [s.end, s.start] : [s.start, s.end];
|
|
3280
|
+
return { ...s, layer, start: m.point(start), end: m.point(end), center: m.point(s.center) };
|
|
3281
|
+
}
|
|
3282
|
+
return { ...s, layer, points: s.points.map(m.point) };
|
|
3283
|
+
}
|
|
3284
|
+
function primitive(p, m) {
|
|
3285
|
+
switch (p.kind) {
|
|
3286
|
+
case "poly":
|
|
3287
|
+
return { ...p, points: p.points.map(m.point) };
|
|
3288
|
+
case "circle":
|
|
3289
|
+
return { ...p, center: m.point(p.center) };
|
|
3290
|
+
case "arc": {
|
|
3291
|
+
const [start, end] = m.mirrors ? [p.end, p.start] : [p.start, p.end];
|
|
3292
|
+
return { ...p, center: m.point(p.center), start: m.point(start), end: m.point(end) };
|
|
3293
|
+
}
|
|
3294
|
+
}
|
|
3295
|
+
}
|
|
3296
|
+
function pad(p, m) {
|
|
3297
|
+
return {
|
|
3298
|
+
...p,
|
|
3299
|
+
at: m.point(p.at),
|
|
3300
|
+
rotation: m.angle(p.rotation),
|
|
3301
|
+
side: m.side(p.side),
|
|
3302
|
+
shape: p.shape.kind === "custom" ? { kind: "custom", primitives: p.shape.primitives.map((x) => primitive(x, m)) } : p.shape
|
|
3303
|
+
};
|
|
3304
|
+
}
|
|
3305
|
+
function text(t, m) {
|
|
3306
|
+
return { ...t, layer: m.layer(t.layer), at: m.point(t.at), angle: m.angle(t.angle), mirror: m.textMirror };
|
|
3307
|
+
}
|
|
3308
|
+
function mapComponent(c, m) {
|
|
3309
|
+
return { pads: c.pads.map((p) => pad(p, m)), graphics: c.graphics.map((s) => shape(s, m)), texts: c.texts.map((t) => text(t, m)) };
|
|
3310
|
+
}
|
|
3311
|
+
function libraryComponent(c) {
|
|
3312
|
+
return {
|
|
3313
|
+
...c,
|
|
3314
|
+
...mapComponent(c, toLibrary(c)),
|
|
3315
|
+
reference: "REF**",
|
|
3316
|
+
value: footprintName(c),
|
|
3317
|
+
origin: { x: 0, y: 0 },
|
|
3318
|
+
rotation: 0,
|
|
3319
|
+
bottom: false
|
|
3320
|
+
};
|
|
3321
|
+
}
|
|
3322
|
+
function signature(c) {
|
|
3323
|
+
const items = [];
|
|
3324
|
+
const flat = (ps) => ps.flatMap((p) => [p.x, p.y]);
|
|
3325
|
+
const undirected = (ps) => {
|
|
3326
|
+
const f = flat(ps);
|
|
3327
|
+
const r = flat([...ps].reverse());
|
|
3328
|
+
for (let i = 0;i < f.length; i++)
|
|
3329
|
+
if (f[i] !== r[i])
|
|
3330
|
+
return f[i] < r[i] ? f : r;
|
|
3331
|
+
return f;
|
|
3332
|
+
};
|
|
3333
|
+
for (const p of c.pads) {
|
|
3334
|
+
const extra = p.shape.kind === "custom" ? p.shape.primitives.flatMap((x) => flat(x.kind === "poly" ? x.points : x.kind === "arc" ? [x.center, x.start, x.end] : [x.center])) : [];
|
|
3335
|
+
items.push({ label: `pad ${p.number} ${p.shape.kind} ${p.side} ${p.drillDiameter}`, nums: [...flat([p.at]), ...extra] });
|
|
3336
|
+
}
|
|
3337
|
+
for (const g of c.graphics) {
|
|
3338
|
+
items.push({ label: `${g.kind} ${g.layer}`, nums: g.kind === "arc" ? flat([g.start, g.end, g.center]) : g.kind === "polyline" ? undirected(g.points) : flat(g.points) });
|
|
3339
|
+
}
|
|
3340
|
+
for (const t of c.texts.filter((x) => x.tag !== "REFDES" && x.tag !== "VALUE"))
|
|
3341
|
+
items.push({ label: `text ${t.tag} ${t.text}`, nums: flat([t.at]) });
|
|
3342
|
+
const key = (i) => `${i.label}|${i.nums.map((v) => Math.round(v / 1000)).join(",")}`;
|
|
3343
|
+
return items.sort((a, b) => key(a) < key(b) ? -1 : key(a) > key(b) ? 1 : 0);
|
|
3344
|
+
}
|
|
3345
|
+
function sameDrawing(a, b) {
|
|
3346
|
+
const x = signature(a);
|
|
3347
|
+
const y = signature(b);
|
|
3348
|
+
return x.length === y.length && x.every((it, i) => {
|
|
3349
|
+
const o = y[i];
|
|
3350
|
+
return it.label === o.label && it.nums.length === o.nums.length && it.nums.every((v, k) => Math.abs(v - o.nums[k]) <= SAME_NM);
|
|
3351
|
+
});
|
|
3352
|
+
}
|
|
3353
|
+
function harmonizeFootprints(board) {
|
|
3354
|
+
const library = new Map;
|
|
3355
|
+
const variants = new Map;
|
|
3356
|
+
const order = board.components.map((c, i) => i).sort((a, b) => Number(board.components[a].bottom) - Number(board.components[b].bottom));
|
|
3357
|
+
const components = [...board.components];
|
|
3358
|
+
for (const i of order) {
|
|
3359
|
+
const c = board.components[i];
|
|
3360
|
+
const base = footprintName(c);
|
|
3361
|
+
const names = variants.get(base) ?? [];
|
|
3362
|
+
let match;
|
|
3363
|
+
for (const name of names) {
|
|
3364
|
+
const lib = library.get(name);
|
|
3365
|
+
const turned = QUARTER_TURNS.map((d) => ({ ...c, rotation: toMillionths(deg2(c.rotation) + d) })).find((t) => sameDrawing(libraryComponent(t), lib));
|
|
3366
|
+
if (turned) {
|
|
3367
|
+
match = { name, turned };
|
|
3368
|
+
break;
|
|
3369
|
+
}
|
|
3370
|
+
}
|
|
3371
|
+
if (!match) {
|
|
3372
|
+
const name = names.length === 0 ? base : `${base}_${names.length + 1}`;
|
|
3373
|
+
names.push(name);
|
|
3374
|
+
variants.set(base, names);
|
|
3375
|
+
library.set(name, { ...libraryComponent(c), name, value: name });
|
|
3376
|
+
match = { name, turned: c };
|
|
3377
|
+
}
|
|
3378
|
+
const lib = library.get(match.name);
|
|
3379
|
+
const placed = mapComponent(lib, toPlaced(match.turned));
|
|
3380
|
+
const fields = c.texts.filter((t) => t.tag === "REFDES" || t.tag === "VALUE");
|
|
3381
|
+
components[i] = {
|
|
3382
|
+
...match.turned,
|
|
3383
|
+
name: match.name,
|
|
3384
|
+
pads: placed.pads,
|
|
3385
|
+
graphics: placed.graphics,
|
|
3386
|
+
texts: [...fields, ...placed.texts.filter((t) => t.tag !== "REFDES" && t.tag !== "VALUE")]
|
|
3387
|
+
};
|
|
3388
|
+
}
|
|
3389
|
+
return { board: { ...board, components }, library };
|
|
3390
|
+
}
|
|
3391
|
+
var asLibraryFile = (body, name) => body.replace(/^\t\(footprint [^\n]*\n/, `(footprint ${JSON.stringify(name)}
|
|
3392
|
+
(version ${KICAD_MOD_VERSION})
|
|
3393
|
+
(generator "multisim2kicad")
|
|
3394
|
+
`);
|
|
3395
|
+
function emitFootprintLibrary(board, library) {
|
|
3396
|
+
const lm = new LayerMap(board);
|
|
3397
|
+
const out = new Map;
|
|
3398
|
+
for (const [name, c] of library) {
|
|
3399
|
+
const body = emitFootprintFor(c, lm, { library: true });
|
|
3400
|
+
out.set(`${name}.kicad_mod`, asLibraryFile(body, name));
|
|
3401
|
+
}
|
|
3402
|
+
for (const h of board.holes.filter((x) => !x.plated)) {
|
|
3403
|
+
const name = mountingHoleName(h.drillDiameter);
|
|
3404
|
+
if (!out.has(`${name}.kicad_mod`))
|
|
3405
|
+
out.set(`${name}.kicad_mod`, asLibraryFile(mountingHoleFootprint(h.drillDiameter, ""), name));
|
|
3406
|
+
}
|
|
3407
|
+
return out;
|
|
3408
|
+
}
|
|
3409
|
+
|
|
3410
|
+
// src/emit/kicad-pro.ts
|
|
3411
|
+
var NM_PER_MM2 = 1e6;
|
|
3412
|
+
var mm2 = (nm) => +(nm / NM_PER_MM2).toFixed(6);
|
|
3413
|
+
var netClass = (name, clearance, width, rules, priority) => ({
|
|
3414
|
+
bus_width: 12,
|
|
3415
|
+
clearance: mm2(clearance),
|
|
3416
|
+
diff_pair_gap: 0.25,
|
|
3417
|
+
diff_pair_via_gap: 0.25,
|
|
3418
|
+
diff_pair_width: 0.2,
|
|
3419
|
+
line_style: 0,
|
|
3420
|
+
microvia_diameter: 0.3,
|
|
3421
|
+
microvia_drill: 0.1,
|
|
3422
|
+
name,
|
|
3423
|
+
pcb_color: "rgba(0, 0, 0, 0.000)",
|
|
3424
|
+
priority,
|
|
3425
|
+
schematic_color: "rgba(0, 0, 0, 0.000)",
|
|
3426
|
+
track_width: mm2(width),
|
|
3427
|
+
via_diameter: mm2(rules.via.diameter),
|
|
3428
|
+
via_drill: mm2(rules.via.drill),
|
|
3429
|
+
wire_width: 6
|
|
3430
|
+
});
|
|
3431
|
+
var netClassName = (clearance, width) => `EW clearance ${mm2(clearance)} track ${mm2(width)}`;
|
|
3432
|
+
function boardProjectSettings(board) {
|
|
3433
|
+
const r = board.rules;
|
|
3434
|
+
if (!r)
|
|
3435
|
+
return;
|
|
3436
|
+
const classes = new Map;
|
|
3437
|
+
for (const n of board.nets) {
|
|
3438
|
+
const clearance = n.clearance ?? r.clearance.trace;
|
|
3439
|
+
const width = n.trackWidth ?? r.trackWidth;
|
|
3440
|
+
if (clearance === r.clearance.trace && width === r.trackWidth)
|
|
3441
|
+
continue;
|
|
3442
|
+
const name = netClassName(clearance, width);
|
|
3443
|
+
const c = classes.get(name) ?? { clearance, width, nets: [] };
|
|
3444
|
+
c.nets.push(n.name);
|
|
3445
|
+
classes.set(name, c);
|
|
3446
|
+
}
|
|
3447
|
+
const ordered = [...classes].sort((a, b) => a[1].clearance - b[1].clearance || a[1].width - b[1].width);
|
|
3448
|
+
return {
|
|
3449
|
+
rules: {
|
|
3450
|
+
min_track_width: mm2(r.minTrackWidth),
|
|
3451
|
+
min_copper_edge_clearance: mm2(r.edgeClearance),
|
|
3452
|
+
min_hole_clearance: mm2(r.clearance.trace),
|
|
3453
|
+
min_through_hole_diameter: 0,
|
|
3454
|
+
min_via_diameter: 0
|
|
3455
|
+
},
|
|
3456
|
+
netSettings: {
|
|
3457
|
+
classes: [netClass("Default", r.clearance.trace, r.trackWidth, r, 2147483647), ...ordered.map(([name, c], i) => netClass(name, c.clearance, c.width, r, i))],
|
|
3458
|
+
meta: { version: 4 },
|
|
3459
|
+
net_colors: null,
|
|
3460
|
+
netclass_assignments: null,
|
|
3461
|
+
netclass_patterns: ordered.flatMap(([name, c]) => c.nets.map((pattern) => ({ netclass: name, pattern })))
|
|
3462
|
+
}
|
|
3463
|
+
};
|
|
3464
|
+
}
|
|
3465
|
+
function boardCustomRules(board) {
|
|
3466
|
+
const r = board.rules;
|
|
3467
|
+
if (!r)
|
|
3468
|
+
return;
|
|
3469
|
+
const rules = [];
|
|
3470
|
+
const add = (what, nm) => {
|
|
3471
|
+
if (nm === r.clearance.trace)
|
|
3472
|
+
return;
|
|
3473
|
+
rules.push([`(rule "EW clearance to ${what.toLowerCase()}s"`, ` (condition "A.Type == '${what}' || B.Type == '${what}'")`, ` (constraint clearance (min ${mm2(nm)}mm)))`].join(`
|
|
3474
|
+
`));
|
|
3475
|
+
};
|
|
3476
|
+
add("Pad", r.clearance.pad);
|
|
3477
|
+
add("Via", r.clearance.via);
|
|
3478
|
+
return rules.length ? ["(version 1)", ...rules, ""].join(`
|
|
3479
|
+
`) : undefined;
|
|
3480
|
+
}
|
|
3481
|
+
|
|
3482
|
+
// src/db/ewdb.ts
|
|
3483
|
+
import { decodeBuffer as decodeBuffer3, decodeMdbBuffer } from "electronics-workbench-decoder";
|
|
3484
|
+
function readEwDatabase(bytes, source = "") {
|
|
3485
|
+
return { source, tables: decodeMdbBuffer(bytes, source).tables };
|
|
3486
|
+
}
|
|
3487
|
+
var rows2 = (db, table) => db.tables[table]?.rows ?? [];
|
|
3488
|
+
var blobBytes = (v) => {
|
|
3489
|
+
const b = v;
|
|
3490
|
+
return b?.value ? Buffer.from(b.value, "base64") : undefined;
|
|
3491
|
+
};
|
|
3492
|
+
function databaseFootprints(db) {
|
|
3493
|
+
const types = new Map(rows2(db, "tObjectTypes").map((r) => [r.lObjectTypeID, String(r.strDocumentType ?? "")]));
|
|
3494
|
+
const blobs = new Map(rows2(db, "tBlobs").map((r) => [r.lBlobID, r.blbBlob]));
|
|
3495
|
+
const components = [];
|
|
3496
|
+
const skipped = [];
|
|
3497
|
+
for (const o of rows2(db, "tObjects")) {
|
|
3498
|
+
const name = String(o.strObjectName ?? "");
|
|
3499
|
+
const type = types.get(o.lObjectTypeID) ?? "?";
|
|
3500
|
+
if (type !== "UBLIB") {
|
|
3501
|
+
skipped.push({ name, reason: type });
|
|
3502
|
+
continue;
|
|
3503
|
+
}
|
|
3504
|
+
const bytes = blobBytes(blobs.get(o.lBlobID));
|
|
3505
|
+
if (!bytes) {
|
|
3506
|
+
skipped.push({ name, reason: "no blob" });
|
|
3507
|
+
continue;
|
|
3508
|
+
}
|
|
3509
|
+
try {
|
|
3510
|
+
const c = parseUbLibraryXml(decodeBuffer3(bytes).xml.toString("latin1"));
|
|
3511
|
+
if (c)
|
|
3512
|
+
components.push({ ...c, name, reference: "REF**", value: name });
|
|
3513
|
+
else
|
|
3514
|
+
skipped.push({ name, reason: "no component" });
|
|
3515
|
+
} catch (e) {
|
|
3516
|
+
skipped.push({ name, reason: String(e) });
|
|
3517
|
+
}
|
|
3518
|
+
}
|
|
3519
|
+
return { components, skipped };
|
|
3520
|
+
}
|
|
3521
|
+
function footprintBoard(components, name) {
|
|
3522
|
+
return {
|
|
3523
|
+
source: { application: "ultiboard", versionMajor: 0, versionMinor: 0, schema: 0 },
|
|
3524
|
+
projectName: name,
|
|
3525
|
+
sheetTitle: name,
|
|
3526
|
+
workArea: { left: 0, bottom: 0, right: 0, top: 0 },
|
|
3527
|
+
layers: [],
|
|
3528
|
+
stackup: { copper: [0, 63], thickness: 1600000 },
|
|
3529
|
+
zones: [],
|
|
3530
|
+
texts: [],
|
|
3531
|
+
ruleAreas: [],
|
|
3532
|
+
shapes: [],
|
|
3533
|
+
tracks: [],
|
|
3534
|
+
holes: [],
|
|
3535
|
+
vias: [],
|
|
3536
|
+
nets: [],
|
|
3537
|
+
components
|
|
3538
|
+
};
|
|
3539
|
+
}
|
|
3540
|
+
|
|
3541
|
+
// src/main.ts
|
|
3542
|
+
var NM_PER_MM3 = 1e6;
|
|
3543
|
+
var libNickname = (base) => base.replace(/[^A-Za-z0-9_.+-]+/g, "_") || "ew";
|
|
3544
|
+
async function convertProject(p, outDir) {
|
|
3545
|
+
await mkdir(outDir, { recursive: true });
|
|
3546
|
+
const written = [];
|
|
3547
|
+
const parsed = p.pcb ? harmonizeFootprints(parsePcbXml(p.pcb.xml)) : undefined;
|
|
3548
|
+
const board = parsed?.board;
|
|
3549
|
+
const sch = p.sch ? parseSchematicXml(p.sch.xml) : undefined;
|
|
3550
|
+
const lib = libNickname(p.base);
|
|
3551
|
+
if (board && sch)
|
|
3552
|
+
adoptSchematicNetNames(board, sch);
|
|
3553
|
+
let links;
|
|
3554
|
+
if (sch) {
|
|
3555
|
+
const footprints = board ? new Map(board.components.map((c) => [c.reference, `${lib}:${footprintName(c)}`])) : undefined;
|
|
3556
|
+
const out = emitKicadSchProject(sch, p.base, { footprints, library: lib });
|
|
3557
|
+
for (const [name, text] of out.files)
|
|
3558
|
+
await writeFile(join(outDir, name), text, "utf8");
|
|
3559
|
+
await writeFile(join(outDir, `${lib}.kicad_sym`), out.symbolLibrary, "utf8");
|
|
3560
|
+
await addLibTableEntry(join(outDir, "sym-lib-table"), "sym_lib_table", lib, `\${KIPRJMOD}/${lib}.kicad_sym`, "Symbols from the Multisim design (multisim2kicad)");
|
|
3561
|
+
links = out.links;
|
|
3562
|
+
written.push(join(outDir, `${p.base}.kicad_sch`));
|
|
3563
|
+
reportSch(p.sch.input, sch, out.files.size);
|
|
3564
|
+
}
|
|
3565
|
+
if (board) {
|
|
3566
|
+
const path = join(outDir, `${p.base}.kicad_pcb`);
|
|
3567
|
+
await writeFile(path, emitKicadPcb(board, { footprintLib: lib, links }), "utf8");
|
|
3568
|
+
written.push(path);
|
|
3569
|
+
const pretty = join(outDir, `${lib}.pretty`);
|
|
3570
|
+
await mkdir(pretty, { recursive: true });
|
|
3571
|
+
for (const [name, text] of emitFootprintLibrary(board, parsed.library))
|
|
3572
|
+
await writeFile(join(pretty, name), text, "utf8");
|
|
3573
|
+
await addLibTableEntry(join(outDir, "fp-lib-table"), "fp_lib_table", lib, `\${KIPRJMOD}/${lib}.pretty`, "Footprints from the Ultiboard design (multisim2kicad)");
|
|
3574
|
+
reportPcb(p.pcb.input, board, links);
|
|
3575
|
+
}
|
|
3576
|
+
if (board) {
|
|
3577
|
+
const dru = boardCustomRules(board);
|
|
3578
|
+
if (dru)
|
|
3579
|
+
await writeFile(join(outDir, `${p.base}.kicad_dru`), dru, "utf8");
|
|
3580
|
+
}
|
|
3581
|
+
await writeProjectFile(join(outDir, `${p.base}.kicad_pro`), !!sch, board);
|
|
3582
|
+
return written;
|
|
3583
|
+
}
|
|
3584
|
+
function adoptSchematicNetNames(board, sch) {
|
|
3585
|
+
const names = new Map;
|
|
3586
|
+
for (const sheet of sch.sheets) {
|
|
3587
|
+
const all = [
|
|
3588
|
+
...sheet.labels.map((l) => l.name),
|
|
3589
|
+
...sheet.symbols.filter((s) => s.kind === "power").map((s) => s.value),
|
|
3590
|
+
...sheet.buses.flatMap((b) => b.members)
|
|
3591
|
+
];
|
|
3592
|
+
for (const n of all)
|
|
3593
|
+
if (n && !names.has(n.toUpperCase()))
|
|
3594
|
+
names.set(n.toUpperCase(), n);
|
|
3595
|
+
}
|
|
3596
|
+
const rename = (n) => names.get(n.toUpperCase()) ?? n;
|
|
3597
|
+
for (const net of board.nets)
|
|
3598
|
+
net.name = rename(net.name);
|
|
3599
|
+
for (const z of board.zones)
|
|
3600
|
+
z.netName = rename(z.netName);
|
|
3601
|
+
for (const v of board.vias)
|
|
3602
|
+
if (v.netName)
|
|
3603
|
+
v.netName = rename(v.netName);
|
|
3604
|
+
}
|
|
3605
|
+
function reportPcb(input, board, links) {
|
|
3606
|
+
const enabled = board.layers.filter((l) => l.state !== 0);
|
|
3607
|
+
const w = (board.workArea.right - board.workArea.left) / NM_PER_MM3;
|
|
3608
|
+
const h = (board.workArea.top - board.workArea.bottom) / NM_PER_MM3;
|
|
3609
|
+
const padCount = board.components.reduce((n, c) => n + c.pads.length, 0);
|
|
3610
|
+
const plated = board.holes.filter((x) => x.plated).length;
|
|
3611
|
+
const netPins = board.nets.reduce((n, net) => n + net.pins.length, 0);
|
|
3612
|
+
console.log(`${basename(input)}`);
|
|
3613
|
+
console.log(` app: ${board.source.application} v${board.source.versionMajor}.${board.source.versionMinor} (schema ${board.source.schema})`);
|
|
3614
|
+
console.log(` project: ${board.projectName}`);
|
|
3615
|
+
console.log(` sheet: "${board.sheetTitle}" workArea ${w.toFixed(1)} x ${h.toFixed(1)} mm`);
|
|
3616
|
+
console.log(` layers: ${board.layers.length} EW layers (${enabled.length} enabled), ${board.stackup.copper.length} copper`);
|
|
3617
|
+
console.log(` parts: ${board.components.length} (${padCount} pads)`);
|
|
3618
|
+
console.log(` tracks: ${board.tracks.length} vias: ${board.vias.length} zones: ${board.zones.length}`);
|
|
3619
|
+
console.log(` holes: ${board.holes.length} (${plated} plated, ${board.holes.length - plated} mounting)`);
|
|
3620
|
+
console.log(` nets: ${board.nets.length} (${netPins} pin refs)`);
|
|
3621
|
+
if (links) {
|
|
3622
|
+
const linked = board.components.filter((c) => links.has(c.reference)).length;
|
|
3623
|
+
console.log(` linked: ${linked}/${board.components.length} footprints to schematic symbols`);
|
|
3624
|
+
}
|
|
3625
|
+
}
|
|
3626
|
+
function reportSch(input, sch, fileCount) {
|
|
3627
|
+
console.log(`${basename(input)}`);
|
|
3628
|
+
console.log(` app: ${sch.source.application} v${sch.source.versionMajor}.${sch.source.versionMinor} (schema ${sch.source.schema})`);
|
|
3629
|
+
console.log(` project: ${sch.projectName}`);
|
|
3630
|
+
for (const sheet of sch.sheets) {
|
|
3631
|
+
const pinCount = sheet.symbols.reduce((n, s) => n + s.pins.length, 0);
|
|
3632
|
+
const power = sheet.symbols.filter((s) => s.kind === "power").length;
|
|
3633
|
+
console.log(` sheet: "${sheet.name}" ${sheet.size.width} x ${sheet.size.height} units`);
|
|
3634
|
+
console.log(` symbols: ${sheet.symbols.length - power} parts + ${power} power ports (${pinCount} pins)`);
|
|
3635
|
+
console.log(` wires: ${sheet.wires.length} labels: ${sheet.labels.length} buses: ${sheet.buses.length}`);
|
|
3636
|
+
}
|
|
3637
|
+
console.log(` instances: ${countInstances(sch.root)} sheet instance(s), ${fileCount} file(s)`);
|
|
3638
|
+
}
|
|
3639
|
+
var countInstances = (i) => 1 + i.children.reduce((n, c) => n + countInstances(c), 0);
|
|
3640
|
+
async function writeProjectFile(path, schematic, board) {
|
|
3641
|
+
let pro = {};
|
|
3642
|
+
try {
|
|
3643
|
+
pro = JSON.parse(await readFile2(path, "utf8"));
|
|
3644
|
+
} catch {}
|
|
3645
|
+
pro.meta ??= { filename: basename(path), version: 3 };
|
|
3646
|
+
if (schematic)
|
|
3647
|
+
pro.schematic = { ...pro.schematic ?? {}, ...kicadProSchematicSettings() };
|
|
3648
|
+
const rules = board && boardProjectSettings(board);
|
|
3649
|
+
if (rules) {
|
|
3650
|
+
pro.board ??= {};
|
|
3651
|
+
pro.board.design_settings ??= {};
|
|
3652
|
+
pro.board.design_settings.rules = { ...pro.board.design_settings.rules ?? {}, ...rules.rules };
|
|
3653
|
+
pro.net_settings = rules.netSettings;
|
|
3654
|
+
}
|
|
3655
|
+
await writeFile(path, `${JSON.stringify(pro, null, 2)}
|
|
3656
|
+
`, "utf8");
|
|
3657
|
+
}
|
|
3658
|
+
async function addLibTableEntry(path, head, name, uri, descr) {
|
|
3659
|
+
const q = (s) => JSON.stringify(s);
|
|
3660
|
+
const entry = ` (lib (name ${q(name)}) (type "KiCad") (uri ${q(uri)}) (options "") (descr ${q(descr)}))`;
|
|
3661
|
+
let lines = [];
|
|
3662
|
+
try {
|
|
3663
|
+
lines = (await readFile2(path, "utf8")).split(/\r?\n/).filter((l) => l.trim().startsWith("(lib "));
|
|
3664
|
+
} catch {}
|
|
3665
|
+
lines = lines.filter((l) => !l.includes(`(name ${q(name)})`));
|
|
3666
|
+
await writeFile(path, [`(${head}`, ` (version 7)`, ...lines, entry, `)`, ``].join(`
|
|
3667
|
+
`), "utf8");
|
|
3668
|
+
}
|
|
3669
|
+
var DESIGN_FILE = /\.(ewprj|ms1\d)(\.xml)?$/i;
|
|
3670
|
+
async function groupProjects(paths) {
|
|
3671
|
+
const files = [];
|
|
3672
|
+
for (const p of paths) {
|
|
3673
|
+
if ((await stat(p)).isDirectory()) {
|
|
3674
|
+
for (const e of await readdir(p, { withFileTypes: true }))
|
|
3675
|
+
if (e.isFile() && DESIGN_FILE.test(e.name))
|
|
3676
|
+
files.push(join(p, e.name));
|
|
3677
|
+
} else
|
|
3678
|
+
files.push(p);
|
|
3679
|
+
}
|
|
3680
|
+
const projects = new Map;
|
|
3681
|
+
for (const file of files) {
|
|
3682
|
+
const design = await loadDesign(file);
|
|
3683
|
+
const base = designBaseName(file);
|
|
3684
|
+
const key = join(resolve(dirname(file)), base).toLowerCase();
|
|
3685
|
+
const proj = projects.get(key) ?? { base };
|
|
3686
|
+
const half = design.kind === "schematic" ? "sch" : "pcb";
|
|
3687
|
+
if (proj[half])
|
|
3688
|
+
throw new Error(`${file}: a second ${half === "sch" ? "schematic" : "board"} for project ${base} (${proj[half].input})`);
|
|
3689
|
+
proj[half] = { input: file, xml: design.xml };
|
|
3690
|
+
projects.set(key, proj);
|
|
3691
|
+
}
|
|
3692
|
+
return [...projects.values()];
|
|
3693
|
+
}
|
|
3694
|
+
async function main(args = process.argv.slice(2)) {
|
|
3695
|
+
let outDir = "out";
|
|
3696
|
+
const inputs = [];
|
|
3697
|
+
for (let i = 0;i < args.length; i++) {
|
|
3698
|
+
if (args[i] === "-o" || args[i] === "--out")
|
|
3699
|
+
outDir = args[++i] ?? outDir;
|
|
3700
|
+
else
|
|
3701
|
+
inputs.push(args[i]);
|
|
3702
|
+
}
|
|
3703
|
+
if (inputs.length === 0) {
|
|
3704
|
+
console.error("usage: multisim2kicad [-o <outDir>] <design.ms14 | design.ewprj | folder | database.prj> [...]");
|
|
3705
|
+
console.error(" A schematic and board with the same name in the same folder become one linked KiCad project.");
|
|
3706
|
+
process.exit(2);
|
|
3707
|
+
}
|
|
3708
|
+
const designs = [];
|
|
3709
|
+
for (const i of inputs) {
|
|
3710
|
+
if (DATABASE_FILE.test(i))
|
|
3711
|
+
await convertDatabase(i, outDir);
|
|
3712
|
+
else
|
|
3713
|
+
designs.push(i);
|
|
3714
|
+
}
|
|
3715
|
+
for (const p of await groupProjects(designs))
|
|
3716
|
+
await convertProject(p, outDir);
|
|
3717
|
+
}
|
|
3718
|
+
var DATABASE_FILE = /\.(prj|usr|prd)$/i;
|
|
3719
|
+
async function convertDatabase(input, outDir) {
|
|
3720
|
+
await mkdir(outDir, { recursive: true });
|
|
3721
|
+
const db = readEwDatabase(await readFile2(input), input);
|
|
3722
|
+
const lib = libNickname(basename(input).replace(DATABASE_FILE, ""));
|
|
3723
|
+
const fps = databaseFootprints(db);
|
|
3724
|
+
const h = harmonizeFootprints(footprintBoard(fps.components, lib));
|
|
3725
|
+
const pretty = join(outDir, `${lib}.pretty`);
|
|
3726
|
+
await mkdir(pretty, { recursive: true });
|
|
3727
|
+
for (const [name, text] of emitFootprintLibrary(h.board, h.library))
|
|
3728
|
+
await writeFile(join(pretty, name), text, "utf8");
|
|
3729
|
+
await addLibTableEntry(join(outDir, "fp-lib-table"), "fp_lib_table", lib, `\${KIPRJMOD}/${lib}.pretty`, `Footprints from the EW database ${basename(input)} (multisim2kicad)`);
|
|
3730
|
+
const syms = databaseSymbols(db, (pkg) => {
|
|
3731
|
+
const name = footprintName({ name: pkg });
|
|
3732
|
+
return h.library.has(name) ? `${lib}:${name}` : undefined;
|
|
3733
|
+
});
|
|
3734
|
+
const symPath = join(outDir, `${lib}.kicad_sym`);
|
|
3735
|
+
await writeFile(symPath, librarySymbolsFile(syms.specs), "utf8");
|
|
3736
|
+
await addLibTableEntry(join(outDir, "sym-lib-table"), "sym_lib_table", lib, `\${KIPRJMOD}/${lib}.kicad_sym`, `Symbols from the EW database ${basename(input)} (multisim2kicad)`);
|
|
3737
|
+
const reasons = new Map;
|
|
3738
|
+
for (const s of fps.skipped)
|
|
3739
|
+
reasons.set(s.reason, (reasons.get(s.reason) ?? 0) + 1);
|
|
3740
|
+
console.log(`${input}`);
|
|
3741
|
+
console.log(` footprints: ${h.library.size} -> ${pretty}`);
|
|
3742
|
+
console.log(` symbols: ${syms.specs.length} -> ${symPath} (${syms.specs.filter((x) => x.footprint).length} with a footprint here)`);
|
|
3743
|
+
for (const w of syms.warnings.slice(0, 20))
|
|
3744
|
+
console.log(` warning: ${w}`);
|
|
3745
|
+
if (syms.warnings.length > 20)
|
|
3746
|
+
console.log(` ... ${syms.warnings.length - 20} more warnings`);
|
|
3747
|
+
if (reasons.size)
|
|
3748
|
+
console.log(` skipped: ${[...reasons].map(([r, n]) => `${n} ${r}`).join(", ")}`);
|
|
3749
|
+
}
|
|
3750
|
+
|
|
3751
|
+
// src/cli.ts
|
|
3752
|
+
main().catch((err) => {
|
|
3753
|
+
console.error(err);
|
|
3754
|
+
process.exit(1);
|
|
3755
|
+
});
|