@rulecad/cad 0.7.12 → 0.7.26

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/TUTORIAL.md ADDED
@@ -0,0 +1,226 @@
1
+ # Your first parts with cad
2
+
3
+ A walk from an empty folder to a part of your own, checked against the thing it fits. It takes about twenty minutes
4
+ and needs Node 20 or later. Every file and command here is run by the tests as written, so what you type is what works.
5
+
6
+ The words used:
7
+
8
+ - **Workspace**: the folder your designs live in.
9
+ - **Project**: a group of designs that belong together (`home`).
10
+ - **Object**: one design: a `.json` of its variables and a `.js` that draws its shape.
11
+ - **Rule set**: facts shared by designs, each with its source: a printer's limits (`x1c`), a screw's sizes (`m4`).
12
+ - **Assembly**: objects placed together, to check how they fit.
13
+
14
+ ## 1. Start a workspace
15
+
16
+ ```sh
17
+ npm create rulecad my-designs
18
+ cd my-designs
19
+ npx cad check home/soap-tray
20
+ ```
21
+
22
+ The workspace comes with one design, a soap tray, and `check` builds it and tests it for printing:
23
+
24
+ ```
25
+ Soap tray 0.1.0
26
+ ✓ files match their schemas
27
+ ✓ every measurement is a variable
28
+ ✓ 110 × 75 × 12 mm, fits the bed
29
+ ✓ 6955.8 mm² flat on the bed
30
+ ✓ no overhangs past 45°
31
+ ✓ closed solid
32
+ ```
33
+
34
+ The first check also copies the printer's rule set into `rules/x1c.json`. It is yours now: when you measure your own
35
+ printer, correct the values there and every design follows.
36
+
37
+ ## 2. See where a number comes from
38
+
39
+ Open `projects/home/objects/soap-tray.json`. Each variable has a value and a `rule` saying why. A value can be a
40
+ number, or arithmetic over other names:
41
+
42
+ ```json
43
+ "wall": { "value": "x1c.line * 4", "unit": "mm", "rule": "Four print lines: stiff, and no gaps between lines" }
44
+ ```
45
+
46
+ `x1c.line` is the printer's line width, from its rule set. Ask what any value rests on:
47
+
48
+ ```sh
49
+ npx cad why home/soap-tray.wall
50
+ npx cad rules home/soap-tray
51
+ ```
52
+
53
+ `why` follows one value down to the rules and their sources; `rules` lists every variable and rule the design uses.
54
+
55
+ ## 3. Change it
56
+
57
+ Variables with a `tweak` range can be changed for one run, without touching the file, or for good:
58
+
59
+ ```sh
60
+ npx cad check home/soap-tray --set length=140
61
+ npx cad set home/soap-tray length=120
62
+ ```
63
+
64
+ `set` edits the `.json` and keeps the rest of the file as it was. It refuses a change that would leave the design
65
+ broken.
66
+
67
+ ## 4. A part of your own
68
+
69
+ A wall hook: a back plate with a hole for an M4 screw, and an arm.
70
+
71
+ ```sh
72
+ npx cad new home/hook
73
+ ```
74
+
75
+ That makes `projects/home/objects/hook.json` and `hook.js` from a template. Replace the `.json` with the hook's
76
+ variables. The screw's sizes come from the `m4` rule set, which is copied into `rules/` the first time it is used:
77
+
78
+ ```json projects/home/objects/hook.json
79
+ {
80
+ "$schema": "https://jonibach.github.io/rulecad/schemas/object.schema.json",
81
+ "name": "hook",
82
+ "title": "Wall hook",
83
+ "version": "0.1.0",
84
+ "uses": ["x1c", "m4"],
85
+ "material": "PETG",
86
+ "orientation": "On its side, so the layers run along the arm and it can't snap off across them.",
87
+ "variables": {
88
+ "width": { "value": 20, "unit": "mm", "rule": "Wide enough for a coat's loop", "label": "Width", "show": true, "tweak": { "min": 10, "max": 60 } },
89
+ "plate": { "value": 50, "unit": "mm", "rule": "The back plate: room for a screw above the arm", "label": "Plate", "show": true },
90
+ "reach": { "value": 30, "unit": "mm", "rule": "How far the arm stands out from the wall", "label": "Reach", "show": true, "tweak": { "min": 15, "max": 60 } },
91
+ "thick": { "value": "x1c.line * 10", "unit": "mm", "rule": "Ten print lines: stiff enough for a coat" },
92
+ "hole": { "value": "m4.clearance + x1c.hole_comp", "unit": "mm", "rule": "An M4 screw's clearance hole, widened for how holes print", "interface": true }
93
+ }
94
+ }
95
+ ```
96
+
97
+ Then the shape. `main(v)` gets the variables as `v`, with the rule sets (`v.x1c.line`), print-aware shapes
98
+ (`v.shapes`) and booleans (`v.ops`). Z is up and the bed is z = 0: draw the part the way it will print.
99
+
100
+ ```js projects/home/objects/hook.js
101
+ // A wall hook: a back plate with a screw hole, and an arm. It lies on its side to print (z is its width).
102
+ import jscad from '@jscad/modeling'
103
+ const { cuboid } = jscad.primitives
104
+
105
+ export function main (v) {
106
+ const plate = cuboid({ size: [v.plate, v.thick, v.width], center: [0, v.thick / 2, v.width / 2] })
107
+ const arm = cuboid({ size: [v.thick, v.reach, v.width], center: [(v.thick - v.plate) / 2, v.thick + v.reach / 2, v.width / 2] })
108
+ // a hole across the part as it prints: a teardrop, so its roof needs no support. It is a line longer than the
109
+ // plate is thick, so it comes out of the back cleanly
110
+ const screw = v.shapes.teardropHole({ d: v.hole, length: v.thick + v.x1c.line, at: [v.plate / 2 / 2, v.thick, v.width / 2], into: '-y' })
111
+ return v.ops.subtract(v.ops.union(plate, arm), screw)
112
+ }
113
+ ```
114
+
115
+ ```sh
116
+ npx cad check home/hook
117
+ npx cad preview home/hook
118
+ npx cad export home/hook
119
+ ```
120
+
121
+ `preview` draws six views as a picture in `.preview/` (it needs Chrome or Chromium). Look at it before you print.
122
+ `export` writes a 3MF for your slicer in `exports/`.
123
+
124
+ ## 5. When something is wrong
125
+
126
+ The check names mistakes rather than drawing something else. The ones everyone makes first:
127
+
128
+ | You wrote | The check says |
129
+ |---|---|
130
+ | a number in the `.js`: `v.plate / 4` | `numbers in hook.js that should be variables: line 10: 4` |
131
+ | a variable that isn't there: `v.thik` | `v.thik: the design has no variable "thik" (did you mean "thick"?)` |
132
+ | a rule that isn't there: `m4.clearence` | `"m4.clearence": no rule "clearence" in m4 (hook.json: variables.hole.value)` |
133
+ | a misspelt key in the `.json`: `"lable"` | `variables.thick.lable: not allowed here (did you mean "label"?)` |
134
+ | nothing returned from `main` | `main() returned no shape: return a JSCAD solid, or named parts` |
135
+
136
+ Only 0, 1 and 2 may be written as numbers in a design: everything else is a variable, so that every measurement can
137
+ be traced. To see a value while you work, `console.log` it in `main`: it comes out with the check's output.
138
+
139
+ ## 6. Check it against what it fits
140
+
141
+ A part is right when it fits the thing it is for. Model that thing as a **reference** object: drawn and checked
142
+ against, never printed. Here, the screw's shank:
143
+
144
+ ```sh
145
+ npx cad new home/screw
146
+ ```
147
+
148
+ ```json projects/home/objects/screw.json
149
+ {
150
+ "$schema": "https://jonibach.github.io/rulecad/schemas/object.schema.json",
151
+ "name": "screw",
152
+ "title": "M4 screw",
153
+ "version": "0.1.0",
154
+ "role": "reference",
155
+ "variables": {
156
+ "d": { "value": 4, "unit": "mm", "rule": "An M4 screw's thread", "interface": true },
157
+ "length": { "value": 16, "unit": "mm", "rule": "Long enough to go through the plate into a wall plug" },
158
+ "sides": { "value": 32, "rule": "Sides drawn round the shank" }
159
+ }
160
+ }
161
+ ```
162
+
163
+ ```js projects/home/objects/screw.js
164
+ // An M4 screw's shank, lying along y: something the hook fits, not something to print.
165
+ import jscad from '@jscad/modeling'
166
+
167
+ export function main (v) {
168
+ return jscad.transforms.rotateX(Math.PI / 2, jscad.primitives.cylinder({ radius: v.d / 2, height: v.length, segments: v.sides }))
169
+ }
170
+ ```
171
+
172
+ An assembly places objects together. Positions are expressions over the items' own variables, so the screw stays in
173
+ the hole when the hook changes:
174
+
175
+ ```json projects/home/assemblies/hook-on-screw.json
176
+ {
177
+ "title": "Hook on its screw",
178
+ "kind": "fit",
179
+ "uses": ["x1c"],
180
+ "items": [
181
+ { "id": "hook", "object": "hook" },
182
+ { "id": "screw", "object": "screw", "at": ["hook.plate / 4", "hook.thick - screw.length / 2", "hook.width / 2"] }
183
+ ]
184
+ }
185
+ ```
186
+
187
+ Now say how they should fit: the gap between the screw and its hole, between the printer's sliding fit and half a
188
+ millimetre. An object that returns one shape has one part, `body`.
189
+
190
+ ```sh
191
+ npx cad add fit home/hook-on-screw --a hook.body --b screw.body --min x1c.fit --max 0.5 --note "The screw in its hole"
192
+ npx cad check home/hook-on-screw
193
+ ```
194
+
195
+ ```
196
+ Hook on its screw (fit: hook 0.1.0, screw 0.1.0)
197
+ ✓ files match their schemas
198
+ ✓ no parts overlap (2 object instances)
199
+ ✓ The screw in its hole: closest gap 0.295 mm
200
+ ```
201
+
202
+ Change `hole` in the hook to something too tight and the check fails with the number. That is the loop: rules, a
203
+ shape from them, and a check against the thing it meets.
204
+
205
+ ## 7. Share it
206
+
207
+ ```sh
208
+ npx cad link home/hook --md
209
+ ```
210
+
211
+ That prints one link that opens the model in a browser, with its rules and downloads. The model travels in the link
212
+ itself: nothing is uploaded.
213
+
214
+ ## Where next
215
+
216
+ [The worked examples](EXAMPLES.md) carry on from here, one for each of these, with the files to write and the
217
+ commands to run, tested the same way as this page. Each is also a section of [the README](README.md):
218
+
219
+ - **Parts**: a design that returns several named parts, supports that break away, a second colour.
220
+ - **Variants**: named sets of inputs, side by side (`home/hook:long`).
221
+ - **Joints and poses**: things that move, checked in every position and swept for collisions.
222
+ - **Versions**: `cad release` compares a design with its last release and says whether an earlier print still fits.
223
+ - **Models from elsewhere**: measure someone else's STL into rules, and match your design against it.
224
+ - **Optimised parts**: the stiffest layout for a load, and an analysis of what you drew.
225
+ - **Boards**: circuit boards from the same rules as the case around them.
226
+ - **Mechanisms printed flat**: springs, catches and triggers in one print, checked through their whole cycle.
package/bin/cad.mjs CHANGED
@@ -4,7 +4,7 @@ import fs from 'node:fs';
4
4
  import path from 'node:path';
5
5
  import { execFileSync } from 'node:child_process';
6
6
  import { fmt, loadRuleSet } from '../lib/rules.mjs';
7
- import { WS, TOOL, paths, config, printerOf } from '../lib/workspace.mjs';
7
+ import { WS, TOOL, paths, config, configError, printerOf } from '../lib/workspace.mjs';
8
8
  import { fromKLE } from '@rulecad/keyboard-layout';
9
9
  import { target, hasTarget } from '../lib/targets.mjs';
10
10
  import { locate, build, pick, lint, readObject, printer, pcbEngine, objectSets } from '../lib/design.mjs';
@@ -12,13 +12,15 @@ import { git, tags, bump, bigger, newer, compare, snapshot, materialise, files,
12
12
  import { check } from '@rulecad/printcheck';
13
13
  import { preview } from '../lib/preview.mjs';
14
14
  import { measure, match } from '../lib/meshcmd.mjs';
15
+ import { cloneBoard } from '../lib/clone.mjs';
15
16
  import { isAssembly, buildAssembly, checkAssembly, shapes, sweep, motionData } from '../lib/assembly.mjs';
16
17
  import { valuesOf, why } from '../lib/explain.mjs';
17
- import { errorData } from '../lib/errors.mjs';
18
+ import { errorData, near } from '../lib/errors.mjs';
18
19
  import { schemaFindings } from '../lib/schema.mjs';
19
20
  import { optimised, readProblem, analysePart, picture, problemFile } from '../lib/optimise.mjs';
20
21
  import { evaluate } from '../lib/rules.mjs';
21
22
  import { setVariables, addToAssembly, parseValue } from '../lib/edit.mjs';
23
+ import { setAt } from '../lib/jsonedit.mjs';
22
24
  import { threemf, slotOf } from '../lib/threemf.mjs';
23
25
  import { liveView } from '../lib/live.mjs';
24
26
  import { filaments, slots, linkTo, objectModel, assemblyModel, VIEW } from '../lib/links.mjs';
@@ -39,6 +41,7 @@ const HELP = `cad: JSCAD designs you can trace, check, share and print (rulecad)
39
41
 
40
42
  cad new <project>/<object> start a design from the template (makes the project if needed)
41
43
  cad import-kle <file> <project>/<name> a keyboard layout from keyboard-layout-editor.com, into layouts/
44
+ cad clone <board.kicad_pcb | GitHub link> <name> a published circuit board into rules/<name>.json, to redraw by rules [--source, --licence]
42
45
  cad agents AGENTS.md: how an AI agent should design in this workspace
43
46
  cad rules <project>/<object> every variable: value, the rule behind it, its source
44
47
  cad values <project>/<object> [names…] the object's variables, resolved [--json]
@@ -46,7 +49,9 @@ const HELP = `cad: JSCAD designs you can trace, check, share and print (rulecad)
46
49
  cad add fit|joint|item|loop|pose <project>/<assembly> --a … --b … --min … add to an assembly, keeping its layout
47
50
  cad why <project>/<object>.<name> what a value reads, down to the rules and their sources [--json] [--depth N]
48
51
  cad check <project>/<object> raw numbers in the design, then printability (exit 1 on a failure) [--json: findings as data]
49
- cad preview <project>/<object> four views as a PNG in .preview/ (prints the path)
52
+ cad preview <project>/<object> six views as a PNG in .preview/ (prints the path)
53
+ cad animate <project>/<object> a lamina mechanism's sequence, start to finish, in .preview/: an animated SVG, the
54
+ data (shapes, forces, energies, strains each frame, JSON) and a page that plays it
50
55
  cad optimise <project>/<problem> the stiffest layout for a problem in the project's problems/ (name:variant for a
51
56
  variant): a picture in .preview/, the result kept for designs [--fresh] [--json]
52
57
  [--watch [port]: a live view of it at http://127.0.0.1:8090/, with a stop button]
@@ -88,15 +93,40 @@ const HELP = `cad: JSCAD designs you can trace, check, share and print (rulecad)
88
93
  --set name=value,name=value change variables that have a tweak range (any command)
89
94
  --part <name> only that part (check, preview, export, link): e.g. --part cap
90
95
  --explode preview: parts moved apart, so each can be seen
91
- --trailer "Co-Authored-By: …" added to release commits (for agents)`;
96
+ --trailer "Co-Authored-By: …" added to release commits (for agents)
97
+ cad --version this tool's version`;
98
+
99
+ // Every command and option there is: a misspelt one is refused by name, not passed over
100
+ const COMMANDS = ['new', 'import-kle', 'clone', 'agents', 'rules', 'values', 'set', 'add', 'why', 'check', 'preview', 'animate', 'optimise', 'optimize', 'export',
101
+ 'show', 'link', 'status', 'release', 'history', 'diff', 'printed', 'measure', 'match', 'variants', 'compare', 'help'];
102
+ const OPTIONS = ['all', 'along', 'at', 'bump', 'depth', 'dry-run', 'explode', 'force', 'fresh', 'json', 'licence', 'license', 'long', 'm', 'material', 'md', 'name', 'new',
103
+ 'no-models', 'no-pictures', 'no-rules', 'note', 'open', 'part', 'place', 'pose', 'progress', 'push', 'result', 'rules', 'samples', 'set', 'short', 'source', 'steps',
104
+ 'sweep', 'tol', 'trailer', 'ttl', 'version', 'watch', 'line',
105
+ 'unit', 'rule', 'label', // cad set
106
+ 'a', 'b', 'min', 'max', 'poses', 'id', 'type', 'parent', 'child', 'follow', 'value', 'ratio', 'object', 'assembly', 'variant', 'rotate']; // cad add
107
+ // What a command takes, where that isn't <project>/<object>
108
+ const USAGE = { add: 'fit|joint|item|loop|pose <project>/<assembly> --key value …', why: '<project>/<object>.<variable>', set: '<project>/<object> name=value …',
109
+ optimise: '<project>/<problem>', optimize: '<project>/<problem>', history: '<project>[/<object>]', release: '<project>[/<object>] -m "what changed"',
110
+ diff: '<project>/<object> <from> [<to>]', compare: '<project>/<object> <a> <b>', match: '<project>/<object> <model.stl|model.3mf>', clone: '<board.kicad_pcb | GitHub link> <name>' };
92
111
 
93
112
  const args = process.argv.slice(2);
94
- // --name value, or -m for one-letter names
95
- const opt = (k) => { const i = args.findIndex((a) => a === `--${k}` || (k.length === 1 && a === `-${k}`)); return i >= 0 ? (args[i + 1] && !args[i + 1].startsWith('--') ? args[i + 1] : true) : undefined; };
113
+ // Options that stand alone. Every other takes the value after it: --name value, or -m for one-letter names
114
+ // (--sweep and --watch take one or not).
115
+ const FLAGS = ['all', 'dry-run', 'explode', 'force', 'fresh', 'json', 'long', 'md', 'new', 'no-models', 'no-pictures', 'no-rules', 'open', 'progress', 'push', 'short'];
116
+ const opt = (k) => {
117
+ const i = args.findIndex((a) => a === `--${k}` || (k.length === 1 && a === `-${k}`));
118
+ if (i < 0) return undefined;
119
+ if (FLAGS.includes(k)) return true;
120
+ if (args[i + 1] && !args[i + 1].startsWith('--')) return args[i + 1];
121
+ if (['sweep', 'watch'].includes(k)) return true;
122
+ throw new Error(`${args[i]} needs a value after it`);
123
+ };
96
124
  // The arguments that aren't options or an option's value: cad values keyboard/case depth width --json
97
- const positional = () => args.filter((a, i) => !a.startsWith('--') && !(i > 0 && args[i - 1].startsWith('--') && !['--json', '--long', '--short', '--md', '--all', '--explode'].includes(args[i - 1])));
98
- const sets = () => Object.fromEntries(String(opt('set') || '').split(',').filter(Boolean).map((p) => p.split('=').map((s) => s.trim())));
99
- const suffix = (set) => Object.entries(set).map(([k, v]) => `-${k}=${v}`).join('');
125
+ const takesValue = (a) => a === '-m' || (a.startsWith('--') && !FLAGS.includes(a.slice(2)));
126
+ const positional = () => args.filter((a, i) => !a.startsWith('--') && a !== '-m' && !(i > 0 && takesValue(args[i - 1])));
127
+ // --set name=value,name=value (a value may hold an = of its own)
128
+ const sets = () => Object.fromEntries(String(opt('set') || '').split(',').filter(Boolean).map((p) => { const i = p.indexOf('='); return i < 0 ? [p.trim(), undefined] : [p.slice(0, i).trim(), p.slice(i + 1).trim()]; }));
129
+ const suffix = (set) => Object.entries(set).map(([k, v]) => `-${k}=${v}`).join('').replace(/[^\w.=+-]/g, '_'); // in file names: nothing that could name another folder
100
130
 
101
131
  // --progress: what a long build or sweep is doing, on one line of stderr
102
132
  const showProgress = (e) => {
@@ -116,7 +146,7 @@ const sig = (n) => (Number.isFinite(n) ? String(Number(n.toPrecision(3))) : Stri
116
146
  const stiffOf = (c) => (c.moment ? c.torsion : c.stiffness);
117
147
  const howFar = (c) => (c.moment ? `turns ${sig(c.angle * 180 / Math.PI)}° under ${sig(c.moment / 1000)} N·m, ${sig(c.torsion / 1000 * Math.PI / 180)} N·m a degree` : `moves ${sig(c.deflection)} mm along its load, ${sig(c.stiffness)} N/mm`);
118
148
  // cad optimise: run a problem (with a progress line), then report it and draw it: a 2D layout as an SVG of its
119
- // densities, a 3D one as the preview's four views of its surface
149
+ // densities, a 3D one as the preview's views of its surface
120
150
  async function optimiseProblem(ref) {
121
151
  const [project, name] = String(ref).split('/');
122
152
  if (!project || !name) throw new Error('usage: cad optimise <project>/<problem>[:variant]');
@@ -127,7 +157,9 @@ async function optimiseProblem(ref) {
127
157
  }
128
158
  const live = !opt('json') && process.stderr.isTTY;
129
159
  // --watch [port]: the live view, served while it runs (a watched run is always run afresh, so there is something to watch)
130
- const watch = opt('watch'), view = watch ? await liveView({ port: watch === true ? 8090 : Number(watch), title: `cad optimise ${ref}` }) : null;
160
+ const watch = opt('watch');
161
+ if (watch && watch !== true && !(Number(watch) > 0 && Number(watch) < 65536)) throw new Error(`--watch takes a port number (got "${watch}")`);
162
+ const view = watch ? await liveView({ port: watch === true ? 8090 : Number(watch), title: `cad optimise ${ref}` }) : null;
131
163
  if (view) say(`watching at ${view.url}`);
132
164
  let r;
133
165
  try {
@@ -140,7 +172,7 @@ async function optimiseProblem(ref) {
140
172
  if (view) { view.close(`finished: ${r.steps} steps${r.converged ? '' : ', not settled'}`, { hold: 10 * 60e3 }); say(`the live view shows the result for ten more minutes (Ctrl-C to stop it)`); }
141
173
  const p = await readProblem(project, name), cells = r.dim === 3 ? `${r.grid.nx} × ${r.grid.ny} × ${r.grid.nz}` : `${r.grid.nx} × ${r.grid.ny}`;
142
174
  const lines = [`${p.material.name}${r.dim === 2 ? `, ${fmt(r.thickness)} mm thick` : ''}: ${r.cases.map((c) => c.moment ? `${c.name} ${sig(c.angle * 180 / Math.PI)}° (${sig(c.torsion / 1000 * Math.PI / 180)} N·m/°)` : `${c.name} ${sig(c.deflection)} mm (${sig(c.stiffness)} N/mm)`).join(', ')}`,
143
- `${fmt(r.volume * 100)}% of the space, ${cells} cells of ${fmt(r.grid.h)} mm, ${r.steps} steps${r.converged ? '' : ' (stopped: not settled)'}${r.overhang ? `, printable built ${r.overhang}` : ''}${r.stress ? `, peak stress ${sig(r.stress.peak)} MPa (limit ${sig(r.stress.limit)})` : ''}${r.dropped ? `; ${r.dropped.length} loose ${r.dropped.length === 1 ? 'piece' : 'pieces'} dropped (${sig(r.dropped.reduce((t, v) => t + v, 0))} mm³)` : ''}${r.emptied ? `; ${r.emptied} ${r.emptied === 1 ? 'cell' : 'cells'} that wouldn't print emptied` : ''}`,
175
+ `${fmt(r.volume * 100)}% of the space, ${cells} cells of ${fmt(r.grid.h)} mm, ${r.steps} steps${r.converged ? '' : ' (stopped: not settled)'}${r.overhang ? `, printable built ${r.overhang}` : ''}${r.stress ? `, peak stress ${sig(r.stress.peak)} MPa (limit ${sig(r.stress.limit)})` : ''}${r.dropped ? `; ${r.dropped.length} loose ${r.dropped.length === 1 ? 'piece' : 'pieces'} dropped (${sig(r.dropped.reduce((t, v) => t + v, 0))} mm³)` : ''}${r.emptied ? `; ${r.emptied} ${r.emptied === 1 ? 'cell' : 'cells'} that wouldn't print emptied` : ''}${r.cleared ? `; sliced as the printer will, ${r.cleared} ${r.cleared === 1 ? 'cell' : 'cells'} under islands emptied` : ''}`,
144
176
  ...(r.unsupported > 0.01 ? [`${fmt(r.unsupported * 100)}% of the kept regions has nothing holding it up (at ${r.overhang ? 'the printer\'s overhang limit' : '45°'} or less): give the part more material to stand them on, or keep less`] : [])];
145
177
  let out;
146
178
  if (r.dim === 3) {
@@ -155,6 +187,7 @@ async function optimiseProblem(ref) {
155
187
  if (opt('json')) return console.log(JSON.stringify((({ density, history, mesh, ...x }) => x)(r), null, 2));
156
188
  console.log(`${r.title}${r.cached ? ' (cached)' : ` (${fmt(r.seconds)} s)`}`);
157
189
  for (const c of r.cases) console.log(` ${c.name}: ${howFar(c)}`);
190
+ if (r.mechanism) console.log(` the output moves ${sig(r.mechanism.travel)} mm its way for ${sig(r.mechanism.input)} mm of push: an advantage of ${sig(r.mechanism.advantage)}`);
158
191
  if (r.stress) console.log(` peak stress ${sig(r.stress.peak)} MPa, the limit ${sig(r.stress.limit)} MPa${r.stress.peak > r.stress.limit * 1.02 ? ': over it (raise the volume, ease the limit, or use a smaller cell)' : ''}`);
159
192
  if (r.dim === 3) console.log(` ${fmt(r.volume * 100)}% of the space filled: ${fmt(r.solid / 1000)} cm³ (${fmt(r.solid / 1000 * (p.material.density || 0))} g of ${p.material.name})${r.overhang ? `, printable built ${r.overhang}` : ''}`);
160
193
  else console.log(` ${fmt(r.volume * 100)}% of the space filled, outline ${fmt(r.area)} mm² (${fmt(r.area * r.thickness / 1000)} cm³ before bosses and holes are made exact)`);
@@ -243,6 +276,9 @@ async function analyses(b, d, tag) {
243
276
  values: { stress: c.stress, at: c.stressAt, ...(safety != null ? { safety } : {}), ...(fatigue != null ? { fatigue } : {}), ...(minSafety != null ? { min: minSafety } : {}) }, refs },
244
277
  ];
245
278
  });
279
+ // Members the grid is too coarse for: under four cells thick, a cell's stiffness is a rough figure
280
+ if (r.thin && r.thin.share > 0.05) found.push({ level: 'warn', code: 'fea.coarse', values: { share: r.thin.share, cells: r.thin.cells, cell: r.grid.h }, refs: { problem: a.problem, part: part.name },
281
+ text: `${a.problem}: ${fmt(r.thin.share * 100)}% of the part is in members under ${r.thin.cells} cells (${fmt(r.thin.cells * r.grid.h)} mm) thick, where the stiffness is rough: use a smaller cell (${fmt(r.grid.h / 2)} mm) and see that it settles` });
246
282
  const grams = m.density ? ` (${fmt((r.volume / 1000) * m.density)} g of ${m.name})` : '';
247
283
  if (a.volume != null) {
248
284
  const want = evaluate(a.volume, lookup), tol = a.tolerance ?? 0.01, off = (r.volume - want) / want;
@@ -265,8 +301,13 @@ async function analyses(b, d, tag) {
265
301
  }
266
302
 
267
303
  async function main() {
268
- const [cmd, ref] = args;
269
- if (!cmd || cmd === 'help') return console.log(HELP);
304
+ const first = args[0], pos = positional(), [cmd = first, ref] = pos; // names first or options first: cad check --json keyboard/case
305
+ if (!first || ['help', '--help', '-h'].includes(first)) return console.log(HELP);
306
+ if (['--version', '-v', 'version'].includes(first)) return console.log(JSON.parse(fs.readFileSync(new URL('../package.json', import.meta.url), 'utf8')).version);
307
+ if (!COMMANDS.includes(cmd)) { const guess = near(cmd, COMMANDS); throw new Error(`no command "${cmd}"${guess ? ` (did you mean "${guess}"?)` : ''}: cad help lists them`); }
308
+ const odd = args.find((a) => a.startsWith('--') && !OPTIONS.includes(a.slice(2)));
309
+ if (odd) { const guess = near(odd.slice(2), OPTIONS); throw new Error(`no option ${odd}${guess ? ` (did you mean --${guess}?)` : ''}: cad help lists them`); }
310
+ if (configError) throw configError;
270
311
 
271
312
  if (cmd === 'new') {
272
313
  const [project, name] = String(ref || '').split('/');
@@ -294,7 +335,7 @@ async function main() {
294
335
  return console.log(`wrote ${path.relative(process.cwd(), to) || 'AGENTS.md'}: how an AI agent should design here (CLAUDE.md includes it)`);
295
336
  }
296
337
  if (cmd === 'import-kle') { // a layout from keyboard-layout-editor.com into a project's layouts/
297
- const [project, name] = String(args[2] || '').split('/');
338
+ const [project, name] = String(pos[2] || '').split('/');
298
339
  if (!ref || !fs.existsSync(ref) || !project || !/^[a-z][a-z0-9-]*$/.test(name || '')) throw new Error('usage: cad import-kle <layout.json> <project>/<name> (the JSON download, or a file with its Raw data)');
299
340
  const { layout, notes } = fromKLE(fs.readFileSync(ref, 'utf8'));
300
341
  const to = path.join(paths.project(project), 'layouts', `${name}.json`);
@@ -305,22 +346,23 @@ async function main() {
305
346
  for (const n of notes) console.log(` note: ${n}`);
306
347
  return;
307
348
  }
349
+ if (cmd === 'clone') return cloneBoard(ref, pos[2], { source: opt('source'), licence: opt('licence') || opt('license'), force: !!opt('force'), noModels: !!opt('no-models') });
308
350
  if (cmd === 'status') return status(ref);
309
351
  if (cmd === 'measure') {
310
352
  if (!ref) throw new Error('usage: cad measure <model.stl|model.3mf> [--along x] [--at 10,50] [--line 0.6,2.5] [--rules <name>]');
311
353
  const list = (k) => (opt(k) && opt(k) !== true ? String(opt(k)).split(k === 'line' ? ';' : ',').filter(Boolean) : []);
312
354
  return measure(ref, { along: opt('along'), at: list('at'), line: list('line'), rules: opt('rules'), source: opt('source'), licence: opt('licence') || opt('license'), force: !!opt('force'), pictures: !opt('no-pictures') });
313
355
  }
314
- if (!ref) throw new Error(`usage: cad ${cmd} <project>/<object>`);
356
+ if (!ref || (cmd === 'add' && !pos[2])) throw new Error(`usage: cad ${cmd} ${USAGE[cmd] || '<project>/<object>'}`);
315
357
  if (cmd === 'release') return ref.includes('/') ? releaseObject(locate(ref)) : opt('all') ? releaseAll(ref) : releaseProject(ref);
316
358
  if (cmd === 'variants') return variants(locate(ref));
317
- if (cmd === 'compare') return compareVariants(locate(ref), args[2], args[3]);
359
+ if (cmd === 'compare') return compareVariants(locate(ref), pos[2], pos[3]);
318
360
  if (cmd === 'history') return history(ref);
319
- if (cmd === 'diff') return diff(locate(ref), args[2], args[3] && !args[3].startsWith('--') ? args[3] : null);
361
+ if (cmd === 'diff') return diff(locate(ref), pos[2], pos[3] || null);
320
362
  if (cmd === 'printed') return printed(locate(ref));
321
363
  if (cmd === 'why') return explainValue(ref);
322
364
  if (cmd === 'set') return editVariables(ref);
323
- if (cmd === 'add') return editAssembly(args[1], args[2]);
365
+ if (cmd === 'add') return editAssembly(pos[1], pos[2]);
324
366
  if (cmd === 'optimise' || cmd === 'optimize') return await optimiseProblem(ref);
325
367
  if (isAssembly(ref)) return assembly(cmd, ref);
326
368
  const [base, at] = ref.split('@');
@@ -332,7 +374,7 @@ async function main() {
332
374
  if (b.circuit && ['check', 'preview', 'export'].includes(cmd)) return board(cmd, d, b, { title, version, tag });
333
375
 
334
376
  if (cmd === 'match') {
335
- const file = args[2];
377
+ const file = pos[2];
336
378
  if (!file || file.startsWith('--')) throw new Error(`usage: cad match ${ref} <model.stl|model.3mf> [--tol 0.2] [--place "rz90 t1,2,3"]`);
337
379
  const tol = opt('tol') ? Number(opt('tol')) : printer(b, d).fit ?? 0.2;
338
380
  const ok = await match(b, d, file, { place: opt('place'), tol, samples: Number(opt('samples')) || 20000, at: opt('at') ? String(opt('at')).split(',') : [], title: `${title} ${version}`, tag, pictures: !opt('no-pictures') });
@@ -368,6 +410,7 @@ async function main() {
368
410
  ...(b.object.role === 'reference'
369
411
  ? [{ level: 'pass', text: `a reference (${(await import('@rulecad/printcheck')).bounds(b.triangles).size.map(fmt).join(' × ')} mm), not printed: no print checks`, code: 'print.reference' }]
370
412
  : check(b.triangles, printer(b, d), { parts: b.parts })),
413
+ ...(b.mechanism?.findings || []), // a lamina mechanism's own: it prints free, stops, holds, clears in every state
371
414
  ...(await analyses(b, d, tag)),
372
415
  ], { object: `${d.project}/${d.name}`, title, version, ...(Object.keys(set).length ? { set } : {}), orientation: b.object.orientation, parts: b.parts.map((p) => ({ name: p.name, role: p.role || 'part' })) });
373
416
  if (b.object.orientation) say(` orientation: ${b.object.orientation}`);
@@ -376,6 +419,18 @@ async function main() {
376
419
  return;
377
420
  }
378
421
 
422
+ if (cmd === 'animate') {
423
+ if (!b.mechanism) throw new Error(`${d.project}/${d.name} isn't a lamina mechanism: cad animate plays the sequence of one made with flexures.lamina()`);
424
+ const out = paths.preview(d.project, `${d.name}${tag}-sequence.svg`);
425
+ fs.mkdirSync(path.dirname(out), { recursive: true });
426
+ fs.writeFileSync(out, (await import('../lib/animate.mjs')).sequenceSvg(b.mechanism, { title: `${title} ${version}: ${(b.mechanism.sequence || []).join(', ')}` }));
427
+ // and the sequence as data (shapes, forces, energies, strains each frame), with a page that plays it
428
+ const { playerData, playerHtml } = await import('../lib/player.mjs'), data = playerData(b.mechanism, { title, version, object: `${d.project}/${d.name}` });
429
+ const json = paths.preview(d.project, `${d.name}${tag}-sequence.json`), html = paths.preview(d.project, `${d.name}${tag}-player.html`);
430
+ fs.writeFileSync(json, JSON.stringify(data)); fs.writeFileSync(html, playerHtml(data));
431
+ console.log(out); console.log(json); return console.log(html);
432
+ }
433
+
379
434
  if (cmd === 'preview') {
380
435
  const out = paths.preview(d.project, `${d.name}${tag}${opt('explode') ? '-exploded' : ''}.png`);
381
436
  const size = (await import('@rulecad/printcheck')).bounds(b.triangles).size.map((n) => fmt(n)).join(' × ');
@@ -418,6 +473,7 @@ async function editVariables(ref) {
418
473
  const pairs = positional().slice(2);
419
474
  if (!ref || !pairs.length || pairs.some((p) => !p.includes('='))) throw new Error('usage: cad set <project>/<object> name=value [name=value …] [--unit mm] [--rule "why"] [--label "Label"] [--new]');
420
475
  const extra = Object.fromEntries(['unit', 'rule', 'label'].filter((k) => typeof opt(k) === 'string').map((k) => [k, opt(k)]));
476
+ if (pairs.length > 1 && (extra.rule || extra.label)) throw new Error(`--${extra.rule ? 'rule' : 'label'} describes one variable: set ${pairs.map((p) => p.split('=')[0]).join(' and ')} one at a time`);
421
477
  const changes = Object.fromEntries(pairs.map((p) => { const i = p.indexOf('='); return [p.slice(0, i).trim(), { value: parseValue(p.slice(i + 1).trim()), ...extra }]; }));
422
478
  const r = await setVariables(ref, changes, { create: !!opt('new') });
423
479
  if (opt('json')) return console.log(JSON.stringify(r));
@@ -475,7 +531,7 @@ async function board(cmd, d, b, { title, version, tag }) {
475
531
  ...(schemaProblems.length ? schemaProblems : [{ level: 'pass', text: 'files match their schemas', code: 'schema' }]),
476
532
  ...(b.units || []).map((u) => ({ level: 'warn', text: `units: ${u.message}`, code: 'units', refs: { file: own(d.json), path: u.path, variable: u.name } })),
477
533
  raw.length ? { level: 'fail', text: `numbers in ${path.basename(d.js)} that should be variables: ${raw.map((r) => `line ${r.line}: ${r.text}`).join(', ')}` } : { level: 'pass', text: 'every measurement is a variable' },
478
- ...(await pcb.checks(b.circuit, b.values, b.matrix)),
534
+ ...(await pcb.checks(b.circuit, b.values, b.matrix, b.source)),
479
535
  ]);
480
536
  if (b.object.orientation) console.log(` ${b.object.orientation}`);
481
537
  process.exitCode = failed ? 1 : 0;
@@ -658,8 +714,8 @@ async function releaseObject(d, { batch = false } = {}) {
658
714
  const message = opt('m');
659
715
  if (!message || message === true) throw new Error('say what changed: -m "Wider slot for a looser fit"');
660
716
  const object = readObject(d), b = await build(d);
661
- const raw = lint(fs.readFileSync(d.js, 'utf8')), fails = (b.circuit ? await (await pcbEngine()).checks(b.circuit, b.values, b.matrix) // boards: the board's checks
662
- : b.object.role === 'reference' ? [] : check(b.triangles, printer(b, d), { parts: b.parts })).filter((r) => r.level === 'fail'); // references aren't printed
717
+ const raw = lint(fs.readFileSync(d.js, 'utf8')), fails = (b.circuit ? await (await pcbEngine()).checks(b.circuit, b.values, b.matrix, b.source) // boards: the board's checks
718
+ : b.object.role === 'reference' ? [] : [...check(b.triangles, printer(b, d), { parts: b.parts }), ...(b.mechanism?.findings || [])]).filter((r) => r.level === 'fail'); // references aren't printed; a mechanism's own checks count
663
719
  if (raw.length || fails.length) throw new Error(`fix the check first: ${[...raw.map((r) => `raw number ${r.text} on line ${r.line}`), ...fails.map((f) => f.text)].join('; ')}`);
664
720
  let { last, kind, reasons } = await since(d);
665
721
  if (!kind) throw new Error(`nothing has changed since ${last.version}`);
@@ -676,17 +732,25 @@ async function releaseObject(d, { batch = false } = {}) {
676
732
  if (opt('dry-run')) return;
677
733
  const allowed = [...files(d, object), `projects/${d.project}/CHANGELOG.md`, path.relative(WS, printsFile(d))];
678
734
  if (!batch) onlyChanged(allowed); // releaseAll checked the whole tree first
679
- fs.writeFileSync(d.json, fs.readFileSync(d.json, 'utf8').replace(/"version":\s*"[^"]*"/, `"version": "${version}"`));
735
+ fs.writeFileSync(d.json, setAt(fs.readFileSync(d.json, 'utf8'), ['version'], version)); // the object's own version (added, if it had none), nothing else
680
736
  const log = changelog(d.dir, `${d.name} ${version} (${kind}), ${today()}`, message, reasons);
681
737
  commitAndTag([...files(d, object), log].filter((f) => fs.existsSync(path.join(WS, f))), `${tag}: ${message}`, tag, `${kind}: ${message}${b.circuit ? `\n\nengine: ${engineId()}` : ''}`);
682
738
  console.log(`tagged ${tag}${opt('push') ? ' and pushed' : ' (not pushed: --push, or git push --follow-tags)'}`);
683
739
  }
684
740
 
741
+ // A project's project.json, or a plain word that there's no such project (and which there are)
742
+ function projectFile(project) {
743
+ const pj = path.join(paths.project(project), 'project.json');
744
+ if (!fs.existsSync(pj)) { const have = projects(); throw new Error(`no project "${project}"${have.length ? ` (projects: ${have.join(', ')})` : ': cad new <project>/<object> starts one'}`); }
745
+ return pj;
746
+ }
747
+ // The workspace's projects: the folders under projects/ that hold a project.json (not a stray file, such as .DS_Store)
748
+ const projects = () => (fs.existsSync(paths.projects) ? fs.readdirSync(paths.projects).filter((p) => fs.existsSync(path.join(paths.project(p), 'project.json'))).sort() : []);
749
+
685
750
  async function releaseProject(project) {
686
751
  const message = opt('m');
687
752
  if (!message || message === true) throw new Error('say what this release is: -m "First full set"');
688
- const dir = paths.project(project), pj = path.join(dir, 'project.json');
689
- if (!fs.existsSync(pj)) throw new Error(`no project "${project}"`);
753
+ const dir = paths.project(project), pj = projectFile(project);
690
754
  const p = JSON.parse(fs.readFileSync(pj, 'utf8')), manifest = {};
691
755
  for (const name of p.objects) {
692
756
  const d = locate(`${project}/${name}`), s = await since(d);
@@ -722,7 +786,7 @@ async function releaseProject(project) {
722
786
 
723
787
  // Release every object in a project that changed, then the project: the tree may hold changes only to their files.
724
788
  async function releaseAll(project) {
725
- const pj = JSON.parse(fs.readFileSync(path.join(paths.project(project), 'project.json'), 'utf8'));
789
+ const pj = JSON.parse(fs.readFileSync(projectFile(project), 'utf8'));
726
790
  const changed = [];
727
791
  for (const n of pj.objects) { const d = locate(`${project}/${n}`); if ((await since(d)).kind) changed.push(d); }
728
792
  const allowed = new Set([`projects/${project}/project.json`, `projects/${project}/CHANGELOG.md`, `projects/${project}/prints.jsonl`,
@@ -754,8 +818,9 @@ async function compareVariants(d, a, b) {
754
818
  }
755
819
 
756
820
  async function status(project) {
757
- for (const p of project ? [project] : fs.readdirSync(paths.projects)) {
758
- const pj = JSON.parse(fs.readFileSync(path.join(paths.project(p), 'project.json'), 'utf8'));
821
+ if (!project && !projects().length) return console.log(`no projects in ${WS} yet: cad new <project>/<object> starts one`);
822
+ for (const p of project ? [project] : projects()) {
823
+ const pj = JSON.parse(fs.readFileSync(projectFile(p), 'utf8'));
759
824
  console.log(`${p}${pj.version ? `@${pj.version}` : ''}`);
760
825
  for (const name of pj.objects) {
761
826
  const s = await since(locate(`${p}/${name}`));
@@ -790,7 +855,8 @@ async function diff(d, from, to) {
790
855
  function printed(d) {
791
856
  const result = opt('result');
792
857
  if (!['ok', 'failed'].includes(result)) throw new Error('--result ok or --result failed (and --note "what happened")');
793
- const object = readObject(d), version = opt('version') || tags(d.project, d.name).at(-1)?.version || object.version;
858
+ const object = readObject(d), released = tags(d.project, d.name).map((t) => t.version), version = opt('version') || released.at(-1) || object.version;
859
+ if (opt('version') && version !== object.version && !released.includes(version)) throw new Error(`${d.name} has no version ${version} (${released.length ? `releases: ${released.join(', ')}` : `unreleased, at ${object.version}`})`);
794
860
  const entry = { date: today(), object: d.name, version, ...(opt('set') ? { set: opt('set') } : {}), material: opt('material') || object.material, result, ...(opt('note') ? { note: opt('note') } : {}) };
795
861
  fs.appendFileSync(printsFile(d), JSON.stringify(entry) + '\n');
796
862
  console.log(`logged in ${path.relative(WS, printsFile(d))}: ${d.name}@${version} ${result}`);
@@ -798,6 +864,6 @@ function printed(d) {
798
864
 
799
865
  main().catch((e) => {
800
866
  if (opt('json')) console.log(JSON.stringify({ error: errorData({ ...e, message: e.message, code: e.code, file: e.file && path.relative(WS, e.file) }) }, null, 2));
801
- else console.error(`${e.message}${e.file ? ` (${path.relative(WS, e.file)}${e.path ? `: ${e.path}` : ''})` : ''}`);
867
+ else console.error(`${e.message}${e.file ? ` (${path.relative(WS, e.file)}${e.line ? `:${e.line}` : ''}${e.path ? `: ${e.path}` : ''})` : ''}`);
802
868
  process.exit(1);
803
869
  });
@@ -0,0 +1,71 @@
1
+ // A lamina mechanism's sequence as one animated SVG: the frame drawn once, and each moving part (bodies, and the
2
+ // flexures drawn bent) frame by frame, holding a moment at each state. Self-contained: it plays in any browser, with
3
+ // nothing to install. Frames come from @rulecad/flexures lamina() (followers pushed aside where their drivers meet them).
4
+ const COLOURS = { ground: '#c9ccd1', body: '#2f6fb3', flexure: '#e07a1f' };
5
+ const HOLD = 8; // a state is shown this many frames' time
6
+ const STEP = 0.06; // seconds a frame
7
+
8
+ const fmt = (n) => +n.toFixed(2);
9
+ const pathOf = (outlines) => outlines.map((o) => `M${o.map(([x, y]) => `${fmt(x)} ${fmt(-y)}`).join('L')}Z`).join('');
10
+ const escape = (s) => String(s).replace(/[<>&"]/g, (c) => ({ '<': '&lt;', '>': '&gt;', '&': '&amp;', '"': '&quot;' })[c]);
11
+
12
+ /**
13
+ * @param {{ frames: { from: string, to: string, t: number, parts: Record<string, number[][][]> }[], joints: Record<string, object> }} mechanism
14
+ * @param {{ title?: string }} [o]
15
+ * @returns {string} the SVG
16
+ */
17
+ export function sequenceSvg(mechanism, { title = '' } = {}) {
18
+ const frames = mechanism.frames || [];
19
+ if (!frames.length) throw new Error('the mechanism has no sequence to animate: give its lamina a sequence of states');
20
+ const flexures = new Set(Object.keys(mechanism.joints || {})), kind = (n) => (n === 'ground' ? 'ground' : flexures.has(n) ? 'flexure' : 'body');
21
+ // The view: everything every frame reaches, with a margin and a line for the caption
22
+ let lo = [Infinity, Infinity], hi = [-Infinity, -Infinity];
23
+ for (const fr of frames) for (const outs of Object.values(fr.parts)) for (const o of outs) for (const [x, y] of o) { lo = [Math.min(lo[0], x), Math.min(lo[1], -y)]; hi = [Math.max(hi[0], x), Math.max(hi[1], -y)]; }
24
+ const pad = Math.max(hi[0] - lo[0], hi[1] - lo[1]) * 0.05, caption = pad * 2;
25
+ // The force curves of the steps a hand drives, a chart each, in a row under the drawing
26
+ const charts = (mechanism.curves || []).flatMap((tr) => tr.curve.filter((c) => c.points.length > 1).map((c) => ({ from: tr.from, to: tr.to, ...c })));
27
+ const chartH = charts.length ? (hi[1] - lo[1]) * 0.35 : 0;
28
+ const vb = [lo[0] - pad, lo[1] - pad - caption, hi[0] - lo[0] + 2 * pad, hi[1] - lo[1] + 2 * pad + caption * 2 + (chartH ? chartH + caption * 1.5 : 0)]; // a band above for the key, below for the step and the charts
29
+ // Timing: each frame its share; a state (the first frame of each step, and the last) held longer
30
+ const weights = frames.map((fr, i) => (fr.t === 0 || i === frames.length - 1 ? HOLD : 1)), total = weights.reduce((a, b) => a + b, 0);
31
+ const starts = []; weights.reduce((at, w) => { starts.push(at / total); return at + w; }, 0);
32
+ const dur = `${fmt(total * STEP)}s`;
33
+ const show = (i) => { // visible only during frame i
34
+ const a = fmt(starts[i]), b = fmt(i + 1 < frames.length ? starts[i + 1] : 1);
35
+ const keys = [...new Set([0, a, b, 1])].sort((x, y) => x - y), values = keys.map((k) => (k >= a && k < b ? 'inline' : 'none'));
36
+ if (i === frames.length - 1) values[values.length - 1] = 'inline';
37
+ return `<animate attributeName="display" values="${values.join(';')}" keyTimes="${keys.join(';')}" dur="${dur}" calcMode="discrete" repeatCount="indefinite"/>`;
38
+ };
39
+ const ground = frames[0].parts.ground ? `<path d="${pathOf(frames[0].parts.ground)}" fill="${COLOURS.ground}" fill-rule="evenodd"/>` : '';
40
+ const size = fmt(caption * 0.45), textY = fmt(hi[1] + pad + caption * 0.65), keyY = fmt(vb[1] + caption * 0.65);
41
+ // Each chart: its box, the curve, and where frame i sits on it (if frame i is in its step)
42
+ const chartTop = hi[1] + pad + caption * 1.5, cw = vb[2] / Math.max(1, charts.length), inner = (k) => ({ x0: vb[0] + k * cw + pad * 1.5, x1: vb[0] + (k + 1) * cw - pad * 0.5, y0: chartTop + caption * 0.6, y1: chartTop + chartH });
43
+ const scaled = charts.map((c, k) => {
44
+ const b = inner(k), xs = c.points.map(([x]) => Math.abs(x)), fs = c.points.map(([, F]) => F), xm = Math.max(1e-9, ...xs), fmin = Math.min(0, ...fs), fmax = Math.max(1e-9, ...fs);
45
+ const at = ([x, F]) => [b.x0 + (Math.abs(x) / xm) * (b.x1 - b.x0), b.y1 - ((F - fmin) / (fmax - fmin)) * (b.y1 - b.y0)];
46
+ return { ...c, b, at, fmax, xm };
47
+ });
48
+ const chartArt = scaled.map((c) => {
49
+ const pts = c.points.map(c.at), zero = c.at([0, 0])[1];
50
+ const small = fmt(Math.min(size * 0.6, (c.b.x1 - c.b.x0) / 22)); // two short lines, sized to fit the chart's width
51
+ return `<g font-family="system-ui, sans-serif" fill="#555"><text x="${fmt(c.b.x0)}" y="${fmt(c.b.y0 - caption * 0.45)}" font-size="${small}">${escape(`${c.from} to ${c.to}, ${c.joint}`)}</text><text x="${fmt(c.b.x0)}" y="${fmt(c.b.y0 - caption * 0.1)}" font-size="${small}">${escape(`up to ${c.fmax.toFixed(1)} N over ${c.xm.toFixed(1)} mm`)}</text>
52
+ <line x1="${fmt(c.b.x0)}" y1="${fmt(zero)}" x2="${fmt(c.b.x1)}" y2="${fmt(zero)}" stroke="#ccc" stroke-width="${fmt(size * 0.04)}"/><line x1="${fmt(c.b.x0)}" y1="${fmt(c.b.y0)}" x2="${fmt(c.b.x0)}" y2="${fmt(c.b.y1)}" stroke="#ccc" stroke-width="${fmt(size * 0.04)}"/>
53
+ <polyline points="${pts.map(([x, y]) => `${fmt(x)},${fmt(y)}`).join(' ')}" fill="none" stroke="#2f6fb3" stroke-width="${fmt(size * 0.08)}"/></g>`;
54
+ }).join('\n');
55
+ const markerOf = (fr) => scaled.filter((c) => c.from === fr.from && c.to === fr.to).map((c) => { const p = c.at(c.points[Math.min(c.points.length - 1, Math.round(fr.t * (c.points.length - 1)))]); return `<circle cx="${fmt(p[0])}" cy="${fmt(p[1])}" r="${fmt(size * 0.25)}" fill="#e07a1f"/>`; }).join('');
56
+ const body = frames.map((fr, i) => {
57
+ const label = fr.label || (fr.t === 0 && fr.from === fr.to ? fr.from : fr.t === 0 ? fr.from : `${fr.from} to ${fr.to}`);
58
+ const shapes = Object.entries(fr.parts).filter(([n]) => n !== 'ground').map(([n, o]) => `<path d="${pathOf(o)}" fill="${COLOURS[kind(n)]}" fill-rule="evenodd"/>`).join('');
59
+ return `<g display="${i ? 'none' : 'inline'}">${show(i)}${shapes}${markerOf(fr)}<text x="${fmt(vb[0] + pad)}" y="${textY}" font-size="${size}" font-family="system-ui, sans-serif" fill="#333">${escape(label)}</text></g>`;
60
+ }).join('\n');
61
+ const key = Object.entries(COLOURS).map(([k, c], i) => `<rect x="${fmt(vb[0] + pad + i * size * 5)}" y="${fmt(keyY - size * 0.8)}" width="${size}" height="${size}" fill="${c}"/><text x="${fmt(vb[0] + pad + i * size * 5 + size * 1.3)}" y="${keyY}" font-size="${fmt(size * 0.8)}" font-family="system-ui, sans-serif" fill="#555">${{ ground: 'frame', body: 'moves', flexure: 'bends' }[k]}</text>`).join('');
62
+ return `<svg xmlns="http://www.w3.org/2000/svg" viewBox="${vb.map(fmt).join(' ')}" width="900">
63
+ <title>${escape(title)}</title>
64
+ <rect x="${fmt(vb[0])}" y="${fmt(vb[1])}" width="${fmt(vb[2])}" height="${fmt(vb[3])}" fill="#fff"/>
65
+ ${ground}
66
+ ${body}
67
+ ${chartArt}
68
+ ${key}
69
+ </svg>
70
+ `;
71
+ }