formacad 0.0.0-stage → 0.2.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 (97) hide show
  1. package/LICENSE +200 -0
  2. package/README.md +98 -2
  3. package/build/cli/src/forma.d.ts +2 -0
  4. package/build/cli/src/forma.js +546 -0
  5. package/build/cli/src/forma.js.map +1 -0
  6. package/build/cli/src/mcp.d.ts +1 -0
  7. package/build/cli/src/mcp.js +495 -0
  8. package/build/cli/src/mcp.js.map +1 -0
  9. package/build/cli/src/preview.d.ts +31 -0
  10. package/build/cli/src/preview.js +427 -0
  11. package/build/cli/src/preview.js.map +1 -0
  12. package/build/core/fonts/Roboto-Bold.ttf +0 -0
  13. package/build/core/fonts/Roboto-Regular.ttf +0 -0
  14. package/build/core/src/bevel.d.ts +41 -0
  15. package/build/core/src/bevel.js +548 -0
  16. package/build/core/src/bevel.js.map +1 -0
  17. package/build/core/src/difflib.d.ts +3 -0
  18. package/build/core/src/difflib.js +94 -0
  19. package/build/core/src/difflib.js.map +1 -0
  20. package/build/core/src/errors.d.ts +9 -0
  21. package/build/core/src/errors.js +14 -0
  22. package/build/core/src/errors.js.map +1 -0
  23. package/build/core/src/export2d.d.ts +10 -0
  24. package/build/core/src/export2d.js +127 -0
  25. package/build/core/src/export2d.js.map +1 -0
  26. package/build/core/src/geometry.d.ts +93 -0
  27. package/build/core/src/geometry.js +946 -0
  28. package/build/core/src/geometry.js.map +1 -0
  29. package/build/core/src/gltf.d.ts +6 -0
  30. package/build/core/src/gltf.js +154 -0
  31. package/build/core/src/gltf.js.map +1 -0
  32. package/build/core/src/host.d.ts +28 -0
  33. package/build/core/src/host.js +113 -0
  34. package/build/core/src/host.js.map +1 -0
  35. package/build/core/src/importers.d.ts +12 -0
  36. package/build/core/src/importers.js +1025 -0
  37. package/build/core/src/importers.js.map +1 -0
  38. package/build/core/src/index.d.ts +92 -0
  39. package/build/core/src/index.js +227 -0
  40. package/build/core/src/index.js.map +1 -0
  41. package/build/core/src/inflate.d.ts +15 -0
  42. package/build/core/src/inflate.js +230 -0
  43. package/build/core/src/inflate.js.map +1 -0
  44. package/build/core/src/interp.d.ts +178 -0
  45. package/build/core/src/interp.js +3012 -0
  46. package/build/core/src/interp.js.map +1 -0
  47. package/build/core/src/lexer.d.ts +14 -0
  48. package/build/core/src/lexer.js +217 -0
  49. package/build/core/src/lexer.js.map +1 -0
  50. package/build/core/src/manifold.d.ts +26 -0
  51. package/build/core/src/manifold.js +687 -0
  52. package/build/core/src/manifold.js.map +1 -0
  53. package/build/core/src/modeling.d.ts +18 -0
  54. package/build/core/src/modeling.js +483 -0
  55. package/build/core/src/modeling.js.map +1 -0
  56. package/build/core/src/parser.d.ts +46 -0
  57. package/build/core/src/parser.js +478 -0
  58. package/build/core/src/parser.js.map +1 -0
  59. package/build/core/src/scad/colors.d.ts +1 -0
  60. package/build/core/src/scad/colors.js +37 -0
  61. package/build/core/src/scad/colors.js.map +1 -0
  62. package/build/core/src/scad/convert.d.ts +33 -0
  63. package/build/core/src/scad/convert.js +2842 -0
  64. package/build/core/src/scad/convert.js.map +1 -0
  65. package/build/core/src/scad/parser.d.ts +239 -0
  66. package/build/core/src/scad/parser.js +578 -0
  67. package/build/core/src/scad/parser.js.map +1 -0
  68. package/build/core/src/scad/sources.d.ts +39 -0
  69. package/build/core/src/scad/sources.js +171 -0
  70. package/build/core/src/scad/sources.js.map +1 -0
  71. package/build/core/src/std.d.ts +3 -0
  72. package/build/core/src/std.js +47 -0
  73. package/build/core/src/std.js.map +1 -0
  74. package/build/core/src/surface.d.ts +21 -0
  75. package/build/core/src/surface.js +253 -0
  76. package/build/core/src/surface.js.map +1 -0
  77. package/build/core/src/threemf.d.ts +4 -0
  78. package/build/core/src/threemf.js +127 -0
  79. package/build/core/src/threemf.js.map +1 -0
  80. package/build/core/src/ttf.d.ts +39 -0
  81. package/build/core/src/ttf.js +473 -0
  82. package/build/core/src/ttf.js.map +1 -0
  83. package/build/core/src/values.d.ts +146 -0
  84. package/build/core/src/values.js +365 -0
  85. package/build/core/src/values.js.map +1 -0
  86. package/build/core/src/xml.d.ts +13 -0
  87. package/build/core/src/xml.js +152 -0
  88. package/build/core/src/xml.js.map +1 -0
  89. package/build/core/std/electronics.forma +120 -0
  90. package/build/core/std/enclosures.forma +76 -0
  91. package/build/core/std/fasteners.forma +170 -0
  92. package/build/core/std/gridfinity.forma +182 -0
  93. package/build/core/std/joints.forma +120 -0
  94. package/build/core/std/mechanics.forma +276 -0
  95. package/build/core/std/patterns.forma +138 -0
  96. package/build/core/std/threads.forma +152 -0
  97. package/package.json +59 -4
@@ -0,0 +1,3012 @@
1
+ // The interpreter: runs a parsed program and produces a Shape. Ported from the Python reference engine;
2
+ // every message, label and check is kept identical so both engines pass the same tests.
3
+ import { FormaError } from './errors.js';
4
+ import { lex, UNITS } from './lexer.js';
5
+ import { Parser } from './parser.js';
6
+ import { suggest } from './difflib.js';
7
+ import { bboxOf, convexHull2d, convexHull3d, csgIntersectMany, csgSubtract, csgSubtractMany, csgUnion, fan, makePoly, matDet, matMul, openEdges, pointInOutline, prism2d, primBox, primCone, primSphere, primTorus, pyRound, quality, rotAxis, rotX, rotY, rotZ, segmentsFor, signedArea, sliceZ, stretchZ, cleanOutline, volume, } from './geometry.js';
8
+ import { manifoldContoursToPrism, manifoldHull3d, manifoldMinkowski, manifoldOffset2d, manifoldProject, manifoldSlice } from './manifold.js';
9
+ import { applyBevel2d, applyBevel3d, EDGE_SELECTORS } from './bevel.js';
10
+ import { loft3d, SHELL_FACES, shell3d, sweep3d } from './modeling.js';
11
+ import { getBundledFont, layoutText, parseTtfBytes } from './ttf.js';
12
+ import { getStdSource, listStdModules } from './std.js';
13
+ import { basename, dirname, extname, join, readText, stem } from './host.js';
14
+ import { read3mf, readDxf, readObj, readStl, readSvg } from './importers.js';
15
+ import { buildSurfaceMesh, decodePngGray, downsampleGrid, MAX_SURFACE_MESH_CELLS, MAX_SURFACE_MESH_RES, parseHeightText, } from './surface.js';
16
+ import { BBox, BUILTIN_LAYERS, Builtin, Closure, Component, dimExp, Enum, Env, EXP_DIM, flattenShapes, FontValue, RandomValue, RangeValue, StructInstance, StructType, FunctionValue, LayerValue, Module, Q, Shape, show, typename, } from './values.js';
17
+ export const COLORS = {
18
+ white: '#f4f6f8', black: '#1d1f22', red: '#d64541', orange: '#f08a24', yellow: '#f4d03f',
19
+ green: '#3fa34d', blue: '#3a78c9', purple: '#8e5bc5', pink: '#f29bb8', brown: '#7b4a2e',
20
+ gray: '#8a9099', grey: '#8a9099', silver: '#c4cad2', gold: '#d4a72c',
21
+ };
22
+ export const SHAPE_METHODS = ['at', 'move', 'rotate', 'scale', 'resize', 'mirror', 'transform', 'align', 'above', 'below', 'leftOf', 'rightOf', 'inFrontOf', 'behind', 'color', 'layer', 'extrude', 'revolve', 'offset', 'slice', 'project', 'fillet', 'chamfer', 'shell', 'sweep'];
23
+ const REQUIRED = Symbol('required');
24
+ const radians = (d) => (d * Math.PI) / 180;
25
+ const degrees = (r) => (r * 180) / Math.PI;
26
+ const isQ = (v) => v instanceof Q;
27
+ const isList = (v) => Array.isArray(v);
28
+ const isWhole = (x) => Number.isFinite(x) && x === Math.trunc(x);
29
+ class ReturnSignal {
30
+ value;
31
+ constructor(value) {
32
+ this.value = value;
33
+ }
34
+ }
35
+ /** Labelled and positional arguments of a call, with the checks shared by all builtins. */
36
+ class Args {
37
+ f;
38
+ pos;
39
+ vals = new Map();
40
+ constructor(f, args, pos, allowed, positional = []) {
41
+ this.f = f;
42
+ this.pos = pos;
43
+ let pi = 0;
44
+ for (let [label, val, apos] of args) {
45
+ if (label === null) {
46
+ if (pi >= positional.length) {
47
+ const hint = allowed.map((a) => a + ':').join(', ');
48
+ throw new FormaError(`${f}: add a label to this value (${hint})`, apos);
49
+ }
50
+ label = positional[pi++];
51
+ }
52
+ if (!allowed.includes(label)) {
53
+ throw new FormaError(`${f} has no parameter '${label}'${suggest(label, allowed)}. Available: ${allowed.join(', ')}`, apos);
54
+ }
55
+ if (this.vals.has(label))
56
+ throw new FormaError(`${f}: '${label}' is given twice`, apos);
57
+ this.vals.set(label, [val, apos]);
58
+ }
59
+ }
60
+ has(label) {
61
+ return this.vals.has(label);
62
+ }
63
+ at(label) {
64
+ return this.vals.get(label)[1];
65
+ }
66
+ raw(label, def = REQUIRED) {
67
+ if (!this.vals.has(label)) {
68
+ if (def === REQUIRED)
69
+ throw new FormaError(`${this.f} needs '${label}:'`, this.pos);
70
+ return def;
71
+ }
72
+ return this.vals.get(label)[0];
73
+ }
74
+ q(label, def, dim, what) {
75
+ if (!this.vals.has(label)) {
76
+ if (def === REQUIRED)
77
+ throw new FormaError(`${this.f} needs '${label}:' (${what})`, this.pos);
78
+ return def;
79
+ }
80
+ const [v, apos] = this.vals.get(label);
81
+ if (!isQ(v) || (v.dim !== null && v.dim !== dim)) {
82
+ throw new FormaError(`${this.f}: ${label}: must be ${what}, got ${typename(v)} (${show(v)})`, apos);
83
+ }
84
+ return v.v;
85
+ }
86
+ length(label, def = REQUIRED) { return this.q(label, def, 'len', 'a length like 10mm'); }
87
+ angle(label, def = REQUIRED) { return this.q(label, def, 'angle', 'an angle like 45deg'); }
88
+ number(label, def = REQUIRED) { return this.q(label, def, null, 'a plain number'); }
89
+ flag(label, def = false) {
90
+ const v = this.raw(label, def);
91
+ if (typeof v !== 'boolean')
92
+ throw new FormaError(`${this.f}: ${label}: must be true or false`, this.at(label));
93
+ return v;
94
+ }
95
+ positive(label, value) {
96
+ if (value <= 0) {
97
+ throw new FormaError(`${this.f}: ${label} must be greater than 0`, this.has(label) ? this.at(label) : this.pos);
98
+ }
99
+ return value;
100
+ }
101
+ radius(r = 'r', d = 'd', def = REQUIRED) {
102
+ if (this.has(r) && this.has(d))
103
+ throw new FormaError(`${this.f}: give either ${r}: or ${d}:, not both`, this.pos);
104
+ if (this.has(d))
105
+ return this.positive(d, this.length(d)) / 2;
106
+ if (this.has(r) || def === REQUIRED) {
107
+ if (!this.has(r))
108
+ throw new FormaError(`${this.f} needs a size: '${r}:' (radius) or '${d}:' (diameter)`, this.pos);
109
+ return this.positive(r, this.length(r));
110
+ }
111
+ return def;
112
+ }
113
+ }
114
+ function checkSameKind(shapes, what, pos) {
115
+ const kinds = new Set(shapes.map((s) => s.is2d));
116
+ if (kinds.size > 1) {
117
+ throw new FormaError(`${what} mixes 2D and 3D shapes — turn the 2D ones into 3D first with .extrude(height:) or .revolve()`, pos);
118
+ }
119
+ return kinds.size ? [...kinds][0] : false;
120
+ }
121
+ function combine(shapes, what, pos) {
122
+ const active = shapes.filter((s) => s.layer.exportable || s.layer.overlay);
123
+ if (!active.length)
124
+ return new Shape([]);
125
+ const is2d = checkSameKind(active, what, pos);
126
+ if (active.length === 1)
127
+ return active[0];
128
+ return new Shape(csgUnion(active.map((s) => s.world())), undefined, undefined, null, is2d);
129
+ }
130
+ export function qArith(op, a, b, pos) {
131
+ const da = a.dim, db = b.dim;
132
+ if (op === '+' || op === '-' || op === '%') {
133
+ if (da && db && da !== db) {
134
+ const verb = { '+': 'add', '-': 'subtract', '%': 'take the remainder of' }[op];
135
+ throw new FormaError(`can't ${verb} ${typename(a)} (${a}) and ${typename(b)} (${b})`, pos);
136
+ }
137
+ if (op === '%') {
138
+ if (b.v === 0)
139
+ throw new FormaError('remainder by zero', pos);
140
+ return new Q(a.v % b.v, da || db);
141
+ }
142
+ return new Q(op === '+' ? a.v + b.v : a.v - b.v, da || db);
143
+ }
144
+ if (op === '*') {
145
+ if (da === 'angle' || db === 'angle') {
146
+ if (da && db)
147
+ throw new FormaError(`can't multiply ${a} by ${b}`, pos);
148
+ return new Q(a.v * b.v, da || db);
149
+ }
150
+ const e = dimExp(da) + dimExp(db);
151
+ if (e > 3)
152
+ throw new FormaError(`${a} * ${b} would give mm${'⁴⁵⁶'[e - 4]} — Forma only knows mm, mm² and mm³`, pos);
153
+ return new Q(a.v * b.v, EXP_DIM[e]);
154
+ }
155
+ if (op === '/') {
156
+ if (b.v === 0)
157
+ throw new FormaError('division by zero', pos);
158
+ if (da === 'angle' || db === 'angle') {
159
+ if (da === db)
160
+ return new Q(a.v / b.v);
161
+ if (db)
162
+ throw new FormaError(`can't divide ${typename(a)} by ${typename(b)}`, pos);
163
+ return new Q(a.v / b.v, da);
164
+ }
165
+ const e = dimExp(da) - dimExp(db);
166
+ if (e < 0)
167
+ throw new FormaError(`can't divide ${typename(a)} (${a}) by ${typename(b)} (${b})`, pos);
168
+ return new Q(a.v / b.v, EXP_DIM[e]);
169
+ }
170
+ if (op === '^') {
171
+ if (db)
172
+ throw new FormaError(`the power must be a plain number, got ${typename(b)}`, pos);
173
+ if (da === 'angle')
174
+ throw new FormaError("can't raise an angle to a power", pos);
175
+ let dim = null;
176
+ if (da) {
177
+ const e = dimExp(da) * b.v;
178
+ if (!isWhole(e) || !(e >= 0 && e <= 3))
179
+ throw new FormaError(`${a} ^ ${b} doesn't give mm, mm² or mm³`, pos);
180
+ dim = EXP_DIM[e];
181
+ }
182
+ if (a.v < 0 && !isWhole(b.v))
183
+ throw new FormaError("can't raise a negative number to a fractional power", pos);
184
+ const r = a.v ** b.v;
185
+ if (!Number.isFinite(r) && Number.isFinite(a.v) && Number.isFinite(b.v))
186
+ throw new FormaError('the number is too large', pos);
187
+ return new Q(r, dim);
188
+ }
189
+ throw new FormaError(`unknown operator '${op}'`, pos);
190
+ }
191
+ export class Interp {
192
+ host;
193
+ overrides;
194
+ rawOverrides;
195
+ modules = new Map();
196
+ loading = [];
197
+ moduleDepth = 0;
198
+ callEnv = null;
199
+ params = new Map();
200
+ paramMeta = new Map();
201
+ log = [];
202
+ exported = null;
203
+ /** Shapes collected per layer for multi-layer preview and --layer export. */
204
+ layerMeta = new Map();
205
+ layerEntries = new Map();
206
+ /** Top-level shapes grouped by exportable layer name (when multiple exportable layers are used). */
207
+ exportLayerShapes = new Map();
208
+ funcDepth = 0;
209
+ builtins = new Env();
210
+ globals;
211
+ path;
212
+ constructor(opts) {
213
+ this.host = opts.host;
214
+ this.overrides = opts.overrides ?? new Map();
215
+ this.rawOverrides = opts.rawOverrides ?? new Map();
216
+ const table = {
217
+ Bezier: this.bBezier, Box: this.bBox, Circle: this.bCircle, Cone: this.bCone, Cylinder: this.bCylinder, Difference: this.bDifference,
218
+ Extrude: this.bExtrude, Font: this.bFont, ForEach: this.bForEach, Helix: this.bHelix, Hull: this.bHull, Import: this.bImport,
219
+ Intersection: this.bIntersection, Layer: this.bLayer, Loft: this.bLoft, Minkowski: this.bMinkowski, Offset: this.bOffset,
220
+ Polygon: this.bPolygon, Polyhedron: this.bPolyhedron, Project: this.bProject,
221
+ Random: this.bRandom, Rect: this.bRect, Revolve: this.bRevolve, Slice: this.bSlice,
222
+ Sphere: this.bSphere, Spline: this.bSpline, Surface: this.bSurface, Text: this.bText, Torus: this.bTorus, Union: this.bUnion,
223
+ abs: this.bAbs, acos: this.bAcos, asin: this.bAsin, assert: this.bAssert, atan: this.bAtan, atan2: this.bAtan2,
224
+ ceil: this.bCeil, chr: this.bChr, concat: this.bConcat, cos: this.bCos, cross: this.bCross, dot: this.bDot, exp: this.bExp,
225
+ floor: this.bFloor, isAngle: this.bIsAngle, isArea: this.bIsArea, isBool: this.bIsBool, isFunction: this.bIsFunction,
226
+ isLength: this.bIsLength, isList: this.bIsList, isNumber: this.bIsNumber, isShape: this.bIsShape, isString: this.bIsString,
227
+ isVolume: this.bIsVolume,
228
+ log: this.bLog, log10: this.bLog10, max: this.bMax, min: this.bMin, norm: this.bNorm, ord: this.bOrd,
229
+ pow: this.bPow, print: this.bPrint, round: this.bRound, sign: this.bSign, sin: this.bSin, sqrt: this.bSqrt,
230
+ stride: this.bStride, tan: this.bTan, typeOf: this.bTypeOf,
231
+ };
232
+ for (const [name, fn] of Object.entries(table))
233
+ this.builtins.vars.set(name, new Builtin(name, fn.bind(this)));
234
+ this.builtins.vars.set('Cube', this.builtins.vars.get('Box'));
235
+ this.builtins.vars.set('Group', this.builtins.vars.get('Union'));
236
+ this.builtins.vars.set('Square', this.builtins.vars.get('Rect'));
237
+ this.builtins.vars.set('pi', new Q(Math.PI));
238
+ this.globals = new Env(this.builtins);
239
+ this.path = opts.path ?? null;
240
+ this.globals.vars.set(' dir', this.path ? dirname(this.path) : this.host.cwd());
241
+ }
242
+ // ---- running -------------------------------------------------------------------------
243
+ run(prog, allow2d = false) {
244
+ const declared = prog.filter((st) => st[0] === 'param').map((st) => st[2]);
245
+ for (const name of new Set([...this.overrides.keys(), ...this.rawOverrides.keys()])) {
246
+ if (!declared.includes(name))
247
+ throw new FormaError(`-D ${name}: there is no 'param ${name}' in the file${suggest(name, declared)}`);
248
+ }
249
+ const top = [];
250
+ for (const st of prog)
251
+ this.exec(st, this.globals, top);
252
+ let result;
253
+ if (this.exported !== null) {
254
+ result = this.exported;
255
+ if (result.layer.exportable)
256
+ this.recordExportLayer(result.layer, result);
257
+ }
258
+ else if (!top.length) {
259
+ throw new FormaError("the file doesn't create any shapes — write a shape like Sphere(r: 10mm), or use 'export'");
260
+ }
261
+ else {
262
+ for (const s of top) {
263
+ if (s.layer.exportable && s.layer.name === 'default')
264
+ this.recordExportLayer(BUILTIN_LAYERS.default, s);
265
+ }
266
+ result = combine(top, 'the file', null);
267
+ }
268
+ if (result.is2d && !allow2d) {
269
+ throw new FormaError('the result is a flat 2D shape, which cannot be printed — make it 3D with .extrude(height: 5mm) or .revolve()');
270
+ }
271
+ return result;
272
+ }
273
+ recordLayerEntry(layer, shape) {
274
+ if (!this.layerMeta.has(layer.name))
275
+ this.layerMeta.set(layer.name, layer);
276
+ let list = this.layerEntries.get(layer.name);
277
+ if (!list) {
278
+ list = [];
279
+ this.layerEntries.set(layer.name, list);
280
+ }
281
+ const colored = layer.color && shape.color === null ? shape.derive({ color: layer.color }) : shape;
282
+ list.push(colored);
283
+ }
284
+ recordExportLayer(layer, shape) {
285
+ if (!this.layerMeta.has(layer.name))
286
+ this.layerMeta.set(layer.name, layer);
287
+ let list = this.exportLayerShapes.get(layer.name);
288
+ if (!list) {
289
+ list = [];
290
+ this.exportLayerShapes.set(layer.name, list);
291
+ }
292
+ list.push(shape);
293
+ }
294
+ resolveColorArg(v, apos) {
295
+ let cname = v instanceof Enum ? v.name : typeof v === 'string' ? v : null;
296
+ if (cname === null)
297
+ throw new FormaError('color must be a color name (like .blue) or "#rrggbb"', apos);
298
+ if (!cname.startsWith('#')) {
299
+ if (!(cname in COLORS)) {
300
+ throw new FormaError(`unknown color '${cname}'${suggest(cname, Object.keys(COLORS))}. Available: ${Object.keys(COLORS).join(', ')}`, apos);
301
+ }
302
+ return COLORS[cname];
303
+ }
304
+ if (Array.from(cname).length !== 7 || !/^#[0-9a-fA-F]{6}$/.test(cname)) {
305
+ throw new FormaError('colors in hex look like "#ff8800"', apos);
306
+ }
307
+ return cname;
308
+ }
309
+ resolveLayerTarget(v, pos) {
310
+ if (v instanceof LayerValue)
311
+ return v;
312
+ if (v instanceof Enum) {
313
+ const builtins = Object.keys(BUILTIN_LAYERS);
314
+ if (v.name in BUILTIN_LAYERS)
315
+ return BUILTIN_LAYERS[v.name];
316
+ throw new FormaError(`unknown built-in layer '.${v.name}'${suggest(v.name, builtins)}. Available: ${builtins.map((b) => '.' + b).join(', ')}`, pos);
317
+ }
318
+ throw new FormaError('.layer needs a Layer(...) value or a built-in layer (.default, .debug, .reference, .hidden)', pos);
319
+ }
320
+ applyLayerToShape(shape, layer) {
321
+ if (layer.overlay) {
322
+ this.recordLayerEntry(layer, shape);
323
+ // Overlay shapes (like .debug) still participate in booleans on .default
324
+ return shape;
325
+ }
326
+ if (!layer.exportable) {
327
+ this.recordLayerEntry(layer, shape);
328
+ const colored = layer.color && shape.color === null ? shape.derive({ color: layer.color, layer }) : shape.derive({ layer });
329
+ return colored;
330
+ }
331
+ const next = layer.color && shape.color === null ? shape.derive({ color: layer.color, layer }) : shape.derive({ layer });
332
+ if (layer.name !== 'default')
333
+ this.recordExportLayer(layer, next);
334
+ return next;
335
+ }
336
+ doImport(st, env) {
337
+ const [, pos, rel, alias] = st;
338
+ if (!env.vars.has(' dir'))
339
+ throw new FormaError('import must be at the top of the file, not inside a block', pos);
340
+ if (!rel.endsWith('.forma'))
341
+ throw new FormaError(`import loads .forma files; for meshes use Import("${rel}") as a shape`, pos);
342
+ let mod;
343
+ if (rel.startsWith('std/')) {
344
+ const name = rel.slice(4);
345
+ const src = getStdSource(name);
346
+ if (src === null) {
347
+ const avail = listStdModules();
348
+ throw new FormaError(`unknown standard library 'std/${name}'${suggest(name, avail)}. Available: ${avail.map((f) => 'std/' + f).join(', ')}`, pos);
349
+ }
350
+ mod = this.loadModuleFromSource('std/' + name, src, pos);
351
+ }
352
+ else {
353
+ const full = join(env.vars.get(' dir'), rel);
354
+ if (!this.host.isFile(full))
355
+ throw new FormaError(`can't find '${rel}' (looked for ${full})`, pos);
356
+ mod = this.loadModule(full, pos);
357
+ }
358
+ if (alias) {
359
+ env.define(alias, mod, pos);
360
+ return;
361
+ }
362
+ for (const name of mod.names()) {
363
+ if (env.vars.has(name)) {
364
+ const s = stem(basename(rel));
365
+ throw new FormaError(`'${name}' from ${rel} clashes with a name defined here — use: import "${rel}" as ${s.replace(/-/g, '_')}`, pos);
366
+ }
367
+ env.vars.set(name, mod.env.vars.get(name));
368
+ }
369
+ }
370
+ loadModuleFromSource(key, source, pos) {
371
+ if (this.modules.has(key))
372
+ return this.modules.get(key);
373
+ if (this.loading.includes(key)) {
374
+ const chain = this.loading.slice(this.loading.indexOf(key)).concat(key).map(basename).join(' → ');
375
+ throw new FormaError(`circular import: ${chain}`, pos);
376
+ }
377
+ this.loading.push(key);
378
+ this.moduleDepth++;
379
+ try {
380
+ const env = new Env(this.builtins);
381
+ env.vars.set(' dir', dirname(key));
382
+ for (const st of new Parser(lex(source, key)).program())
383
+ this.exec(st, env, []);
384
+ const mod = new Module(stem(basename(key)), env, key);
385
+ this.modules.set(key, mod);
386
+ return mod;
387
+ }
388
+ finally {
389
+ this.moduleDepth--;
390
+ this.loading.pop();
391
+ }
392
+ }
393
+ loadModule(full, pos) {
394
+ const cached = this.modules.get(full);
395
+ if (cached)
396
+ return cached;
397
+ if (this.loading.includes(full) || full === this.path) {
398
+ const chain = [...this.loading, full].map((p) => basename(p)).join(' → ');
399
+ throw new FormaError(`import cycle: ${chain}`, pos);
400
+ }
401
+ const prog = new Parser(lex(readText(this.host, full), full)).program();
402
+ const env = new Env(this.builtins);
403
+ env.vars.set(' dir', dirname(full));
404
+ this.loading.push(full);
405
+ this.moduleDepth++;
406
+ try {
407
+ for (const st of prog)
408
+ this.exec(st, env, []);
409
+ }
410
+ finally {
411
+ this.moduleDepth--;
412
+ this.loading.pop();
413
+ }
414
+ const mod = new Module(stem(basename(full)), env, full);
415
+ this.modules.set(full, mod);
416
+ return mod;
417
+ }
418
+ runBlock(stmts, env, collect) {
419
+ for (const st of stmts)
420
+ this.exec(st, env, collect);
421
+ }
422
+ exec(st, env, collect) {
423
+ const kind = st[0], pos = st[1];
424
+ if (kind === 'expr') {
425
+ flattenShapes(this.eval(st[2], env), collect);
426
+ }
427
+ else if (kind === 'let') {
428
+ env.define(st[2], this.eval(st[3], env), pos);
429
+ }
430
+ else if (kind === 'param' && this.moduleDepth) {
431
+ env.define(st[2], this.eval(st[3], env), pos); // params of a library are just constants
432
+ }
433
+ else if (kind === 'param') {
434
+ const name = st[2];
435
+ const defVal = this.eval(st[3], env);
436
+ let val;
437
+ if (this.overrides.has(name)) {
438
+ val = this.overrides.get(name);
439
+ }
440
+ else if (this.rawOverrides.has(name)) {
441
+ if (typeof defVal === 'string') {
442
+ val = this.rawOverrides.get(name);
443
+ }
444
+ else {
445
+ throw new FormaError(`-D ${name}: can't read value '${this.rawOverrides.get(name)}'`, pos);
446
+ }
447
+ }
448
+ else {
449
+ val = defVal;
450
+ }
451
+ const constraint = st[4] ?? null;
452
+ if (constraint) {
453
+ if (constraint.kind === 'range') {
454
+ const lo = this.eval(constraint.min, env);
455
+ const hi = this.eval(constraint.max, env);
456
+ if (!(val instanceof Q) || !(lo instanceof Q) || !(hi instanceof Q)) {
457
+ throw new FormaError(`param '${name}' range bounds and value must be numbers or quantities`, pos);
458
+ }
459
+ if (val.dim !== lo.dim || lo.dim !== hi.dim) {
460
+ throw new FormaError(`param '${name}' range units don't match: ${typename(val)} vs ${typename(lo)}...${typename(hi)}`, pos);
461
+ }
462
+ if (lo.v >= hi.v) {
463
+ throw new FormaError(`param '${name}' min (${show(lo)}) must be less than max (${show(hi)})`, pos);
464
+ }
465
+ let stepStr;
466
+ if (constraint.step) {
467
+ const stVal = this.eval(constraint.step, env);
468
+ if (!(stVal instanceof Q) || stVal.dim !== val.dim || stVal.v <= 0) {
469
+ throw new FormaError(`param '${name}' step must be a positive ${typename(val)}`, pos);
470
+ }
471
+ stepStr = show(stVal);
472
+ }
473
+ if (val.v < lo.v || val.v > hi.v) {
474
+ throw new FormaError(`param '${name}' = ${show(val)} is outside ${show(lo)}...${show(hi)}`, pos);
475
+ }
476
+ let animateMeta;
477
+ if (constraint.animate) {
478
+ const anim = constraint.animate;
479
+ if (anim.closure)
480
+ throw new FormaError(`param '${name}': .animate() does not take a block`, anim.pos);
481
+ const allowed = ['duration', 'frames', 'loop', 'ease'];
482
+ const seen = new Set();
483
+ let duration = 3;
484
+ let frames = 24;
485
+ let loop = 'cycle';
486
+ let ease = 'linear';
487
+ for (const [lbl, expr, apos] of anim.args) {
488
+ if (!lbl)
489
+ throw new FormaError(`param '${name}': .animate() expects named arguments (duration:, frames:, loop:, ease:)`, apos);
490
+ if (!allowed.includes(lbl)) {
491
+ throw new FormaError(`param '${name}': unknown .animate() option '${lbl}'${suggest(lbl, allowed)}`, apos);
492
+ }
493
+ if (seen.has(lbl))
494
+ throw new FormaError(`param '${name}': duplicate .animate() option '${lbl}'`, apos);
495
+ seen.add(lbl);
496
+ const av = this.eval(expr, env);
497
+ if (lbl === 'duration') {
498
+ if (!(av instanceof Q) || av.dim !== null || av.v <= 0) {
499
+ throw new FormaError(`param '${name}': .animate(duration:) must be a positive number of seconds`, apos);
500
+ }
501
+ duration = av.v;
502
+ }
503
+ else if (lbl === 'frames') {
504
+ if (!(av instanceof Q) || av.dim !== null || !Number.isInteger(av.v) || av.v < 2 || av.v > 600) {
505
+ throw new FormaError(`param '${name}': .animate(frames:) must be a whole number from 2 to 600`, apos);
506
+ }
507
+ frames = av.v;
508
+ }
509
+ else if (lbl === 'loop') {
510
+ const loops = ['cycle', 'bounce', 'once'];
511
+ if (!(av instanceof Enum) || !loops.includes(av.name)) {
512
+ const hint = av instanceof Enum ? suggest(av.name, loops) : '';
513
+ throw new FormaError(`param '${name}': .animate(loop:) must be .cycle, .bounce, or .once${hint}`, apos);
514
+ }
515
+ loop = av.name;
516
+ }
517
+ else if (lbl === 'ease') {
518
+ const eases = ['linear', 'in', 'out', 'inOut'];
519
+ if (!(av instanceof Enum) || !eases.includes(av.name)) {
520
+ const hint = av instanceof Enum ? suggest(av.name, eases) : '';
521
+ throw new FormaError(`param '${name}': .animate(ease:) must be .linear, .in, .out, or .inOut${hint}`, apos);
522
+ }
523
+ ease = av.name;
524
+ }
525
+ }
526
+ animateMeta = { duration, frames, loop, ease };
527
+ }
528
+ const meta = { min: show(lo), max: show(hi) };
529
+ if (stepStr)
530
+ meta.step = stepStr;
531
+ if (animateMeta)
532
+ meta.animate = animateMeta;
533
+ this.paramMeta.set(name, meta);
534
+ }
535
+ else if (constraint.kind === 'options') {
536
+ const opts = this.eval(constraint.expr, env);
537
+ if (!isList(opts) || opts.length === 0) {
538
+ throw new FormaError(`param '${name}' options after 'in' must be a non-empty list`, pos);
539
+ }
540
+ const eq = (a, b) => (a instanceof Q && b instanceof Q && a.dim === b.dim && a.v === b.v)
541
+ || (a instanceof Enum && b instanceof Enum && a.name === b.name)
542
+ || pyEquals(a, b);
543
+ if (!opts.some((o) => eq(val, o))) {
544
+ throw new FormaError(`param '${name}' = ${show(val)} must be one of: ${opts.map(show).join(', ')}`, pos);
545
+ }
546
+ this.paramMeta.set(name, { options: opts.map(show) });
547
+ }
548
+ }
549
+ if (typeof defVal === 'string' || typeof val === 'string') {
550
+ const existing = this.paramMeta.get(name) ?? {};
551
+ this.paramMeta.set(name, { ...existing, type: 'string' });
552
+ }
553
+ this.params.set(name, val);
554
+ env.define(name, val, pos);
555
+ }
556
+ else if (kind === 'component') {
557
+ env.define(st[2], new Component(st[2], st[3], st[4], env, pos), pos);
558
+ }
559
+ else if (kind === 'func') {
560
+ env.define(st[2], new FunctionValue(st[2], st[3], st[4], env, pos), pos);
561
+ }
562
+ else if (kind === 'struct') {
563
+ const sname = st[2];
564
+ const fields = st[3];
565
+ const seen = new Set();
566
+ for (const [fname, , fpos] of fields) {
567
+ if (seen.has(fname))
568
+ throw new FormaError(`struct '${sname}' already has a field '${fname}'`, fpos);
569
+ seen.add(fname);
570
+ }
571
+ const methods = new Map();
572
+ for (const m of st[4]) {
573
+ const mname = m[2];
574
+ if (seen.has(mname) || methods.has(mname)) {
575
+ throw new FormaError(`struct '${sname}' already has a member '${mname}'`, m[1]);
576
+ }
577
+ methods.set(mname, new FunctionValue(mname, m[3], m[4], env, m[1]));
578
+ }
579
+ env.define(sname, new StructType(sname, fields, methods, env, pos), pos);
580
+ }
581
+ else if (kind === 'return') {
582
+ if (this.funcDepth === 0)
583
+ throw new FormaError("'return' can only be used inside a func", pos);
584
+ throw new ReturnSignal(this.eval(st[2], env));
585
+ }
586
+ else if (kind === 'import') {
587
+ this.doImport(st, env);
588
+ }
589
+ else if (kind === 'export' && this.moduleDepth) {
590
+ // a library's export is ignored when it is imported
591
+ }
592
+ else if (kind === 'export') {
593
+ const v = this.eval(st[2], env);
594
+ const shapes = [];
595
+ flattenShapes(v, shapes);
596
+ if (!shapes.length)
597
+ throw new FormaError(`export needs a shape, got ${typename(v)}`, pos);
598
+ this.exported = combine(shapes, 'export', pos);
599
+ }
600
+ else if (kind === 'for') {
601
+ const seq = this.eval(st[3], env);
602
+ if (seq instanceof RangeValue) {
603
+ throw new FormaError(`'for' needs a whole-number range like 0..<4, or use stride(from: ${seq.lo}, to: ${seq.hi}, by: ...)`, pos);
604
+ }
605
+ if (!isList(seq))
606
+ throw new FormaError(`'for' needs a list or range like 0..<4, got ${typename(seq)}`, pos);
607
+ for (const item of seq) {
608
+ const inner = new Env(env);
609
+ inner.define(st[2], item, pos);
610
+ this.runBlock(st[4], inner, collect);
611
+ }
612
+ }
613
+ else if (kind === 'if') {
614
+ const c = this.eval(st[2], env);
615
+ if (typeof c !== 'boolean')
616
+ throw new FormaError(`'if' needs true/false, got ${typename(c)}`, pos);
617
+ if (c)
618
+ this.runBlock(st[3], new Env(env), collect);
619
+ else if (st[4] !== null)
620
+ this.runBlock(st[4], new Env(env), collect);
621
+ }
622
+ }
623
+ // ---- expressions ---------------------------------------------------------------------
624
+ eval(e, env) {
625
+ const k = e[0], pos = e[1];
626
+ switch (k) {
627
+ case 'num': return new Q(e[2], e[3]);
628
+ case 'str':
629
+ case 'bool': return e[2];
630
+ case 'fstr': return e[2].map((part) => show(this.eval(part, env))).join('');
631
+ case 'name': {
632
+ if (env.has(e[2]))
633
+ return env.lookup(e[2]);
634
+ throw new FormaError(`unknown name '${e[2]}'${suggest(e[2], env.names())}`, pos);
635
+ }
636
+ case 'enum': return new Enum(e[2]);
637
+ case 'ternary': {
638
+ const c = this.eval(e[2], env);
639
+ if (typeof c !== 'boolean')
640
+ throw new FormaError(`the condition before '?' must be true/false, got ${typename(c)}`, pos);
641
+ return this.eval(c ? e[3] : e[4], env);
642
+ }
643
+ case 'index': {
644
+ const obj = this.eval(e[2], env), idx = this.eval(e[3], env);
645
+ if (typeof obj === 'string') {
646
+ if (!isQ(idx) || idx.dim !== null || !isWhole(idx.v)) {
647
+ throw new FormaError(`a text index must be a whole number like [0], got ${show(idx)}`, pos);
648
+ }
649
+ const chars = Array.from(obj);
650
+ const i = idx.v;
651
+ if (!(i >= 0 && i < chars.length)) {
652
+ throw new FormaError(`index ${i} is outside the text (it has ${chars.length} characters, so use 0...${Math.max(0, chars.length - 1)})`, pos);
653
+ }
654
+ return chars[i];
655
+ }
656
+ if (!isList(obj))
657
+ throw new FormaError(`only lists and text can be indexed with [ ], got ${typename(obj)}`, pos);
658
+ if (!isQ(idx) || idx.dim !== null || !isWhole(idx.v)) {
659
+ throw new FormaError(`a list index must be a whole number like [0], got ${show(idx)}`, pos);
660
+ }
661
+ const i = idx.v;
662
+ if (!(i >= 0 && i < obj.length)) {
663
+ throw new FormaError(`index ${i} is outside the list (it has ${obj.length} items, so use 0...${obj.length - 1})`, pos);
664
+ }
665
+ return obj[i];
666
+ }
667
+ case 'list': return e[2].map((x) => this.eval(x, env));
668
+ case 'neg': {
669
+ const v = this.eval(e[2], env);
670
+ if (isQ(v))
671
+ return new Q(-v.v, v.dim);
672
+ if (isList(v))
673
+ return v.map((x) => this.arith('*', x, new Q(-1), pos));
674
+ throw new FormaError(`can't negate ${typename(v)}`, pos);
675
+ }
676
+ case 'not': {
677
+ const v = this.eval(e[2], env);
678
+ if (typeof v !== 'boolean')
679
+ throw new FormaError(`'!' needs true/false, got ${typename(v)}`, pos);
680
+ return !v;
681
+ }
682
+ case 'range': {
683
+ const lo = this.eval(e[2], env), hi = this.eval(e[3], env);
684
+ if (!isQ(lo) || !isQ(hi))
685
+ throw new FormaError('ranges need numbers or quantities, like 0..<4 or 2mm...10mm', pos);
686
+ if (lo.dim !== hi.dim) {
687
+ throw new FormaError(`range bounds must have the same units: ${typename(lo)} (${lo}) vs ${typename(hi)} (${hi})`, pos);
688
+ }
689
+ if (lo.dim === null && isWhole(lo.v) && isWhole(hi.v)) {
690
+ const out = [];
691
+ const end = hi.v + (e[4] ? 1 : 0);
692
+ for (let i = lo.v; i < end; i++)
693
+ out.push(new Q(i));
694
+ return out;
695
+ }
696
+ return new RangeValue(lo, hi, Boolean(e[4]));
697
+ }
698
+ case 'bin': {
699
+ const op = e[2];
700
+ if (op === '&&' || op === '||') {
701
+ const a = this.eval(e[3], env);
702
+ if (typeof a !== 'boolean')
703
+ throw new FormaError(`'${op}' needs true/false, got ${typename(a)}`, pos);
704
+ if ((op === '&&' && !a) || (op === '||' && a))
705
+ return a;
706
+ const b = this.eval(e[4], env);
707
+ if (typeof b !== 'boolean')
708
+ throw new FormaError(`'${op}' needs true/false, got ${typename(b)}`, pos);
709
+ return b;
710
+ }
711
+ const a = this.eval(e[3], env), b = this.eval(e[4], env);
712
+ if (['<', '<=', '>', '>=', '==', '!='].includes(op))
713
+ return this.compare(op, a, b, pos);
714
+ return this.arith(op, a, b, pos);
715
+ }
716
+ case 'member': return this.getMember(this.eval(e[2], env), e[3], pos);
717
+ case 'closure': return new Closure(e[2], e[3], env, pos);
718
+ case 'call': {
719
+ const callee = e[2], args = e[3], closure = e[4];
720
+ const argv = args.map(([lbl, x, p]) => [lbl, this.eval(x, env), p]);
721
+ const clo = closure ? new Closure(closure[2], closure[3], env, closure[1]) : null;
722
+ if (callee[0] === 'member') {
723
+ const obj = this.eval(callee[2], env);
724
+ return this.callMethod(obj, callee[3], argv, clo, callee[1]);
725
+ }
726
+ const fn = this.eval(callee, env);
727
+ this.callEnv = env;
728
+ return this.call(fn, argv, clo, pos);
729
+ }
730
+ }
731
+ throw new FormaError(`internal: unknown node ${k}`, pos);
732
+ }
733
+ arith(op, a, b, pos) {
734
+ if (isQ(a) && isQ(b))
735
+ return qArith(op, a, b, pos);
736
+ if (isList(a) && isList(b) && (op === '+' || op === '-')) {
737
+ if (a.length !== b.length)
738
+ throw new FormaError(`can't ${op} lists of different lengths (${a.length} and ${b.length})`, pos);
739
+ return a.map((x, i) => this.arith(op, x, b[i], pos));
740
+ }
741
+ if (isList(a) && isQ(b) && (op === '*' || op === '/'))
742
+ return a.map((x) => this.arith(op, x, b, pos));
743
+ if (isQ(a) && isList(b) && op === '*')
744
+ return b.map((x) => this.arith(op, a, x, pos));
745
+ if (op === '+' && (typeof a === 'string' || typeof b === 'string'))
746
+ return show(a) + show(b);
747
+ throw new FormaError(`can't use '${op}' with ${typename(a)} and ${typename(b)}`, pos);
748
+ }
749
+ compare(op, a, b, pos) {
750
+ if (isQ(a) && isQ(b)) {
751
+ if (a.dim && b.dim && a.dim !== b.dim) {
752
+ throw new FormaError(`can't compare ${typename(a)} (${a}) with ${typename(b)} (${b})`, pos);
753
+ }
754
+ const x = a.v, y = b.v;
755
+ switch (op) {
756
+ case '<': return x < y - 1e-9;
757
+ case '<=': return x <= y + 1e-9;
758
+ case '>': return x > y + 1e-9;
759
+ case '>=': return x >= y - 1e-9;
760
+ case '==': return Math.abs(x - y) <= 1e-9;
761
+ default: return Math.abs(x - y) > 1e-9;
762
+ }
763
+ }
764
+ if (op === '==' || op === '!=') {
765
+ let eq;
766
+ if (a instanceof Enum && b instanceof Enum)
767
+ eq = a.name === b.name;
768
+ else
769
+ eq = pyEquals(a, b);
770
+ return op === '==' ? eq : !eq;
771
+ }
772
+ throw new FormaError(`can't compare ${typename(a)} with ${typename(b)} using '${op}'`, pos);
773
+ }
774
+ getMember(obj, name, pos) {
775
+ if (obj instanceof Module) {
776
+ if (obj.env.vars.has(name) && !name.startsWith(' '))
777
+ return obj.env.vars.get(name);
778
+ throw new FormaError(`${typename(obj)} has nothing called '${name}'${suggest(name, obj.names())}. It has: ${obj.names().join(', ') || 'nothing'}`, pos);
779
+ }
780
+ if (obj instanceof Shape) {
781
+ if (name === 'bbox') {
782
+ let bb = bboxOf(obj.world());
783
+ if (bb === null)
784
+ throw new FormaError('this shape is empty, so it has no bounding box', pos);
785
+ if (obj.is2d)
786
+ bb = [[bb[0][0], bb[0][1], 0], [bb[1][0], bb[1][1], 0]];
787
+ return new BBox(bb[0], bb[1]);
788
+ }
789
+ if (name === 'width' || name === 'depth' || name === 'height') {
790
+ return this.getMember(this.getMember(obj, 'bbox', pos), name, pos);
791
+ }
792
+ if (name === 'area') {
793
+ if (!obj.is2d)
794
+ throw new FormaError('.area is for 2D shapes; 3D shapes have .volume', pos);
795
+ return new Q(volume(obj.world()), 'area');
796
+ }
797
+ if (name === 'volume') {
798
+ if (obj.is2d)
799
+ throw new FormaError('a 2D shape has no volume; use .area', pos);
800
+ return new Q(volume(obj.world()), 'vol');
801
+ }
802
+ if (SHAPE_METHODS.includes(name))
803
+ throw new FormaError(`'${name}' is a method — call it like .${name}(...)`, pos);
804
+ const props = ['bbox', 'width', 'depth', 'height', 'area', 'volume'];
805
+ throw new FormaError(`a shape has no property '${name}'${suggest(name, [...props, ...SHAPE_METHODS])}. Try: ${props.join(', ')}`, pos);
806
+ }
807
+ if (obj instanceof BBox)
808
+ return obj.get(name, pos);
809
+ if (isList(obj)) {
810
+ if (name === 'count')
811
+ return new Q(obj.length);
812
+ if (name === 'first' || name === 'last') {
813
+ if (!obj.length)
814
+ throw new FormaError('the list is empty', pos);
815
+ return name === 'first' ? obj[0] : obj[obj.length - 1];
816
+ }
817
+ if (name === 'x' || name === 'y' || name === 'z') {
818
+ const i = 'xyz'.indexOf(name);
819
+ if (i >= obj.length)
820
+ throw new FormaError(`this list has ${obj.length} items, so it has no .${name}`, pos);
821
+ return obj[i];
822
+ }
823
+ }
824
+ if (obj instanceof StructInstance) {
825
+ if (obj.fields.has(name))
826
+ return obj.fields.get(name);
827
+ const mnames = ['with', ...obj.type.methods.keys()];
828
+ if (mnames.includes(name))
829
+ throw new FormaError(`'${name}' is a method — call it like .${name}(...)`, pos);
830
+ const fnames = [...obj.fields.keys()];
831
+ throw new FormaError(`${obj.type.name} has no field '${name}'${suggest(name, [...fnames, ...mnames])}. Fields: ${fnames.join(', ') || 'none'}`, pos);
832
+ }
833
+ if (obj instanceof RandomValue) {
834
+ if (name === 'seed')
835
+ return new Q(obj.seed);
836
+ const rm = ['next', 'int', 'bool', 'pick', 'list'];
837
+ if (rm.includes(name))
838
+ throw new FormaError(`'${name}' is a method — call it like .${name}(...)`, pos);
839
+ throw new FormaError(`a random generator has no property '${name}'${suggest(name, ['seed', ...rm])}`, pos);
840
+ }
841
+ if (typeof obj === 'string') {
842
+ const chars = Array.from(obj);
843
+ if (name === 'count')
844
+ return new Q(chars.length);
845
+ if (name === 'first' || name === 'last') {
846
+ if (!chars.length)
847
+ throw new FormaError('the text is empty', pos);
848
+ return name === 'first' ? chars[0] : chars[chars.length - 1];
849
+ }
850
+ const sm = ['upper', 'lower', 'trim', 'split', 'replace', 'chars', 'contains', 'startsWith', 'endsWith'];
851
+ if (sm.includes(name))
852
+ throw new FormaError(`'${name}' is a method — call it like .${name}(...)`, pos);
853
+ throw new FormaError(`text has no property '${name}'${suggest(name, ['count', 'first', 'last', ...sm])}`, pos);
854
+ }
855
+ if (isQ(obj) && name in UNITS && UNITS[name][1] === obj.dim)
856
+ return new Q(obj.v / UNITS[name][0]); // size.mm
857
+ throw new FormaError(`${typename(obj)} has no property '${name}'`, pos);
858
+ }
859
+ // ---- calls ----------------------------------------------------------------------------
860
+ call(fn, argv, clo, pos) {
861
+ if (fn instanceof Builtin)
862
+ return fn.fn(argv, clo, pos);
863
+ if (fn instanceof FunctionValue)
864
+ return this.callFunction(fn, argv, clo, pos);
865
+ if (fn instanceof Closure) {
866
+ if (clo !== null)
867
+ throw new FormaError("a closure doesn't take a { } block", pos);
868
+ const a = new Args('closure', argv, pos, fn.params, fn.params);
869
+ const vals = fn.params.map((pname) => a.raw(pname));
870
+ return this.closureValue(fn, vals);
871
+ }
872
+ if (fn instanceof Component)
873
+ return this.callComponent(fn, argv, clo, pos);
874
+ if (fn instanceof StructType)
875
+ return this.constructStruct(fn, argv, clo, pos);
876
+ throw new FormaError(`${typename(fn)} can't be called like a function`, pos);
877
+ }
878
+ constructStruct(st, argv, clo, pos) {
879
+ if (clo !== null)
880
+ throw new FormaError(`struct '${st.name}' doesn't take a { } block`, pos);
881
+ const names = st.fields.map((f) => f[0]);
882
+ const a = new Args(st.name, argv, pos, names, names);
883
+ const evalEnv = new Env(st.env);
884
+ const values = new Map();
885
+ for (const [fname, def] of st.fields) {
886
+ let val;
887
+ if (a.has(fname))
888
+ val = a.raw(fname);
889
+ else if (def !== null)
890
+ val = this.eval(def, evalEnv);
891
+ else
892
+ throw new FormaError(`${st.name} needs '${fname}:'`, pos);
893
+ values.set(fname, val);
894
+ evalEnv.define(fname, val, pos);
895
+ }
896
+ return new StructInstance(st, values);
897
+ }
898
+ bindParams(comp, argv, pos) {
899
+ const names = comp.params.map((p) => p[0]);
900
+ const a = new Args(comp.name, argv, pos, names, names);
901
+ const env = new Env(comp.env);
902
+ for (const [pname, def] of comp.params) {
903
+ let val;
904
+ if (a.has(pname))
905
+ val = a.raw(pname);
906
+ else if (def !== null)
907
+ val = this.eval(def, env);
908
+ else
909
+ throw new FormaError(`${comp.name} needs '${pname}:'`, pos);
910
+ env.define(pname, val, pos);
911
+ }
912
+ return env;
913
+ }
914
+ callFunction(fn, argv, clo, pos) {
915
+ if (clo !== null)
916
+ throw new FormaError(`function '${fn.name}' doesn't take a { } block`, pos);
917
+ const env = this.bindParams(fn, argv, pos);
918
+ const body = fn.body;
919
+ if (body.length === 1 && body[0][0] === 'expr')
920
+ return this.eval(body[0][2], env); // implicit return, like Swift
921
+ this.funcDepth++;
922
+ try {
923
+ this.runBlock(body, env, []);
924
+ }
925
+ catch (r) {
926
+ if (r instanceof ReturnSignal)
927
+ return r.value;
928
+ throw r;
929
+ }
930
+ finally {
931
+ this.funcDepth--;
932
+ }
933
+ throw new FormaError(`function '${fn.name}' ended without 'return'`, fn.pos);
934
+ }
935
+ callComponent(comp, argv, clo, pos) {
936
+ const env = this.bindParams(comp, argv, pos);
937
+ env.define('children', clo ? this.runClosure(clo) : [], pos);
938
+ const shapes = [];
939
+ this.runBlock(comp.body, env, shapes);
940
+ if (!shapes.length)
941
+ throw new FormaError(`component '${comp.name}' didn't create any shapes`, pos);
942
+ return combine(shapes, comp.name, pos);
943
+ }
944
+ runClosure(clo, values = []) {
945
+ const env = new Env(clo.env);
946
+ if (values.length !== clo.params.length) {
947
+ throw new FormaError(`this block expects ${clo.params.length} value(s) (${clo.params.join(', ') || 'none'}) but gets ${values.length}`, clo.pos);
948
+ }
949
+ clo.params.forEach((name, i) => env.define(name, values[i], clo.pos));
950
+ const shapes = [];
951
+ this.runBlock(clo.body, env, shapes);
952
+ return shapes;
953
+ }
954
+ closureValue(clo, values) {
955
+ const env = new Env(clo.env);
956
+ if (values.length !== clo.params.length) {
957
+ throw new FormaError(`this block expects ${clo.params.length} value(s) but gets ${values.length} — write it like { item in ... }`, clo.pos);
958
+ }
959
+ clo.params.forEach((name, i) => env.define(name, values[i], clo.pos));
960
+ if (clo.body.length === 1 && clo.body[0][0] === 'expr')
961
+ return this.eval(clo.body[0][2], env);
962
+ this.funcDepth++;
963
+ try {
964
+ this.runBlock(clo.body, env, []);
965
+ }
966
+ catch (r) {
967
+ if (r instanceof ReturnSignal)
968
+ return r.value;
969
+ throw r;
970
+ }
971
+ finally {
972
+ this.funcDepth--;
973
+ }
974
+ throw new FormaError("this block has several lines, so it needs 'return'", clo.pos);
975
+ }
976
+ children(name, argv, clo, pos) {
977
+ const shapes = [];
978
+ for (const [label, v, apos] of argv) {
979
+ if (label !== null)
980
+ throw new FormaError(`${name} doesn't take '${label}:' — put shapes inside { }`, apos);
981
+ flattenShapes(v, shapes);
982
+ }
983
+ if (clo)
984
+ shapes.push(...this.runClosure(clo));
985
+ return shapes;
986
+ }
987
+ // ---- builtins: shapes -------------------------------------------------------------------
988
+ lenOf(v, what, pos) {
989
+ if (!isQ(v) || v.dim === 'angle')
990
+ throw new FormaError(`${what}: expected a length, got ${typename(v)}`, pos);
991
+ return v.v;
992
+ }
993
+ bSphere(argv, _c, pos) {
994
+ const a = new Args('Sphere', argv, pos, ['r', 'd', 'segments'], ['r']);
995
+ const r = a.radius();
996
+ return new Shape(primSphere(r, segmentsFor(r, a.number('segments', null))));
997
+ }
998
+ bBox(argv, _c, pos) {
999
+ const a = new Args('Box', argv, pos, ['size', 'width', 'depth', 'height', 'center'], ['size']);
1000
+ let sx, sy, sz;
1001
+ if (a.has('size')) {
1002
+ const v = a.raw('size');
1003
+ if (isList(v)) {
1004
+ if (v.length !== 3)
1005
+ throw new FormaError('Box: size: needs 3 values [width, depth, height]', a.at('size'));
1006
+ [sx, sy, sz] = v.map((x) => this.lenOf(x, 'Box size', a.at('size')));
1007
+ }
1008
+ else {
1009
+ sx = sy = sz = a.length('size');
1010
+ }
1011
+ }
1012
+ else {
1013
+ sx = a.length('width');
1014
+ sy = a.length('depth');
1015
+ sz = a.length('height');
1016
+ }
1017
+ for (const s of [sx, sy, sz])
1018
+ if (s <= 0)
1019
+ throw new FormaError('Box: all sizes must be greater than 0', pos);
1020
+ const z0 = a.flag('center') ? -sz / 2 : 0;
1021
+ return new Shape(primBox(sx, sy, sz, z0), undefined, undefined, null, false, { kind: 'box', sx, sy, sz, z0 });
1022
+ }
1023
+ bCylinder(argv, _c, pos) {
1024
+ const a = new Args('Cylinder', argv, pos, ['r', 'd', 'h', 'segments', 'center'], ['r']);
1025
+ const r = a.radius();
1026
+ const h = a.positive('h', a.length('h'));
1027
+ const seg = segmentsFor(r, a.number('segments', null));
1028
+ const z0 = a.flag('center') ? -h / 2 : 0;
1029
+ return new Shape(primCone(r, r, h, seg, z0), undefined, undefined, null, false, { kind: 'cone', r1: r, r2: r, h, seg, z0 });
1030
+ }
1031
+ bCone(argv, _c, pos) {
1032
+ const a = new Args('Cone', argv, pos, ['r1', 'd1', 'r2', 'd2', 'h', 'segments', 'center'], []);
1033
+ const r1 = a.radius('r1', 'd1');
1034
+ if (a.has('r2') && a.has('d2'))
1035
+ throw new FormaError('Cone: give either r2: or d2:, not both', pos);
1036
+ const r2 = a.has('r2') ? a.length('r2') : a.has('d2') ? a.length('d2') / 2 : 0;
1037
+ if (r2 < 0)
1038
+ throw new FormaError('Cone: the top size must not be negative', pos);
1039
+ const h = a.positive('h', a.length('h'));
1040
+ const seg = segmentsFor(Math.max(r1, r2), a.number('segments', null));
1041
+ const z0 = a.flag('center') ? -h / 2 : 0;
1042
+ return new Shape(primCone(r1, r2, h, seg, z0), undefined, undefined, null, false, { kind: 'cone', r1, r2, h, seg, z0 });
1043
+ }
1044
+ bTorus(argv, _c, pos) {
1045
+ const a = new Args('Torus', argv, pos, ['r', 'd', 'tube', 'segments'], ['r']);
1046
+ const R = a.radius();
1047
+ const t = a.positive('tube', a.length('tube'));
1048
+ if (t >= R)
1049
+ throw new FormaError('Torus: tube: must be smaller than r:', pos);
1050
+ const seg = segmentsFor(R + t, a.number('segments', null));
1051
+ return new Shape(primTorus(R, t, seg, Math.max(8, segmentsFor(t))));
1052
+ }
1053
+ bPolyhedron(argv, _c, pos) {
1054
+ const a = new Args('Polyhedron', argv, pos, ['points', 'faces'], ['points', 'faces']);
1055
+ const rawPts = a.raw('points');
1056
+ const ptsPos = a.at('points');
1057
+ if (!isList(rawPts))
1058
+ throw new FormaError('Polyhedron: points: must be a list like [[0mm, 0mm, 0mm], ...]', ptsPos);
1059
+ const pts = rawPts.map((p, i) => {
1060
+ if (!(isList(p) && p.length === 3 && p.every((c) => isQ(c) && (c.dim === null || c.dim === 'len')))) {
1061
+ throw new FormaError(`Polyhedron: point ${i} must be [x, y, z] with three lengths, got ${show(p)}`, ptsPos);
1062
+ }
1063
+ return [p[0].v, p[1].v, p[2].v];
1064
+ });
1065
+ if (pts.length < 4)
1066
+ throw new FormaError('Polyhedron needs at least 4 points', ptsPos);
1067
+ const rawFaces = a.raw('faces');
1068
+ const facesPos = a.at('faces');
1069
+ if (!isList(rawFaces))
1070
+ throw new FormaError('Polyhedron: faces: must be a list of index lists like [[0, 1, 2], ...]', facesPos);
1071
+ if (rawFaces.length < 4)
1072
+ throw new FormaError('Polyhedron needs at least 4 faces', facesPos);
1073
+ let polys = [];
1074
+ rawFaces.forEach((f, fi) => {
1075
+ if (!isList(f) || f.length < 3) {
1076
+ throw new FormaError(`Polyhedron: face ${fi} must be a list of at least 3 point indices`, facesPos);
1077
+ }
1078
+ const verts = f.map((idxVal) => {
1079
+ if (!isQ(idxVal) || idxVal.dim !== null || !isWhole(idxVal.v)) {
1080
+ throw new FormaError(`Polyhedron: face ${fi} indices must be whole numbers, got ${show(idxVal)}`, facesPos);
1081
+ }
1082
+ const idx = idxVal.v;
1083
+ if (idx < 0 || idx >= pts.length) {
1084
+ throw new FormaError(`Polyhedron: face ${fi} index ${idx} is out of range (0..${pts.length - 1})`, facesPos);
1085
+ }
1086
+ return pts[idx];
1087
+ });
1088
+ const poly = makePoly(verts);
1089
+ if (poly)
1090
+ polys.push(poly);
1091
+ });
1092
+ if (!polys.length)
1093
+ throw new FormaError('Polyhedron has no valid faces', pos);
1094
+ const holes = openEdges(polys);
1095
+ if (holes === 0 && volume(polys) < -1e-9) {
1096
+ polys = polys.map((p) => p.flipped());
1097
+ }
1098
+ else if (holes > 0) {
1099
+ this.log.push({
1100
+ line: pos[0], kind: 'warning',
1101
+ text: `Polyhedron is not a closed mesh (${holes} open edges) — Difference/Union with it may give wrong results`,
1102
+ });
1103
+ }
1104
+ return new Shape(polys);
1105
+ }
1106
+ // ---- builtins: combining -----------------------------------------------------------------
1107
+ bRandom(argv, clo, pos) {
1108
+ if (clo !== null)
1109
+ throw new FormaError("Random doesn't take a { } block", pos);
1110
+ const a = new Args('Random', argv, pos, ['seed'], ['seed']);
1111
+ const seed = a.number('seed', 0);
1112
+ return new RandomValue(seed);
1113
+ }
1114
+ randomBounds(method, argv, pos, defLo = new Q(0), defHi = new Q(1)) {
1115
+ const a = new Args(method, argv, pos, ['in', 'min', 'max'], ['in']);
1116
+ if (a.has('in')) {
1117
+ if (a.has('min') || a.has('max'))
1118
+ throw new FormaError(`${method}: use either in: or min:/max:, not both`, pos);
1119
+ const r = a.raw('in');
1120
+ const rpos = a.at('in');
1121
+ if (r instanceof RangeValue) {
1122
+ if (r.lo.v > r.hi.v)
1123
+ throw new FormaError(`${method}: range min (${r.lo}) must not exceed max (${r.hi})`, rpos);
1124
+ return [r.lo, r.hi];
1125
+ }
1126
+ if (isList(r) && r.length >= 2 && isQ(r[0]) && isQ(r[r.length - 1])) {
1127
+ const lo = r[0], hi = r[r.length - 1];
1128
+ if (lo.dim !== hi.dim)
1129
+ throw new FormaError(`${method}: range bounds must have matching units`, rpos);
1130
+ return [lo, hi];
1131
+ }
1132
+ throw new FormaError(`${method}: in: expects a range like 2mm...10mm or 1...6`, rpos);
1133
+ }
1134
+ if (a.has('min') || a.has('max')) {
1135
+ const lo = a.raw('min', defLo), hi = a.raw('max', defHi);
1136
+ if (!isQ(lo) || !isQ(hi) || lo.dim !== hi.dim) {
1137
+ throw new FormaError(`${method}: min: and max: must be numbers or quantities with matching units`, pos);
1138
+ }
1139
+ if (lo.v > hi.v)
1140
+ throw new FormaError(`${method}: min (${lo}) must not exceed max (${hi})`, pos);
1141
+ return [lo, hi];
1142
+ }
1143
+ return [defLo, defHi];
1144
+ }
1145
+ bSurface(argv, clo, pos) {
1146
+ const a = new Args('Surface', argv, pos, ['file', 'heights', 'width', 'depth', 'height', 'base', 'cols', 'rows', 'invert', 'center', 'maxRes'], ['file']);
1147
+ const base = a.length('base', 1);
1148
+ if (base < 0)
1149
+ throw new FormaError('Surface: base: must not be negative', a.at('base'));
1150
+ const center = a.flag('center', true);
1151
+ const invert = a.flag('invert', false);
1152
+ // Mode 1: math closure Surface(width:, depth:, cols:, rows:, base:) { x, y in ... }
1153
+ if (clo !== null) {
1154
+ if (a.has('file') || a.has('heights')) {
1155
+ throw new FormaError("Surface: don't pass file/heights when using a { x, y in ... } block", pos);
1156
+ }
1157
+ const width = a.positive('width', a.length('width', 50));
1158
+ const depth = a.positive('depth', a.length('depth', width));
1159
+ const cols = Math.trunc(a.number('cols', 32));
1160
+ const rows = Math.trunc(a.number('rows', cols));
1161
+ if (cols < 2 || rows < 2)
1162
+ throw new FormaError('Surface: cols: and rows: must be at least 2', pos);
1163
+ if (cols > MAX_SURFACE_MESH_RES || rows > MAX_SURFACE_MESH_RES || cols * rows > MAX_SURFACE_MESH_CELLS) {
1164
+ throw new FormaError(`Surface: mesh grid ${cols}x${rows} exceeds the ${MAX_SURFACE_MESH_CELLS.toLocaleString('en')} sample limit (max ${MAX_SURFACE_MESH_RES} per side)`, pos);
1165
+ }
1166
+ const x0 = center ? -width / 2 : 0;
1167
+ const y0 = center ? -depth / 2 : 0;
1168
+ const vals = new Float64Array(cols * rows);
1169
+ let maxV = -Infinity;
1170
+ for (let r = 0; r < rows; r++) {
1171
+ const y = y0 + (r / (rows - 1)) * depth;
1172
+ for (let c = 0; c < cols; c++) {
1173
+ const x = x0 + (c / (cols - 1)) * width;
1174
+ const v = this.lenOf(this.closureValue(clo, [new Q(x, 'len'), new Q(y, 'len')]), 'Surface', clo.pos);
1175
+ vals[r * cols + c] = v;
1176
+ if (v > maxV)
1177
+ maxV = v;
1178
+ }
1179
+ }
1180
+ const polys = buildSurfaceMesh(cols, rows, (c, r) => {
1181
+ const v = vals[r * cols + c];
1182
+ return base + (invert ? maxV - v : v);
1183
+ }, width, depth, center);
1184
+ return new Shape(polys);
1185
+ }
1186
+ // Mode 2: inline 2D heights: [[...], ...]
1187
+ if (a.has('heights')) {
1188
+ if (a.has('file'))
1189
+ throw new FormaError('Surface: pass either a file or heights:, not both', pos);
1190
+ const raw = a.raw('heights');
1191
+ const hpos = a.at('heights');
1192
+ if (!isList(raw) || raw.length < 2)
1193
+ throw new FormaError('Surface: heights: needs a 2D list of at least 2x2 values', hpos);
1194
+ const rows = raw.length;
1195
+ if (!isList(raw[0]) || raw[0].length < 2)
1196
+ throw new FormaError('Surface: each row in heights: needs at least 2 values', hpos);
1197
+ const cols = raw[0].length;
1198
+ const vals = new Float64Array(cols * rows);
1199
+ let maxV = -Infinity;
1200
+ for (let r = 0; r < rows; r++) {
1201
+ const row = raw[r];
1202
+ if (!isList(row) || row.length !== cols) {
1203
+ throw new FormaError(`Surface: heights: row ${r} has different length than row 0 (${cols})`, hpos);
1204
+ }
1205
+ for (let c = 0; c < cols; c++) {
1206
+ const v = this.lenOf(row[c], 'Surface heights', hpos);
1207
+ vals[r * cols + c] = v;
1208
+ if (v > maxV)
1209
+ maxV = v;
1210
+ }
1211
+ }
1212
+ const width = a.positive('width', a.length('width', (cols - 1) * 1));
1213
+ const depth = a.positive('depth', a.length('depth', (rows - 1) * 1));
1214
+ const polys = buildSurfaceMesh(cols, rows, (c, r) => {
1215
+ const v = vals[r * cols + c];
1216
+ return base + (invert ? maxV - v : v);
1217
+ }, width, depth, center);
1218
+ return new Shape(polys);
1219
+ }
1220
+ // Mode 3: PNG or DAT/CSV file
1221
+ const rel = a.raw('file');
1222
+ if (typeof rel !== 'string') {
1223
+ throw new FormaError('Surface needs a PNG/DAT file path, heights: [[...]], or a { x, y in ... } block', pos);
1224
+ }
1225
+ const dir = (this.callEnv && this.callEnv.vars.has(' dir') ? this.callEnv.vars.get(' dir') : this.globals.vars.get(' dir'));
1226
+ const full = join(dir, rel);
1227
+ if (!this.host.isFile(full))
1228
+ throw new FormaError(`Surface: can't find '${rel}' (looked for ${full})`, a.at('file'));
1229
+ const rawMaxRes = Math.trunc(a.number('maxRes', 160));
1230
+ if (rawMaxRes > MAX_SURFACE_MESH_RES) {
1231
+ throw new FormaError(`Surface: maxRes: ${rawMaxRes} exceeds the ${MAX_SURFACE_MESH_RES} limit`, a.at('maxRes'));
1232
+ }
1233
+ const maxRes = Math.max(8, rawMaxRes);
1234
+ const ext = extname(full).toLowerCase();
1235
+ if (ext === '.png') {
1236
+ const grid = downsampleGrid(decodePngGray(this.host.readBytes(full), pos), maxRes);
1237
+ const width = a.positive('width', a.length('width', grid.width));
1238
+ const depth = a.positive('depth', a.length('depth', width * (grid.height / grid.width)));
1239
+ const height = a.positive('height', a.length('height', 5));
1240
+ const polys = buildSurfaceMesh(grid.width, grid.height, (c, r) => {
1241
+ // Flip Y so row 0 (top of PNG) maps to +Y
1242
+ const lum = grid.data[(grid.height - 1 - r) * grid.width + c];
1243
+ return base + (invert ? 1 - lum : lum) * height;
1244
+ }, width, depth, center);
1245
+ return new Shape(polys);
1246
+ }
1247
+ const grid = downsampleGrid(parseHeightText(readText(this.host, full), pos), maxRes);
1248
+ const width = a.positive('width', a.length('width', grid.width));
1249
+ const depth = a.positive('depth', a.length('depth', grid.height));
1250
+ let minV = Infinity, maxV = -Infinity;
1251
+ for (let i = 0; i < grid.data.length; i++) {
1252
+ if (grid.data[i] < minV)
1253
+ minV = grid.data[i];
1254
+ if (grid.data[i] > maxV)
1255
+ maxV = grid.data[i];
1256
+ }
1257
+ const hasHeight = a.has('height');
1258
+ const targetH = hasHeight ? a.positive('height', a.length('height')) : 0;
1259
+ const span = maxV - minV;
1260
+ const polys = buildSurfaceMesh(grid.width, grid.height, (c, r) => {
1261
+ const rawV = grid.data[(grid.height - 1 - r) * grid.width + c];
1262
+ const norm = span > 1e-12 ? (rawV - minV) / span : 0;
1263
+ const h = hasHeight ? (invert ? 1 - norm : norm) * targetH : (invert ? maxV - rawV : rawV);
1264
+ return base + h;
1265
+ }, width, depth, center);
1266
+ return new Shape(polys);
1267
+ }
1268
+ bUnion(argv, clo, pos) {
1269
+ const shapes = this.children('Union', argv, clo, pos);
1270
+ const active = shapes.filter((s) => s.layer.exportable || s.layer.overlay);
1271
+ if (!active.length)
1272
+ return new Shape([]);
1273
+ const is2d = checkSameKind(active, 'Union', pos);
1274
+ const hasCustomExport = active.some((s) => s.layer.exportable && s.layer.name !== 'default');
1275
+ if (hasCustomExport) {
1276
+ for (const s of active) {
1277
+ if (s.layer.exportable && s.layer.name === 'default')
1278
+ this.recordExportLayer(BUILTIN_LAYERS.default, s);
1279
+ }
1280
+ // Mark combined result with a sentinel so top-level run() doesn't re-record the merged union as 'default'
1281
+ return new Shape(csgUnion(active.map((s) => s.world())), undefined, undefined, null, is2d, null, new LayerValue('__merged__', null, 1, true, false, true));
1282
+ }
1283
+ return new Shape(csgUnion(active.map((s) => s.world())), undefined, undefined, null, is2d);
1284
+ }
1285
+ bDifference(argv, clo, pos) {
1286
+ const shapes = this.children('Difference', argv, clo, pos).filter((s) => s.layer.exportable || s.layer.overlay);
1287
+ if (!shapes.length)
1288
+ throw new FormaError('Difference needs at least one shape', pos);
1289
+ const is2d = checkSameKind(shapes, 'Difference', pos);
1290
+ const base = shapes[0].world();
1291
+ if (shapes.length === 1)
1292
+ return new Shape(base, undefined, undefined, null, is2d);
1293
+ const cutters = shapes.slice(1).map((s) => (is2d ? stretchZ(s.world()) : s.world()));
1294
+ return new Shape(csgSubtractMany(base, cutters), undefined, undefined, null, is2d);
1295
+ }
1296
+ bIntersection(argv, clo, pos) {
1297
+ const shapes = this.children('Intersection', argv, clo, pos).filter((s) => s.layer.exportable || s.layer.overlay);
1298
+ if (!shapes.length)
1299
+ throw new FormaError('Intersection needs at least one shape', pos);
1300
+ const is2d = checkSameKind(shapes, 'Intersection', pos);
1301
+ const sets = shapes.map((s, i) => (is2d && i > 0 ? stretchZ(s.world()) : s.world()));
1302
+ return new Shape(csgIntersectMany(sets), undefined, undefined, null, is2d);
1303
+ }
1304
+ bLayer(argv, clo, pos) {
1305
+ const a = new Args('Layer', argv, pos, ['name', 'color', 'opacity', 'export', 'overlay', 'visible'], ['name']);
1306
+ let layer;
1307
+ const rawName = a.raw('name');
1308
+ const namePos = a.at('name');
1309
+ if (rawName instanceof LayerValue) {
1310
+ layer = rawName;
1311
+ }
1312
+ else if (rawName instanceof Enum) {
1313
+ layer = this.resolveLayerTarget(rawName, namePos);
1314
+ }
1315
+ else if (typeof rawName === 'string') {
1316
+ const name = rawName.trim();
1317
+ if (!name)
1318
+ throw new FormaError('Layer: name must not be empty', namePos);
1319
+ const color = a.has('color') ? this.resolveColorArg(a.raw('color'), a.at('color')) : null;
1320
+ const opacity = a.number('opacity', 1);
1321
+ if (!(opacity >= 0 && opacity <= 1))
1322
+ throw new FormaError('Layer: opacity must be between 0 and 1', a.at('opacity'));
1323
+ const overlay = a.flag('overlay', false);
1324
+ const exportable = a.has('export') ? a.flag('export', true) : !overlay;
1325
+ const visible = a.flag('visible', true);
1326
+ layer = new LayerValue(name, color, opacity, exportable, overlay, visible);
1327
+ }
1328
+ else {
1329
+ throw new FormaError('Layer needs a name in quotes, like Layer("Lid", color: .blue)', namePos);
1330
+ }
1331
+ if (clo !== null) {
1332
+ const shapes = this.runClosure(clo);
1333
+ return shapes.map((s) => this.applyLayerToShape(s, layer));
1334
+ }
1335
+ return layer;
1336
+ }
1337
+ bHelix(argv, clo, pos) {
1338
+ if (clo !== null)
1339
+ throw new FormaError("Helix doesn't take a { } block", pos);
1340
+ const a = new Args('Helix', argv, pos, ['r', 'd', 'pitch', 'turns', 'height', 'segments', 'leftHand']);
1341
+ const r = a.radius();
1342
+ if (r <= 0)
1343
+ throw new FormaError('Helix: radius must be greater than 0', pos);
1344
+ let pitch = a.has('pitch') ? a.length('pitch') : null;
1345
+ let turns = a.has('turns') ? a.number('turns') : null;
1346
+ const height = a.has('height') ? a.length('height') : null;
1347
+ if (pitch !== null && pitch <= 0)
1348
+ throw new FormaError('Helix: pitch: must be greater than 0', a.at('pitch'));
1349
+ if (turns !== null && turns <= 0)
1350
+ throw new FormaError('Helix: turns: must be greater than 0', a.at('turns'));
1351
+ if (height !== null && height <= 0)
1352
+ throw new FormaError('Helix: height: must be greater than 0', a.at('height'));
1353
+ if (pitch !== null && turns !== null) {
1354
+ // use both
1355
+ }
1356
+ else if (height !== null && turns !== null) {
1357
+ pitch = height / turns;
1358
+ }
1359
+ else if (height !== null && pitch !== null) {
1360
+ turns = height / pitch;
1361
+ }
1362
+ else if (pitch !== null) {
1363
+ turns = 1;
1364
+ }
1365
+ else if (height !== null) {
1366
+ turns = 1;
1367
+ pitch = height;
1368
+ }
1369
+ else {
1370
+ throw new FormaError('Helix needs pitch: and/or height: (for example Helix(r: 12mm, pitch: 5mm, turns: 4))', pos);
1371
+ }
1372
+ const segPerTurn = a.has('segments') ? Math.max(6, Math.round(a.number('segments'))) : segmentsFor(r);
1373
+ const totalSteps = Math.max(4, Math.round(segPerTurn * turns));
1374
+ const dir = a.flag('leftHand', false) ? -1 : 1;
1375
+ const totalH = pitch * turns;
1376
+ const pts = [];
1377
+ for (let i = 0; i <= totalSteps; i++) {
1378
+ const frac = i / totalSteps;
1379
+ const ang = dir * 2 * Math.PI * turns * frac;
1380
+ pts.push([new Q(r * Math.cos(ang), 'len'), new Q(r * Math.sin(ang), 'len'), new Q(totalH * frac, 'len')]);
1381
+ }
1382
+ return pts;
1383
+ }
1384
+ parseCurvePoints(raw, name, pos) {
1385
+ if (!isList(raw) || raw.length < 2) {
1386
+ throw new FormaError(`${name}: points: needs a list of at least 2 points`, pos);
1387
+ }
1388
+ const first = raw[0];
1389
+ if (!isList(first) || (first.length !== 2 && first.length !== 3)) {
1390
+ throw new FormaError(`${name}: points must be [x, y] or [x, y, z]`, pos);
1391
+ }
1392
+ const dims = first.length;
1393
+ const pts = [];
1394
+ for (let i = 0; i < raw.length; i++) {
1395
+ const p = raw[i];
1396
+ if (!isList(p) || p.length !== dims) {
1397
+ throw new FormaError(`${name}: point ${i} must have ${dims} coordinates`, pos);
1398
+ }
1399
+ const coords = [];
1400
+ for (let c = 0; c < dims; c++) {
1401
+ const v = p[c];
1402
+ if (!isQ(v) || (v.dim !== 'len' && v.dim !== null)) {
1403
+ throw new FormaError(`${name}: point ${i} coordinate must be a length, got ${typename(v)}`, pos);
1404
+ }
1405
+ coords.push(v.v);
1406
+ }
1407
+ pts.push(coords);
1408
+ }
1409
+ return { pts, dims };
1410
+ }
1411
+ bBezier(argv, clo, pos) {
1412
+ if (clo !== null)
1413
+ throw new FormaError("Bezier doesn't take a { } block", pos);
1414
+ const a = new Args('Bezier', argv, pos, ['points', 'segments'], ['points', 'segments']);
1415
+ const { pts, dims } = this.parseCurvePoints(a.raw('points'), 'Bezier', a.at('points'));
1416
+ const segs = a.has('segments') ? Math.max(2, Math.round(a.number('segments'))) : 24;
1417
+ const out = [];
1418
+ for (let k = 0; k <= segs; k++) {
1419
+ const t = k / segs;
1420
+ let cur = pts;
1421
+ while (cur.length > 1) {
1422
+ const next = [];
1423
+ for (let i = 0; i < cur.length - 1; i++) {
1424
+ const p = [];
1425
+ for (let c = 0; c < dims; c++)
1426
+ p.push(cur[i][c] * (1 - t) + cur[i + 1][c] * t);
1427
+ next.push(p);
1428
+ }
1429
+ cur = next;
1430
+ }
1431
+ out.push(cur[0].map((v) => new Q(v, 'len')));
1432
+ }
1433
+ return out;
1434
+ }
1435
+ bSpline(argv, clo, pos) {
1436
+ if (clo !== null)
1437
+ throw new FormaError("Spline doesn't take a { } block", pos);
1438
+ const a = new Args('Spline', argv, pos, ['points', 'segments', 'closed'], ['points', 'segments']);
1439
+ const { pts, dims } = this.parseCurvePoints(a.raw('points'), 'Spline', a.at('points'));
1440
+ const closed = a.flag('closed', false);
1441
+ const sub = a.has('segments') ? Math.max(2, Math.round(a.number('segments'))) : 8;
1442
+ const m = pts.length;
1443
+ if (closed && m < 3)
1444
+ throw new FormaError('Spline(closed: true) needs at least 3 points', pos);
1445
+ const cr = (p0, p1, p2, p3, t) => {
1446
+ const t2 = t * t, t3 = t2 * t;
1447
+ return 0.5 * ((2 * p1) + (-p0 + p2) * t + (2 * p0 - 5 * p1 + 4 * p2 - p3) * t2 + (-p0 + 3 * p1 - 3 * p2 + p3) * t3);
1448
+ };
1449
+ const out = [];
1450
+ const spans = closed ? m : m - 1;
1451
+ for (let s = 0; s < spans; s++) {
1452
+ const p0 = closed ? pts[(s - 1 + m) % m] : pts[Math.max(0, s - 1)];
1453
+ const p1 = pts[s];
1454
+ const p2 = pts[(s + 1) % m];
1455
+ const p3 = closed ? pts[(s + 2) % m] : pts[Math.min(m - 1, s + 2)];
1456
+ const steps = !closed && s === spans - 1 ? sub + 1 : sub;
1457
+ for (let k = 0; k < steps; k++) {
1458
+ const t = k / sub;
1459
+ const coord = [];
1460
+ for (let c = 0; c < dims; c++)
1461
+ coord.push(new Q(cr(p0[c], p1[c], p2[c], p3[c], t), 'len'));
1462
+ out.push(coord);
1463
+ }
1464
+ }
1465
+ return out;
1466
+ }
1467
+ bLoft(argv, clo, pos) {
1468
+ if (clo === null)
1469
+ throw new FormaError('Loft needs a { } block with 2 or more 2D profiles', pos);
1470
+ const a = new Args('Loft', argv, pos, ['height', 'smooth', 'segments']);
1471
+ const smooth = a.flag('smooth', false);
1472
+ const segments = a.number('segments', null);
1473
+ const height = a.has('height') ? a.length('height') : null;
1474
+ if (height !== null && height <= 0)
1475
+ throw new FormaError('Loft: height: must be greater than 0', a.at('height'));
1476
+ const shapes = this.children('Loft', [], clo, pos);
1477
+ if (shapes.length < 2)
1478
+ throw new FormaError('Loft needs at least 2 2D profiles inside { }', pos);
1479
+ for (const s of shapes) {
1480
+ if (!s.is2d)
1481
+ throw new FormaError('Loft profiles must be 2D shapes (like Circle, Rect, or Polygon)', pos);
1482
+ }
1483
+ const allZeroZ = shapes.every((s) => Math.abs(s.pos[2]) < 1e-6);
1484
+ const profiles = shapes.map((s, idx) => {
1485
+ const z = height !== null && allZeroZ ? (height * idx) / (shapes.length - 1) : s.pos[2];
1486
+ const polys2d = s.derive({ pos: [s.pos[0], s.pos[1], 0] }).world();
1487
+ return { polys2d, z };
1488
+ });
1489
+ const polys = loft3d(profiles, smooth, segments, pos);
1490
+ return new Shape(polys, undefined, undefined, shapes[0].color ?? null);
1491
+ }
1492
+ bHull(argv, clo, pos) {
1493
+ const shapes = this.children('Hull', argv, clo, pos);
1494
+ if (!shapes.length)
1495
+ throw new FormaError('Hull needs at least one shape inside { }', pos);
1496
+ const is2d = checkSameKind(shapes, 'Hull', pos);
1497
+ const pts = [];
1498
+ for (const sh of shapes)
1499
+ for (const p of sh.world())
1500
+ for (const v of p.v)
1501
+ pts.push(v);
1502
+ if (is2d) {
1503
+ const outline = convexHull2d(pts.map(([x, y]) => [x, y]));
1504
+ if (outline.length < 3)
1505
+ throw new FormaError('Hull: the shapes have no area', pos);
1506
+ return new Shape(prism2d(outline, 'Hull', pos), undefined, undefined, null, true);
1507
+ }
1508
+ const mPolys = manifoldHull3d(pts);
1509
+ if (mPolys !== null)
1510
+ return new Shape(mPolys);
1511
+ const tris = convexHull3d(pts);
1512
+ if (tris === null)
1513
+ throw new FormaError('Hull: the shapes are flat — a 3D hull needs some thickness', pos);
1514
+ return new Shape(tris.map((t) => makePoly(t)).filter((p) => p !== null));
1515
+ }
1516
+ bMinkowski(argv, clo, pos) {
1517
+ const shapes = this.children('Minkowski', argv, clo, pos);
1518
+ if (!shapes.length)
1519
+ throw new FormaError('Minkowski needs at least one shape inside { }', pos);
1520
+ const is2d = checkSameKind(shapes, 'Minkowski', pos);
1521
+ if (shapes.length === 1)
1522
+ return shapes[0];
1523
+ const polys = manifoldMinkowski(shapes.map((s) => s.world()), is2d);
1524
+ if (polys === null)
1525
+ throw new FormaError('Minkowski requires closed (manifold) shapes', pos);
1526
+ return new Shape(polys, undefined, undefined, null, is2d);
1527
+ }
1528
+ bForEach(argv, clo, pos) {
1529
+ if (argv.length !== 1 || argv[0][0] !== null || !isList(argv[0][1])) {
1530
+ throw new FormaError('ForEach needs one list, like ForEach([1, 2, 3]) { x in ... }', pos);
1531
+ }
1532
+ if (clo === null)
1533
+ throw new FormaError('ForEach needs a block: ForEach(list) { item in ... }', pos);
1534
+ const out = [];
1535
+ for (const item of argv[0][1])
1536
+ out.push(...this.runClosure(clo, [item]));
1537
+ return out;
1538
+ }
1539
+ // ---- builtins: helpers -----------------------------------------------------------------
1540
+ bAssert(argv, _c, pos) {
1541
+ if (!argv.length || typeof argv[0][1] !== 'boolean') {
1542
+ throw new FormaError('assert needs a true/false check, like assert(part.height <= 200mm, "too tall")', pos);
1543
+ }
1544
+ if (!argv[0][1])
1545
+ throw new FormaError('assertion failed: ' + (argv.length > 1 ? show(argv[1][1]) : 'check failed'), pos);
1546
+ return null;
1547
+ }
1548
+ bPrint(argv, _c, pos) {
1549
+ this.log.push({ line: pos[0], text: argv.map(([, v]) => show(v)).join(' ') });
1550
+ return null;
1551
+ }
1552
+ nums(name, argv, pos) {
1553
+ let vals = argv.map(([, v]) => v);
1554
+ if (vals.length === 1 && isList(vals[0]))
1555
+ vals = vals[0];
1556
+ if (!vals.length || !vals.every(isQ))
1557
+ throw new FormaError(`${name} needs numbers`, pos);
1558
+ const dims = new Set(vals.map((v) => v.dim).filter((d) => d !== null));
1559
+ if (dims.size > 1)
1560
+ throw new FormaError(`${name}: mixed lengths and angles`, pos);
1561
+ return [vals, dims.size ? [...dims][0] : null];
1562
+ }
1563
+ bMin(argv, _c, pos) {
1564
+ const [vals, dim] = this.nums('min', argv, pos);
1565
+ return new Q(Math.min(...vals.map((v) => v.v)), dim);
1566
+ }
1567
+ bMax(argv, _c, pos) {
1568
+ const [vals, dim] = this.nums('max', argv, pos);
1569
+ return new Q(Math.max(...vals.map((v) => v.v)), dim);
1570
+ }
1571
+ bAbs(argv, _c, pos) {
1572
+ const [vals, dim] = this.nums('abs', argv, pos);
1573
+ return new Q(Math.abs(vals[0].v), dim);
1574
+ }
1575
+ trig(fn, name, argv, pos) {
1576
+ const v = this.one(name, argv, pos, '30deg');
1577
+ if (v.dim !== 'angle')
1578
+ throw new FormaError(`${name} needs an angle — add deg or rad, like ${name}(30deg)`, pos);
1579
+ return new Q(fn(radians(v.v)));
1580
+ }
1581
+ bSin(argv, _c, pos) { return this.trig(Math.sin, 'sin', argv, pos); }
1582
+ bCos(argv, _c, pos) { return this.trig(Math.cos, 'cos', argv, pos); }
1583
+ bTan(argv, _c, pos) { return this.trig(Math.tan, 'tan', argv, pos); }
1584
+ // ---- 2D and extrusion --------------------------------------------------------------------
1585
+ axisOf(v, pos) {
1586
+ if (v instanceof Enum && ['x', 'y', 'z'].includes(v.name)) {
1587
+ return [0, 1, 2].map((i) => ('xyz'.indexOf(v.name) === i ? 1 : 0));
1588
+ }
1589
+ if (isList(v) && v.length === 3 && v.every((c) => isQ(c) && c.dim !== 'angle')) {
1590
+ const axis = v.map((c) => c.v);
1591
+ if (axis.every((c) => Math.abs(c) < 1e-12))
1592
+ throw new FormaError('the axis [0, 0, 0] has no direction', pos);
1593
+ return axis;
1594
+ }
1595
+ throw new FormaError('an axis is .x, .y, .z or a direction like [1, 1, 0]', pos);
1596
+ }
1597
+ points2d(v, what, pos) {
1598
+ if (!isList(v))
1599
+ throw new FormaError(`${what}: points: must be a list like [[0mm, 0mm], [10mm, 0mm], [0mm, 10mm]]`, pos);
1600
+ return v.map((p, i) => {
1601
+ if (!(isList(p) && p.length === 2 && p.every((c) => isQ(c) && (c.dim === null || c.dim === 'len')))) {
1602
+ throw new FormaError(`${what}: point ${i} must be [x, y] with two lengths, got ${show(p)}`, pos);
1603
+ }
1604
+ return [p[0].v, p[1].v];
1605
+ });
1606
+ }
1607
+ regular(n, r) {
1608
+ const pts = [];
1609
+ for (let i = 0; i < n; i++)
1610
+ pts.push([r * Math.cos((2 * Math.PI * i) / n), r * Math.sin((2 * Math.PI * i) / n)]);
1611
+ return pts;
1612
+ }
1613
+ bCircle(argv, _c, pos) {
1614
+ const a = new Args('Circle', argv, pos, ['r', 'd', 'segments'], ['r']);
1615
+ const r = a.radius();
1616
+ const n = segmentsFor(r, a.number('segments', null));
1617
+ return new Shape(prism2d(this.regular(n, r), 'Circle', pos), undefined, undefined, null, true);
1618
+ }
1619
+ bRect(argv, _c, pos) {
1620
+ const a = new Args('Rect', argv, pos, ['size', 'width', 'height'], ['size']);
1621
+ let w, h;
1622
+ if (a.has('size')) {
1623
+ const v = a.raw('size');
1624
+ if (isList(v)) {
1625
+ if (v.length !== 2)
1626
+ throw new FormaError('Rect: size: needs 2 values [width, height]', a.at('size'));
1627
+ [w, h] = v.map((x) => this.lenOf(x, 'Rect size', a.at('size')));
1628
+ }
1629
+ else {
1630
+ w = h = a.length('size');
1631
+ }
1632
+ }
1633
+ else {
1634
+ w = a.length('width');
1635
+ h = a.length('height');
1636
+ }
1637
+ if (w <= 0 || h <= 0)
1638
+ throw new FormaError('Rect: sizes must be greater than 0', pos);
1639
+ const pts = [[-w / 2, -h / 2], [w / 2, -h / 2], [w / 2, h / 2], [-w / 2, h / 2]];
1640
+ return new Shape(prism2d(pts, 'Rect', pos), undefined, undefined, null, true);
1641
+ }
1642
+ bPolygon(argv, _c, pos) {
1643
+ const a = new Args('Polygon', argv, pos, ['points', 'sides', 'r', 'd'], ['points']);
1644
+ let pts;
1645
+ if (a.has('points')) {
1646
+ if (a.has('sides') || a.has('r') || a.has('d'))
1647
+ throw new FormaError('Polygon: use either points: or sides: with r:/d:', pos);
1648
+ pts = this.points2d(a.raw('points'), 'Polygon', a.at('points'));
1649
+ }
1650
+ else {
1651
+ const n = a.number('sides');
1652
+ if (!isWhole(n) || n < 3)
1653
+ throw new FormaError('Polygon: sides: must be a whole number, 3 or more', a.at('sides'));
1654
+ pts = this.regular(n, a.radius());
1655
+ }
1656
+ return new Shape(prism2d(pts, 'Polygon', pos), undefined, undefined, null, true);
1657
+ }
1658
+ parseEnumOption(v, allowed, what, pos) {
1659
+ if (!(v instanceof Enum) || !allowed.includes(v.name)) {
1660
+ const hint = v instanceof Enum ? suggest(v.name, [...allowed]) : '';
1661
+ throw new FormaError(`${what} must be ${allowed.map((x) => '.' + x).join(', ')}${hint}`, pos);
1662
+ }
1663
+ return v.name;
1664
+ }
1665
+ bFont(argv, _c, pos) {
1666
+ const a = new Args('Font', argv, pos, ['file', 'size', 'weight', 'spacing', 'lineHeight', 'align', 'valign'], ['file']);
1667
+ let base = new FontValue();
1668
+ let file = base.file;
1669
+ let ttf = base.ttf;
1670
+ if (a.has('file')) {
1671
+ const f = a.raw('file');
1672
+ const fpos = a.at('file');
1673
+ if (f instanceof FontValue) {
1674
+ base = f;
1675
+ file = f.file;
1676
+ ttf = f.ttf;
1677
+ }
1678
+ else if (typeof f === 'string') {
1679
+ const env = this.callEnv;
1680
+ const dir = env ? env.lookup(' dir') : this.host.cwd();
1681
+ const full = join(dir, f);
1682
+ if (!this.host.isFile(full))
1683
+ throw new FormaError(`Font: can't find '${f}' (looked for ${full})`, fpos);
1684
+ try {
1685
+ ttf = parseTtfBytes(this.host.readBytes(full));
1686
+ }
1687
+ catch (e) {
1688
+ throw new FormaError(`Font: can't read '${basename(f)}': ${e?.message ?? e}`, fpos);
1689
+ }
1690
+ file = basename(f);
1691
+ }
1692
+ else {
1693
+ throw new FormaError('Font: expected a .ttf file path in quotes or another Font', fpos);
1694
+ }
1695
+ }
1696
+ const size = a.has('size') ? a.positive('size', a.length('size')) : base.size;
1697
+ const weight = a.has('weight')
1698
+ ? this.parseEnumOption(a.raw('weight'), ['regular', 'bold'], 'Font: weight:', a.at('weight'))
1699
+ : base.weight;
1700
+ const spacing = a.has('spacing') ? a.positive('spacing', a.number('spacing')) : base.spacing;
1701
+ const lineHeight = a.has('lineHeight') ? a.positive('lineHeight', a.number('lineHeight')) : base.lineHeight;
1702
+ const align = a.has('align')
1703
+ ? this.parseEnumOption(a.raw('align'), ['left', 'center', 'right'], 'Font: align:', a.at('align'))
1704
+ : base.align;
1705
+ const valign = a.has('valign')
1706
+ ? this.parseEnumOption(a.raw('valign'), ['baseline', 'bottom', 'center', 'top'], 'Font: valign:', a.at('valign'))
1707
+ : base.valign;
1708
+ return new FontValue(file, size, weight, spacing, lineHeight, align, valign, ttf);
1709
+ }
1710
+ renderText(textVal, textPos, fontVal, size, align, valign, segOverride, pos) {
1711
+ if (typeof textVal !== 'string') {
1712
+ throw new FormaError(`Text needs text in quotes, like Text("Forma"), got ${typename(textVal)}`, textPos);
1713
+ }
1714
+ if (!textVal.trim())
1715
+ throw new FormaError('Text: text must not be empty', textPos);
1716
+ const ttf = fontVal.ttf ?? getBundledFont(fontVal.weight);
1717
+ if (!ttf)
1718
+ throw new FormaError('Text: default Roboto font could not be loaded', pos);
1719
+ const defaultSteps = { draft: 4, normal: 6, fine: 10 }[quality.name];
1720
+ const curveSteps = segOverride !== null ? Math.max(2, Math.trunc(segOverride)) : defaultSteps;
1721
+ const contours = layoutText(ttf, textVal, {
1722
+ size,
1723
+ spacing: fontVal.spacing,
1724
+ lineHeight: fontVal.lineHeight,
1725
+ align,
1726
+ valign,
1727
+ curveSteps,
1728
+ });
1729
+ if (!contours.length)
1730
+ throw new FormaError(`Text: no printable glyphs found for "${textVal}"`, pos);
1731
+ const polys = manifoldContoursToPrism(contours, 'NonZero');
1732
+ if (!polys || !polys.length)
1733
+ throw new FormaError(`Text: failed to build 2D geometry for "${textVal}"`, pos);
1734
+ return new Shape(polys, undefined, undefined, null, true);
1735
+ }
1736
+ bText(argv, _c, pos) {
1737
+ const a = new Args('Text', argv, pos, ['text', 'size', 'font', 'align', 'valign', 'segments'], ['text']);
1738
+ const textVal = a.raw('text');
1739
+ const textPos = a.at('text');
1740
+ let font = new FontValue();
1741
+ if (a.has('font')) {
1742
+ const fv = a.raw('font');
1743
+ if (!(fv instanceof FontValue)) {
1744
+ throw new FormaError(`Text: font: must be a Font (like Font(size: 12mm, weight: .bold)), got ${typename(fv)}`, a.at('font'));
1745
+ }
1746
+ font = fv;
1747
+ }
1748
+ const size = a.has('size') ? a.positive('size', a.length('size')) : font.size;
1749
+ const align = a.has('align')
1750
+ ? this.parseEnumOption(a.raw('align'), ['left', 'center', 'right'], 'Text: align:', a.at('align'))
1751
+ : font.align;
1752
+ const valign = a.has('valign')
1753
+ ? this.parseEnumOption(a.raw('valign'), ['baseline', 'bottom', 'center', 'top'], 'Text: valign:', a.at('valign'))
1754
+ : font.valign;
1755
+ const seg = a.number('segments', null);
1756
+ return this.renderText(textVal, textPos, font, size, align, valign, seg, pos);
1757
+ }
1758
+ doExtrude(shape, argv, pos) {
1759
+ const a = new Args('extrude', argv, pos, ['height', 'twist', 'scale', 'slices', 'center'], ['height']);
1760
+ const h = a.positive('height', a.length('height'));
1761
+ const twist = radians(a.angle('twist', 0));
1762
+ const sc = a.raw('scale', null);
1763
+ let sx, sy;
1764
+ if (sc === null)
1765
+ sx = sy = 1;
1766
+ else if (isQ(sc) && sc.dim === null)
1767
+ sx = sy = sc.v;
1768
+ else if (isList(sc) && sc.length === 2 && sc.every((c) => isQ(c) && c.dim === null))
1769
+ [sx, sy] = sc.map((c) => c.v);
1770
+ else
1771
+ throw new FormaError('extrude: scale: must be a plain number like 0.5 or [x, y]', a.at('scale'));
1772
+ if (sx < 0 || sy < 0)
1773
+ throw new FormaError('extrude: scale: must not be negative', a.at('scale'));
1774
+ const z0 = a.flag('center') ? -h / 2 : 0;
1775
+ const polys = shape.world();
1776
+ if (twist === 0 && sx === 1 && sy === 1) {
1777
+ const extruded = polys.map((p) => makePoly(p.v.map(([x, y, z]) => [x, y, z * h + z0]), p.c))
1778
+ .filter((p) => p !== null);
1779
+ return new Shape(extruded, undefined, undefined, null, false, { kind: 'extrude', profilePolys: polys, h, z0 });
1780
+ }
1781
+ const step = { draft: 10, normal: 5, fine: 2 }[quality.name];
1782
+ const ns = a.number('slices', null);
1783
+ const n = ns !== null ? Math.trunc(ns) : Math.max(1, Math.ceil(Math.abs(degrees(twist)) / step));
1784
+ if (n < 1)
1785
+ throw new FormaError('extrude: slices: must be 1 or more', pos);
1786
+ const out = [];
1787
+ for (const p of sliceZ(polys, n)) {
1788
+ for (const tri of fan(p.v)) {
1789
+ const m = tri.map(([x, y, t]) => {
1790
+ const X = x * (1 + (sx - 1) * t), Y = y * (1 + (sy - 1) * t);
1791
+ const c = Math.cos(twist * t), s = Math.sin(twist * t);
1792
+ return [X * c - Y * s, X * s + Y * c, t * h + z0];
1793
+ });
1794
+ const q = makePoly(m, p.c);
1795
+ if (q)
1796
+ out.push(q);
1797
+ }
1798
+ }
1799
+ return new Shape(out);
1800
+ }
1801
+ doRevolve(shape, argv, pos) {
1802
+ const a = new Args('revolve', argv, pos, ['angle', 'segments'], ['angle']);
1803
+ const ang = a.angle('angle', 360);
1804
+ if (!(ang > 0 && ang <= 360))
1805
+ throw new FormaError('revolve: angle: must be between 0deg and 360deg', pos);
1806
+ let polys = shape.world();
1807
+ let minX = Infinity, maxX = -Infinity;
1808
+ for (const p of polys)
1809
+ for (const v of p.v) {
1810
+ minX = Math.min(minX, v[0]);
1811
+ maxX = Math.max(maxX, v[0]);
1812
+ }
1813
+ if (minX < -1e-6) {
1814
+ throw new FormaError(`revolve: the profile must be on the right side of the axis (x ≥ 0), but it reaches x = ${new Q(minX, 'len')}. Move it with .at(x: ...)`, pos);
1815
+ }
1816
+ const full = ang > 360 - 1e-9;
1817
+ const ns = a.number('segments', null);
1818
+ const n = ns !== null ? Math.trunc(ns) : Math.max(3, Math.ceil((segmentsFor(maxX) * ang) / 360));
1819
+ if (full) { // the start and end caps would touch each other, so they are dropped
1820
+ polys = polys.filter((p) => !(p.v.every((v) => v[2] < 1e-6) || p.v.every((v) => v[2] > 1 - 1e-6)));
1821
+ }
1822
+ const A = radians(ang);
1823
+ const out = [];
1824
+ for (const p of sliceZ(polys, n)) {
1825
+ for (const tri of fan(p.v)) {
1826
+ const m = tri.slice().reverse().map(([x, y, t]) => {
1827
+ const th = full && t > 1 - 1e-9 ? 0 : A * t;
1828
+ return [x * Math.cos(th), x * Math.sin(th), y];
1829
+ });
1830
+ const q = makePoly(m, p.c);
1831
+ if (q)
1832
+ out.push(q);
1833
+ }
1834
+ }
1835
+ return new Shape(out);
1836
+ }
1837
+ flatChildren(name, clo, pos) {
1838
+ if (clo === null)
1839
+ throw new FormaError(`${name} needs 2D shapes inside { }`, pos);
1840
+ const shapes = this.runClosure(clo);
1841
+ if (!shapes.length)
1842
+ throw new FormaError(`${name} { } is empty`, pos);
1843
+ if (!shapes.every((s) => s.is2d))
1844
+ throw new FormaError(`${name} { } takes 2D shapes (Circle, Rect, Polygon)`, pos);
1845
+ return combine(shapes, name, pos);
1846
+ }
1847
+ solidChildren(name, clo, pos) {
1848
+ if (clo === null)
1849
+ throw new FormaError(`${name} needs 3D shapes inside { }`, pos);
1850
+ const shapes = this.runClosure(clo);
1851
+ if (!shapes.length)
1852
+ throw new FormaError(`${name} { } is empty`, pos);
1853
+ if (shapes.some((s) => s.is2d))
1854
+ throw new FormaError(`${name} { } takes 3D shapes (Box, Sphere, Cylinder, ...)`, pos);
1855
+ return combine(shapes, name, pos);
1856
+ }
1857
+ doOffset(shape, argv, pos) {
1858
+ const a = new Args('offset', argv, pos, ['r', 'delta', 'join', 'miterLimit', 'segments'], ['r']);
1859
+ if (a.has('r') && a.has('delta'))
1860
+ throw new FormaError('offset: give either r: or delta:, not both', pos);
1861
+ if (!a.has('r') && !a.has('delta')) {
1862
+ throw new FormaError("offset needs 'r:' (rounded) or 'delta:' (sharp), like .offset(r: 2mm)", pos);
1863
+ }
1864
+ const isRoundDefault = a.has('r');
1865
+ const amount = isRoundDefault ? a.length('r') : a.length('delta');
1866
+ const joinVal = a.raw('join', new Enum(isRoundDefault ? 'round' : 'miter'));
1867
+ if (!(joinVal instanceof Enum) || !['round', 'miter', 'square'].includes(joinVal.name)) {
1868
+ throw new FormaError('offset: join: must be .round, .miter or .square', a.has('join') ? a.at('join') : pos);
1869
+ }
1870
+ const miterLimit = a.number('miterLimit', 2);
1871
+ if (miterLimit < 2)
1872
+ throw new FormaError('offset: miterLimit: must be at least 2', a.at('miterLimit'));
1873
+ const seg = segmentsFor(Math.max(Math.abs(amount), 1), a.number('segments', null));
1874
+ const polys = manifoldOffset2d(shape.world(), amount, joinVal.name, miterLimit, seg);
1875
+ if (polys === null)
1876
+ throw new FormaError('offset failed — check that the 2D shape is valid', pos);
1877
+ return new Shape(polys, undefined, undefined, null, true);
1878
+ }
1879
+ parseEdges(v, kind, pos) {
1880
+ const allowed = EDGE_SELECTORS;
1881
+ const one = (item) => {
1882
+ if (!(item instanceof Enum) || !allowed.includes(item.name)) {
1883
+ const hint = item instanceof Enum ? suggest(item.name, [...allowed]) : '';
1884
+ throw new FormaError(`${kind}: edges: expects one of ${allowed.map((e) => '.' + e).join(', ')} (or a list like [.top, .vertical])${hint}`, pos);
1885
+ }
1886
+ return item.name;
1887
+ };
1888
+ if (isList(v)) {
1889
+ if (!v.length)
1890
+ throw new FormaError(`${kind}: edges: list must not be empty`, pos);
1891
+ return v.map(one);
1892
+ }
1893
+ return [one(v)];
1894
+ }
1895
+ doBevel(shape, kind, argv, pos) {
1896
+ const isFillet = kind === 'fillet';
1897
+ const allowed = isFillet ? ['r', 'edges', 'segments'] : ['size', 'edges'];
1898
+ const positional = isFillet ? ['r'] : ['size'];
1899
+ const a = new Args('.' + kind, argv, pos, allowed, positional);
1900
+ const size = isFillet ? a.positive('r', a.length('r')) : a.positive('size', a.length('size'));
1901
+ const seg = isFillet ? a.number('segments', null) : null;
1902
+ if (shape.is2d) {
1903
+ if (a.has('edges')) {
1904
+ throw new FormaError(`.${kind}: 2D shapes don't use edges: — .${kind}(${isFillet ? 'r:' : 'size:'}) rounds all 2D corners`, a.at('edges'));
1905
+ }
1906
+ // Apply in local space to preserve .at() / .rotate() / .color()
1907
+ const polys = applyBevel2d(shape.polys, kind, size, seg, pos);
1908
+ return shape.derive({ polys, meta: null });
1909
+ }
1910
+ const selectors = a.has('edges') ? this.parseEdges(a.raw('edges'), kind, a.at('edges')) : ['all'];
1911
+ const res = applyBevel3d(shape.polys, shape.meta, kind, size, selectors, seg, pos);
1912
+ return shape.derive({ polys: res.polys, meta: res.meta });
1913
+ }
1914
+ doSlice(shape, argv, pos) {
1915
+ const a = new Args('slice', argv, pos, ['z'], ['z']);
1916
+ const z = a.length('z', 0);
1917
+ const polys = manifoldSlice(shape.world(), z);
1918
+ if (polys === null)
1919
+ throw new FormaError('slice requires a closed (manifold) 3D shape', pos);
1920
+ return new Shape(polys, undefined, undefined, null, true);
1921
+ }
1922
+ doProject(shape, argv, pos) {
1923
+ new Args('project', argv, pos, [], []);
1924
+ const polys = manifoldProject(shape.world());
1925
+ if (polys === null)
1926
+ throw new FormaError('project requires a closed (manifold) 3D shape', pos);
1927
+ return new Shape(polys, undefined, undefined, null, true);
1928
+ }
1929
+ bExtrude(argv, clo, pos) {
1930
+ return this.doExtrude(this.flatChildren('Extrude', clo, pos), argv, pos);
1931
+ }
1932
+ bRevolve(argv, clo, pos) {
1933
+ return this.doRevolve(this.flatChildren('Revolve', clo, pos), argv, pos);
1934
+ }
1935
+ bOffset(argv, clo, pos) {
1936
+ return this.doOffset(this.flatChildren('Offset', clo, pos), argv, pos);
1937
+ }
1938
+ bSlice(argv, clo, pos) {
1939
+ return this.doSlice(this.solidChildren('Slice', clo, pos), argv, pos);
1940
+ }
1941
+ bProject(argv, clo, pos) {
1942
+ return this.doProject(this.solidChildren('Project', clo, pos), argv, pos);
1943
+ }
1944
+ // ---- import of files ----------------------------------------------------------------------
1945
+ bImport(argv, _c, pos) {
1946
+ const a = new Args('Import', argv, pos, ['file', 'center', 'up', 'dpi', 'object'], ['file']);
1947
+ const rel = a.raw('file');
1948
+ if (typeof rel !== 'string')
1949
+ throw new FormaError('Import needs a file name in quotes, like Import("part.stl")', pos);
1950
+ if (rel.endsWith('.forma'))
1951
+ throw new FormaError(`to use code from another file, write at the top: import "${rel}"`, pos);
1952
+ const ext = extname(rel).toLowerCase();
1953
+ if (!['.stl', '.obj', '.svg', '.dxf', '.3mf'].includes(ext)) {
1954
+ throw new FormaError(`Import reads .stl, .obj, .3mf, .svg and .dxf; '${basename(rel)}' is not supported yet`, pos);
1955
+ }
1956
+ if (a.has('object') && ext !== '.3mf')
1957
+ throw new FormaError('Import: object: is only for .3mf files', a.at('object'));
1958
+ const env = this.callEnv;
1959
+ const base = env ? env.lookup(' dir') : this.host.cwd();
1960
+ const full = join(base, rel);
1961
+ if (!this.host.isFile(full))
1962
+ throw new FormaError(`can't find '${rel}' (looked for ${full})`, pos);
1963
+ let shape;
1964
+ if (ext === '.svg' || ext === '.dxf') {
1965
+ if (a.has('up'))
1966
+ throw new FormaError(`Import: up: is for 3D files; a ${ext.slice(1).toUpperCase()} is flat`, a.at('up'));
1967
+ if (ext === '.svg') {
1968
+ const dpi = a.number('dpi', 96);
1969
+ if (dpi <= 0)
1970
+ throw new FormaError('Import: dpi: must be greater than 0', a.at('dpi'));
1971
+ shape = this.outlinesToShape(readSvg(this.host, full, pos, dpi), basename(full), pos);
1972
+ }
1973
+ else {
1974
+ if (a.has('dpi'))
1975
+ throw new FormaError('Import: dpi: is only for SVG files', a.at('dpi'));
1976
+ shape = this.outlinesToShape(readDxf(this.host, full, pos), basename(full), pos);
1977
+ }
1978
+ }
1979
+ else {
1980
+ if (a.has('dpi'))
1981
+ throw new FormaError('Import: dpi: is only for SVG files', a.at('dpi'));
1982
+ let polys;
1983
+ if (ext === '.3mf') {
1984
+ const only = a.raw('object', null);
1985
+ if (only !== null && typeof only !== 'string')
1986
+ throw new FormaError('Import: object: needs a name in quotes', a.at('object'));
1987
+ polys = csgUnion(read3mf(this.host, full, pos, only)[0]);
1988
+ }
1989
+ else {
1990
+ polys = ext === '.stl' ? readStl(this.host, full, pos) : readObj(this.host, full, pos);
1991
+ }
1992
+ const holes = openEdges(polys);
1993
+ if (holes) {
1994
+ this.log.push({
1995
+ line: pos[0], kind: 'warning',
1996
+ text: `${basename(rel)} is not a closed mesh (${holes} open edges) — Difference/Union with it may give wrong results`,
1997
+ });
1998
+ }
1999
+ shape = new Shape(polys);
2000
+ const up = a.raw('up', new Enum('z'));
2001
+ if (!(up instanceof Enum) || !['y', 'z'].includes(up.name)) {
2002
+ throw new FormaError('Import: up: must be .z (default) or .y (Blender and most game tools)', pos);
2003
+ }
2004
+ if (up.name === 'y')
2005
+ shape = new Shape(shape.derive({ M: rotX(Math.PI / 2) }).world());
2006
+ }
2007
+ if (a.flag('center')) {
2008
+ const bb = bboxOf(shape.world());
2009
+ const cx = (bb[0][0] + bb[1][0]) / 2, cy = (bb[0][1] + bb[1][1]) / 2;
2010
+ shape = new Shape(shape.derive({ pos: [-cx, -cy, 0] }).world(), undefined, undefined, null, shape.is2d);
2011
+ }
2012
+ return shape;
2013
+ }
2014
+ outlinesToShape(elements, name, pos) {
2015
+ const parts = [];
2016
+ for (const [label, outlines] of elements) {
2017
+ const rings = [];
2018
+ for (let o of outlines) {
2019
+ o = cleanOutline(o);
2020
+ if (o.length < 3)
2021
+ continue;
2022
+ const area = signedArea(o);
2023
+ if (Math.abs(area) > 1e-6)
2024
+ rings.push([Math.abs(area), o]);
2025
+ }
2026
+ if (!rings.length)
2027
+ continue;
2028
+ // nesting depth decides what is filled: outline, hole, island in a hole, ...
2029
+ const depth = rings.map(([ar, o], i) => rings.filter(([ar2, o2], j) => j !== i && ar2 > ar && pointInOutline(o[0], o2)).length);
2030
+ const levels = new Map();
2031
+ try {
2032
+ rings.forEach(([, o], i) => {
2033
+ if (!levels.has(depth[i]))
2034
+ levels.set(depth[i], []);
2035
+ levels.get(depth[i]).push(prism2d(o, `${name} ${label}`, pos));
2036
+ });
2037
+ }
2038
+ catch (e) {
2039
+ if (e instanceof FormaError)
2040
+ throw new FormaError(`${name} ${label}: an outline crosses itself, so it cannot be filled`, pos);
2041
+ throw e;
2042
+ }
2043
+ let result = [];
2044
+ for (const dp of [...levels.keys()].sort((x, y) => x - y)) {
2045
+ const group = csgUnion(levels.get(dp));
2046
+ if (dp === 0)
2047
+ result = group;
2048
+ else if (dp % 2)
2049
+ result = csgSubtract(result, stretchZ(group));
2050
+ else
2051
+ result = csgUnion([result, group]);
2052
+ }
2053
+ parts.push(result);
2054
+ }
2055
+ if (!parts.length)
2056
+ throw new FormaError(`'${name}' has no filled shapes (paths, rects, circles or polygons)`, pos);
2057
+ return new Shape(csgUnion(parts), undefined, undefined, null, true);
2058
+ }
2059
+ // ---- math (names follow Swift) --------------------------------------------------------------
2060
+ one(name, argv, pos, example = '2') {
2061
+ if (argv.length !== 1 || argv[0][0] !== null || !isQ(argv[0][1])) {
2062
+ throw new FormaError(`${name} needs one number, like ${name}(${example})`, pos);
2063
+ }
2064
+ return argv[0][1];
2065
+ }
2066
+ plain(name, argv, pos) {
2067
+ const v = this.one(name, argv, pos);
2068
+ if (v.dim !== null)
2069
+ throw new FormaError(`${name} needs a plain number, got ${typename(v)}`, pos);
2070
+ return v.v;
2071
+ }
2072
+ bFloor(argv, _c, pos) { const v = this.one('floor', argv, pos, '2.7'); return new Q(Math.floor(v.v), v.dim); }
2073
+ bCeil(argv, _c, pos) { const v = this.one('ceil', argv, pos, '2.1'); return new Q(Math.ceil(v.v), v.dim); }
2074
+ bRound(argv, _c, pos) {
2075
+ const v = this.one('round', argv, pos, '2.5');
2076
+ const r = Math.floor(Math.abs(v.v) + 0.5);
2077
+ return new Q(v.v < 0 || Object.is(v.v, -0) ? -r : r, v.dim);
2078
+ }
2079
+ bSign(argv, _c, pos) {
2080
+ const v = this.one('sign', argv, pos, '-3');
2081
+ return new Q((v.v > 0 ? 1 : 0) - (v.v < 0 ? 1 : 0));
2082
+ }
2083
+ bPow(argv, _c, pos) {
2084
+ if (argv.length !== 2 || argv.some(([l]) => l !== null))
2085
+ throw new FormaError('pow needs two numbers, like pow(2, 10)', pos);
2086
+ return this.arith('^', argv[0][1], argv[1][1], pos);
2087
+ }
2088
+ bExp(argv, _c, pos) {
2089
+ const r = Math.exp(this.plain('exp', argv, pos));
2090
+ if (r === Infinity)
2091
+ throw new FormaError('exp: the result is too large', pos);
2092
+ return new Q(r);
2093
+ }
2094
+ logOf(fn, name, argv, pos) {
2095
+ const x = this.plain(name, argv, pos);
2096
+ if (x <= 0)
2097
+ throw new FormaError(`${name} needs a number greater than 0`, pos);
2098
+ return new Q(fn(x));
2099
+ }
2100
+ bLog(argv, _c, pos) { return this.logOf(Math.log, 'log', argv, pos); }
2101
+ bLog10(argv, _c, pos) { return this.logOf(Math.log10, 'log10', argv, pos); }
2102
+ bSqrt(argv, _c, pos) {
2103
+ const v = this.one('sqrt', argv, pos, '16');
2104
+ if (v.dim === 'angle' || (v.dim && dimExp(v.dim) % 2))
2105
+ throw new FormaError(`sqrt of ${typename(v)} doesn't give a length or a number`, pos);
2106
+ if (v.v < 0)
2107
+ throw new FormaError('sqrt of a negative number', pos);
2108
+ return new Q(Math.sqrt(v.v), EXP_DIM[Math.floor(dimExp(v.dim) / 2)]);
2109
+ }
2110
+ inv(fn, name, argv, pos, limit = true) {
2111
+ const x = this.plain(name, argv, pos);
2112
+ if (limit && !(x >= -1 && x <= 1))
2113
+ throw new FormaError(`${name} needs a number between -1 and 1`, pos);
2114
+ return new Q(degrees(fn(x)), 'angle');
2115
+ }
2116
+ bAsin(argv, _c, pos) { return this.inv(Math.asin, 'asin', argv, pos); }
2117
+ bAcos(argv, _c, pos) { return this.inv(Math.acos, 'acos', argv, pos); }
2118
+ bAtan(argv, _c, pos) { return this.inv(Math.atan, 'atan', argv, pos, false); }
2119
+ bAtan2(argv, _c, pos) {
2120
+ if (argv.length !== 2 || argv.some(([l]) => l !== null) || !argv.every(([, v]) => isQ(v))) {
2121
+ throw new FormaError('atan2 needs two numbers: atan2(y, x)', pos);
2122
+ }
2123
+ const y = argv[0][1], x = argv[1][1];
2124
+ if ((y.dim && x.dim && y.dim !== x.dim) || x.dim === 'angle' || y.dim === 'angle') {
2125
+ throw new FormaError('atan2: y and x must be the same kind (both lengths or both numbers)', pos);
2126
+ }
2127
+ return new Q(degrees(Math.atan2(y.v, x.v)), 'angle');
2128
+ }
2129
+ vec(name, v, pos) {
2130
+ if (!(isList(v) && v.length && v.every(isQ)))
2131
+ throw new FormaError(`${name} needs a list of numbers like [1, 2, 3]`, pos);
2132
+ return v;
2133
+ }
2134
+ bNorm(argv, _c, pos) {
2135
+ if (argv.length !== 1)
2136
+ throw new FormaError('norm needs one list, like norm([3mm, 4mm])', pos);
2137
+ let sq = new Q(0);
2138
+ for (const c of this.vec('norm', argv[0][1], pos))
2139
+ sq = this.arith('+', sq, this.arith('*', c, c, pos), pos);
2140
+ return this.bSqrt([[null, sq, pos]], null, pos);
2141
+ }
2142
+ bDot(argv, _c, pos) {
2143
+ if (argv.length !== 2)
2144
+ throw new FormaError('dot needs two lists', pos);
2145
+ const a = this.vec('dot', argv[0][1], pos), b = this.vec('dot', argv[1][1], pos);
2146
+ if (a.length !== b.length)
2147
+ throw new FormaError('dot: the lists must have the same length', pos);
2148
+ let acc = new Q(0);
2149
+ a.forEach((x, i) => { acc = this.arith('+', acc, this.arith('*', x, b[i], pos), pos); });
2150
+ return acc;
2151
+ }
2152
+ bCross(argv, _c, pos) {
2153
+ if (argv.length !== 2)
2154
+ throw new FormaError('cross needs two lists of 3 numbers', pos);
2155
+ const a = this.vec('cross', argv[0][1], pos), b = this.vec('cross', argv[1][1], pos);
2156
+ if (a.length !== 3 || b.length !== 3)
2157
+ throw new FormaError('cross needs two lists of 3 numbers', pos);
2158
+ const m = (x, y) => this.arith('*', x, y, pos);
2159
+ const d = (x, y) => this.arith('-', x, y, pos);
2160
+ return [d(m(a[1], b[2]), m(a[2], b[1])), d(m(a[2], b[0]), m(a[0], b[2])), d(m(a[0], b[1]), m(a[1], b[0]))];
2161
+ }
2162
+ bStride(argv, _c, pos) {
2163
+ const a = new Args('stride', argv, pos, ['from', 'to', 'through', 'by']);
2164
+ if (a.has('to') === a.has('through'))
2165
+ throw new FormaError('stride needs either to: (end excluded) or through: (end included)', pos);
2166
+ const start = a.raw('from'), end = a.raw(a.has('to') ? 'to' : 'through'), step = a.raw('by');
2167
+ for (const v of [start, end, step]) {
2168
+ if (!isQ(v))
2169
+ throw new FormaError('stride needs numbers, like stride(from: 0mm, to: 50mm, by: 10mm)', pos);
2170
+ }
2171
+ const s0 = start, e0 = end, st = step;
2172
+ const dims = new Set([s0.dim, e0.dim, st.dim].filter((d) => d !== null));
2173
+ if (dims.size > 1)
2174
+ throw new FormaError('stride: from:, to: and by: must be the same kind', pos);
2175
+ if (st.v === 0)
2176
+ throw new FormaError('stride: by: must not be 0', pos);
2177
+ const dim = dims.size ? [...dims][0] : null;
2178
+ const inclusive = a.has('through');
2179
+ const out = [];
2180
+ for (let i = 0;; i++) {
2181
+ const v = s0.v + i * st.v;
2182
+ if ((st.v > 0 && (inclusive ? v > e0.v + 1e-9 : v >= e0.v - 1e-9))
2183
+ || (st.v < 0 && (inclusive ? v < e0.v - 1e-9 : v <= e0.v + 1e-9)))
2184
+ break;
2185
+ out.push(new Q(v, dim));
2186
+ if (i + 1 > 100000)
2187
+ throw new FormaError('stride makes more than 100000 values', pos);
2188
+ }
2189
+ return out;
2190
+ }
2191
+ bConcat(argv, _c, _pos) {
2192
+ const out = [];
2193
+ for (const [, v, apos] of argv) {
2194
+ if (!isList(v))
2195
+ throw new FormaError(`concat joins lists, got ${typename(v)}`, apos);
2196
+ out.push(...v);
2197
+ }
2198
+ return out;
2199
+ }
2200
+ bChr(argv, c, pos) {
2201
+ if (c !== null)
2202
+ throw new FormaError("chr doesn't take a { } block", pos);
2203
+ const a = new Args('chr', argv, pos, ['code'], ['code']);
2204
+ const n = a.number('code');
2205
+ if (!isWhole(n) || n < 0 || n > 0x10ffff) {
2206
+ throw new FormaError('chr: code must be a whole Unicode code point (0 to 1114111)', a.at('code'));
2207
+ }
2208
+ return String.fromCodePoint(n);
2209
+ }
2210
+ bOrd(argv, c, pos) {
2211
+ if (c !== null)
2212
+ throw new FormaError("ord doesn't take a { } block", pos);
2213
+ const a = new Args('ord', argv, pos, ['text'], ['text']);
2214
+ const s = a.raw('text');
2215
+ if (typeof s !== 'string' || s.length === 0) {
2216
+ throw new FormaError('ord needs a non-empty text string, like ord("A")', a.at('text'));
2217
+ }
2218
+ return new Q(s.codePointAt(0));
2219
+ }
2220
+ singleValueArg(name, argv, c, pos) {
2221
+ if (c !== null)
2222
+ throw new FormaError(`${name} doesn't take a { } block`, pos);
2223
+ const a = new Args(name, argv, pos, ['value'], ['value']);
2224
+ return a.raw('value');
2225
+ }
2226
+ bTypeOf(argv, c, pos) {
2227
+ const v = this.singleValueArg('typeOf', argv, c, pos);
2228
+ if (v instanceof Q) {
2229
+ if (v.dim === null)
2230
+ return 'Number';
2231
+ if (v.dim === 'len')
2232
+ return 'Length';
2233
+ if (v.dim === 'area')
2234
+ return 'Area';
2235
+ if (v.dim === 'vol')
2236
+ return 'Volume';
2237
+ return 'Angle';
2238
+ }
2239
+ if (typeof v === 'string')
2240
+ return 'String';
2241
+ if (typeof v === 'boolean')
2242
+ return 'Bool';
2243
+ if (isList(v))
2244
+ return 'List';
2245
+ if (v instanceof Shape)
2246
+ return 'Shape';
2247
+ if (v instanceof Enum)
2248
+ return 'Enum';
2249
+ if (v instanceof FontValue)
2250
+ return 'Font';
2251
+ if (v instanceof LayerValue)
2252
+ return 'Layer';
2253
+ if (v instanceof RangeValue)
2254
+ return 'Range';
2255
+ if (v instanceof RandomValue)
2256
+ return 'Random';
2257
+ if (v instanceof StructInstance)
2258
+ return v.type.name;
2259
+ if (v instanceof FunctionValue || v instanceof Builtin || v instanceof Closure)
2260
+ return 'Function';
2261
+ if (v instanceof Component)
2262
+ return 'Component';
2263
+ return typename(v);
2264
+ }
2265
+ bIsNumber(argv, c, pos) {
2266
+ const v = this.singleValueArg('isNumber', argv, c, pos);
2267
+ return v instanceof Q && v.dim === null;
2268
+ }
2269
+ bIsLength(argv, c, pos) {
2270
+ const v = this.singleValueArg('isLength', argv, c, pos);
2271
+ return v instanceof Q && v.dim === 'len';
2272
+ }
2273
+ bIsAngle(argv, c, pos) {
2274
+ const v = this.singleValueArg('isAngle', argv, c, pos);
2275
+ return v instanceof Q && v.dim === 'angle';
2276
+ }
2277
+ bIsArea(argv, c, pos) {
2278
+ const v = this.singleValueArg('isArea', argv, c, pos);
2279
+ return v instanceof Q && v.dim === 'area';
2280
+ }
2281
+ bIsVolume(argv, c, pos) {
2282
+ const v = this.singleValueArg('isVolume', argv, c, pos);
2283
+ return v instanceof Q && v.dim === 'vol';
2284
+ }
2285
+ bIsString(argv, c, pos) {
2286
+ return typeof this.singleValueArg('isString', argv, c, pos) === 'string';
2287
+ }
2288
+ bIsBool(argv, c, pos) {
2289
+ return typeof this.singleValueArg('isBool', argv, c, pos) === 'boolean';
2290
+ }
2291
+ bIsFunction(argv, c, pos) {
2292
+ const v = this.singleValueArg('isFunction', argv, c, pos);
2293
+ return v instanceof Closure || v instanceof FunctionValue || v instanceof Builtin;
2294
+ }
2295
+ bIsList(argv, c, pos) {
2296
+ return isList(this.singleValueArg('isList', argv, c, pos));
2297
+ }
2298
+ bIsShape(argv, c, pos) {
2299
+ return this.singleValueArg('isShape', argv, c, pos) instanceof Shape;
2300
+ }
2301
+ // ---- methods ---------------------------------------------------------------------------------
2302
+ callMethod(obj, name, argv, clo, pos) {
2303
+ if (obj instanceof Module) {
2304
+ this.callEnv = null;
2305
+ return this.call(this.getMember(obj, name, pos), argv, clo, pos);
2306
+ }
2307
+ if (obj instanceof FontValue) {
2308
+ if (name === 'text') {
2309
+ const a = new Args('.text', argv, pos, ['text', 'size', 'align', 'valign', 'segments'], ['text']);
2310
+ const size = a.has('size') ? a.positive('size', a.length('size')) : obj.size;
2311
+ const align = a.has('align')
2312
+ ? this.parseEnumOption(a.raw('align'), ['left', 'center', 'right'], '.text: align:', a.at('align'))
2313
+ : obj.align;
2314
+ const valign = a.has('valign')
2315
+ ? this.parseEnumOption(a.raw('valign'), ['baseline', 'bottom', 'center', 'top'], '.text: valign:', a.at('valign'))
2316
+ : obj.valign;
2317
+ return this.renderText(a.raw('text'), a.at('text'), obj, size, align, valign, a.number('segments', null), pos);
2318
+ }
2319
+ throw new FormaError(`a font has no method '${name}'${suggest(name, ['text'])}`, pos);
2320
+ }
2321
+ if (isList(obj) && (name === 'map' || name === 'filter' || name === 'contains' || name === 'firstIndex'
2322
+ || name === 'find' || name === 'reverse' || name === 'sort' || name === 'reduce' || name === 'join')) {
2323
+ if (name === 'map') {
2324
+ if (clo !== null && !argv.length)
2325
+ return obj.map((x) => this.closureValue(clo, [x]));
2326
+ if (clo === null && argv.length === 1 && !argv[0][0]) {
2327
+ const fn = argv[0][1];
2328
+ if (fn instanceof Closure || fn instanceof FunctionValue || fn instanceof Builtin) {
2329
+ return obj.map((x) => this.call(fn, [[null, x, pos]], null, pos));
2330
+ }
2331
+ }
2332
+ throw new FormaError('.map needs a block or function: list.map { item in ... }', pos);
2333
+ }
2334
+ if (name === 'filter') {
2335
+ const pred = (x) => {
2336
+ if (clo !== null && !argv.length)
2337
+ return this.closureValue(clo, [x]);
2338
+ if (clo === null && argv.length === 1 && !argv[0][0]) {
2339
+ const fn = argv[0][1];
2340
+ if (fn instanceof Closure || fn instanceof FunctionValue || fn instanceof Builtin) {
2341
+ return this.call(fn, [[null, x, pos]], null, pos);
2342
+ }
2343
+ }
2344
+ throw new FormaError('.filter needs a block or function: list.filter { item in ... }', pos);
2345
+ };
2346
+ if (clo === null && !(argv.length === 1 && !argv[0][0])) {
2347
+ throw new FormaError('.filter needs a block or function: list.filter { item in ... }', pos);
2348
+ }
2349
+ const out = [];
2350
+ for (const x of obj) {
2351
+ const keepIt = pred(x);
2352
+ if (typeof keepIt !== 'boolean')
2353
+ throw new FormaError(`.filter block must give true/false, got ${typename(keepIt)}`, clo ? clo.pos : pos);
2354
+ if (keepIt)
2355
+ out.push(x);
2356
+ }
2357
+ return out;
2358
+ }
2359
+ if (name === 'contains') {
2360
+ if (clo !== null)
2361
+ throw new FormaError(".contains doesn't take a { } block", pos);
2362
+ const a = new Args('.contains', argv, pos, ['of', 'value'], ['of']);
2363
+ const target = a.has('of') ? a.raw('of') : a.raw('value');
2364
+ return obj.some((x) => pyEquals(x, target));
2365
+ }
2366
+ if (name === 'firstIndex') {
2367
+ if (clo !== null) {
2368
+ if (argv.length)
2369
+ throw new FormaError('.firstIndex with a block takes no arguments: list.firstIndex { x in ... }', pos);
2370
+ for (let i = 0; i < obj.length; i++) {
2371
+ const ok = this.closureValue(clo, [obj[i]]);
2372
+ if (typeof ok !== 'boolean')
2373
+ throw new FormaError(`.firstIndex block must give true/false, got ${typename(ok)}`, clo.pos);
2374
+ if (ok)
2375
+ return new Q(i);
2376
+ }
2377
+ return new Q(-1);
2378
+ }
2379
+ const a = new Args('.firstIndex', argv, pos, ['of', 'value'], ['of']);
2380
+ const target = a.has('of') ? a.raw('of') : a.raw('value');
2381
+ const idx = obj.findIndex((x) => pyEquals(x, target));
2382
+ return new Q(idx);
2383
+ }
2384
+ if (name === 'find') {
2385
+ if (clo === null)
2386
+ throw new FormaError('.find needs a block: list.find { item in ... }', pos);
2387
+ const a = new Args('.find', argv, pos, ['default'], ['default']);
2388
+ for (const x of obj) {
2389
+ const ok = this.closureValue(clo, [x]);
2390
+ if (typeof ok !== 'boolean')
2391
+ throw new FormaError(`.find block must give true/false, got ${typename(ok)}`, clo.pos);
2392
+ if (ok)
2393
+ return x;
2394
+ }
2395
+ if (a.has('default'))
2396
+ return a.raw('default');
2397
+ throw new FormaError('.find: no matching item found (pass default: ... or check with .contains / .firstIndex)', pos);
2398
+ }
2399
+ if (name === 'reverse') {
2400
+ if (clo !== null || argv.length)
2401
+ throw new FormaError('.reverse() takes no arguments', pos);
2402
+ return [...obj].reverse();
2403
+ }
2404
+ if (name === 'sort') {
2405
+ if (argv.length)
2406
+ throw new FormaError('.sort takes no arguments (use .sort() or .sort { a, b in a < b })', pos);
2407
+ const copy = [...obj];
2408
+ if (clo !== null) {
2409
+ copy.sort((x, y) => {
2410
+ const before = this.closureValue(clo, [x, y]);
2411
+ if (typeof before !== 'boolean')
2412
+ throw new FormaError(`.sort block must give true/false, got ${typename(before)}`, clo.pos);
2413
+ if (before)
2414
+ return -1;
2415
+ const after = this.closureValue(clo, [y, x]);
2416
+ if (typeof after !== 'boolean')
2417
+ throw new FormaError(`.sort block must give true/false, got ${typename(after)}`, clo.pos);
2418
+ return after ? 1 : 0;
2419
+ });
2420
+ return copy;
2421
+ }
2422
+ if (copy.length <= 1)
2423
+ return copy;
2424
+ if (copy.every((x) => typeof x === 'string')) {
2425
+ return copy.sort((a, b) => (a < b ? -1 : a > b ? 1 : 0));
2426
+ }
2427
+ if (copy.every((x) => isQ(x))) {
2428
+ const dim = copy[0].dim;
2429
+ if (!copy.every((x) => x.dim === dim)) {
2430
+ throw new FormaError('.sort() cannot mix different units in one list', pos);
2431
+ }
2432
+ return copy.sort((a, b) => a.v - b.v);
2433
+ }
2434
+ throw new FormaError('.sort() without a block works on numbers, quantities of the same unit, or text (pass { a, b in ... } for custom sorting)', pos);
2435
+ }
2436
+ if (name === 'reduce') {
2437
+ if (clo === null)
2438
+ throw new FormaError('.reduce needs a block: list.reduce(0) { acc, item in acc + item }', pos);
2439
+ const a = new Args('.reduce', argv, pos, ['initial'], ['initial']);
2440
+ let acc = a.raw('initial');
2441
+ for (const x of obj)
2442
+ acc = this.closureValue(clo, [acc, x]);
2443
+ return acc;
2444
+ }
2445
+ // join
2446
+ if (clo !== null)
2447
+ throw new FormaError(".join doesn't take a { } block", pos);
2448
+ const a = new Args('.join', argv, pos, ['by', 'sep'], ['by']);
2449
+ const sep = a.has('by') ? a.raw('by') : a.has('sep') ? a.raw('sep') : '';
2450
+ if (typeof sep !== 'string')
2451
+ throw new FormaError('.join separator must be text, like .join(", ")', pos);
2452
+ return obj.map(show).join(sep);
2453
+ }
2454
+ if (obj instanceof StructInstance) {
2455
+ if (clo !== null)
2456
+ throw new FormaError(`.${name} on ${obj.type.name} doesn't take a { } block`, pos);
2457
+ if (name === 'with') {
2458
+ const names = obj.type.fields.map((f) => f[0]);
2459
+ const a = new Args(`${obj.type.name}.with`, argv, pos, names);
2460
+ const next = new Map(obj.fields);
2461
+ for (const fname of names) {
2462
+ if (a.has(fname))
2463
+ next.set(fname, a.raw(fname));
2464
+ }
2465
+ return new StructInstance(obj.type, next);
2466
+ }
2467
+ const method = obj.type.methods.get(name);
2468
+ if (!method) {
2469
+ const avail = ['with', ...obj.type.methods.keys()];
2470
+ throw new FormaError(`${obj.type.name} has no method '${name}'${suggest(name, avail)}. Available: ${avail.join(', ')}`, pos);
2471
+ }
2472
+ const boundEnv = new Env(method.env);
2473
+ boundEnv.define('self', obj, pos);
2474
+ for (const [k, v] of obj.fields)
2475
+ boundEnv.define(k, v, pos);
2476
+ const boundFn = new FunctionValue(method.name, method.params, method.body, boundEnv, method.pos);
2477
+ return this.callFunction(boundFn, argv, null, pos);
2478
+ }
2479
+ if (obj instanceof RandomValue) {
2480
+ if (clo !== null)
2481
+ throw new FormaError(`.${name} on Random doesn't take a { } block`, pos);
2482
+ if (name === 'next') {
2483
+ const [lo, hi] = this.randomBounds('.next', argv, pos);
2484
+ return new Q(lo.v + obj.nextUnit() * (hi.v - lo.v), lo.dim);
2485
+ }
2486
+ if (name === 'int') {
2487
+ const [lo, hi] = this.randomBounds('.int', argv, pos, new Q(0), new Q(1));
2488
+ if (lo.dim !== null || hi.dim !== null || !isWhole(lo.v) || !isWhole(hi.v)) {
2489
+ throw new FormaError(`.int needs whole plain numbers, like .int(in: 1...6), got ${lo}...${hi}`, pos);
2490
+ }
2491
+ const span = hi.v - lo.v + 1;
2492
+ return new Q(lo.v + Math.floor(obj.nextUnit() * span));
2493
+ }
2494
+ if (name === 'bool') {
2495
+ const a = new Args('.bool', argv, pos, ['chance'], ['chance']);
2496
+ const chance = a.number('chance', 0.5);
2497
+ if (chance < 0 || chance > 1)
2498
+ throw new FormaError('.bool: chance: must be between 0 and 1', pos);
2499
+ return obj.nextUnit() < chance;
2500
+ }
2501
+ if (name === 'pick') {
2502
+ const a = new Args('.pick', argv, pos, ['from', 'list'], ['from']);
2503
+ const raw = a.has('from') ? a.raw('from') : a.raw('list');
2504
+ if (!isList(raw) || raw.length === 0)
2505
+ throw new FormaError('.pick needs a non-empty list, like .pick([.red, .blue])', pos);
2506
+ return raw[Math.floor(obj.nextUnit() * raw.length)];
2507
+ }
2508
+ if (name === 'list') {
2509
+ const a = new Args('.list', argv, pos, ['count', 'in', 'min', 'max'], ['count', 'in']);
2510
+ const count = a.number('count');
2511
+ if (!isWhole(count) || count < 0)
2512
+ throw new FormaError('.list: count: must be a whole number >= 0', a.at('count'));
2513
+ const subArgv = argv.filter(([lbl], idx) => lbl !== 'count' && !(lbl === null && idx === 0));
2514
+ const [lo, hi] = this.randomBounds('.list', subArgv, pos);
2515
+ const out = [];
2516
+ for (let i = 0; i < count; i++)
2517
+ out.push(new Q(lo.v + obj.nextUnit() * (hi.v - lo.v), lo.dim));
2518
+ return out;
2519
+ }
2520
+ const rm = ['next', 'int', 'bool', 'pick', 'list'];
2521
+ throw new FormaError(`Random has no method '${name}'${suggest(name, rm)}. Available: ${rm.join(', ')}`, pos);
2522
+ }
2523
+ if (typeof obj === 'string') {
2524
+ if (clo !== null)
2525
+ throw new FormaError(`.${name} on text doesn't take a { } block`, pos);
2526
+ if (name === 'upper' || name === 'lower' || name === 'trim' || name === 'chars') {
2527
+ if (argv.length)
2528
+ throw new FormaError(`.${name}() takes no arguments`, pos);
2529
+ if (name === 'upper')
2530
+ return obj.toUpperCase();
2531
+ if (name === 'lower')
2532
+ return obj.toLowerCase();
2533
+ if (name === 'trim')
2534
+ return obj.trim();
2535
+ return Array.from(obj);
2536
+ }
2537
+ if (name === 'split') {
2538
+ const a = new Args('.split', argv, pos, ['by', 'sep'], ['by']);
2539
+ const sepVal = a.has('by') ? a.raw('by') : a.raw('sep');
2540
+ if (typeof sepVal !== 'string')
2541
+ throw new FormaError('.split needs a separator text, like .split(",")', pos);
2542
+ return sepVal === '' ? Array.from(obj) : obj.split(sepVal);
2543
+ }
2544
+ if (name === 'contains' || name === 'startsWith' || name === 'endsWith') {
2545
+ const a = new Args('.' + name, argv, pos, ['text'], ['text']);
2546
+ const sub = a.raw('text');
2547
+ if (typeof sub !== 'string')
2548
+ throw new FormaError(`.${name} needs text`, pos);
2549
+ if (name === 'contains')
2550
+ return obj.includes(sub);
2551
+ if (name === 'startsWith')
2552
+ return obj.startsWith(sub);
2553
+ return obj.endsWith(sub);
2554
+ }
2555
+ if (name === 'replace') {
2556
+ const a = new Args('.replace', argv, pos, ['old', 'with', 'regex', 'pattern', 'flags'], ['old', 'with']);
2557
+ const repl = a.raw('with');
2558
+ if (typeof repl !== 'string')
2559
+ throw new FormaError('.replace needs replacement text (with: "...")', pos);
2560
+ if (a.has('regex') || a.has('pattern')) {
2561
+ if (a.has('old'))
2562
+ throw new FormaError('.replace: use either old: or regex:, not both', pos);
2563
+ const pat = a.has('regex') ? a.raw('regex') : a.raw('pattern');
2564
+ if (typeof pat !== 'string')
2565
+ throw new FormaError('.replace: regex: must be text', pos);
2566
+ const flags = a.raw('flags', 'g');
2567
+ if (typeof flags !== 'string')
2568
+ throw new FormaError('.replace: flags: must be text like "gi"', pos);
2569
+ try {
2570
+ return obj.replace(new RegExp(pat, flags), repl);
2571
+ }
2572
+ catch (e) {
2573
+ throw new FormaError(`.replace: invalid regular expression '${pat}': ${e?.message ?? e}`, pos);
2574
+ }
2575
+ }
2576
+ const old = a.raw('old');
2577
+ if (typeof old !== 'string')
2578
+ throw new FormaError('.replace needs text to find, like .replace("a", "b") or .replace(regex: "\\\\d+", with: "#")', pos);
2579
+ return old === '' ? obj : obj.split(old).join(repl);
2580
+ }
2581
+ const sm = ['upper', 'lower', 'trim', 'split', 'replace', 'chars', 'contains', 'startsWith', 'endsWith'];
2582
+ throw new FormaError(`text has no method '${name}'${suggest(name, sm)}. Available: ${sm.join(', ')}`, pos);
2583
+ }
2584
+ if (!(obj instanceof Shape)) {
2585
+ if (isList(obj)) {
2586
+ if (obj.length && obj.every((x) => x instanceof Shape) && SHAPE_METHODS.includes(name)) {
2587
+ return obj.map((x) => this.callMethod(x, name, argv, clo, pos));
2588
+ }
2589
+ const lm = ['map', 'filter', 'contains', 'firstIndex', 'find', 'reverse', 'sort', 'reduce', 'join'];
2590
+ throw new FormaError(`a list has no method '${name}'${suggest(name, lm)}. Available: ${lm.join(', ')}`, pos);
2591
+ }
2592
+ throw new FormaError(`${typename(obj)} has no method '${name}'`, pos);
2593
+ }
2594
+ if (!SHAPE_METHODS.includes(name)) {
2595
+ throw new FormaError(`a shape has no method '${name}'${suggest(name, SHAPE_METHODS)}. Available: ${SHAPE_METHODS.join(', ')}`, pos);
2596
+ }
2597
+ const flat = obj.is2d;
2598
+ if (name === 'at' || name === 'move') {
2599
+ const a = new Args('.' + name, argv, pos, ['x', 'y', 'z'], ['x', 'y', 'z']);
2600
+ const d = [a.length('x', 0), a.length('y', 0), a.length('z', 0)];
2601
+ const p = obj.pos;
2602
+ return obj.derive({ pos: [p[0] + d[0], p[1] + d[1], p[2] + d[2]] });
2603
+ }
2604
+ if (name === 'above' || name === 'below' || name === 'leftOf' || name === 'rightOf' || name === 'inFrontOf' || name === 'behind') {
2605
+ if (clo !== null)
2606
+ throw new FormaError(`.${name} doesn't take a { } block`, pos);
2607
+ const a = new Args('.' + name, argv, pos, ['to', 'gap'], ['to', 'gap']);
2608
+ const target = a.raw('to');
2609
+ if (!(target instanceof Shape))
2610
+ throw new FormaError(`.${name} needs another shape, like lid.${name}(base)`, a.at('to'));
2611
+ if ((name === 'above' || name === 'below') && (flat || target.is2d)) {
2612
+ throw new FormaError(`.${name} needs 3D shapes (2D shapes are flat in Z)`, pos);
2613
+ }
2614
+ const gap = a.length('gap', 0);
2615
+ const bbA = bboxOf(obj.world());
2616
+ const bbB = bboxOf(target.world());
2617
+ if (!bbA || !bbB)
2618
+ throw new FormaError(`.${name}: shape is empty`, pos);
2619
+ let dx = 0, dy = 0, dz = 0;
2620
+ if (name === 'above')
2621
+ dz = bbB[1][2] + gap - bbA[0][2];
2622
+ else if (name === 'below')
2623
+ dz = bbB[0][2] - gap - bbA[1][2];
2624
+ else if (name === 'rightOf')
2625
+ dx = bbB[1][0] + gap - bbA[0][0];
2626
+ else if (name === 'leftOf')
2627
+ dx = bbB[0][0] - gap - bbA[1][0];
2628
+ else if (name === 'behind')
2629
+ dy = bbB[1][1] + gap - bbA[0][1];
2630
+ else if (name === 'inFrontOf')
2631
+ dy = bbB[0][1] - gap - bbA[1][1];
2632
+ return obj.derive({ pos: [obj.pos[0] + dx, obj.pos[1] + dy, obj.pos[2] + dz] });
2633
+ }
2634
+ if (name === 'align') {
2635
+ if (clo !== null)
2636
+ throw new FormaError(".align doesn't take a { } block", pos);
2637
+ const a = new Args('.align', argv, pos, ['to', 'x', 'y', 'z', 'gap'], ['to']);
2638
+ const target = a.raw('to');
2639
+ if (!(target instanceof Shape))
2640
+ throw new FormaError('.align needs another shape: part.align(x: .center, z: .top, to: base)', a.at('to'));
2641
+ if (!a.has('x') && !a.has('y') && !a.has('z')) {
2642
+ throw new FormaError('.align needs at least one axis (x:, y:, or z:)', pos);
2643
+ }
2644
+ if (a.has('z') && (flat || target.is2d)) {
2645
+ throw new FormaError('.align: z: is only for 3D shapes', a.at('z'));
2646
+ }
2647
+ const gap = a.length('gap', 0);
2648
+ const bbA = bboxOf(obj.world());
2649
+ const bbB = bboxOf(target.world());
2650
+ if (!bbA || !bbB)
2651
+ throw new FormaError('.align: shape is empty', pos);
2652
+ let dx = 0, dy = 0, dz = 0;
2653
+ if (a.has('x')) {
2654
+ const mode = this.parseEnumOption(a.raw('x'), ['left', 'center', 'right', 'leftOf', 'rightOf'], '.align: x:', a.at('x'));
2655
+ if (mode === 'left')
2656
+ dx = bbB[0][0] + gap - bbA[0][0];
2657
+ else if (mode === 'right')
2658
+ dx = bbB[1][0] - gap - bbA[1][0];
2659
+ else if (mode === 'center')
2660
+ dx = (bbB[0][0] + bbB[1][0]) / 2 - (bbA[0][0] + bbA[1][0]) / 2;
2661
+ else if (mode === 'leftOf')
2662
+ dx = bbB[0][0] - gap - bbA[1][0];
2663
+ else
2664
+ dx = bbB[1][0] + gap - bbA[0][0];
2665
+ }
2666
+ if (a.has('y')) {
2667
+ const mode = this.parseEnumOption(a.raw('y'), ['front', 'center', 'back', 'inFrontOf', 'behind'], '.align: y:', a.at('y'));
2668
+ if (mode === 'front')
2669
+ dy = bbB[0][1] + gap - bbA[0][1];
2670
+ else if (mode === 'back')
2671
+ dy = bbB[1][1] - gap - bbA[1][1];
2672
+ else if (mode === 'center')
2673
+ dy = (bbB[0][1] + bbB[1][1]) / 2 - (bbA[0][1] + bbA[1][1]) / 2;
2674
+ else if (mode === 'inFrontOf')
2675
+ dy = bbB[0][1] - gap - bbA[1][1];
2676
+ else
2677
+ dy = bbB[1][1] + gap - bbA[0][1];
2678
+ }
2679
+ if (a.has('z')) {
2680
+ const mode = this.parseEnumOption(a.raw('z'), ['bottom', 'center', 'top', 'below', 'above'], '.align: z:', a.at('z'));
2681
+ if (mode === 'bottom')
2682
+ dz = bbB[0][2] + gap - bbA[0][2];
2683
+ else if (mode === 'top')
2684
+ dz = bbB[1][2] - gap - bbA[1][2];
2685
+ else if (mode === 'center')
2686
+ dz = (bbB[0][2] + bbB[1][2]) / 2 - (bbA[0][2] + bbA[1][2]) / 2;
2687
+ else if (mode === 'below')
2688
+ dz = bbB[0][2] - gap - bbA[1][2];
2689
+ else
2690
+ dz = bbB[1][2] + gap - bbA[0][2];
2691
+ }
2692
+ return obj.derive({ pos: [obj.pos[0] + dx, obj.pos[1] + dy, obj.pos[2] + dz] });
2693
+ }
2694
+ if (name === 'rotate') {
2695
+ const a = new Args('.rotate', argv, pos, ['x', 'y', 'z', 'by', 'around']);
2696
+ if (!argv.length)
2697
+ throw new FormaError('.rotate needs an angle, like .rotate(z: 45deg) or .rotate(by: 30deg, around: [1, 1, 0])', pos);
2698
+ let R;
2699
+ if (a.has('by') || a.has('around')) {
2700
+ if (a.has('x') || a.has('y') || a.has('z'))
2701
+ throw new FormaError('.rotate: use either x:/y:/z: or by:/around:, not both', pos);
2702
+ const axis = this.axisOf(a.raw('around', new Enum('z')), a.has('around') ? a.at('around') : pos);
2703
+ if (flat && (Math.abs(axis[0]) > 1e-12 || Math.abs(axis[1]) > 1e-12))
2704
+ throw new FormaError('a 2D shape can only rotate around z', pos);
2705
+ R = rotAxis(axis, radians(a.angle('by')));
2706
+ }
2707
+ else {
2708
+ if (flat && (a.has('x') || a.has('y')))
2709
+ throw new FormaError('a 2D shape can only rotate around z: .rotate(z: 45deg)', pos);
2710
+ R = matMul(rotZ(radians(a.angle('z', 0))), matMul(rotY(radians(a.angle('y', 0))), rotX(radians(a.angle('x', 0)))));
2711
+ }
2712
+ return obj.derive({ M: matMul(R, obj.M) });
2713
+ }
2714
+ if (name === 'scale') {
2715
+ let s;
2716
+ if (argv.length === 1 && argv[0][0] === null) {
2717
+ const a = new Args('.scale', argv, pos, ['factor'], ['factor']);
2718
+ const f = a.number('factor');
2719
+ s = [f, f, flat ? 1 : f];
2720
+ }
2721
+ else {
2722
+ const a = new Args('.scale', argv, pos, ['x', 'y', 'z']);
2723
+ if (flat && a.has('z'))
2724
+ throw new FormaError('a 2D shape has no z to scale', pos);
2725
+ s = [a.number('x', 1), a.number('y', 1), a.number('z', 1)];
2726
+ }
2727
+ if (s.some((v) => Math.abs(v) < 1e-9))
2728
+ throw new FormaError('.scale: factors must not be 0', pos);
2729
+ return obj.derive({ M: matMul([[s[0], 0, 0], [0, s[1], 0], [0, 0, s[2]]], obj.M), meta: null });
2730
+ }
2731
+ if (name === 'resize') {
2732
+ const a = new Args('.resize', argv, pos, ['size', 'x', 'y', 'z', 'auto'], ['size']);
2733
+ if (flat && a.has('z'))
2734
+ throw new FormaError('a 2D shape has no z to resize', a.at('z'));
2735
+ const targets = [null, null, null];
2736
+ if (a.has('size')) {
2737
+ if (a.has('x') || a.has('y') || a.has('z')) {
2738
+ throw new FormaError('.resize: use either size: or x:/y:/z:, not both', pos);
2739
+ }
2740
+ const v = a.raw('size');
2741
+ const spos = a.at('size');
2742
+ if (isList(v)) {
2743
+ const expected = flat ? 2 : 3;
2744
+ if (v.length !== expected && !(flat && v.length === 2)) {
2745
+ throw new FormaError(`.resize: size: needs ${expected} values ${flat ? '[width, depth]' : '[width, depth, height]'}`, spos);
2746
+ }
2747
+ v.forEach((item, k) => {
2748
+ const len = this.lenOf(item, '.resize size', spos);
2749
+ if (len < 0)
2750
+ throw new FormaError('.resize: sizes must not be negative', spos);
2751
+ targets[k] = len > 0 ? len : null;
2752
+ });
2753
+ }
2754
+ else {
2755
+ const len = a.positive('size', a.length('size'));
2756
+ targets[0] = len;
2757
+ targets[1] = len;
2758
+ if (!flat)
2759
+ targets[2] = len;
2760
+ }
2761
+ }
2762
+ else {
2763
+ if (a.has('x'))
2764
+ targets[0] = a.positive('x', a.length('x'));
2765
+ if (a.has('y'))
2766
+ targets[1] = a.positive('y', a.length('y'));
2767
+ if (a.has('z'))
2768
+ targets[2] = a.positive('z', a.length('z'));
2769
+ }
2770
+ if (targets.every((t) => t === null)) {
2771
+ throw new FormaError('.resize needs at least one target size, like .resize(x: 50mm) or .resize(x: 50mm, auto: true)', pos);
2772
+ }
2773
+ const autoFlags = [false, false, false];
2774
+ if (a.has('auto')) {
2775
+ const av = a.raw('auto');
2776
+ const apos = a.at('auto');
2777
+ if (typeof av === 'boolean') {
2778
+ autoFlags[0] = autoFlags[1] = av;
2779
+ autoFlags[2] = flat ? false : av;
2780
+ }
2781
+ else if (isList(av) && (av.length === 2 || av.length === 3) && av.every((x) => typeof x === 'boolean')) {
2782
+ av.forEach((b, k) => { autoFlags[k] = flat && k === 2 ? false : b; });
2783
+ }
2784
+ else {
2785
+ throw new FormaError('.resize: auto: must be true, false, or a list of booleans like [false, true, true]', apos);
2786
+ }
2787
+ }
2788
+ const bb = obj.bbox();
2789
+ if (!bb)
2790
+ throw new FormaError('.resize: cannot resize an empty shape', pos);
2791
+ const cur = [bb[1][0] - bb[0][0], bb[1][1] - bb[0][1], bb[1][2] - bb[0][2]];
2792
+ let autoScale = null;
2793
+ const factors = [1, 1, 1];
2794
+ for (let k = 0; k < 3; k++) {
2795
+ if (targets[k] !== null) {
2796
+ if (cur[k] < 1e-9)
2797
+ throw new FormaError(`.resize: shape has zero size along ${'xyz'[k]}`, pos);
2798
+ factors[k] = targets[k] / cur[k];
2799
+ if (autoScale === null)
2800
+ autoScale = factors[k];
2801
+ }
2802
+ }
2803
+ for (let k = 0; k < 3; k++) {
2804
+ if (targets[k] === null && autoFlags[k] && autoScale !== null) {
2805
+ factors[k] = autoScale;
2806
+ }
2807
+ }
2808
+ return obj.derive({ M: matMul([[factors[0], 0, 0], [0, factors[1], 0], [0, 0, factors[2]]], obj.M), meta: null });
2809
+ }
2810
+ if (name === 'mirror') {
2811
+ const v = argv.length === 1 ? argv[0][1] : null;
2812
+ if (!(v instanceof Enum) || !['x', 'y', 'z'].includes(v.name)) {
2813
+ throw new FormaError('.mirror needs an axis: .mirror(.x), .mirror(.y) or .mirror(.z)', pos);
2814
+ }
2815
+ const ax = 'xyz'.indexOf(v.name);
2816
+ if (flat && ax === 2)
2817
+ throw new FormaError('a 2D shape can only be mirrored with .x or .y', pos);
2818
+ const S = [0, 1, 2].map((i) => [0, 1, 2].map((j) => (i === j ? (i === ax ? -1 : 1) : 0)));
2819
+ return obj.derive({ M: matMul(S, obj.M) });
2820
+ }
2821
+ if (name === 'transform') {
2822
+ const a = new Args('.transform', argv, pos, ['matrix'], ['matrix']);
2823
+ const raw = a.raw('matrix');
2824
+ const mpos = a.at('matrix');
2825
+ if (!isList(raw) || (raw.length !== 3 && raw.length !== 4)) {
2826
+ throw new FormaError('.transform(matrix:) needs a 3×4 or 4×4 list of rows', mpos);
2827
+ }
2828
+ const A = [];
2829
+ const t = [0, 0, 0];
2830
+ for (let r = 0; r < 3; r++) {
2831
+ const row = raw[r];
2832
+ if (!isList(row) || row.length !== 4) {
2833
+ throw new FormaError(`.transform: row ${r} must be a list of 4 values`, mpos);
2834
+ }
2835
+ const mRow = [];
2836
+ for (let c = 0; c < 3; c++) {
2837
+ const cell = row[c];
2838
+ if (!isQ(cell) || cell.dim !== null || !Number.isFinite(cell.v)) {
2839
+ throw new FormaError(`.transform: matrix[${r}][${c}] must be a dimensionless number, got ${typename(cell)}`, mpos);
2840
+ }
2841
+ mRow.push(cell.v);
2842
+ }
2843
+ const tr = row[3];
2844
+ if (!isQ(tr) || !Number.isFinite(tr.v) || (tr.dim !== 'len' && !(tr.dim === null && tr.v === 0))) {
2845
+ throw new FormaError(`.transform: translation matrix[${r}][3] needs a length (e.g. 10mm or 0), got ${typename(tr)}`, mpos);
2846
+ }
2847
+ t[r] = tr.v;
2848
+ A.push(mRow);
2849
+ }
2850
+ if (raw.length === 4) {
2851
+ const last = raw[3];
2852
+ if (!isList(last) || last.length !== 4) {
2853
+ throw new FormaError('.transform: 4th row must be [0, 0, 0, 1]', mpos);
2854
+ }
2855
+ const exp = [0, 0, 0, 1];
2856
+ for (let c = 0; c < 4; c++) {
2857
+ const cell = last[c];
2858
+ if (!isQ(cell) || cell.dim !== null || Math.abs(cell.v - exp[c]) > 1e-9) {
2859
+ throw new FormaError('.transform: 4th row must be [0, 0, 0, 1] (projective transforms are not supported)', mpos);
2860
+ }
2861
+ }
2862
+ }
2863
+ const mat3 = A;
2864
+ if (Math.abs(matDet(mat3)) < 1e-12) {
2865
+ throw new FormaError('.transform: matrix is singular (determinant is 0)', mpos);
2866
+ }
2867
+ if (flat && (Math.abs(mat3[2][0]) > 1e-9 || Math.abs(mat3[2][1]) > 1e-9 || Math.abs(t[2]) > 1e-9)) {
2868
+ throw new FormaError('.transform: a 2D shape cannot be tilted or moved in Z — extrude it first', mpos);
2869
+ }
2870
+ const [px, py, pz] = obj.pos;
2871
+ const newPos = [
2872
+ mat3[0][0] * px + mat3[0][1] * py + mat3[0][2] * pz + t[0],
2873
+ mat3[1][0] * px + mat3[1][1] * py + mat3[1][2] * pz + t[1],
2874
+ mat3[2][0] * px + mat3[2][1] * py + mat3[2][2] * pz + t[2],
2875
+ ];
2876
+ return obj.derive({ M: matMul(mat3, obj.M), pos: newPos, meta: null });
2877
+ }
2878
+ if (name === 'color') {
2879
+ if (!argv.length || argv[0][0] !== null) {
2880
+ throw new FormaError('.color needs a color, like .color(.orange) or .color("#ff8800", opacity: 0.5)', pos);
2881
+ }
2882
+ const [, v, apos] = argv[0];
2883
+ const a = new Args('.color', argv.slice(1), pos, ['opacity']);
2884
+ let cname = this.resolveColorArg(v, apos);
2885
+ const op = a.number('opacity', 1);
2886
+ if (!(op >= 0 && op <= 1))
2887
+ throw new FormaError('.color: opacity must be between 0 and 1', a.at('opacity'));
2888
+ if (op < 1)
2889
+ cname += pyRound(op * 255).toString(16).padStart(2, '0');
2890
+ return obj.derive({ color: cname });
2891
+ }
2892
+ if (name === 'layer') {
2893
+ if (argv.length !== 1 || argv[0][0] !== null) {
2894
+ throw new FormaError('.layer needs one layer, like .layer(.debug), .layer(.reference) or .layer(myLayer)', pos);
2895
+ }
2896
+ const target = this.resolveLayerTarget(argv[0][1], argv[0][2]);
2897
+ return this.applyLayerToShape(obj, target);
2898
+ }
2899
+ if (name === 'extrude' || name === 'revolve' || name === 'offset') {
2900
+ if (!flat)
2901
+ throw new FormaError(`.${name} works on 2D shapes (Circle, Rect, Polygon); this shape is already 3D`, pos);
2902
+ if (name === 'extrude')
2903
+ return this.doExtrude(obj, argv, pos);
2904
+ if (name === 'revolve')
2905
+ return this.doRevolve(obj, argv, pos);
2906
+ return this.doOffset(obj, argv, pos);
2907
+ }
2908
+ if (name === 'slice' || name === 'project') {
2909
+ if (flat)
2910
+ throw new FormaError(`.${name} works on 3D shapes; this shape is already 2D`, pos);
2911
+ return name === 'slice' ? this.doSlice(obj, argv, pos) : this.doProject(obj, argv, pos);
2912
+ }
2913
+ if (name === 'fillet' || name === 'chamfer') {
2914
+ return this.doBevel(obj, name, argv, pos);
2915
+ }
2916
+ if (name === 'shell') {
2917
+ if (clo !== null)
2918
+ throw new FormaError(".shell doesn't take a { } block", pos);
2919
+ if (flat)
2920
+ throw new FormaError('.shell is for 3D shapes — extrude it first, or use .offset() for 2D', pos);
2921
+ const a = new Args('.shell', argv, pos, ['wall', 'open'], ['wall', 'open']);
2922
+ const wall = a.length('wall');
2923
+ const openSet = new Set();
2924
+ if (a.has('open')) {
2925
+ const raw = a.raw('open');
2926
+ const items = isList(raw) ? raw : [raw];
2927
+ for (const item of items) {
2928
+ const face = this.parseEnumOption(item, SHELL_FACES, '.shell: open:', a.at('open'));
2929
+ if (face !== 'none')
2930
+ openSet.add(face);
2931
+ }
2932
+ }
2933
+ const shelled = shell3d(obj.polys, wall, openSet, obj.meta, pos);
2934
+ return obj.derive({ polys: shelled, meta: null });
2935
+ }
2936
+ if (name === 'sweep') {
2937
+ if (clo !== null)
2938
+ throw new FormaError(".sweep doesn't take a { } block", pos);
2939
+ if (!flat)
2940
+ throw new FormaError('.sweep is for 2D shapes like Circle or Rect', pos);
2941
+ const a = new Args('.sweep', argv, pos, ['path', 'closed', 'twist', 'scale', 'smooth'], ['path']);
2942
+ const rawPath = a.raw('path');
2943
+ if (!isList(rawPath) || rawPath.length < 2) {
2944
+ throw new FormaError('.sweep: path: must be a list of 3D points like [[0mm, 0mm, 0mm], [0mm, 0mm, 30mm]]', a.at('path'));
2945
+ }
2946
+ const ptLen = (v, label) => {
2947
+ if (isQ(v) && (v.dim === 'len' || v.dim === null))
2948
+ return v.v;
2949
+ throw new FormaError(`${label} must be a length, got ${typename(v)}`, a.at('path'));
2950
+ };
2951
+ const pts = rawPath.map((pt, idx) => {
2952
+ if (!isList(pt) || pt.length !== 3) {
2953
+ throw new FormaError(`.sweep: path point ${idx} must be [x, y, z]`, a.at('path'));
2954
+ }
2955
+ return [
2956
+ ptLen(pt[0], `.sweep: path[${idx}].x`),
2957
+ ptLen(pt[1], `.sweep: path[${idx}].y`),
2958
+ ptLen(pt[2], `.sweep: path[${idx}].z`),
2959
+ ];
2960
+ });
2961
+ const closed = a.flag('closed', false);
2962
+ const twistRad = a.has('twist') ? (a.angle('twist') * Math.PI) / 180 : 0;
2963
+ const smooth = a.flag('smooth', false);
2964
+ let scaleEnd = [1, 1];
2965
+ if (a.has('scale')) {
2966
+ const sv = a.raw('scale');
2967
+ if (isQ(sv) && sv.dim === null) {
2968
+ if (sv.v <= 0)
2969
+ throw new FormaError('.sweep: scale: must be greater than 0', a.at('scale'));
2970
+ scaleEnd = [sv.v, sv.v];
2971
+ }
2972
+ else if (isList(sv) && sv.length === 2 && isQ(sv[0]) && sv[0].dim === null && isQ(sv[1]) && sv[1].dim === null) {
2973
+ if (sv[0].v <= 0 || sv[1].v <= 0)
2974
+ throw new FormaError('.sweep: scale: values must be greater than 0', a.at('scale'));
2975
+ scaleEnd = [sv[0].v, sv[1].v];
2976
+ }
2977
+ else {
2978
+ throw new FormaError('.sweep: scale: must be a number or [sx, sy]', a.at('scale'));
2979
+ }
2980
+ }
2981
+ const profilePolys = obj.derive({ pos: [obj.pos[0], obj.pos[1], 0] }).world();
2982
+ const swept = sweep3d(profilePolys, pts, { closed, twistRad, scaleEnd, smooth }, pos);
2983
+ return new Shape(swept, undefined, undefined, obj.color, false, null, obj.layer);
2984
+ }
2985
+ throw new FormaError(`internal: method '${name}'`, pos);
2986
+ }
2987
+ }
2988
+ /** Python's == for values that are not numbers: same type and equal content (objects by identity). */
2989
+ function pyEquals(a, b) {
2990
+ if (typeof a !== typeof b)
2991
+ return false;
2992
+ if (isQ(a) && isQ(b))
2993
+ return a.dim === b.dim && Math.abs(a.v - b.v) <= 1e-9;
2994
+ if (a instanceof Enum && b instanceof Enum)
2995
+ return a.name === b.name;
2996
+ if (a instanceof StructInstance && b instanceof StructInstance) {
2997
+ if (a.type !== b.type || a.fields.size !== b.fields.size)
2998
+ return false;
2999
+ for (const [k, v] of a.fields)
3000
+ if (!pyEquals(v, b.fields.get(k)))
3001
+ return false;
3002
+ return true;
3003
+ }
3004
+ if (isList(a) && isList(b))
3005
+ return a.length === b.length && a.every((x, i) => pyEquals(x, b[i]));
3006
+ if (isList(a) !== isList(b))
3007
+ return false;
3008
+ if (a !== null && typeof a === 'object' && b !== null && typeof b === 'object' && a.constructor !== b.constructor)
3009
+ return false;
3010
+ return a === b;
3011
+ }
3012
+ //# sourceMappingURL=interp.js.map