formacad 0.0.0-stage → 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.
Files changed (73) hide show
  1. package/LICENSE +200 -0
  2. package/README.md +87 -2
  3. package/build/cli/src/forma.d.ts +2 -0
  4. package/build/cli/src/forma.js +285 -0
  5. package/build/cli/src/forma.js.map +1 -0
  6. package/build/cli/src/preview.d.ts +3 -0
  7. package/build/cli/src/preview.js +268 -0
  8. package/build/cli/src/preview.js.map +1 -0
  9. package/build/core/fonts/Roboto-Bold.ttf +0 -0
  10. package/build/core/fonts/Roboto-Regular.ttf +0 -0
  11. package/build/core/src/bevel.d.ts +41 -0
  12. package/build/core/src/bevel.js +548 -0
  13. package/build/core/src/bevel.js.map +1 -0
  14. package/build/core/src/difflib.d.ts +3 -0
  15. package/build/core/src/difflib.js +94 -0
  16. package/build/core/src/difflib.js.map +1 -0
  17. package/build/core/src/errors.d.ts +9 -0
  18. package/build/core/src/errors.js +14 -0
  19. package/build/core/src/errors.js.map +1 -0
  20. package/build/core/src/export2d.d.ts +7 -0
  21. package/build/core/src/export2d.js +79 -0
  22. package/build/core/src/export2d.js.map +1 -0
  23. package/build/core/src/geometry.d.ts +92 -0
  24. package/build/core/src/geometry.js +946 -0
  25. package/build/core/src/geometry.js.map +1 -0
  26. package/build/core/src/host.d.ts +28 -0
  27. package/build/core/src/host.js +113 -0
  28. package/build/core/src/host.js.map +1 -0
  29. package/build/core/src/importers.d.ts +11 -0
  30. package/build/core/src/importers.js +711 -0
  31. package/build/core/src/importers.js.map +1 -0
  32. package/build/core/src/index.d.ts +81 -0
  33. package/build/core/src/index.js +155 -0
  34. package/build/core/src/index.js.map +1 -0
  35. package/build/core/src/inflate.d.ts +15 -0
  36. package/build/core/src/inflate.js +230 -0
  37. package/build/core/src/inflate.js.map +1 -0
  38. package/build/core/src/interp.d.ts +142 -0
  39. package/build/core/src/interp.js +2026 -0
  40. package/build/core/src/interp.js.map +1 -0
  41. package/build/core/src/lexer.d.ts +14 -0
  42. package/build/core/src/lexer.js +217 -0
  43. package/build/core/src/lexer.js.map +1 -0
  44. package/build/core/src/manifold.d.ts +26 -0
  45. package/build/core/src/manifold.js +687 -0
  46. package/build/core/src/manifold.js.map +1 -0
  47. package/build/core/src/parser.d.ts +46 -0
  48. package/build/core/src/parser.js +408 -0
  49. package/build/core/src/parser.js.map +1 -0
  50. package/build/core/src/std.d.ts +3 -0
  51. package/build/core/src/std.js +47 -0
  52. package/build/core/src/std.js.map +1 -0
  53. package/build/core/src/threemf.d.ts +4 -0
  54. package/build/core/src/threemf.js +127 -0
  55. package/build/core/src/threemf.js.map +1 -0
  56. package/build/core/src/ttf.d.ts +39 -0
  57. package/build/core/src/ttf.js +473 -0
  58. package/build/core/src/ttf.js.map +1 -0
  59. package/build/core/src/values.d.ts +116 -0
  60. package/build/core/src/values.js +294 -0
  61. package/build/core/src/values.js.map +1 -0
  62. package/build/core/src/xml.d.ts +13 -0
  63. package/build/core/src/xml.js +152 -0
  64. package/build/core/src/xml.js.map +1 -0
  65. package/build/core/std/electronics.forma +120 -0
  66. package/build/core/std/enclosures.forma +76 -0
  67. package/build/core/std/fasteners.forma +170 -0
  68. package/build/core/std/gridfinity.forma +182 -0
  69. package/build/core/std/joints.forma +120 -0
  70. package/build/core/std/mechanics.forma +276 -0
  71. package/build/core/std/patterns.forma +138 -0
  72. package/build/core/std/threads.forma +152 -0
  73. package/package.json +58 -4
@@ -0,0 +1,711 @@
1
+ // Readers for STL, OBJ (+MTL), SVG and 3MF. Ported from the Python reference engine.
2
+ import { FormaError } from './errors.js';
3
+ import { fan, makePoly, pyRound, quality, segmentsFor } from './geometry.js';
4
+ import { basename, dirname, join } from './host.js';
5
+ import { attrLocal, iterElements, parseXml, XmlError } from './xml.js';
6
+ import { ZipReader } from './inflate.js';
7
+ import { suggest } from './difflib.js';
8
+ function readBytes(host, path, pos) {
9
+ try {
10
+ return host.readBytes(path);
11
+ }
12
+ catch (e) {
13
+ throw new FormaError(`can't read '${path}': ${e?.message ?? e}`, pos);
14
+ }
15
+ }
16
+ const decodeUtf8 = (b) => new TextDecoder('utf-8').decode(b);
17
+ /** Python's float(): strict, so '' and '1.2.3' are errors. */
18
+ export function pyFloat(s) {
19
+ if (s === undefined || s === null)
20
+ throw new TypeError('missing number');
21
+ const t = s.trim();
22
+ if (/^[+-]?(\d+\.?\d*|\.\d+)([eE][+-]?\d+)?$/.test(t))
23
+ return parseFloat(t);
24
+ if (/^[+-]?(inf|infinity)$/i.test(t))
25
+ return t.startsWith('-') ? -Infinity : Infinity;
26
+ if (/^[+-]?nan$/i.test(t))
27
+ return NaN;
28
+ throw new RangeError(`could not convert string to float: '${s}'`);
29
+ }
30
+ function pyInt(s) {
31
+ if (s === undefined || s === null)
32
+ throw new TypeError('missing number');
33
+ const t = s.trim();
34
+ if (!/^[+-]?\d+$/.test(t))
35
+ throw new RangeError(`invalid literal for int(): '${s}'`);
36
+ return parseInt(t, 10);
37
+ }
38
+ const keep = (list) => list.filter((p) => p !== null);
39
+ // ---- STL ------------------------------------------------------------------------------
40
+ export function readStl(host, path, pos) {
41
+ const data = readBytes(host, path, pos);
42
+ const name = basename(path);
43
+ let tris = [];
44
+ const dv = new DataView(data.buffer, data.byteOffset, data.byteLength);
45
+ if (data.length >= 84 && 84 + 50 * dv.getUint32(80, true) === data.length) {
46
+ const n = dv.getUint32(80, true);
47
+ for (let i = 0; i < n; i++) {
48
+ const o = 84 + 50 * i;
49
+ const f = (k) => dv.getFloat32(o + 4 * k, true);
50
+ tris.push([[f(3), f(4), f(5)], [f(6), f(7), f(8)], [f(9), f(10), f(11)]]);
51
+ }
52
+ }
53
+ else {
54
+ const words = decodeUtf8(data).split(/\s+/).filter(Boolean);
55
+ const verts = [];
56
+ words.forEach((w, i) => {
57
+ if (w === 'vertex') {
58
+ try {
59
+ verts.push(words.slice(i + 1, i + 4).map(pyFloat));
60
+ }
61
+ catch {
62
+ throw new FormaError(`'${name}' is not a valid STL file`, pos);
63
+ }
64
+ }
65
+ });
66
+ if (!verts.length || verts.length % 3)
67
+ throw new FormaError(`'${name}' is not a valid STL file`, pos);
68
+ for (let i = 0; i < verts.length; i += 3)
69
+ tris.push(verts.slice(i, i + 3));
70
+ }
71
+ const out = keep(tris.map((t) => makePoly(t)));
72
+ if (!out.length)
73
+ throw new FormaError(`'${name}' has no triangles`, pos);
74
+ return out;
75
+ }
76
+ // ---- OBJ ------------------------------------------------------------------------------
77
+ function readMtl(host, path) {
78
+ const colors = new Map();
79
+ let text;
80
+ try {
81
+ text = decodeUtf8(host.readBytes(path));
82
+ }
83
+ catch {
84
+ return colors;
85
+ }
86
+ let name = null;
87
+ for (const line of text.split('\n')) {
88
+ const parts = line.split('#', 1)[0].split(/\s+/).filter(Boolean);
89
+ if (!parts.length)
90
+ continue;
91
+ if (parts[0] === 'newmtl') {
92
+ name = parts.slice(1).join(' ');
93
+ }
94
+ else if (parts[0] === 'Kd' && name !== null && parts.length >= 4) {
95
+ try {
96
+ const [r, g, b] = parts.slice(1, 4).map((x) => Math.min(1, Math.max(0, pyFloat(x))));
97
+ const hex = (x) => pyRound(x * 255).toString(16).padStart(2, '0');
98
+ colors.set(name, '#' + hex(r) + hex(g) + hex(b));
99
+ }
100
+ catch {
101
+ // ignore a broken colour, like the Python engine
102
+ }
103
+ }
104
+ }
105
+ return colors;
106
+ }
107
+ export function readObj(host, path, pos) {
108
+ const name = basename(path);
109
+ const lines = decodeUtf8(readBytes(host, path, pos)).split('\n');
110
+ const verts = [];
111
+ const out = [];
112
+ const mtl = new Map();
113
+ let color = null;
114
+ lines.forEach((line, k) => {
115
+ const lineno = k + 1;
116
+ const parts = line.split('#', 1)[0].split(/\s+/).filter(Boolean);
117
+ if (!parts.length)
118
+ return;
119
+ const kind = parts[0];
120
+ try {
121
+ if (kind === 'v') {
122
+ if (parts.length < 4)
123
+ throw new RangeError('short');
124
+ verts.push([pyFloat(parts[1]), pyFloat(parts[2]), pyFloat(parts[3])]);
125
+ }
126
+ else if (kind === 'f') {
127
+ const idx = [];
128
+ for (const tok of parts.slice(1)) {
129
+ let i = pyInt(tok.split('/')[0]);
130
+ i = i > 0 ? i - 1 : verts.length + i;
131
+ if (!(i >= 0 && i < verts.length)) {
132
+ throw new FormaError(`${name} line ${lineno}: the face uses vertex ${tok}, which doesn't exist`, pos);
133
+ }
134
+ idx.push(i);
135
+ }
136
+ const pts = idx.map((i) => verts[i]);
137
+ for (const tri of pts.length > 3 ? fan(pts) : [pts]) {
138
+ const q = makePoly(tri, color);
139
+ if (q)
140
+ out.push(q);
141
+ }
142
+ }
143
+ else if (kind === 'mtllib') {
144
+ for (const [k2, v] of readMtl(host, join(dirname(path), parts.slice(1).join(' '))))
145
+ mtl.set(k2, v);
146
+ }
147
+ else if (kind === 'usemtl') {
148
+ color = mtl.get(parts.slice(1).join(' ')) ?? null;
149
+ }
150
+ }
151
+ catch (e) {
152
+ if (e instanceof FormaError)
153
+ throw e;
154
+ throw new FormaError(`${name} line ${lineno}: can't read '${line.trim().slice(0, 40)}'`, pos);
155
+ }
156
+ });
157
+ if (!out.length)
158
+ throw new FormaError(`'${name}' has no faces`, pos);
159
+ return out;
160
+ }
161
+ // ---- SVG ------------------------------------------------------------------------------
162
+ const NUM = '[-+]?(?:\\d*\\.\\d+|\\d+\\.?)(?:[eE][-+]?\\d+)?';
163
+ const svgNumAll = () => new RegExp(NUM, 'g');
164
+ const SVG_UNIT_MM = { mm: 1.0, cm: 10.0, in: 25.4, pt: 25.4 / 72, pc: 25.4 / 6 };
165
+ const SVG_SKIP = new Set(['defs', 'clipPath', 'mask', 'symbol', 'style', 'title', 'desc', 'metadata', 'pattern',
166
+ 'marker', 'linearGradient', 'radialGradient', 'filter', 'text', 'image', 'script']);
167
+ function svgLength(text, pxMm) {
168
+ const m = new RegExp(`^\\s*(${NUM})\\s*([a-z%]*)\\s*$`).exec(text ?? '');
169
+ if (!m)
170
+ return null;
171
+ const v = parseFloat(m[1]), unit = m[2];
172
+ if (unit === '' || unit === 'px')
173
+ return v * pxMm;
174
+ return unit in SVG_UNIT_MM ? v * SVG_UNIT_MM[unit] : null;
175
+ }
176
+ function svgFloat(text, def = 0) {
177
+ const m = new RegExp('^' + NUM).exec((text ?? '').trim());
178
+ return m ? parseFloat(m[0]) : def;
179
+ }
180
+ function affMul(m, n) {
181
+ const [a, b, c, d, e, f] = m;
182
+ const [A, B, C, D, E, F] = n;
183
+ return [a * A + c * B, b * A + d * B, a * C + c * D, b * C + d * D, a * E + c * F + e, b * E + d * F + f];
184
+ }
185
+ function svgTransform(text) {
186
+ let m = [1, 0, 0, 1, 0, 0];
187
+ const re = /(matrix|translate|scale|rotate|skewX|skewY)\s*\(([^)]*)\)/g;
188
+ for (const [, name, args] of (text ?? '').matchAll(re)) {
189
+ const v = (args.match(svgNumAll()) ?? []).map(parseFloat);
190
+ if (!v.length)
191
+ continue;
192
+ let t;
193
+ if (name === 'matrix' && v.length === 6)
194
+ t = v;
195
+ else if (name === 'translate')
196
+ t = [1, 0, 0, 1, v[0], v.length > 1 ? v[1] : 0];
197
+ else if (name === 'scale')
198
+ t = [v[0], 0, 0, v.length > 1 ? v[1] : v[0], 0, 0];
199
+ else if (name === 'rotate') {
200
+ const a = (v[0] * Math.PI) / 180;
201
+ t = [Math.cos(a), Math.sin(a), -Math.sin(a), Math.cos(a), 0, 0];
202
+ if (v.length === 3)
203
+ t = affMul(affMul([1, 0, 0, 1, v[1], v[2]], t), [1, 0, 0, 1, -v[1], -v[2]]);
204
+ }
205
+ else if (name === 'skewX')
206
+ t = [1, 0, Math.tan((v[0] * Math.PI) / 180), 1, 0, 0];
207
+ else if (name === 'skewY')
208
+ t = [1, Math.tan((v[0] * Math.PI) / 180), 0, 1, 0, 0];
209
+ else
210
+ continue;
211
+ m = affMul(m, t);
212
+ }
213
+ return m;
214
+ }
215
+ function svgArc(x1, y1, rx, ry, phi, fa, fs, x2, y2, segs) {
216
+ if (rx === 0 || ry === 0 || (x1 === x2 && y1 === y2))
217
+ return [[x2, y2]];
218
+ rx = Math.abs(rx);
219
+ ry = Math.abs(ry);
220
+ const cp = Math.cos((phi * Math.PI) / 180), sp = Math.sin((phi * Math.PI) / 180);
221
+ const dx = (x1 - x2) / 2, dy = (y1 - y2) / 2;
222
+ const x1p = cp * dx + sp * dy, y1p = -sp * dx + cp * dy;
223
+ const lam = (x1p * x1p) / (rx * rx) + (y1p * y1p) / (ry * ry);
224
+ if (lam > 1) {
225
+ rx *= Math.sqrt(lam);
226
+ ry *= Math.sqrt(lam);
227
+ }
228
+ const num = rx * rx * ry * ry - rx * rx * y1p * y1p - ry * ry * x1p * x1p;
229
+ const den = rx * rx * y1p * y1p + ry * ry * x1p * x1p;
230
+ let coef = den ? Math.sqrt(Math.max(0, num / den)) : 0;
231
+ if (fa === fs)
232
+ coef = -coef;
233
+ const cxp = (coef * rx * y1p) / ry, cyp = (-coef * ry * x1p) / rx;
234
+ const cx = cp * cxp - sp * cyp + (x1 + x2) / 2, cy = sp * cxp + cp * cyp + (y1 + y2) / 2;
235
+ const ang = (ux, uy, vx, vy) => Math.atan2(ux * vy - uy * vx, ux * vx + uy * vy);
236
+ const t1 = ang(1, 0, (x1p - cxp) / rx, (y1p - cyp) / ry);
237
+ let dt = ang((x1p - cxp) / rx, (y1p - cyp) / ry, (-x1p - cxp) / rx, (-y1p - cyp) / ry);
238
+ if (!fs && dt > 0)
239
+ dt -= 2 * Math.PI;
240
+ else if (fs && dt < 0)
241
+ dt += 2 * Math.PI;
242
+ const n = segs(Math.abs(dt) * Math.max(rx, ry));
243
+ const pts = [];
244
+ for (let k = 1; k < n; k++) {
245
+ const t = t1 + (dt * k) / n;
246
+ const ex = rx * Math.cos(t), ey = ry * Math.sin(t);
247
+ pts.push([cx + cp * ex - sp * ey, cy + sp * ex + cp * ey]);
248
+ }
249
+ pts.push([x2, y2]);
250
+ return pts;
251
+ }
252
+ function bezier(p0, p1, p2, p3, segs) {
253
+ const length = Math.hypot(p1[0] - p0[0], p1[1] - p0[1]) + Math.hypot(p2[0] - p1[0], p2[1] - p1[1])
254
+ + Math.hypot(p3[0] - p2[0], p3[1] - p2[1]);
255
+ const n = segs(length);
256
+ const out = [];
257
+ for (let k = 1; k <= n; k++) {
258
+ const t = k / n, u = 1 - t;
259
+ out.push([
260
+ u ** 3 * p0[0] + 3 * u * u * t * p1[0] + 3 * u * t * t * p2[0] + t ** 3 * p3[0],
261
+ u ** 3 * p0[1] + 3 * u * u * t * p1[1] + 3 * u * t * t * p2[1] + t ** 3 * p3[1],
262
+ ]);
263
+ }
264
+ return out;
265
+ }
266
+ class PathError extends Error {
267
+ }
268
+ /** Parses path data into closed sub-paths (lists of points in user units). */
269
+ function svgPath(d, segs) {
270
+ let i = 0;
271
+ const n = d.length;
272
+ const subpaths = [];
273
+ let cur = [];
274
+ let x = 0, y = 0, sx = 0, sy = 0;
275
+ let cmd = null, last = null;
276
+ let c2 = [0, 0], q1 = [0, 0];
277
+ const numRe = new RegExp(NUM, 'y');
278
+ const skip = () => { while (i < n && ' \t\r\n,'.includes(d[i]))
279
+ i++; };
280
+ const num = () => {
281
+ skip();
282
+ numRe.lastIndex = i;
283
+ const m = numRe.exec(d);
284
+ if (!m)
285
+ throw new PathError(`expected a number at character ${i}`);
286
+ i = numRe.lastIndex;
287
+ return parseFloat(m[0]);
288
+ };
289
+ const flag = () => {
290
+ skip();
291
+ if (i < n && (d[i] === '0' || d[i] === '1')) {
292
+ i++;
293
+ return d[i - 1] === '1';
294
+ }
295
+ throw new PathError(`expected an arc flag 0 or 1 at character ${i}`);
296
+ };
297
+ const finish = () => {
298
+ if (cur.length >= 3)
299
+ subpaths.push(cur);
300
+ cur = [];
301
+ };
302
+ for (;;) {
303
+ skip();
304
+ if (i >= n)
305
+ break;
306
+ const ch = d[i];
307
+ if (/\p{L}/u.test(ch)) {
308
+ cmd = ch;
309
+ i++;
310
+ }
311
+ else if (cmd === null || cmd === 'Z' || cmd === 'z')
312
+ throw new PathError("path data must start with a command like 'M'");
313
+ else if (cmd === 'M')
314
+ cmd = 'L';
315
+ else if (cmd === 'm')
316
+ cmd = 'l';
317
+ const rel = cmd !== cmd.toUpperCase();
318
+ const C = cmd.toUpperCase();
319
+ const ox = rel ? x : 0, oy = rel ? y : 0;
320
+ if (C !== 'M' && !cur.length && C !== 'Z')
321
+ cur = [[x, y]];
322
+ if (C === 'M') {
323
+ finish();
324
+ x = num() + ox;
325
+ y = num() + oy;
326
+ sx = x;
327
+ sy = y;
328
+ cur = [[x, y]];
329
+ }
330
+ else if (C === 'L') {
331
+ x = num() + ox;
332
+ y = num() + oy;
333
+ cur.push([x, y]);
334
+ }
335
+ else if (C === 'H') {
336
+ x = num() + ox;
337
+ cur.push([x, y]);
338
+ }
339
+ else if (C === 'V') {
340
+ y = num() + oy;
341
+ cur.push([x, y]);
342
+ }
343
+ else if (C === 'C' || C === 'S') {
344
+ let p1;
345
+ if (C === 'C')
346
+ p1 = [num() + ox, num() + oy];
347
+ else
348
+ p1 = last === 'C' || last === 'S' ? [2 * x - c2[0], 2 * y - c2[1]] : [x, y];
349
+ const p2 = [num() + ox, num() + oy];
350
+ const p3 = [num() + ox, num() + oy];
351
+ cur.push(...bezier([x, y], p1, p2, p3, segs));
352
+ c2 = p2;
353
+ [x, y] = p3;
354
+ }
355
+ else if (C === 'Q' || C === 'T') {
356
+ let q;
357
+ if (C === 'Q')
358
+ q = [num() + ox, num() + oy];
359
+ else
360
+ q = last === 'Q' || last === 'T' ? [2 * x - q1[0], 2 * y - q1[1]] : [x, y];
361
+ const p3 = [num() + ox, num() + oy];
362
+ const p1 = [x + (2 / 3) * (q[0] - x), y + (2 / 3) * (q[1] - y)];
363
+ const p2 = [p3[0] + (2 / 3) * (q[0] - p3[0]), p3[1] + (2 / 3) * (q[1] - p3[1])];
364
+ cur.push(...bezier([x, y], p1, p2, p3, segs));
365
+ q1 = q;
366
+ [x, y] = p3;
367
+ }
368
+ else if (C === 'A') {
369
+ const rx = num(), ry = num(), phi = num();
370
+ const fa = flag(), fs = flag();
371
+ const nx = num() + ox, ny = num() + oy;
372
+ cur.push(...svgArc(x, y, rx, ry, phi, fa, fs, nx, ny, segs));
373
+ x = nx;
374
+ y = ny;
375
+ }
376
+ else if (C === 'Z') {
377
+ finish();
378
+ x = sx;
379
+ y = sy;
380
+ }
381
+ else {
382
+ throw new PathError(`unknown path command '${cmd}'`);
383
+ }
384
+ last = C;
385
+ }
386
+ finish();
387
+ return subpaths;
388
+ }
389
+ /** Returns [element description, closed outlines in mm][]. */
390
+ export function readSvg(host, path, pos, dpi = 96) {
391
+ const name = basename(path);
392
+ let root;
393
+ try {
394
+ root = parseXml(decodeUtf8(readBytes(host, path, pos)));
395
+ }
396
+ catch (e) {
397
+ if (e instanceof FormaError)
398
+ throw e;
399
+ throw new FormaError(`can't read '${name}': ${e?.message ?? e}`, pos);
400
+ }
401
+ const px = 25.4 / dpi;
402
+ const W = svgLength(root.attrs.get('width'), px), H = svgLength(root.attrs.get('height'), px);
403
+ const vb = (root.attrs.get('viewBox') ?? '').match(svgNumAll())?.map(parseFloat) ?? [];
404
+ let base;
405
+ if (vb.length === 4 && vb[2] > 0 && vb[3] > 0) {
406
+ let sxm = W ? W / vb[2] : null;
407
+ let sym = H ? H / vb[3] : null;
408
+ sxm = sxm || sym || px;
409
+ sym = sym || sxm;
410
+ base = [sxm, 0, 0, -sym, -vb[0] * sxm, (vb[1] + vb[3]) * sym];
411
+ }
412
+ else {
413
+ const top = H ? H / px : 0;
414
+ base = [px, 0, 0, -px, 0, top * px];
415
+ }
416
+ const scaleEst = Math.sqrt(Math.abs(base[0] * base[3]));
417
+ const fs = quality.fs / 3;
418
+ const segs = (lengthUser) => Math.max(4, Math.min(96, Math.ceil((lengthUser * scaleEst) / fs)));
419
+ const found = [];
420
+ const walk = (el, ctm) => {
421
+ const t = el.tag;
422
+ const style = el.attrs.get('style') ?? '';
423
+ if (SVG_SKIP.has(t) || el.attrs.get('display') === 'none' || style.replace(/ /g, '').includes('display:none'))
424
+ return;
425
+ ctm = affMul(ctm, svgTransform(el.attrs.get('transform')));
426
+ const id = el.attrs.get('id');
427
+ const label = `<${t}${id ? ` id="${id}"` : ''}>`;
428
+ let outlines = [];
429
+ const get = (k) => el.attrs.get(k);
430
+ try {
431
+ if (t === 'path') {
432
+ outlines = svgPath(get('d') ?? '', segs);
433
+ }
434
+ else if (t === 'rect') {
435
+ const x0 = svgFloat(get('x')), y0 = svgFloat(get('y'));
436
+ const w = svgFloat(get('width')), h = svgFloat(get('height'));
437
+ const rxA = get('rx'), ryA = get('ry');
438
+ let rx = svgFloat(rxA !== undefined ? rxA : ryA);
439
+ let ry = svgFloat(ryA !== undefined ? ryA : get('rx'));
440
+ rx = Math.min(rx, w / 2);
441
+ ry = Math.min(ry, h / 2);
442
+ if (w > 0 && h > 0) {
443
+ if (rx > 0 && ry > 0) {
444
+ const pts = [];
445
+ const n = segs((Math.PI / 2) * Math.max(rx, ry));
446
+ for (const [cx, cy, a0] of [[x0 + w - rx, y0 + ry, -90], [x0 + w - rx, y0 + h - ry, 0],
447
+ [x0 + rx, y0 + h - ry, 90], [x0 + rx, y0 + ry, 180]]) {
448
+ for (let k = 0; k <= n; k++) {
449
+ const a = ((a0 + (90 * k) / n) * Math.PI) / 180;
450
+ pts.push([cx + rx * Math.cos(a), cy + ry * Math.sin(a)]);
451
+ }
452
+ }
453
+ outlines = [pts];
454
+ }
455
+ else {
456
+ outlines = [[[x0, y0], [x0 + w, y0], [x0 + w, y0 + h], [x0, y0 + h]]];
457
+ }
458
+ }
459
+ }
460
+ else if (t === 'circle' || t === 'ellipse') {
461
+ const cx = svgFloat(get('cx')), cy = svgFloat(get('cy'));
462
+ let rx, ry;
463
+ if (t === 'circle')
464
+ rx = ry = svgFloat(get('r'));
465
+ else {
466
+ rx = svgFloat(get('rx'));
467
+ ry = svgFloat(get('ry'));
468
+ }
469
+ if (rx > 0 && ry > 0) {
470
+ const n = segmentsFor(Math.max(rx, ry) * scaleEst);
471
+ const pts = [];
472
+ for (let k = 0; k < n; k++) {
473
+ pts.push([cx + rx * Math.cos((2 * Math.PI * k) / n), cy + ry * Math.sin((2 * Math.PI * k) / n)]);
474
+ }
475
+ outlines = [pts];
476
+ }
477
+ }
478
+ else if (t === 'polygon' || t === 'polyline') {
479
+ const v = (get('points') ?? '').match(svgNumAll())?.map(parseFloat) ?? [];
480
+ const pts = [];
481
+ for (let k = 0; k + 1 < v.length; k += 2)
482
+ pts.push([v[k], v[k + 1]]);
483
+ outlines = [pts];
484
+ }
485
+ }
486
+ catch (e) {
487
+ if (e instanceof PathError)
488
+ throw new FormaError(`${name}: ${e.message} in ${label}`, pos);
489
+ throw e;
490
+ }
491
+ const mm = [];
492
+ for (const o of outlines) {
493
+ const [a, b, c, d, e, f] = affMul(base, ctm);
494
+ mm.push(o.map(([x, y]) => [a * x + c * y + e, b * x + d * y + f]));
495
+ }
496
+ if (mm.length)
497
+ found.push([label, mm]);
498
+ for (const child of el.children)
499
+ walk(child, ctm);
500
+ };
501
+ walk(root, [1, 0, 0, 1, 0, 0]);
502
+ return found;
503
+ }
504
+ // ---- 3MF ------------------------------------------------------------------------------
505
+ const UNIT_3MF = {
506
+ micron: 0.001, millimeter: 1.0, centimeter: 10.0, inch: 25.4, foot: 304.8, meter: 1000.0,
507
+ };
508
+ const M4_ID = [[1, 0, 0], [0, 1, 0], [0, 0, 1], [0, 0, 0]];
509
+ /** 3MF transform: 12 numbers, rows of a 4x3 matrix applied to row vectors [x y z 1]. */
510
+ function tf3mf(text) {
511
+ const parts = (text ?? '').split(/\s+/).filter(Boolean);
512
+ const v = parts.map(pyFloat);
513
+ if (v.length !== 12)
514
+ return M4_ID;
515
+ return [[v[0], v[1], v[2]], [v[3], v[4], v[5]], [v[6], v[7], v[8]], [v[9], v[10], v[11]]];
516
+ }
517
+ /** First a, then b. */
518
+ function tfMul(a, b) {
519
+ const rows = [];
520
+ for (let i = 0; i < 4; i++) {
521
+ const r = [0, 1, 2].map((j) => a[i][0] * b[0][j] + a[i][1] * b[1][j] + a[i][2] * b[2][j]);
522
+ rows.push((i === 3 ? r.map((x, j) => x + b[3][j]) : r));
523
+ }
524
+ return rows;
525
+ }
526
+ function tfApply(m, [x, y, z]) {
527
+ return [
528
+ x * m[0][0] + y * m[1][0] + z * m[2][0] + m[3][0],
529
+ x * m[0][1] + y * m[1][1] + z * m[2][1] + m[3][1],
530
+ x * m[0][2] + y * m[1][2] + z * m[2][2] + m[3][2],
531
+ ];
532
+ }
533
+ /** Returns [polygon sets — one per mesh part, object names]. */
534
+ export function read3mf(host, path, pos, only = null) {
535
+ const name = basename(path);
536
+ let zf;
537
+ try {
538
+ zf = new ZipReader(readBytes(host, path, pos));
539
+ }
540
+ catch (e) {
541
+ if (e instanceof FormaError)
542
+ throw e;
543
+ throw new FormaError(`'${name}' is not a valid 3MF file (it should be a zip archive)`, pos);
544
+ }
545
+ let total = 0;
546
+ for (const e of zf.entries.values())
547
+ total += e.usize;
548
+ if (total > 2_000_000_000)
549
+ throw new FormaError(`'${name}' unpacks to more than 2 GB — refusing to read it`, pos);
550
+ const names = new Map();
551
+ for (const n of zf.names())
552
+ names.set(n.toLowerCase(), n);
553
+ const readEntry = (n) => {
554
+ try {
555
+ return zf.read(n);
556
+ }
557
+ catch (e) {
558
+ throw new FormaError(`'${name}': can't unpack ${n} (${e?.message ?? e})`, pos);
559
+ }
560
+ };
561
+ let rootPath = '3D/3dmodel.model';
562
+ if (names.has('_rels/.rels')) {
563
+ try {
564
+ for (const rel of parseXml(decodeUtf8(readEntry(names.get('_rels/.rels')))).children) {
565
+ if ((rel.attrs.get('Type') ?? '').endsWith('/3dmodel')) {
566
+ rootPath = (rel.attrs.get('Target') || rootPath).replace(/^\/+/, '');
567
+ break;
568
+ }
569
+ }
570
+ }
571
+ catch (e) {
572
+ if (!(e instanceof XmlError))
573
+ throw e;
574
+ }
575
+ }
576
+ const models = new Map();
577
+ const load = (mpath) => {
578
+ const key = mpath.replace(/^\/+/, '').toLowerCase();
579
+ const cached = models.get(key);
580
+ if (cached)
581
+ return cached;
582
+ if (!names.has(key))
583
+ throw new FormaError(`'${name}' refers to '${mpath}', which is missing from the archive`, pos);
584
+ let root;
585
+ try {
586
+ root = parseXml(decodeUtf8(readEntry(names.get(key))));
587
+ }
588
+ catch (e) {
589
+ if (e instanceof FormaError)
590
+ throw e;
591
+ throw new FormaError(`'${name}': broken XML in ${mpath} (${e?.message ?? e})`, pos);
592
+ }
593
+ const objects = new Map();
594
+ const groups = new Map();
595
+ for (const el of iterElements(root)) {
596
+ if (el.tag === 'object') {
597
+ objects.set(el.attrs.get('id'), el);
598
+ }
599
+ else if (el.tag === 'basematerials' || el.tag === 'colorgroup') {
600
+ const cols = el.children.map((c) => {
601
+ const col = ((el.tag === 'basematerials' ? c.attrs.get('displaycolor') : c.attrs.get('color')) || '')
602
+ .trim().toLowerCase();
603
+ return /^#[0-9a-f]{6}([0-9a-f]{2})?$/.test(col) ? col : null;
604
+ });
605
+ groups.set(el.attrs.get('id'), cols);
606
+ }
607
+ }
608
+ const model = { root, objects, groups };
609
+ models.set(key, model);
610
+ return model;
611
+ };
612
+ const colorOf = (groups, pid, idx) => {
613
+ if (!groups.has(pid) || idx === undefined)
614
+ return null;
615
+ const t = idx.trim();
616
+ if (!/^[+-]?\d+$/.test(t))
617
+ return null;
618
+ const list = groups.get(pid);
619
+ let i = parseInt(t, 10);
620
+ if (i < 0)
621
+ i += list.length;
622
+ return i >= 0 && i < list.length ? list[i] : null;
623
+ };
624
+ const mesh = (mkey, oid, m, depth, out) => {
625
+ if (depth > 32)
626
+ throw new FormaError(`'${name}': components are nested too deeply (a loop?)`, pos);
627
+ const { objects, groups } = load(mkey);
628
+ const obj = objects.get(oid);
629
+ if (!obj)
630
+ throw new FormaError(`'${name}': object id ${oid ?? 'None'} is missing in ${mkey}`, pos);
631
+ const opid = obj.attrs.get('pid'), oidx = obj.attrs.get('pindex') ?? '0';
632
+ for (const child of obj.children) {
633
+ if (child.tag === 'mesh') {
634
+ const partPolys = [];
635
+ out.push(partPolys);
636
+ let verts = [];
637
+ let tris = [];
638
+ for (const part of child.children) {
639
+ if (part.tag === 'vertices') {
640
+ try {
641
+ verts = part.children.map((v) => tfApply(m, [pyFloat(v.attrs.get('x')), pyFloat(v.attrs.get('y')), pyFloat(v.attrs.get('z'))]));
642
+ }
643
+ catch {
644
+ throw new FormaError(`'${name}': a vertex has a broken coordinate`, pos);
645
+ }
646
+ }
647
+ else if (part.tag === 'triangles') {
648
+ tris = part.children;
649
+ }
650
+ }
651
+ for (const tri of tris) {
652
+ let pts;
653
+ try {
654
+ pts = ['v1', 'v2', 'v3'].map((k) => {
655
+ let i = pyInt(tri.attrs.get(k));
656
+ if (i < 0)
657
+ i += verts.length;
658
+ if (!(i >= 0 && i < verts.length))
659
+ throw new RangeError('index');
660
+ return verts[i];
661
+ });
662
+ }
663
+ catch {
664
+ throw new FormaError(`'${name}': a triangle uses a vertex that doesn't exist`, pos);
665
+ }
666
+ const col = colorOf(groups, tri.attrs.get('pid') ?? opid, tri.attrs.get('p1') ?? oidx);
667
+ const q = makePoly(pts, col);
668
+ if (q)
669
+ partPolys.push(q);
670
+ }
671
+ }
672
+ else if (child.tag === 'components') {
673
+ for (const comp of child.children) {
674
+ const sub = attrLocal(comp, 'path');
675
+ mesh(sub ? sub : mkey, comp.attrs.get('objectid'), tfMul(tf3mf(comp.attrs.get('transform')), m), depth + 1, out);
676
+ }
677
+ }
678
+ }
679
+ };
680
+ const { root } = load(rootPath);
681
+ const unit = UNIT_3MF[root.attrs.get('unit') ?? 'millimeter'] ?? 1.0;
682
+ const items = [...iterElements(root)].filter((el) => el.tag === 'item');
683
+ const available = [];
684
+ const sets = [];
685
+ for (const item of items) {
686
+ const sub = attrLocal(item, 'path');
687
+ const mkey = sub ? sub : rootPath;
688
+ const oid = item.attrs.get('objectid');
689
+ const obj = load(mkey).objects.get(oid);
690
+ const oname = (obj ? obj.attrs.get('name') : undefined) || `object ${oid ?? 'None'}`;
691
+ available.push(oname);
692
+ if (only !== null && oname !== only)
693
+ continue;
694
+ const parts = [];
695
+ mesh(mkey, oid, tf3mf(item.attrs.get('transform')), 0, parts);
696
+ for (let polys of parts) {
697
+ if (unit !== 1.0) {
698
+ polys = keep(polys.map((p) => makePoly(p.v.map(([x, y, z]) => [x * unit, y * unit, z * unit]), p.c)));
699
+ }
700
+ sets.push(polys);
701
+ }
702
+ }
703
+ if (only !== null && !sets.length) {
704
+ throw new FormaError(`'${name}' has no object named '${only}'${suggest(only, available)}. `
705
+ + `Objects: ${available.join(', ') || 'none'}`, pos);
706
+ }
707
+ if (!sets.some((s) => s.length))
708
+ throw new FormaError(`'${name}' has no triangles`, pos);
709
+ return [sets, available];
710
+ }
711
+ //# sourceMappingURL=importers.js.map