@rulecad/cad 0.7.42 → 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,8 +81,13 @@ 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]
83
89
  cad list <project>/<assembly> what it takes to build: bought parts by set, fasteners, wire, printed parts in grams
84
- cad wires <project>/<assembly> the wiring sheet: each wire's length, gauge and ends [--out wiring.md]
90
+ cad wires <project>/<assembly> the wiring sheet: each wire's length, gauge and ends, written to exports/ [--out wiring.md]
85
91
  cad measured <project>/<assembly> <name>=<value> … a measurement, where the estimate was: a rule (x1c.press=0.08) or a
86
92
  check's prediction (task.accuracy=0.8): says what moved, and keeps a ledger of predicted
87
93
  against measured, shown by cad history [--unit mm] [--source "how"] [--rule "what it is"]
@@ -110,8 +116,8 @@ const HELP = `cad: JSCAD designs you can trace, check, share and print (rulecad)
110
116
 
111
117
  // Every command and option there is: a misspelt one is refused by name, not passed over
112
118
  const COMMANDS = ['new', 'import-kle', 'clone', 'agents', 'trust', 'rules', 'values', 'set', 'add', 'why', 'check', 'preview', 'animate', 'optimise', 'optimize', 'export',
113
- 'show', 'link', 'status', 'release', 'history', 'diff', 'printed', 'measure', 'measured', 'list', 'wires', 'match', 'variants', 'compare', 'help'];
114
- const OPTIONS = ['table', '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',
115
121
  'no-models', 'no-pictures', 'no-rules', 'note', 'open', 'part', 'place', 'pose', 'progress', 'push', 'result', 'rules', 'samples', 'set', 'short', 'source', 'steps',
116
122
  'sweep', 'tol', 'trailer', 'ttl', 'version', 'watch', 'line',
117
123
  'unit', 'rule', 'label', 'from', 'out', // cad set, cad rules
@@ -124,7 +130,7 @@ const USAGE = { add: 'fit|joint|item|loop|pose <project>/<assembly> --key value
124
130
  const args = process.argv.slice(2);
125
131
  // Options that stand alone. Every other takes the value after it: --name value, or -m for one-letter names
126
132
  // (--sweep and --watch take one or not).
127
- const FLAGS = ['table', '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'];
128
134
  const opt = (k) => {
129
135
  const i = args.findIndex((a) => a === `--${k}` || (k.length === 1 && a === `-${k}`));
130
136
  if (i < 0) return undefined;
@@ -418,6 +424,8 @@ async function main() {
418
424
  if (cmd === 'compare') return compareVariants(locate(ref), pos[2], pos[3]);
419
425
  if (cmd === 'measured') return measuredCommand(ref);
420
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);
421
429
  if (cmd === 'history') return history(ref);
422
430
  if (cmd === 'diff') return diff(locate(ref), pos[2], pos[3] || null);
423
431
  if (cmd === 'printed') return printed(locate(ref));
@@ -657,11 +665,20 @@ async function assembly(cmd, ref) {
657
665
  process.exitCode = report(findings, { assembly: ref, title, kind: a.kind || 'fit', ...(pose ? { pose } : {}) }) ? 1 : 0;
658
666
  return;
659
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
+ }
660
677
  if (cmd === 'preview') {
661
678
  const out = paths.preview(s.project, `${s.name}${pose ? `-${pose}` : ''}${opt('explode') ? '-exploded' : ''}.png`);
662
679
  const size = (await import('@rulecad/printcheck')).bounds(s.triangles).size.map((n) => fmt(n)).join(' × ');
663
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
664
- 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') });
665
682
  return console.log(out);
666
683
  }
667
684
  if (cmd === 'export') {
@@ -677,7 +694,8 @@ async function assembly(cmd, ref) {
677
694
  return console.log(out);
678
695
  }
679
696
  const link = async () => {
680
- 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)`);
681
699
  const url = await linkTo(model);
682
700
  return { view: url, stl: `${url}&get=stl`, '3mf': `${url}&get=3mf`, src: model.src, size: url.length, title, version: '' };
683
701
  };
@@ -902,6 +920,47 @@ async function status(project) {
902
920
  }
903
921
  }
904
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
+
905
964
  async function listCommand(what, ref) {
906
965
  if (!isAssembly(ref)) throw new Error(`cad ${what} works on an assembly (<project>/<assembly>), and there is no "${ref}"`);
907
966
  const s = await buildAssembly(ref);
@@ -913,7 +972,8 @@ async function listCommand(what, ref) {
913
972
  if (opt('json')) return console.log(JSON.stringify(rows.map(({ route, ...r }) => r), null, 2));
914
973
  if (!rows.length) return console.log(`${ref} has no "wires"`);
915
974
  if (opt('out')) { fs.writeFileSync(path.resolve(opt('out')), wiringSheet(rows) + '\n'); return console.log(`wrote ${opt('out')}`); }
916
- console.log(wiringSheet(rows));
975
+ const { writeWiring } = await import('../lib/buildpage.mjs'), file = writeWiring(s);
976
+ console.log(wiringSheet(rows)); say(path.relative(WS, file));
917
977
  }
918
978
 
919
979
  async function measuredCommand(ref) {
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
@@ -35,9 +35,15 @@ import { ops as booleans } from '@rulecad/shapes';
35
35
  import { motorBuilt, motorDrives, shaftFits, loadsOf, motorChecks, shaftFit, axisOf } from './motors.mjs';
36
36
  import { runningChecks, seatFit } from './seats.mjs';
37
37
  import { seatSize } from '@rulecad/shapes';
38
- import { wiresOf, wireChecks, wireRows } from './wires.mjs';
38
+ import { wiresOf, wireChecks, wireRows, wireTubes, wireRoutes } from './wires.mjs';
39
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';
40
45
  import { boughtBuilt, boughtFindings, boughtSets } from './bought.mjs';
46
+ import { orderChecks } from './order.mjs';
41
47
 
42
48
  export const assemblyPath = (ref) => { const [project, name] = String(ref).split('/'); return path.join(paths.project(project || ''), 'assemblies', `${name || ''}.json`); };
43
49
  export const isAssembly = (ref) => String(ref).includes('/') && host.exists(assemblyPath(ref.split('@')[0]));
@@ -102,7 +108,7 @@ export async function buildAssembly(ref, stack = [], overrides = {}, opts = {})
102
108
  const source = async (it, extra) => {
103
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); }
104
110
  if (it.bought) {
105
- const key = JSON.stringify(['bought', it.id, it.bought, it.variant]);
111
+ const key = JSON.stringify(['bought', it.id, it.bought, it.variant, it.set]);
106
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));
107
113
  return built.get(key);
108
114
  }
@@ -133,7 +139,7 @@ export async function buildAssembly(ref, stack = [], overrides = {}, opts = {})
133
139
  const [ref, named] = String(it.object).split(':'), [objName, pin] = ref.split('@'), variant = named || it.variant;
134
140
  const d = locate(`${project}/${objName}`), at = { ...(pin ? materialise(d, pin) : d), ...(variant ? { variant } : {}) };
135
141
  const b = await build(at, set, opts);
136
- 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)
137
143
  }
138
144
  }
139
145
  return built.get(key);
@@ -195,7 +201,7 @@ export async function buildAssembly(ref, stack = [], overrides = {}, opts = {})
195
201
  }
196
202
  for (const c of copies) { placed.push([it, c]); ids.push(c.id); }
197
203
  }
198
- const motion = motionOf(a, placed, num, ref), wires = wiresOf(a, placed, motion.joints);
204
+ const motion = motionOf(a, placed, num, ref), wires = wiresOf(a, placed, motion.joints), task = taskOf(a, motion, num), gait = gaitOf(a, motion, num);
199
205
  fits.push(...shaftFits(motion.drives, motion.joints, placed.map(([, c]) => c.id)).map((x) => ({ ...x, num })));
200
206
  for (const [it, c] of placed) {
201
207
  const src = c.src, id = c.id;
@@ -207,7 +213,7 @@ export async function buildAssembly(ref, stack = [], overrides = {}, opts = {})
207
213
  for (const n of sub.seen) seen.add(n);
208
214
  items.push({ ...it, id, sub, role: 'part' });
209
215
  } else {
210
- objects.push({ id, objName: src.objName, version: src.version, built: src.b, role: src.role, ...(src.bought ? { bought: src.bought } : {}), ...(src.motor ? { motor: src.motor } : {}) });
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 } : {}) });
211
217
  items.push({ ...it, id, objName: src.objName, built: src.b, version: src.version, role: src.role });
212
218
  }
213
219
  }
@@ -267,7 +273,7 @@ export async function buildAssembly(ref, stack = [], overrides = {}, opts = {})
267
273
  const v = jointValues(motion, p), moved = partsAt(placeItems(motion, v));
268
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) };
269
275
  };
270
- const s = { a, project, name, items, parts, objects, fits, requires, values, num, seen, motion, wires, 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,
271
277
  polygons: parts.flatMap((p) => p.polygons), triangles: parts.flatMap((p) => p.triangles) };
272
278
  return s;
273
279
  }
@@ -429,6 +435,7 @@ function planetaries(list, joints, items, num) {
429
435
  // Every part where it is with these joints at 0
430
436
  const v = jointValues({ joints, poses: {} }, {});
431
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)
432
439
  const worlds = placeItems({ items, joints }, v), W = (k) => worlds[k];
433
440
  const O = org(W(idx.sun)), Z = col(W(idx.sun), 2), X0 = col(W(idx.sun), 0);
434
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));
@@ -445,7 +452,7 @@ function planetaries(list, joints, items, num) {
445
452
  const rot = (d) => { const r = { [held[0]]: 0, [drive]: sg[drive] * d }; r[third] = (sigma0 - coef[drive] * r[drive]) / coef[third]; return r; };
446
453
  // a straight line in the driver's value (f: degrees in, radians out): [ratio, offset in degrees]
447
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)
448
- 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
449
456
  const [k3, o3] = lin((d) => sg[third] * rot(d * DEG)[third]);
450
457
  follower.follow = [lead.id, k3, o3]; free(follower);
451
458
  const findings = [], f = (level, text, code, between) => findings.push({ level, text, code, ...(between ? { between } : {}) });
@@ -645,6 +652,8 @@ export function anchorsAt(s, values = s.jointValues) {
645
652
  // keyCentres(layout): each key's centre, from lib/layout.mjs (kept under this name for older callers)
646
653
  export { keyCentres };
647
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 });
648
657
 
649
658
  // ---------- checks ----------
650
659
  export { closest };
@@ -860,6 +869,12 @@ export function checkAssembly(s) {
860
869
  runningChecks(s, f, { axisOf, placeItems, jointValues, mul });
861
870
  if (s.wires?.length) wireChecks(s, f, { placeItems, jointValues, mul });
862
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);
863
878
  // Plates print everything: no references
864
879
  if (s.a.kind === 'plate') {
865
880
  const refs = s.objects.filter((o) => o.role === 'reference' && !o.unplaced); // an unplaced item only lends its numbers
@@ -957,6 +972,7 @@ export function motionData(s) {
957
972
  poses: mo.poses, ...(s.pose ? { pose: s.pose } : {}),
958
973
  part: s.parts.map((p) => names.indexOf(p.item)),
959
974
  ...(allow.length ? { allow } : {}),
975
+ ...(s.gait ? { sequence: gaitSequence(s) ?? undefined } : {}),
960
976
  } };
961
977
  }
962
978
 
package/lib/bought.mjs CHANGED
@@ -59,6 +59,11 @@ const SHAPES = {
59
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
60
  },
61
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]) } }; },
62
67
  supply(v) {
63
68
  const w = v.body_width, d = v.body_depth, h = v.body_length;
64
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]) } };
@@ -81,6 +86,8 @@ export function boughtModel(name, variant) {
81
86
  // An item with "bought": built like any other, a reference, its figures in values and its rules in entries
82
87
  export function boughtBuilt(spec, it, num, id) {
83
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' } }; }
84
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"`);
85
92
  const values = Object.fromEntries(Object.entries(m.rules).filter(([, r]) => typeof r.value === 'number').map(([k, r]) => [k, r.value]));
86
93
  let shape;
@@ -0,0 +1,81 @@
1
+ // What a machine's model link adds to the model, all read from the same assembly the checks read: the task (the pen, the
2
+ // plane, the margins' figures), a step file, the wires' routes, and the build page (shopping list, plates, wiring sheet,
3
+ // assembly steps, machine settings).
4
+ import fs from 'node:fs';
5
+ import path from 'node:path';
6
+ import { sheetFrame } from '@rulecad/robots';
7
+ import { compactSteps } from '@rulecad/model-link';
8
+ import { paths } from './workspace.mjs';
9
+ import { host } from './host.mjs';
10
+ import { accuracyOf, sample, chainOf } from './task.mjs';
11
+ import { machineOf } from './machine.mjs';
12
+ import { shoppingList } from './list.mjs';
13
+ import { wiresFor, wireRoutesOf } from './assembly.mjs';
14
+ import { orderOf, isBuilt } from './order.mjs';
15
+ import { platesOf } from './plates.mjs';
16
+ import { wiringSheet } from './wires.mjs';
17
+ import { readLedger } from './measured.mjs';
18
+ import { fmt } from './rules.mjs';
19
+
20
+ const guard = async (fn) => { try { return await fn(); } catch (e) { return { error: e.message }; } };
21
+ const r = (x) => +Number(x).toFixed(6);
22
+
23
+ // The plane the pen moves on: the sheet, or the middle of a region or a volume
24
+ function planeOf(t) {
25
+ if (t.sheet) { const f = sheetFrame(t.sheet); return { at: f.at, u: f.u, v: f.v, n: f.n, width: f.width, height: f.height }; }
26
+ const area = t.region ?? t.volume, xr = area.x ?? [area.lo[0], area.hi[0]], yr = area.y ?? [area.lo[1], area.hi[1]], zr = area.z != null ? (Array.isArray(area.z) ? area.z : [area.z, area.z]) : area.lo ? [area.lo[2] ?? 0, area.hi?.[2] ?? area.lo[2] ?? 0] : [0, 0];
27
+ // The two longest sides are the plane the page draws on: a volume can be flat in any of its axes, or a single point
28
+ const at = [(xr[0] + xr[1]) / 2, (yr[0] + yr[1]) / 2, (zr[0] + zr[1]) / 2], side = [xr[1] - xr[0], yr[1] - yr[0], zr[1] - zr[0]], thin = side.indexOf(Math.min(...side));
29
+ const [a, b] = [0, 1, 2].filter((k) => k !== thin), axis = (k) => [0, 1, 2].map((m) => (m === k ? 1 : 0)), n = [0, 1, 2].map((m) => (m === thin ? (thin === 1 ? -1 : 1) : 0));
30
+ return { at, u: axis(a), v: axis(b), n, width: Math.max(side[a], 1), height: Math.max(side[b], 1) };
31
+ }
32
+
33
+ /** The task as the page reads it. @param {object} s a built assembly with a task @param {object[]} findings from checkAssembly */
34
+ export function taskData(s, findings) {
35
+ const t = s.task, { elbow } = sample(s), plane = planeOf(t);
36
+ const terms = t.accuracy != null ? accuracyOf(s).list.flatMap((j, i) => j.terms.map((x) => [i, x.term, r(x.value), x.kind ?? ''])) : [];
37
+ const loads = (s.motion.loads || []).map((l) => (l.mass != null ? { item: l.item, at: [l.frame[3], l.frame[7], l.frame[11]].map(r), mass: l.mass } : { joint: l.joint, value: l.value }));
38
+ const torque = findings.filter((x) => x.code === 'motor.torque' && x.values?.available != null).map((x) => ({ joint: x.refs.joint, available: r(x.values.available) }));
39
+ const hot = findings.filter((x) => x.code === 'motor.heat' && x.values?.case != null).sort((a, b) => (b.values.case / b.values.softening) - (a.values.case / a.values.softening))[0];
40
+ return { tool: t.tool, item: t.item, point: t.point.map(r), plane: { at: plane.at.map(r), u: plane.u.map(r), v: plane.v.map(r), n: plane.n.map(r), width: r(plane.width), height: r(plane.height) },
41
+ ...(elbow ? { elbow } : {}), ...(t.speed != null ? { speed: t.speed } : {}), ...(t.accuracy != null ? { accuracy: t.accuracy } : {}), ...(t.deflection ? { deflection: t.deflection } : {}),
42
+ ...(terms.length ? { terms } : {}), ...(loads.length ? { loads, gravity: s.motion.gravity } : {}), ...(torque.length ? { torque } : {}), ...(hot ? { heat: { motor: hot.refs?.item ?? '', case: r(hot.values.case), softening: hot.values.softening } } : {}) };
43
+ }
44
+
45
+ /** A step file for the link: the one asked for, or the newest cad plot wrote for this assembly. @returns {object|null} the compact form */
46
+ export function stepsData(s, asked) {
47
+ const dir = paths.exports(s.project), base = `${s.name}-`;
48
+ let file = typeof asked === 'string' ? asked : null;
49
+ if (!file && asked !== false && fs.existsSync(dir)) file = fs.readdirSync(dir).filter((f) => f.startsWith(base) && f.endsWith('.steps.json')).map((f) => path.join(dir, f)).sort((a, b) => fs.statSync(b).mtimeMs - fs.statSync(a).mtimeMs)[0] ?? null;
50
+ if (!file) return null;
51
+ if (!host.exists(file)) throw new Error(`no step file "${file}": cad plot writes them to exports/`);
52
+ const steps = compactSteps(JSON.parse(fs.readFileSync(file, 'utf8'))), names = chainOf(s).names;
53
+ if (names.join() !== steps.names.join()) throw new Error(`the step file ${path.basename(file)} is for joints ${steps.names.join(', ')}, and this machine's are ${names.join(', ')}: plot it again`);
54
+ return steps;
55
+ }
56
+
57
+ /** The build page. @param {object} s a built assembly */
58
+ export async function buildData(s) {
59
+ const list = await guard(() => shoppingList(s));
60
+ const wires = await guard(() => (s.wires?.length ? wiresFor(s).map(({ route, ...w }) => w) : null));
61
+ const plates = await guard(() => platesOf(s).then(({ bed, gap, plates: p, findings }) => ({ bed, gap, plates: p, findings })));
62
+ const order = isBuilt(s) ? await guard(() => orderOf(s)) : null;
63
+ const machine = s.task ? await guard(() => machineOf(s)) : null;
64
+ return { build: { list, wires, plates, order, machine } };
65
+ }
66
+
67
+ // The ledger, in the rules sheet's own rows: each prediction the bench can measure, the measurement once it's in
68
+ export function ledgerRows(s, findings) {
69
+ const entries = readLedger(s.project).filter((e) => e.assembly === s.name), rows = [], done = new Set();
70
+ for (const e of entries) { done.add(e.name); rows.push(['Predicted against measured', e.name, fmt(e.measured), e.unit || '', `predicted ${e.predicted != null ? `${fmt(e.predicted)}${e.was ? ` (${e.was})` : ''}` : 'nothing'}${e.ratio != null ? `, ratio ${fmt(+e.ratio.toFixed(3))}` : ''}${e.figure ? `, ${e.figure}` : ''}`, '', 'measured', e.source ?? '', e.date ?? '']); }
71
+ for (const x of findings) if (x.predict && !done.has(x.predict.name ?? x.code)) rows.push(['Predicted against measured', x.predict.name ?? x.code, fmt(x.predict.value), x.predict.unit ?? '', `${x.predict.figure}: nobody has measured it yet (cad measured ${s.project}/${s.name} ${x.predict.name ?? x.code}=<value>)`, '', 'prediction']);
72
+ return rows.map((row) => row.map(String));
73
+ }
74
+
75
+ /** The wiring sheet in the exports: <assembly>.wiring.md. @returns {string|null} the file */
76
+ export function writeWiring(s) {
77
+ if (!s.wires?.length) return null;
78
+ const dir = paths.exports(s.project), file = path.join(dir, `${s.name}.wiring.md`);
79
+ fs.mkdirSync(dir, { recursive: true }); fs.writeFileSync(file, `# ${s.project}/${s.name}: wiring\n\n${wiringSheet(wiresFor(s))}\n`);
80
+ return file;
81
+ }
package/lib/gait.mjs ADDED
@@ -0,0 +1,66 @@
1
+ // A gait in an assembly: poses in time. Each leg is the chain from the body to its foot; the cycle comes from
2
+ // @rulecad/robots, and the checks run through it: stability, the swing foot's clearance, each joint's torque against its
3
+ // motor, and the sweep along the sequence for one leg hitting another or the body.
4
+ // "gait": { "legs": ["fl.foot.tip", …], "pattern": "trot", "stride": 40, "lift": 15, "period": 1.2, "height": 120, "mass": 1.5 }
5
+ import { chainFromMotion, fk, gait } from '@rulecad/robots';
6
+ import { performance } from '@rulecad/motors';
7
+ import { trainFrom, workingSpeed, atCurrent } from './motors.mjs';
8
+
9
+ const n3 = (x, d = 2) => String(Number(x.toFixed(d)));
10
+
11
+ /** The gait as written, its legs as chains, refused by name when the assembly is built. */
12
+ export function gaitOf(a, motion, num) {
13
+ const g = a.gait; if (!g) return null;
14
+ if (!Array.isArray(g.legs) || !g.legs.length) throw new Error('gait: legs is a list of feet, <item>.<anchor>');
15
+ const legs = g.legs.map((ref) => {
16
+ const [id, name] = String(ref).split('.'), mark = motion.marks.find((m) => m.id === id && m.name === name);
17
+ if (!mark) throw new Error(`gait: no anchor "${ref}" (items: ${[...new Set(motion.marks.map((m) => m.id))].join(', ')})`);
18
+ // A leg's gearbox sits beside its links, so the foot's plane is not the hip anchor's: it stands in its own plane, over the hip
19
+ const c = chainFromMotion(motion, { tip: id, tool: [mark.frame[3], mark.frame[7], mark.frame[11]] }), zero = fk(c, c.names.map(() => 0)), hip = zero.frames[0].at;
20
+ return { name: id, chain: c, at: [hip[0], zero.position[1], hip[2]] };
21
+ });
22
+ const out = { legs, pattern: g.pattern, stride: num(g.stride), lift: num(g.lift), period: num(g.period), height: num(g.height), mass: num(g.mass), ...(g.steps ? { steps: num(g.steps) } : {}), ...(g.com ? { com: g.com.map(num) } : {}) };
23
+ return out;
24
+ }
25
+
26
+ // The joint values of a frame of the cycle, in the assembly's terms
27
+ export const frameValues = (s, frame, jointValues) => { // a joint behind a gearbox is moved by the motor's shaft it follows
28
+ const set = {};
29
+ for (const e of frame.feet) { const l = s.gait.legs.find((x) => x.name === e.leg); l.chain.names.forEach((n, i) => { let j = s.motion.joints.find((x) => x.id === n), v = e.q[i]; while (j.follow) { const [lead, r = 1, o = 0] = j.follow; v = (v - o) / r; j = s.motion.joints.find((x) => x.id === lead); } set[j.id] = [v]; }); }
30
+ return jointValues(s.motion, set);
31
+ };
32
+ export const framesOf = (s) => (s.gaitRun ??= gait(s.gait));
33
+
34
+ export function gaitChecks(s, f, { jointValues, placeItems, sweepOne }) {
35
+ if (!s.gait) return;
36
+ const r = framesOf(s);
37
+ for (const x of r.findings) f(x.level, `gait: ${x.text}`, x.level === 'pass' || x.level === 'info' ? null : 'gait: fails', { code: x.code, values: x.values, refs: x.refs });
38
+ if (!r.summary?.torque) return;
39
+ const lift = r.summary.clearance, min = s.a.gait.clearance != null ? s.num(s.a.gait.clearance) : s.gait.lift * 0.5;
40
+ f(lift >= min ? 'pass' : 'fail', `gait: the swing foot clears the ground by ${n3(lift, 1)} mm (wanted ${n3(min, 1)})`, lift >= min ? null : 'gait: foot drags', { code: 'gait.clearance', values: { lift, min } });
41
+ // Each driven joint's torque through the cycle, against its motor
42
+ const motion = s.motion;
43
+ for (const [id, t] of Object.entries(r.summary.torque)) {
44
+ const j = motion.joints.find((x) => x.id === id), tr = j && trainFrom(motion, id), d = tr && motion.drives.find((x) => x.joint === tr.root);
45
+ if (!d) { f('warn', `gait: nothing drives ${id}, so its ${n3(t, 3)} N m through the cycle isn't checked`, `gait: ${id} undriven`, { code: 'gait.torque', refs: { joint: id } }); continue; }
46
+ const speed = workingSpeed(d.model, d.spec), avail = atCurrent(d.model, d.spec, performance(d.model, { speed }).motor.torque) * tr.ratio * tr.efficiency, margin = avail / t, level = margin < 1 ? 'fail' : margin < 2 ? 'warn' : 'pass';
47
+ f(level, `gait: ${id} needs ${n3(t, 3)} N m at its worst in the cycle, and ${d.id} gives ${n3(avail, 3)} N m there, ${n3(margin, 1)} times over`, level === 'pass' ? null : `gait: ${id} ${n3(margin, 1)}×`, { code: 'motor.torque', refs: { joint: id, item: d.id }, values: { needed: t, available: avail, margin } });
48
+ }
49
+ // Leg against leg, leg against body: the cycle as a sweep
50
+ const every = Math.max(1, Math.floor(r.frames.length / 12)); let clashes = null, first = null;
51
+ for (const [k, frame] of r.frames.entries()) { if (k % every) continue; const c = sweepOne(frameValues(s, frame, jointValues)); if (c.length && !clashes) { clashes = c; first = frame.t; } }
52
+ if (clashes) f('fail', `gait: at ${n3(first * 100, 0)}% of the cycle ${clashes.slice(0, 3).map(([a, b]) => `${a} hits ${b}`).join(', ')}`, 'gait: clash', { code: 'gait.sweep', refs: { at: first } });
53
+ else f('pass', `gait: nothing collides through the cycle (${Math.ceil(r.frames.length / every)} poses of it)`, null, { code: 'gait.sweep' });
54
+ }
55
+
56
+ // A gait as joint values through its cycle, for the viewer's Motion panel and cad animate: the joints that lead
57
+ // (a motor's shaft in place of a gearbox's output), and their values at each frame
58
+ export function gaitSequence(s) {
59
+ if (!s.gait) return null;
60
+ const r = framesOf(s); if (!r.frames.length) return null;
61
+ const leads = (id) => { let j = s.motion.joints.find((x) => x.id === id); while (j.follow) j = s.motion.joints.find((x) => x.id === j.follow[0]); return j.id; };
62
+ const names = [...new Set(s.gait.legs.flatMap((l) => l.chain.names).map(leads))];
63
+ const toLead = (id, q) => { let j = s.motion.joints.find((x) => x.id === id), v = q; while (j.follow) { const [lead, ratio = 1, offset = 0] = j.follow; v = (v - offset) / ratio; j = s.motion.joints.find((x) => x.id === lead); } return v; };
64
+ const round = (x) => Number(x.toFixed(4));
65
+ return { kind: 'gait', period: s.gait.period, names, q: r.frames.map((f) => names.map((n) => { for (const e of f.feet) { const l = s.gait.legs.find((x) => x.name === e.leg); const i = l.chain.names.findIndex((m) => leads(m) === n); if (i >= 0) return round(toLead(l.chain.names[i], e.q[i])); } return 0; })) };
66
+ }
package/lib/grip.mjs ADDED
@@ -0,0 +1,23 @@
1
+ // A compliant gripper's grip: a servo through its horn closes two fingers on leaf flexures. What the servo gives, less what
2
+ // bending the leaves takes, is the grip; the payload is held by friction against gravity and the arm's acceleration.
3
+ // "grip": { "servo": "gripper_servo", "horn": 12, "leaf": { "length": 30, "thickness": 1.2, "width": 8 }, "travel": 6, "friction": 0.4 }
4
+ import { leafModel } from '@rulecad/flexures';
5
+ import { peekRuleSet } from './rules.mjs';
6
+ import { materialOf } from './list.mjs';
7
+
8
+ const G = 9.80665, n3 = (x, d = 2) => String(Number(x.toFixed(d)));
9
+
10
+ export function gripChecks(s, f) {
11
+ const g = s.a.task?.grip; if (!g) return;
12
+ const code = 'tool.grip', d = s.motion.drives.find((x) => x.id === g.servo), payload = s.task.payload ?? 0;
13
+ if (!d) throw new Error(`task.grip: servo "${g.servo}" isn't a motor item (${s.motion.drives.map((x) => x.id).join(', ') || 'none'})`);
14
+ if (d.model.type !== 'servo') throw new Error(`task.grip: ${g.servo} is a ${d.model.type}: the grip is worked out for a servo through its horn`);
15
+ const name = String(g.material ?? materialOf(s.project).name).toLowerCase(), rules = peekRuleSet(name).rules, E = rules.modulus.value, strength = rules.strength.value;
16
+ const horn = s.num(g.horn), travel = s.num(g.travel), lever = g.lever != null ? s.num(g.lever) : 1, mu = s.num(g.friction ?? 0.4), L = { length: s.num(g.leaf.length), thickness: s.num(g.leaf.thickness), width: s.num(g.leaf.width) }, m = leafModel(L, { E });
17
+ const torque = d.model.figures.stall_torque.value * (g.torque_share != null ? s.num(g.torque_share) : 0.6), pull = ((torque * 1000) / horn / 2) * lever, spring = m.stiffness * travel, grip = pull - spring, accel = (s.task.accel ?? 0) / 1000, need = payload * (G + accel);
18
+ const held = 2 * mu * grip, margin = need > 0 ? held / need : Infinity, want = g.margin != null ? s.num(g.margin) : 2, stress = m.stress(travel), strain = stress / strength, values = { grip, pull, spring, held, need, margin, stress };
19
+ if (grip <= 0) f('fail', `the grip: the servo pulls each finger with ${n3(pull)} N and the leaves take ${n3(spring)} N to close: it can't close them. A longer or thinner leaf`, 'grip: too stiff', { code, values });
20
+ else if (margin < 1) f('fail', `the grip: ${n3(grip)} N a finger holds ${n3(held)} N at μ ${mu}, and the payload needs ${n3(need)} N: it drops`, 'grip: drops', { code, values });
21
+ else f(margin < want ? 'warn' : 'pass', `the grip: ${n3(grip)} N a finger (${n3(pull)} N from the servo at ${n3(torque, 3)} N m, less ${n3(spring)} N to bend the leaves) holds ${n3(held)} N at μ ${mu}, against ${n3(need)} N for ${n3(payload * 1000, 0)} g: ${n3(margin, 1)} times over`, margin < want ? `grip: ${n3(margin, 1)}×` : null, { code, values });
22
+ f(strain > 1 ? 'fail' : strain > 0.6 ? 'warn' : 'pass', `the fingers at full close: ${n3(stress, 1)} MPa in a ${name.toUpperCase()} leaf, ${n3(strain * 100, 0)}% of its ${strength} MPa`, strain > 0.6 ? `finger ${n3(strain * 100, 0)}% strength` : null, { code: 'tool.strain', values: { stress, strength } });
23
+ }
package/lib/links.mjs CHANGED
@@ -6,8 +6,9 @@ import { fmt } from './rules.mjs';
6
6
  import { paths, config } from './workspace.mjs';
7
7
  import { host, readJson } from './host.mjs';
8
8
  import { pcbEngine } from './design.mjs';
9
- import { shapes, motionData } from './assembly.mjs';
9
+ import { shapes, motionData, checkAssembly, wireRoutesOf } from './assembly.mjs';
10
10
  import { slotOf } from './threemf.mjs';
11
+ import { taskData, stepsData, buildData, ledgerRows } from './buildpage.mjs';
11
12
 
12
13
  /** The project's filaments: { base: { slot: 1, … }, legend: { slot: 2, … } } in project.json. @param {string} project */
13
14
  export const filaments = (project) => readJson(path.join(paths.project(project), 'project.json')).filaments || {};
@@ -53,7 +54,7 @@ export async function objectModel(b, { title, version, src, set, filaments: fil
53
54
  }
54
55
 
55
56
  /** A built assembly as a model: each shape once and placed (nine keys cost one keycap), its boards' views, its joints. */
56
- export async function assemblyModel(s, { title, versions, filaments: fil = {}, noRules = false }) {
57
+ export async function assemblyModel(s, { title, versions, filaments: fil = {}, noRules = false, steps }) {
57
58
  const placed = shapes(s.parts), list = placed.shapes.length ? placed.place.map(([i, ...m], n) => { const p = placed.shapes[i].part; return { shape: i, role: p.role, label: p.object || p.label, slot: slotOf(fil, p.filament), triangles: triangles(placed.shapes[i].triangles), matrix: m, name: s.parts[n].name }; }) : [];
58
59
  // A pose that sets items' variables draws some parts differently (a flexure bent): each such part's shape in that
59
60
  // pose goes in the link as a "pose" part, placed as the part is, to be swapped in when the page shows the pose
@@ -87,5 +88,13 @@ export async function assemblyModel(s, { title, versions, filaments: fil = {}, n
87
88
  model.motion.swap = {};
88
89
  alts.forEach((x, i) => (model.motion.swap[x.pose] ||= []).push([x.of, list.length - alts.length + i]));
89
90
  }
91
+ // A machine's link carries the rest of the project: its task, a drawing to play, its wires' routes, the build page
92
+ if (s.wires?.length) model.wires = wireRoutesOf(s);
93
+ if (s.task || s.wires?.length || s.objects.some((o) => o.bought || o.motor)) {
94
+ const findings = s.task ? checkAssembly(s) : [];
95
+ if (s.task && model.motion) { model.task = taskData(s, findings); const carried = stepsData(s, steps); if (carried) model.steps = carried; }
96
+ Object.assign(model, await buildData(s));
97
+ if (!noRules && s.task) { const rows = ledgerRows(s, findings); if (rows.length) model.sheet = [...rows, ...(model.sheet ?? [])]; }
98
+ }
90
99
  return model;
91
100
  }