@rulecad/cad 0.7.41 → 0.7.43

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/README.md CHANGED
@@ -418,6 +418,17 @@ An item can be a motor instead of a printed object: `{ "id": "drive", "motor": {
418
418
  - `motor.heat`: the motor's case against the softening point of the material the project prints in. Too hot says the current to set the driver to.
419
419
  - A `"shaft": true` fit (or `"press"`) between a motor and what it drives reads the bore from the part as drawn: that it's on the shaft (`shaft.seat`), that its flat is there (`shaft.flat`; the shaft turns to meet it, so where the flat faces doesn't matter), how much of the flat it grips (`shaft.grip`), and, pressed on, the hoop stress in the hub (`shaft.hoop`).
420
420
 
421
+ ### Building it
422
+
423
+ Once an assembly is checked, these say how to make it. They all read the assembly itself, so they can't disagree with it.
424
+
425
+ - `cad order <project>/<assembly>`: the order it goes together in, each step with the part and the fasteners named from its `fastens` notes (`"fastener": "M3x12", "count": 2` on a fit puts them on the shopping list and the step). `--preview` writes a picture of each step to `.preview/`: what's there, and the new part held off along the way it goes on. The order is found by taking the assembly apart, so a part goes in after what it's fastened into, a bearing before its shaft, and a nut trapped by a wall before the neighbour that traps it. A part goes on along a straight line that clears everything already there; which line comes from the part as drawn.
426
+ - `assembly.order` is `cad check`'s finding on it: a part no order can reach fails by name, and a part sealed inside another too. A fit can say where a screw is driven from with `"access": "<item>.<anchor>"`, the anchor's z pointing out along the screw: whatever stands on that line goes on after the screw, and if it has to go on first the screw can't be reached at all. Works on an assembly's own items; a component (an assembly used as an item) goes on as one step.
427
+ - `cad plates <project>/<assembly>`: every printed part laid out on beds, in its print orientation (as it's drawn), grouped by filament so each plate is one colour change, spaced by the first layer's rule (the printer's `print_gap` plus twice its `foot`, up to whole lines; `--gap` for your own). They're written as `kind: "plate"` assemblies called `<assembly>-<filament>-<n>` and checked as prints; `cad export` makes each one's 3MF. Each plate remembers what's on it by its build's hash (`"packed"` in its file): a changed part re-packs only its plate, so the other plates keep their files untouched, and a part too big for the bed is said by name (`plate.bed`).
428
+ - `cad wires <project>/<assembly>`: the wiring sheet, printed and written to `exports/<project>/<assembly>.wiring.md` (`cad machine` writes it too): each wire's length through every pose with its service loop, gauge, colour, connectors and board pins. Wires also show faint along their routes in `cad preview` and in the link, moving with the joints, and are never parts: no overlap check sees them.
429
+ - `cad link` for such an assembly carries the rest of the project with the model. A **Build** button on the page opens, beside it, the shopping list, the plates drawn on their beds, the wiring sheet, the assembly steps (each shows the model at that step) and the machine's settings. The Rules panel lists **predicted against measured**: the ledger `cad measured` writes, each with its ratio, and what the checks predict that nobody has measured yet.
430
+ - A link for an assembly with a `task` lets the page move the machine: see "Things that move" in the viewer's README. It carries the newest step file `cad plot` wrote for this assembly (`--steps <file>` for another, `--no-steps` for none). A step file for other joints is refused by name.
431
+
421
432
  ## Optimised parts
422
433
 
423
434
  `cad optimise` finds the stiffest layout of a flat part: where to put a fixed amount of material so the part bends
@@ -646,6 +657,8 @@ nothing jams, that its catches hold, and that every flexure has a hard stop befo
646
657
  moving bodies in blue and the flexures in orange, drawn bent, holding a moment at each state. Under it, each driven step's force against its travel, with a marker that follows the frames; a mechanism that fires adds the shot in slow motion. The printer's
647
658
  `print_gap` is the gap the checks hold it to.
648
659
 
660
+ An assembly with a `gait` (EXAMPLES chapter 14) plays too: `cad animate <project>/<assembly>` writes the cycle as an animated SVG in `.preview/` (a side view of the legs and a plan of the feet and what they stand on) and its data as JSON. The model page plays the same cycle in its Motion panel.
661
+
649
662
  ## Checks
650
663
 
651
664
  - **Closed solids:** every edge must be matched by faces on the other side. T-junctions (an edge covered by several
package/bin/cad.mjs CHANGED
@@ -13,7 +13,7 @@ import { check } from '@rulecad/printcheck';
13
13
  import { preview } from '../lib/preview.mjs';
14
14
  import { measure, match } from '../lib/meshcmd.mjs';
15
15
  import { cloneBoard } from '../lib/clone.mjs';
16
- import { isAssembly, buildAssembly, checkAssembly, shapes, sweep, motionData } from '../lib/assembly.mjs';
16
+ import { isAssembly, buildAssembly, checkAssembly, shapes, sweep, motionData, wireTubesOf } from '../lib/assembly.mjs';
17
17
  import { valuesOf, why } from '../lib/explain.mjs';
18
18
  import { errorData, near } from '../lib/errors.mjs';
19
19
  import { schemaFindings } from '../lib/schema.mjs';
@@ -56,7 +56,7 @@ const HELP = `cad: JSCAD designs you can trace, check, share and print (rulecad)
56
56
  cad why <project>/<object>.<name> what a value reads, down to the rules and their sources [--json] [--depth N]
57
57
  cad check <project>/<object> raw numbers in the design, then printability (exit 1 on a failure) [--json: findings as data]
58
58
  cad preview <project>/<object> six views as a PNG in .preview/ (prints the path)
59
- cad animate <project>/<object> a lamina mechanism's sequence, start to finish, in .preview/: an animated SVG, the
59
+ cad animate <project>/<object> a lamina mechanism's sequence, or an assembly's gait, start to finish, in .preview/: an animated SVG, the
60
60
  data (shapes, forces, energies, strains each frame, JSON) and a page that plays it
61
61
  cad optimise <project>/<problem> the stiffest layout for a problem in the project's problems/ (name:variant for a
62
62
  variant): a picture in .preview/, the result kept for designs [--fresh] [--json]
@@ -67,6 +67,7 @@ const HELP = `cad: JSCAD designs you can trace, check, share and print (rulecad)
67
67
  [--md: one labelled Markdown link, for chat (the page downloads any parts): short unless --long]
68
68
  [--short: the model's data in a secret GitHub Gist, so links are ~80 characters]
69
69
  [--no-rules: leave out the Rules panel's list of values and their sources]
70
+ [--steps file.steps.json | --no-steps: the drawing a machine's link carries, by default the newest cad plot wrote]
70
71
  Assemblies with joints: check checks every pose; --pose <name> picks one (check, preview, show, link)
71
72
  [--sweep [joint]: move each joint (or one) through its range, looking for collisions]
72
73
  [--steps 24: how many steps a sweep takes]
@@ -80,6 +81,17 @@ const HELP = `cad: JSCAD designs you can trace, check, share and print (rulecad)
80
81
  cad printed <project>/<object> --result ok|failed [--note "…"] [--material PETG] [--version 0.1.0]
81
82
  cad release <project> --all -m "…" release every object that changed (each with this message), then the project
82
83
 
84
+ cad machine <project>/<assembly> the machine as plain data: axes, steps, limits, homing, the task, in exports/
85
+ cad plot <project>/<assembly> <drawing.svg> plans a drawing on the machine: a step file in exports/, an animation in
86
+ .preview/, and any stroke refused [--calibrate: the calibration drawing] [--tol 0.1] [--json]
87
+ cad order <project>/<assembly> the order it goes together in, each step with its fasteners [--preview: an exploded picture of each step in .preview/]
88
+ cad plates <project>/<assembly> every printed part on beds, by filament, spaced by the first-layer rule: written as plate assemblies and checked; a changed part re-packs only its plate [--gap mm] [--json]
89
+ cad list <project>/<assembly> what it takes to build: bought parts by set, fasteners, wire, printed parts in grams
90
+ cad wires <project>/<assembly> the wiring sheet: each wire's length, gauge and ends, written to exports/ [--out wiring.md]
91
+ cad measured <project>/<assembly> <name>=<value> … a measurement, where the estimate was: a rule (x1c.press=0.08) or a
92
+ check's prediction (task.accuracy=0.8): says what moved, and keeps a ledger of predicted
93
+ against measured, shown by cad history [--unit mm] [--source "how"] [--rule "what it is"]
94
+ [--table: what the assembly still assumes, as Markdown; --out MEASURE.md: kept in that file]
83
95
  cad measure <model.stl|3mf> a model from elsewhere, measured: size, the stretches along its length with the same
84
96
  cross-section, and each section's shape, with a drawing in .preview/measure/
85
97
  [--along x|y|z] [--at 10,50: sections there too] [--line 0.6,2.5;4.6,2.5: where lines
@@ -104,8 +116,8 @@ const HELP = `cad: JSCAD designs you can trace, check, share and print (rulecad)
104
116
 
105
117
  // Every command and option there is: a misspelt one is refused by name, not passed over
106
118
  const COMMANDS = ['new', 'import-kle', 'clone', 'agents', 'trust', 'rules', 'values', 'set', 'add', 'why', 'check', 'preview', 'animate', 'optimise', 'optimize', 'export',
107
- 'show', 'link', 'status', 'release', 'history', 'diff', 'printed', 'measure', 'match', 'variants', 'compare', 'help'];
108
- const OPTIONS = ['all', 'along', 'at', 'bump', 'depth', 'dry-run', 'explode', 'force', 'fresh', 'json', 'licence', 'license', 'long', 'm', 'material', 'md', 'name', 'new',
119
+ 'show', 'link', 'status', 'release', 'history', 'diff', 'printed', 'measure', 'measured', 'list', 'wires', 'machine', 'plot', 'plates', 'order', 'match', 'variants', 'compare', 'help'];
120
+ const OPTIONS = ['table', 'calibrate', 'preview', 'gap', 'no-steps', 'all', 'along', 'at', 'bump', 'depth', 'dry-run', 'explode', 'force', 'fresh', 'json', 'licence', 'license', 'long', 'm', 'material', 'md', 'name', 'new',
109
121
  'no-models', 'no-pictures', 'no-rules', 'note', 'open', 'part', 'place', 'pose', 'progress', 'push', 'result', 'rules', 'samples', 'set', 'short', 'source', 'steps',
110
122
  'sweep', 'tol', 'trailer', 'ttl', 'version', 'watch', 'line',
111
123
  'unit', 'rule', 'label', 'from', 'out', // cad set, cad rules
@@ -118,7 +130,7 @@ const USAGE = { add: 'fit|joint|item|loop|pose <project>/<assembly> --key value
118
130
  const args = process.argv.slice(2);
119
131
  // Options that stand alone. Every other takes the value after it: --name value, or -m for one-letter names
120
132
  // (--sweep and --watch take one or not).
121
- const FLAGS = ['all', 'dry-run', 'explode', 'force', 'fresh', 'json', 'long', 'md', 'new', 'no-models', 'no-pictures', 'no-rules', 'open', 'progress', 'push', 'short'];
133
+ const FLAGS = ['table', 'calibrate', 'preview', 'no-steps', 'all', 'dry-run', 'explode', 'force', 'fresh', 'json', 'long', 'md', 'new', 'no-models', 'no-pictures', 'no-rules', 'open', 'progress', 'push', 'short'];
122
134
  const opt = (k) => {
123
135
  const i = args.findIndex((a) => a === `--${k}` || (k.length === 1 && a === `-${k}`));
124
136
  if (i < 0) return undefined;
@@ -410,6 +422,10 @@ async function main() {
410
422
  if (cmd === 'release') return ref.includes('/') ? releaseObject(locate(ref)) : opt('all') ? releaseAll(ref) : releaseProject(ref);
411
423
  if (cmd === 'variants') return variants(locate(ref));
412
424
  if (cmd === 'compare') return compareVariants(locate(ref), pos[2], pos[3]);
425
+ if (cmd === 'measured') return measuredCommand(ref);
426
+ if (cmd === 'list' || cmd === 'wires') return listCommand(cmd, ref);
427
+ if (cmd === 'machine' || cmd === 'plot') return machineCommand(cmd, ref);
428
+ if (cmd === 'plates' || cmd === 'order') return platesCommand(cmd, ref);
413
429
  if (cmd === 'history') return history(ref);
414
430
  if (cmd === 'diff') return diff(locate(ref), pos[2], pos[3] || null);
415
431
  if (cmd === 'printed') return printed(locate(ref));
@@ -649,11 +665,20 @@ async function assembly(cmd, ref) {
649
665
  process.exitCode = report(findings, { assembly: ref, title, kind: a.kind || 'fit', ...(pose ? { pose } : {}) }) ? 1 : 0;
650
666
  return;
651
667
  }
668
+ if (cmd === 'animate') {
669
+ if (!s.gait) throw new Error(`${ref} has no gait: cad animate plays a gait ("gait" at the top of the assembly), or a lamina mechanism's sequence`);
670
+ const { gaitSvg, gaitData } = await import('../lib/animate.mjs'), { framesOf } = await import('../lib/gait.mjs'), r = framesOf(s);
671
+ if (!r.frames.length) throw new Error(`${ref}'s gait has nothing to play: ${r.findings.map((x) => x.text).join('; ')}`);
672
+ const svg = paths.preview(s.project, `${s.name}-gait.svg`), json = paths.preview(s.project, `${s.name}-gait.json`);
673
+ fs.mkdirSync(path.dirname(svg), { recursive: true });
674
+ fs.writeFileSync(svg, gaitSvg(s, r, { title: `${title}: ${typeof a.gait.pattern === 'string' ? a.gait.pattern : 'a gait'}` })); fs.writeFileSync(json, JSON.stringify(gaitData(s, r)));
675
+ console.log(svg); return console.log(json);
676
+ }
652
677
  if (cmd === 'preview') {
653
678
  const out = paths.preview(s.project, `${s.name}${pose ? `-${pose}` : ''}${opt('explode') ? '-exploded' : ''}.png`);
654
679
  const size = (await import('@rulecad/printcheck')).bounds(s.triangles).size.map((n) => fmt(n)).join(' × ');
655
680
  const faint = [...new Set(s.parts.filter((p) => p.role !== 'part').map((p) => `${p.object || p.item}${p.role === 'support' ? ' supports' : ''}`))]; // each kind once
656
- await preview(s.parts, { title, meta: `${size} mm · ${versions}${faint.length ? ` · faint: ${faint.join(', ')}` : ''}`, out, explode: !!opt('explode') });
681
+ await preview([...s.parts, ...wireTubesOf(s)], { title, meta: `${size} mm · ${versions}${faint.length ? ` · faint: ${faint.join(', ')}` : ''}`, out, explode: !!opt('explode') });
657
682
  return console.log(out);
658
683
  }
659
684
  if (cmd === 'export') {
@@ -669,7 +694,8 @@ async function assembly(cmd, ref) {
669
694
  return console.log(out);
670
695
  }
671
696
  const link = async () => {
672
- const model = await assemblyModel(s, { title, versions, filaments: filaments(s.project), noRules: !!opt('no-rules') });
697
+ const model = await assemblyModel(s, { title, versions, filaments: filaments(s.project), noRules: !!opt('no-rules'), steps: opt('no-steps') ? false : opt('steps') });
698
+ if (model.steps) say(`carries the drawing ${model.steps.name ?? '(unnamed)'} (${model.steps.b.length} blocks; --no-steps to leave it out)`);
673
699
  const url = await linkTo(model);
674
700
  return { view: url, stl: `${url}&get=stl`, '3mf': `${url}&get=3mf`, src: model.src, size: url.length, title, version: '' };
675
701
  };
@@ -894,10 +920,96 @@ async function status(project) {
894
920
  }
895
921
  }
896
922
 
923
+ async function machineCommand(what, ref) {
924
+ if (!isAssembly(ref)) throw new Error(`cad ${what} works on an assembly (<project>/<assembly>), and there is no "${ref}"`);
925
+ const m = await import('../lib/machine.mjs'), s = await buildAssembly(ref);
926
+ if (what === 'machine') { const out = m.machineOf(s), file = m.writeMachine(s, out); (await import('../lib/buildpage.mjs')).writeWiring(s); return console.log(opt('json') ? JSON.stringify(out, null, 2) : file); }
927
+ const source = positional()[2], tol = opt('tol') != null ? Number(opt('tol')) : undefined;
928
+ if (!source && !opt('calibrate')) throw new Error('usage: cad plot <project>/<assembly> <drawing.svg> [--calibrate]');
929
+ const { sheetFrame } = await import('@rulecad/robots'), f = s.task?.sheet ? sheetFrame(s.task.sheet) : null;
930
+ const svg = opt('calibrate') ? m.CALIBRATION(f?.width ?? 148, f?.height ?? 210) : fs.readFileSync(source, 'utf8'), base = `${s.name}-${opt('calibrate') ? 'calibration' : path.basename(source, path.extname(source))}`;
931
+ const r = m.plot(s, svg, { tolerance: tol, name: base });
932
+ const failed = !r.ok;
933
+ if (opt('json')) { console.log(JSON.stringify({ ok: r.ok, findings: r.findings, ...(r.time ? { time: r.time } : {}), ...(r.ok ? { file: m.writePlot(s, r, base).file } : {}) }, null, 2)); process.exitCode = failed ? 1 : 0; return; }
934
+ report(r.findings, { assembly: ref, title: `${ref}: ${base}` });
935
+ if (r.ok) { const w = m.writePlot(s, r, base); console.log(path.relative(WS, w.file)); console.log(path.relative(WS, w.preview)); }
936
+ process.exitCode = failed ? 1 : 0;
937
+ }
938
+
939
+ async function platesCommand(what, ref) {
940
+ if (!isAssembly(ref)) throw new Error(`cad ${what} works on an assembly (<project>/<assembly>), and there is no "${ref}"`);
941
+ const s = await buildAssembly(ref);
942
+ if (what === 'order') {
943
+ const { orderOf, orderText, stepPictures } = await import('../lib/order.mjs'), r = orderOf(s);
944
+ if (opt('json')) return console.log(JSON.stringify(r, null, 2));
945
+ console.log(orderText(ref, r));
946
+ if (r.stuck) { process.exitCode = 1; return; }
947
+ if (opt('preview')) { const pics = stepPictures(s, r); for (const [i, parts] of pics.entries()) { const st = r.steps[i], out = paths.preview(s.project, `${s.name}-step-${String(st.n).padStart(2, '0')}.png`); await preview(parts, { title: `${s.a.title || s.name}: step ${st.n} of ${r.steps.length}`, meta: st.text, out }); console.log(path.relative(WS, out)); } }
948
+ return;
949
+ }
950
+ const { platesOf, checkPlate } = await import('../lib/plates.mjs'), gap = opt('gap') != null ? Number(opt('gap')) : undefined;
951
+ if (gap != null && !(gap > 0)) throw new Error(`--gap is a distance in mm, above 0 (got ${opt('gap')})`);
952
+ const r = await platesOf(s, { write: true, gap }), results = [];
953
+ for (const p of r.plates.filter((x) => !x.stood)) results.push({ name: p.name, findings: await checkPlate(`${s.project}/${p.name}`) });
954
+ const fails = [...r.findings, ...results.flatMap((x) => x.findings)].some((x) => x.level === 'fail');
955
+ if (opt('json')) { console.log(JSON.stringify({ assembly: ref, bed: r.bed, gap: r.gap, plates: r.plates, repacked: r.touched, removed: r.removed, findings: r.findings, checks: results }, null, 2)); process.exitCode = fails ? 1 : 0; return; }
956
+ report(r.findings);
957
+ say(`${ref}: ${r.plates.length} plate${r.plates.length === 1 ? '' : 's'}, parts ${r.gap} mm apart (the first layer's rule)`);
958
+ for (const p of r.plates) say(` ${p.name}${p.stood ? ' (unchanged)' : ''}: ${p.filament}, ${p.parts.length} part${p.parts.length === 1 ? '' : 's'}, ${p.grams} g, about ${p.minutes} min: ${p.parts.map((x) => x.id).join(', ')}`);
959
+ if (r.removed.length) say(` removed ${r.removed.join(', ')} (nothing is on them now)`);
960
+ for (const x of results) { const bad = x.findings.filter((y) => (y.level === 'fail' || y.level === 'warn') && y.code !== 'rules.estimate'); say(` ${x.name}: ${bad.length ? `${bad.length} to look at` : 'prints clean'}`); for (const y of bad) say(` [${y.level}] ${y.text}`); }
961
+ process.exitCode = fails ? 1 : 0;
962
+ }
963
+
964
+ async function listCommand(what, ref) {
965
+ if (!isAssembly(ref)) throw new Error(`cad ${what} works on an assembly (<project>/<assembly>), and there is no "${ref}"`);
966
+ const s = await buildAssembly(ref);
967
+ if (what === 'list') {
968
+ const { shoppingList, listText } = await import('../lib/list.mjs'), l = shoppingList(s);
969
+ return console.log(opt('json') ? JSON.stringify(l, null, 2) : listText(ref, l));
970
+ }
971
+ const { wiresFor } = await import('../lib/assembly.mjs'), { wiringSheet } = await import('../lib/wires.mjs'), rows = wiresFor(s);
972
+ if (opt('json')) return console.log(JSON.stringify(rows.map(({ route, ...r }) => r), null, 2));
973
+ if (!rows.length) return console.log(`${ref} has no "wires"`);
974
+ if (opt('out')) { fs.writeFileSync(path.resolve(opt('out')), wiringSheet(rows) + '\n'); return console.log(`wrote ${opt('out')}`); }
975
+ const { writeWiring } = await import('../lib/buildpage.mjs'), file = writeWiring(s);
976
+ console.log(wiringSheet(rows)); say(path.relative(WS, file));
977
+ }
978
+
979
+ async function measuredCommand(ref) {
980
+ const { recordMeasured, assumptionsTable, writeTable, ledgerLines } = await import('../lib/measured.mjs');
981
+ if (opt('table')) {
982
+ const table = await assumptionsTable(ref);
983
+ if (opt('out')) { writeTable(path.resolve(opt('out')), table); return console.log(`wrote the table to ${opt('out')}`); }
984
+ return console.log(table);
985
+ }
986
+ const values = Object.fromEntries(positional().slice(2).map((x) => { const i = x.indexOf('='); if (i < 1) throw new Error(`usage: cad measured <project>/<assembly> <name>=<value> … (got "${x}")`); return [x.slice(0, i), Number(x.slice(i + 1))]; }));
987
+ const r = await recordMeasured(ref, values, { unit: opt('unit'), source: opt('source'), rule: opt('rule') });
988
+ if (opt('json')) return console.log(JSON.stringify({ entries: r.entries, moved: r.moved }, null, 2));
989
+ for (const l of ledgerLines(r.entries)) say(l);
990
+ for (const m of r.moved) say(m.figure ? ` ${m.figure}: ${Number(m.from.toFixed(4))} ${m.unit} to ${Number(m.to.toFixed(4))} ${m.unit}` : ` ${m.code}: ${m.text}`);
991
+ if (!r.moved.length) say(' nothing the checks say has moved');
992
+ }
993
+
994
+ async function ledger(project, name) {
995
+ const { readLedger, ledgerLines } = await import('../lib/measured.mjs');
996
+ const rows = readLedger(project).filter((e) => !name || e.assembly === name);
997
+ return { rows, lines: ledgerLines(rows) };
998
+ }
999
+
897
1000
  async function history(ref) {
898
1001
  const [project, name] = ref.split('/');
1002
+ if (name && isAssembly(ref)) {
1003
+ const { rows, lines } = await ledger(project, name);
1004
+ if (opt('json')) return console.log(JSON.stringify({ assembly: ref, ledger: rows }, null, 2));
1005
+ if (!lines.length) return say(`${ref}: nothing measured yet (cad measured ${ref} <name>=<value>)`);
1006
+ say('predicted against measured:'); for (const l of lines) say(` ${l}`);
1007
+ return;
1008
+ }
899
1009
  if (!name) {
900
- if (opt('json')) return console.log(JSON.stringify({ project, releases: tags(project).reverse() }, null, 2));
1010
+ const { rows, lines } = await ledger(project);
1011
+ if (lines.length && !opt('json')) { console.log('predicted against measured:'); for (const l of lines) console.log(` ${l}`); }
1012
+ if (opt('json')) return console.log(JSON.stringify({ project, releases: tags(project).reverse(), ledger: rows }, null, 2));
901
1013
  for (const t of tags(project).reverse()) console.log(`${t.tag} ${t.date} ${t.kind} ${t.message}`);
902
1014
  return status(project);
903
1015
  }
package/lib/animate.mjs CHANGED
@@ -1,6 +1,8 @@
1
1
  // A lamina mechanism's sequence as one animated SVG: the frame drawn once, and each moving part (bodies, and the
2
2
  // flexures drawn bent) frame by frame, holding a moment at each state. Self-contained: it plays in any browser, with
3
3
  // nothing to install. Frames come from @rulecad/flexures lamina() (followers pushed aside where their drivers meet them).
4
+ import { fk } from '@rulecad/robots';
5
+
4
6
  const COLOURS = { ground: '#c9ccd1', body: '#2f6fb3', flexure: '#e07a1f' };
5
7
  const HOLD = 8; // a state is shown this many frames' time
6
8
  const STEP = 0.06; // seconds a frame
@@ -69,3 +71,42 @@ ${key}
69
71
  </svg>
70
72
  `;
71
73
  }
74
+
75
+ // A gait as one animated SVG: the side view (x, z) with each leg's hip, knee and foot drawn as sticks and the ground, and
76
+ // under it the plan (x, y) with the feet in contact and the support they make. Self-contained, as the lamina sequence is.
77
+ export function gaitData(s, r) {
78
+ return { title: s.a.title || s.name, pattern: s.a.gait.pattern, period: s.gait.period, height: s.gait.height, legs: s.gait.legs.map((l) => l.name), frames: r.frames.map((f) => ({ t: f.t, margin: Number.isFinite(f.margin) ? Number(f.margin.toFixed(3)) : null, feet: f.feet.map((e) => ({ leg: e.leg, stance: e.stance, foot: e.foot, q: e.q, load: e.load })) })) };
79
+ }
80
+
81
+ export function gaitSvg(s, r, { title = '' } = {}) {
82
+ const gait = s.gait, joints = (l, q) => { const c = fk(l.chain, q); return [c.frames[0].at, c.frames[1].at, c.position]; };
83
+ const frames = r.frames.map((f) => ({ ...f, sticks: f.feet.map((e) => { const l = gait.legs.find((x) => x.name === e.leg); return { ...e, pts: joints(l, e.q) }; }) }));
84
+ const xs = frames.flatMap((f) => f.sticks.flatMap((e) => e.pts.map((p) => p[0]))), zs = frames.flatMap((f) => f.sticks.flatMap((e) => e.pts.map((p) => p[2])));
85
+ const ys = frames.flatMap((f) => f.sticks.map((e) => e.foot[1]));
86
+ const [x0, x1] = [Math.min(...xs) - 40, Math.max(...xs) + 40], [z0, z1] = [Math.min(...zs, -gait.height) - 40, Math.max(...zs, 0) + 40], [y0, y1] = [Math.min(...ys) - 40, Math.max(...ys) + 40];
87
+ const side = { w: x1 - x0, h: z1 - z0 }, plan = { w: x1 - x0, h: y1 - y0 }, pad = Math.max(side.w, side.h) * 0.04, cap = pad * 1.6;
88
+ const W = side.w + 2 * pad, H = side.h + plan.h + 3 * pad + cap, fx = (x) => fmt(x - x0 + pad), fz = (z) => fmt(z1 - z + pad + cap), fy = (y) => fmt(y - y0 + side.h + 2 * pad + cap);
89
+ const hold = 1 / frames.length, dur = `${fmt(gait.period)}s`;
90
+ const stroke = Math.max(side.w, side.h) * 0.012;
91
+ const body = frames.map((f, i) => {
92
+ const a = fmt(i * hold), b = fmt((i + 1) * hold), keys = [...new Set([0, a, b, 1])].sort((p, q) => p - q), vals = keys.map((k) => (k >= a && k < b ? 'inline' : 'none'));
93
+ const sticks = f.sticks.map((e) => `<polyline points="${e.pts.map((p) => `${fx(p[0])},${fz(p[2])}`).join(' ')}" fill="none" stroke="${e.stance ? '#2f6fb3' : '#e07a1f'}" stroke-width="${fmt(stroke)}" stroke-linecap="round" stroke-linejoin="round"/><circle cx="${fx(e.pts[2][0])}" cy="${fz(e.pts[2][2])}" r="${fmt(stroke * 1.1)}" fill="${e.stance ? '#2f6fb3' : '#e07a1f'}"/>`).join('');
94
+ const down = f.sticks.filter((e) => e.stance).map((e) => e.foot), pts = hull2D(down.map((p) => [p[0], p[1]]));
95
+ const support = pts.length > 1 ? `<polygon points="${pts.map(([x, y]) => `${fx(x)},${fy(y)}`).join(' ')}" fill="#2f6fb333" stroke="#2f6fb3" stroke-width="${fmt(stroke / 2)}"/>` : '';
96
+ const feet = f.sticks.map((e) => `<circle cx="${fx(e.foot[0])}" cy="${fy(e.foot[1])}" r="${fmt(stroke)}" fill="${e.stance ? '#2f6fb3' : '#e07a1f'}"/>`).join('');
97
+ const text = `${fmt(f.time)} s of ${fmt(gait.period)} s${Number.isFinite(f.margin) ? `, ${fmt(f.margin)} mm of balance to spare` : ''}`;
98
+ return `<g display="${i ? 'none' : 'inline'}"><animate attributeName="display" values="${vals.join(';')}" keyTimes="${keys.join(';')}" dur="${dur}" calcMode="discrete" repeatCount="indefinite"/>${sticks}${support}${feet}<text x="${fmt(pad)}" y="${fmt(cap * 0.6)}" font-family="system-ui, sans-serif" font-size="${fmt(pad * 0.7)}" fill="#333">${escape(text)}</text></g>`;
99
+ }).join('\n');
100
+ const ground = `<line x1="${fmt(pad)}" y1="${fz(-gait.height)}" x2="${fmt(W - pad)}" y2="${fz(-gait.height)}" stroke="#555" stroke-width="${fmt(stroke / 2)}"/>`;
101
+ const tag = `<text x="${fmt(pad)}" y="${fmt(side.h + pad + cap * 1.3)}" font-family="system-ui, sans-serif" font-size="${fmt(pad * 0.7)}" fill="#555">Plan: feet in blue are down, orange in swing; quasi-static, so no momentum is counted</text>`;
102
+ return `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 ${fmt(W)} ${fmt(H)}" width="900">\n<title>${escape(title)}</title>\n<rect width="${fmt(W)}" height="${fmt(H)}" fill="#fff"/>\n${ground}\n${tag}\n${body}\n</svg>\n`;
103
+ }
104
+
105
+ const hull2D = (points) => {
106
+ const p = [...points].sort((a, b) => a[0] - b[0] || a[1] - b[1]);
107
+ if (p.length < 3) return p;
108
+ const cross = (o, a, b) => (a[0] - o[0]) * (b[1] - o[1]) - (a[1] - o[1]) * (b[0] - o[0]), lo = [], hi = [];
109
+ for (const x of p) { while (lo.length >= 2 && cross(lo.at(-2), lo.at(-1), x) <= 0) lo.pop(); lo.push(x); }
110
+ for (const x of [...p].reverse()) { while (hi.length >= 2 && cross(hi.at(-2), hi.at(-1), x) <= 0) hi.pop(); hi.push(x); }
111
+ return [...lo.slice(0, -1), ...hi.slice(0, -1)];
112
+ };
package/lib/assembly.mjs CHANGED
@@ -32,7 +32,18 @@ import { keys as keyCentres, readLayout, hasLayout } from './layout.mjs';
32
32
  import { DOFS, frame, turn, mul, pathLength, jointValues, placeItems, jointMatrix } from '@rulecad/model-link';
33
33
  import { gearModel, internalModel, rackModel, mesh as meshOf, phase, rackPhase, contact, wormModel, wormMesh, bevelModel, bevelMesh, compoundEfficiency } from '@rulecad/gears';
34
34
  import { ops as booleans } from '@rulecad/shapes';
35
- import { motorBuilt, motorDrives, shaftFits, loadsOf, motorChecks, shaftFit } from './motors.mjs';
35
+ import { motorBuilt, motorDrives, shaftFits, loadsOf, motorChecks, shaftFit, axisOf } from './motors.mjs';
36
+ import { runningChecks, seatFit } from './seats.mjs';
37
+ import { seatSize } from '@rulecad/shapes';
38
+ import { wiresOf, wireChecks, wireRows, wireTubes, wireRoutes } from './wires.mjs';
39
+ import { printedParts } from './list.mjs';
40
+ import { taskOf, taskChecks } from './task.mjs';
41
+ import { powerChecks } from './power.mjs';
42
+ import { loadChecks } from './loads.mjs';
43
+ import { gripChecks } from './grip.mjs';
44
+ import { gaitOf, gaitChecks, gaitSequence } from './gait.mjs';
45
+ import { boughtBuilt, boughtFindings, boughtSets } from './bought.mjs';
46
+ import { orderChecks } from './order.mjs';
36
47
 
37
48
  export const assemblyPath = (ref) => { const [project, name] = String(ref).split('/'); return path.join(paths.project(project || ''), 'assemblies', `${name || ''}.json`); };
38
49
  export const isAssembly = (ref) => String(ref).includes('/') && host.exists(assemblyPath(ref.split('@')[0]));
@@ -96,6 +107,11 @@ export async function buildAssembly(ref, stack = [], overrides = {}, opts = {})
96
107
  const built = new Map(); // each object or component is built once per set of values, however many copies are placed
97
108
  const source = async (it, extra) => {
98
109
  if (it.motor) { const key = JSON.stringify(['motor', it.id, it.motor]); if (!built.has(key)) built.set(key, motorBuilt(it.motor, num, it.id)); return built.get(key); }
110
+ if (it.bought) {
111
+ const key = JSON.stringify(['bought', it.id, it.bought, it.variant, it.set]);
112
+ if (!built.has(key)) built.set(key, boughtSets().get(it.bought) === 'motor' ? motorBuilt({ model: it.bought }, num, it.id) : boughtBuilt(it.bought, it, num, it.id));
113
+ return built.get(key);
114
+ }
99
115
  // from: inputs worked out from items built before this one ({ "usb_y": "board.pcb.pico_y" }): numbers, in this
100
116
  // assembly's names, so a part can take a value only another part knows once it's built
101
117
  const from = Object.fromEntries(Object.entries(it.from || {}).map(([k, x]) => [k, num(x)]));
@@ -123,7 +139,7 @@ export async function buildAssembly(ref, stack = [], overrides = {}, opts = {})
123
139
  const [ref, named] = String(it.object).split(':'), [objName, pin] = ref.split('@'), variant = named || it.variant;
124
140
  const d = locate(`${project}/${objName}`), at = { ...(pin ? materialise(d, pin) : d), ...(variant ? { variant } : {}) };
125
141
  const b = await build(at, set, opts);
126
- built.set(key, { key, objName, b, version: pin || b.object.version, variant, role: ['reference', 'board'].includes(b.object.role) ? 'reference' : 'part' }); // a board is made by a fab: checked, never printed
142
+ built.set(key, { key, objName, b, version: pin || b.object.version, variant, role: ['reference', 'board'].includes(b.object.role) ? 'reference' : 'part', set: base }); // a board is made by a fab: checked, never printed. set: what it's made with, as printed (not bent by a pose)
127
143
  }
128
144
  }
129
145
  return built.get(key);
@@ -132,7 +148,7 @@ export async function buildAssembly(ref, stack = [], overrides = {}, opts = {})
132
148
  let builtCount = 0;
133
149
  for (const it of a.items || []) {
134
150
  if (!/^[a-z][\w-]*$/.test(it.id || '')) throw new Error(`each item needs an id (letters, digits, - or _): got ${JSON.stringify(it.id)}`);
135
- if ([it.object, it.assembly, it.motor].filter(Boolean).length !== 1) throw new Error(`item ${it.id}: give one of "object", "assembly" or "motor"`);
151
+ if ([it.object, it.assembly, it.motor, it.bought].filter(Boolean).length !== 1) throw new Error(`item ${it.id}: give one of "object", "assembly", "motor" or "bought"`);
136
152
  // Copies: one, a grid from repeat x/y, or a layout's keys. Each: { id, offset (from at), extra (values to set) }
137
153
  const rx = it.repeat?.x, ry = it.repeat?.y, rl = it.repeat?.layout, copies = [];
138
154
  if (rl) {
@@ -185,7 +201,7 @@ export async function buildAssembly(ref, stack = [], overrides = {}, opts = {})
185
201
  }
186
202
  for (const c of copies) { placed.push([it, c]); ids.push(c.id); }
187
203
  }
188
- const motion = motionOf(a, placed, num, ref);
204
+ const motion = motionOf(a, placed, num, ref), wires = wiresOf(a, placed, motion.joints), task = taskOf(a, motion, num), gait = gaitOf(a, motion, num);
189
205
  fits.push(...shaftFits(motion.drives, motion.joints, placed.map(([, c]) => c.id)).map((x) => ({ ...x, num })));
190
206
  for (const [it, c] of placed) {
191
207
  const src = c.src, id = c.id;
@@ -197,7 +213,7 @@ export async function buildAssembly(ref, stack = [], overrides = {}, opts = {})
197
213
  for (const n of sub.seen) seen.add(n);
198
214
  items.push({ ...it, id, sub, role: 'part' });
199
215
  } else {
200
- objects.push({ id, objName: src.objName, version: src.version, built: src.b, role: src.role });
216
+ objects.push({ id, objName: src.objName, version: src.version, built: src.b, role: src.role, ...(src.set ? { set: src.set } : {}), ...(src.variant ? { variant: src.variant } : {}), ...(src.bought ? { bought: src.bought } : {}), ...(src.motor ? { motor: src.motor } : {}) });
201
217
  items.push({ ...it, id, objName: src.objName, built: src.b, version: src.version, role: src.role });
202
218
  }
203
219
  }
@@ -234,6 +250,7 @@ export async function buildAssembly(ref, stack = [], overrides = {}, opts = {})
234
250
  // A fit with * applies to every copy: "key-*.switch.bottom" becomes one fit for key-0-0, key-0-1, …
235
251
  // With * on both sides, each copy is checked against all the others: { "a": "key-*.cap", "b": "key-*.cap" }
236
252
  for (let x of a.fits || []) {
253
+ if (x.seat != null && x.min == null) x = { ...x, min: -1000 }; // a seat presses, so the pair may overlap
237
254
  if (x.holes) x = { ...x, a: x.holes, b: x.into }; // a holes fit: a board's holes (a) over what its screws go into (b)
238
255
  const star = [x.a, x.b].find((n) => n.includes('*'));
239
256
  if (!star) { fits.push({ ...x, num }); continue; }
@@ -256,7 +273,7 @@ export async function buildAssembly(ref, stack = [], overrides = {}, opts = {})
256
273
  const v = jointValues(motion, p), moved = partsAt(placeItems(motion, v));
257
274
  return { ...s, parts: moved, pose: typeof p === 'string' ? p : null, jointValues: v, polygons: moved.flatMap((x) => x.polygons), triangles: moved.flatMap((x) => x.triangles) };
258
275
  };
259
- const s = { a, project, name, items, parts, objects, fits, requires, values, num, seen, motion, pose: typeof pose === 'string' ? pose : null, jointValues: jv, at,
276
+ const s = { a, project, name, items, parts, objects, fits, requires, values, num, seen, motion, wires, task, gait, pose: typeof pose === 'string' ? pose : null, jointValues: jv, at,
260
277
  polygons: parts.flatMap((p) => p.polygons), triangles: parts.flatMap((p) => p.triangles) };
261
278
  return s;
262
279
  }
@@ -418,6 +435,7 @@ function planetaries(list, joints, items, num) {
418
435
  // Every part where it is with these joints at 0
419
436
  const v = jointValues({ joints, poses: {} }, {});
420
437
  for (const j of [lead, follower, ...planetJoints]) v[j.id] = [0];
438
+ if (g.output) { const j2 = moving(index(g.output.ring, 'output ring')); if (j2) v[j2.id] = [0]; } // (a range that leaves out 0 would put the ring where the phase isn't reckoned)
421
439
  const worlds = placeItems({ items, joints }, v), W = (k) => worlds[k];
422
440
  const O = org(W(idx.sun)), Z = col(W(idx.sun), 2), X0 = col(W(idx.sun), 0);
423
441
  const sign = (j) => Math.sign(dot(mul(j.parent < 0 ? [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0] : worlds[j.parent], j.a).filter((_, i) => [2, 6, 10].includes(i)), Z));
@@ -434,7 +452,7 @@ function planetaries(list, joints, items, num) {
434
452
  const rot = (d) => { const r = { [held[0]]: 0, [drive]: sg[drive] * d }; r[third] = (sigma0 - coef[drive] * r[drive]) / coef[third]; return r; };
435
453
  // a straight line in the driver's value (f: degrees in, radians out): [ratio, offset in degrees]
436
454
  const lin = (f) => { const a = f(0), b = f(1), o = a / DEG; return [(b - a) / DEG, ((o + 180) % 360 + 360) % 360 - 180]; }; // (the offset a part-turn: a whole turn is the same place)
437
- const free = (j) => { j.dofs[0] = [-1e6, 1e6, j.dofs[0][2]]; }; // what follows a sun can turn past a turn
455
+ const free = (j) => { j.limits = j.dofs[0].slice(0, 2); j.dofs[0] = [-1e6, 1e6, j.dofs[0][2]]; }; // what follows a sun can turn past a turn
438
456
  const [k3, o3] = lin((d) => sg[third] * rot(d * DEG)[third]);
439
457
  follower.follow = [lead.id, k3, o3]; free(follower);
440
458
  const findings = [], f = (level, text, code, between) => findings.push({ level, text, code, ...(between ? { between } : {}) });
@@ -633,6 +651,9 @@ export function anchorsAt(s, values = s.jointValues) {
633
651
 
634
652
  // keyCentres(layout): each key's centre, from lib/layout.mjs (kept under this name for older callers)
635
653
  export { keyCentres };
654
+ export const wiresFor = (s) => wireRows(s, { placeItems, jointValues, mul });
655
+ export const wireTubesOf = (s) => wireTubes(s, { placeItems, mul });
656
+ export const wireRoutesOf = (s) => wireRoutes(s, { placeItems, mul });
636
657
 
637
658
  // ---------- checks ----------
638
659
  export { closest };
@@ -678,6 +699,14 @@ function saveOverlaps() {
678
699
  // What a project prints in, for the motors' heat and press-fit checks
679
700
  const materialOf = (project) => { try { return readJson(path.join(paths.project(project), 'project.json')).material; } catch { return null; } };
680
701
 
702
+ // What's printed and how much it weighs, so "design small" is seen on every change
703
+ function massFinding(s, f) {
704
+ if (!s.parts.some((p) => p.role === 'reference') && !s.motion?.joints.length) return; // a machine, not a keyboard plate
705
+ const parts = printedParts(s); if (!parts.length) return;
706
+ const sorted = [...parts].sort((a, b) => b.grams - a.grams), total = sorted.reduce((t, p) => t + p.grams, 0);
707
+ f('info', `${Number(total.toFixed(1))} g printed in ${sorted.length} parts; heaviest ${sorted.slice(0, 3).map((p) => `${p.id} ${p.grams} g`).join(', ')}`, null, { code: 'mass.parts', values: { grams: total, parts: Object.fromEntries(sorted.map((p) => [p.id, p.grams])) } });
708
+ }
709
+
681
710
  export function checkAssembly(s) {
682
711
  const out = [], f = (level, text, card, extra) => out.push({ level, text, ...(card && { card }), ...extra }), mm = (n) => `${Number(n.toFixed(3))}`;
683
712
  // Versions: every pin, from this assembly and its components, against every copy of that object
@@ -724,6 +753,7 @@ export function checkAssembly(s) {
724
753
  if (x.holes) { holesFit(x); continue; }
725
754
  if (x.silent) continue; // lets a pair overlap, and has nothing to report
726
755
  if (x.engage != null) { engageFit(x); continue; }
756
+ if (x.seat != null) { seatFit(x, s, f, { placeItems, jointValues, mul, seatSize }); continue; }
727
757
  if (x.shaft != null) { shaftFit(x, s, f, { placeItems, jointValues, mul, materialName: materialOf(s.project) }); continue; }
728
758
  const A = pickIn(x.a, x), key = x.note || `${x.a} / ${x.b}`;
729
759
  const lo = x.min != null ? x.num(x.min) : -Infinity, hi = x.max != null ? x.num(x.max) : Infinity;
@@ -834,7 +864,17 @@ export function checkAssembly(s) {
834
864
  }
835
865
  }
836
866
  }
867
+ boughtFindings(s, f);
868
+ massFinding(s, f);
869
+ runningChecks(s, f, { axisOf, placeItems, jointValues, mul });
870
+ if (s.wires?.length) wireChecks(s, f, { placeItems, jointValues, mul });
837
871
  motorChecks(s, f, { placeItems, jointValues, mul }, materialOf(s.project));
872
+ powerChecks(s, f);
873
+ loadChecks(s, f, { placeItems, jointValues, mul });
874
+ gripChecks(s, f);
875
+ gaitChecks(s, f, { jointValues, placeItems, sweepOne: (v) => clashesOf(s.at(v), named) });
876
+ taskChecks(s, f);
877
+ orderChecks(s, f);
838
878
  // Plates print everything: no references
839
879
  if (s.a.kind === 'plate') {
840
880
  const refs = s.objects.filter((o) => o.role === 'reference' && !o.unplaced); // an unplaced item only lends its numbers
@@ -844,7 +884,7 @@ export function checkAssembly(s) {
844
884
  const est = new Set();
845
885
  for (const o of s.objects) for (const e of o.built.entries) if (e.kind === 'estimate' && (e.used || !e.name.includes('.'))) est.add(e.name);
846
886
  for (const n of s.seen) { const [u, k] = n.split('.'); if (loadRuleSet(u).rules[k]?.kind === 'estimate') est.add(n); }
847
- if (est.size) f('warn', `uses estimates, not measurements: ${[...est].join(', ')}. Measure them and record kind: measured`, `Estimate: ${[...est].join(', ')}`, { code: 'rules.estimate', refs: { rules: [...est] } });
887
+ if (est.size) f('warn', `uses estimates, not measurements: ${[...est].join(', ')}. Measure each and settle it with cad measured ${s.project}/${s.name} <name>=<value>`, `Estimate: ${[...est].join(', ')}`, { code: 'rules.estimate', refs: { rules: [...est] } });
848
888
  saveOverlaps();
849
889
  return out;
850
890
  }
@@ -932,6 +972,7 @@ export function motionData(s) {
932
972
  poses: mo.poses, ...(s.pose ? { pose: s.pose } : {}),
933
973
  part: s.parts.map((p) => names.indexOf(p.item)),
934
974
  ...(allow.length ? { allow } : {}),
975
+ ...(s.gait ? { sequence: gaitSequence(s) ?? undefined } : {}),
935
976
  } };
936
977
  }
937
978
 
package/lib/bought.mjs ADDED
@@ -0,0 +1,105 @@
1
+ // Bought parts in assemblies: a bearing, a switch, a driver, a board or a supply named by its rule set, drawn from the
2
+ // set's figures as a faint reference (never on a plate), with anchors from what it is. A motor is the same thing with a
3
+ // shaft that turns a joint, so its item is built here too (lib/motors.mjs).
4
+ import crypto from 'node:crypto';
5
+ import fs from 'node:fs';
6
+ import jscad from '@jscad/modeling';
7
+ import { peekRuleSet as loadRuleSet } from './rules.mjs';
8
+ import { RULE_DIRS } from './workspace.mjs';
9
+ import { named } from './parts.mjs';
10
+
11
+ const { cuboid, cylinder, polygon } = jscad.primitives, { translate } = jscad.transforms, { union, subtract } = jscad.booleans, { extrudeRotate } = jscad.extrusions;
12
+ const SEG = 48;
13
+
14
+ // Rule sets that are bought parts, for saying what there is
15
+ export function boughtSets() {
16
+ const out = new Map();
17
+ for (const d of RULE_DIRS) if (fs.existsSync(d)) for (const f of fs.readdirSync(d)) {
18
+ if (!f.endsWith('.json') || f === 'vocabulary.json' || f === 'package.json') continue;
19
+ try { const set = JSON.parse(fs.readFileSync(`${d}/${f}`, 'utf8')); if (set.part && !out.has(set.name)) out.set(set.name, set.part); } catch {}
20
+ }
21
+ return out;
22
+ }
23
+
24
+ // A reference item the assembly can place, from its parts, anchors and figures: what a motor and any bought part share
25
+ export function referenceBuilt({ id, key, objName, name, parts, anchors, entries, values, extra = {} }) {
26
+ const b = { object: { name, title: name, role: 'reference', version: '0.0.0', anchors }, values, entries, deps: [], units: {}, parts, polygons: parts.flatMap((p) => p.polygons), triangles: parts.flatMap((p) => p.triangles), hash: crypto.createHash('sha256').update(JSON.stringify([values, entries.map((e) => e.name)])).digest('hex').slice(0, 16) };
27
+ return { key: `${key}:${id}:${b.hash}`, objName, b, version: '0.0.0', role: 'reference', ...extra };
28
+ }
29
+
30
+ const z = (at, axis = [0, 0, 1]) => ({ at, axis });
31
+ const box = (w, d, h, x = 0, y = 0, z0 = 0) => translate([x, y, z0 + h / 2], cuboid({ size: [w, d, h] }));
32
+
33
+ // What each kind of part looks like, from its figures. Each returns { parts: { name: solid }, anchors }
34
+ const SHAPES = {
35
+ bearing(v, set) {
36
+ const r = v.bore / 2, R = v.outer_diameter / 2, w = v.width, c = Math.min(v.chamfer ?? 0.2, (R - r) / 4, w / 4);
37
+ const flange = v.flange_diameter ? v.flange_diameter / 2 : 0, f = v.flange_width ?? 0;
38
+ const pts = flange
39
+ ? [[r + c, 0], [R - c, 0], [R, c], [R, w - f], [flange, w - f], [flange, w], [r + c, w], [r, w - c], [r, c]]
40
+ : [[r + c, 0], [R - c, 0], [R, c], [R, w - c], [R - c, w], [r + c, w], [r, w - c], [r, c]];
41
+ return { parts: { body: extrudeRotate({ segments: SEG }, polygon({ points: pts })) }, anchors: { bore: z([0, 0, w / 2]), outer: z([0, 0, w / 2]), face: z([0, 0, 0]), top: z([0, 0, w]) } };
42
+ },
43
+ switch(v) {
44
+ const w = v.body_width, d = v.body_depth, h = v.body_length, holes = (v.mount_hole_spacing ?? 0) / 2, up = h / 2;
45
+ const pin = (x) => translate([x, 0, up], jscad.transforms.rotateX(Math.PI / 2, cylinder({ radius: (v.mount_hole_diameter ?? 2.4) / 2, height: d + 2, segments: 24 })));
46
+ const body = holes ? subtract(box(w, d, h), pin(-holes), pin(holes)) : box(w, d, h);
47
+ return { parts: { body, lever: box(w, Math.min(4, d), 0.4, w * 0.1, 0, h + 2) }, anchors: { lever: z([w * 0.6, 0, h + 2]), left: z([-holes, 0, up], [0, 1, 0]), right: z([holes, 0, up], [0, 1, 0]), base: z([0, 0, 0]) } };
48
+ },
49
+ board(v, set) {
50
+ const w = v.body_width, d = v.body_depth, t = 1.6;
51
+ const axes = [...new Set(Object.keys(set.rules).map((k) => /^step_pin_(\w+)$/.exec(k)?.[1]).filter(Boolean))].map((a) => a.toUpperCase());
52
+ // Where a board's axis connectors are along its edge is for routing a wire, no closer than that
53
+ const sockets = Object.fromEntries(axes.map((a, i) => [a, z([-w / 2 + ((i + 0.5) * w) / axes.length, d / 2, t], [0, 1, 0])]));
54
+ return { parts: { body: box(w, d, t) }, anchors: { centre: z([0, 0, t / 2]), top: z([0, 0, t]), bottom: z([0, 0, 0]), ...sockets } };
55
+ },
56
+ driver(v) {
57
+ const w = v.body_width, d = v.body_depth, t = 1.6, row = v.row_spacing / 2, pins = v.pin_count / 2, pitch = v.pin_pitch, run = pitch * (pins - 1), pin = 0.64, drop = 8;
58
+ const rows = [-row, row].flatMap((y) => Array.from({ length: pins }, (_, i) => box(pin, pin, drop + t, -run / 2 + i * pitch, y, -drop)));
59
+ return { parts: { body: union(box(w, d, t), box(5, 5, 1, 0, 0, t)), pins: union(rows) }, anchors: { header: z([0, 0, 0]), top: z([0, 0, t]) } };
60
+ },
61
+ encoder(v, set) { return SHAPES.board(v, set); },
62
+ linear_bearing(v) { // bore along z, from z = 0
63
+ const r = v.bore / 2, R = v.outer_diameter / 2, L = v.length, c = 0.3;
64
+ return { parts: { body: extrudeRotate({ segments: SEG }, polygon({ points: [[r + c, 0], [R - c, 0], [R, c], [R, L - c], [R - c, L], [r + c, L], [r, L - c], [r, c]] })) }, anchors: { bore: z([0, 0, L / 2]), face: z([0, 0, 0]), top: z([0, 0, L]) } };
65
+ },
66
+ rod(v) { return { parts: { body: translate([0, 0, v.length / 2], cylinder({ radius: v.diameter / 2, height: v.length, segments: SEG })) }, anchors: { bottom: z([0, 0, 0]), top: z([0, 0, v.length]) } }; },
67
+ supply(v) {
68
+ const w = v.body_width, d = v.body_depth, h = v.body_length;
69
+ return { parts: { body: box(w, d, h) }, anchors: { base: z([0, 0, 0]), top: z([0, 0, h]), terminals: z([0, -d / 2, h / 2], [0, -1, 0]) } };
70
+ },
71
+ };
72
+
73
+ export function boughtModel(name, variant) {
74
+ const sets = boughtSets();
75
+ if (!sets.has(name)) throw new Error(`no bought part "${name}" (${[...sets.keys()].sort().join(', ')})`);
76
+ const set = loadRuleSet(name);
77
+ let rules = set.rules;
78
+ if (variant != null) {
79
+ const vs = set.variants || {};
80
+ if (!vs[variant]) throw new Error(`${name} has no variant "${variant}" (${Object.keys(vs).join(', ') || 'none'})`);
81
+ rules = { ...set.rules, ...Object.fromEntries(Object.entries(vs[variant].values ?? {}).map(([k, value]) => [k, { ...set.rules[k], value, kind: vs[variant].kind ?? set.rules[k]?.kind, source: vs[variant].source ?? set.rules[k]?.source }])) };
82
+ }
83
+ return { name, part: set.part, variant: variant ?? null, rules };
84
+ }
85
+
86
+ // An item with "bought": built like any other, a reference, its figures in values and its rules in entries
87
+ export function boughtBuilt(spec, it, num, id) {
88
+ const m = boughtModel(spec, it.variant);
89
+ // Figures that differ from the set's, by name: a smaller supply, a measured bearing
90
+ for (const [k, x] of Object.entries(it.set || {})) { if (!m.rules[k]) throw new Error(`item ${id}: ${spec} has no figure "${k}" (${Object.keys(m.rules).join(', ')})`); m.rules = { ...m.rules, [k]: { ...m.rules[k], value: num(x), kind: 'estimate', source: 'set on this item' } }; }
91
+ if (!SHAPES[m.part]) throw new Error(`item ${id}: ${spec} is a ${m.part}: bought parts are ${Object.keys(SHAPES).join(', ')}, and a motor goes in "motor"`);
92
+ const values = Object.fromEntries(Object.entries(m.rules).filter(([, r]) => typeof r.value === 'number').map(([k, r]) => [k, r.value]));
93
+ let shape;
94
+ try { shape = SHAPES[m.part](values, m); } catch (e) { throw new Error(`item ${id}: ${spec} doesn't say enough to draw it: ${e.message}`); }
95
+ const missing = Object.entries(shape.anchors).filter(([, a]) => a.at.some((c) => !Number.isFinite(c))).map(([k]) => k);
96
+ if (missing.length) throw new Error(`item ${id}: ${spec}: its rules don't place the anchors ${missing.join(', ')}`);
97
+ const parts = named(shape.parts, Object.fromEntries(Object.keys(shape.parts).map((k) => [k, { label: `${m.name} ${k}` }])));
98
+ const entries = Object.entries(m.rules).map(([k, r]) => ({ name: `${m.name}.${k}`, value: r.value, unit: r.unit, rule: r.rule, kind: r.kind, source: r.source, checked: r.checked, set: m.name }));
99
+ return referenceBuilt({ id, key: 'bought', objName: `bought:${m.name}`, name: m.name, parts, anchors: shape.anchors, entries, values, extra: { bought: { set: m.name, variant: m.variant, part: m.part, mass: values.mass ?? null } } });
100
+ }
101
+
102
+ // One line in the check for each bought item, so the shopping list and the wiring can read it
103
+ export function boughtFindings(s, f) {
104
+ for (const o of s.objects) if (o.bought) f('info', `${o.id}: ${o.bought.set}${o.bought.variant ? ` (${o.bought.variant})` : ''}, a ${o.bought.part}`, null, { code: 'bought.item', refs: { item: o.id, set: o.bought.set, variant: o.bought.variant, part: o.bought.part } });
105
+ }