@rulecad/cad 0.7.45 → 0.7.47

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/EXAMPLES.md CHANGED
@@ -976,6 +976,9 @@ The check says which motor it is and how far a step moves (`0.0879° a step`, or
976
976
  on the pinion's axis, the force reaching the slide against the 1 N it has to push and how many times over, how fast the
977
977
  slide moves, and that the slide holds with the power off: the 28BYJ-48's own gearbox friction, far more than the load can
978
978
  turn it back with. The torque's line ends `(rests on community figures: measure it)`, because that's what its torque is.
979
+ `motor.mount` bends the rail under the motor by FE, held where its feet are screwed on: the shaft's tip moves a few
980
+ thousandths of a millimetre against the pinion's seat on the rail, far inside the 0.2 mm the pinion is drawn with. A NEMA 17 hung from a 2 mm PLA plate would
981
+ fail the same check, and say how thick the plate would need to be.
979
982
 
980
983
  ### The spool winder, driven
981
984
 
@@ -1211,8 +1214,14 @@ speed to it.
1211
1214
  ```sh
1212
1215
  npx cad check home/winder-driven # warns: nothing says whether it holds with the power off
1213
1216
  npx cad check home/winder-driven --sweep --steps 12 # warns, as above
1217
+ npx cad animate home/winder-driven
1218
+ npx cad preview home/winder-driven --check
1214
1219
  ```
1215
1220
 
1221
+ `cad animate` cuts the gearbox across its shafts and turns it: the planets roll round the held ring as the sun turns,
1222
+ and the reel, picked out as the part with the load, turns a quarter as far. `cad preview --check` labels the motor's
1223
+ torque where it starts and where it arrives, with the margin and the open question of holding unpowered.
1224
+
1216
1225
  The check says the sun drives the carrier at a quarter of its speed, the shaft has 6.6 mm of its flat in the sun's
1217
1226
  bore, and the motor gives `0.45 N m there against 0.2 N m needed, 2.25 times over (rests on derived figures)`: scaled
1218
1227
  from the 100:1 gearbox's, so measure it. It takes a DC motor's working speed as half its free speed: the reel at
package/README.md CHANGED
@@ -417,9 +417,10 @@ An item can be a motor instead of a printed object: `{ "id": "drive", "motor": {
417
417
  - A compound planetary is a `planetary` with `"output": { "ring", "planet", "teeth" }`: a second ring on the planets' second step, following them in phase.
418
418
  - `motor.torque`: what reaches the joint through the gears, against the load: a fail under 1 times, a warning under the margin. It says what its figures rest on. `motor.speed`: how fast it moves and how long its range takes. Stages pass on `stageEfficiency` of the power (0.95 a mesh, an estimate).
419
419
  - `motor.holds`: with the power on (holding torque, or stall torque) and off (detent torque, a built-in gearbox's friction, a worm that locks, gears under 50% efficient, or `"brake": "a ratchet and pawl"` on the joint). Dropping with the power off is a warning: it may be what you want.
420
- - `motor.mount`: the part a motor is fastened to (a `fastens` fit), read as drawn: how thick it is at the screw holes against the screws' size, and the screws' bearing on the plastic under the motor's full torque. How far the whole part bends isn't checked yet.
420
+ - `motor.mount`: the part a motor is fastened to (a `fastens` fit), read as drawn: how thick it is at the screw holes against the screws' size, and the screws' bearing on the plastic under the motor's full torque. Then the whole part bent, by FE on the part as drawn (cubes, two across the plate at the screws): the motor's weight at its centre, along `gravity` in the pose it's checked in, and its full torque (the larger of its working and holding torque), both carried into the plate where the screws clamp it. The part is held at the joint that carries it, if one does; else where it meets the printed parts it's fastened to that sit below it; failing both, on its lowest face. It reports how far the shaft's tip moves (against the driven joint's seat, where that is on the same part, since the two move together), against the printer's `fit` clearance (or the motor's `"deflection"` in mm), and the peak stress against the material's `strength`; under 2 times either fails, and says what fixes it: the plate thickness that would do (bending goes with its cube), ribs, or how much stiffer a material would have to be. Cells this coarse read a plate 10 to 20% stiff, and a cell's stress is read at its centre, so the peak is scaled up to the surface; it's an estimate, said as one. Kept in `.cache/mount`.
421
421
  - `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.
422
422
  - 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`).
423
+ - `cad preview --check` of an assembly with a motor writes `<assembly>-check.png`: the same six views, with a label at each joint the motor's torque passes through (what reaches it, and at the loaded joint the margin and whether it holds unpowered). The rest view never carries them.
423
424
  - `cad preview` of an assembly with a motor draws each one at work beside the picture, as SVG: `<assembly>-<motor>-curve.svg`, its torque against speed at the output with the load and the working speed marked, and `<assembly>-<motor>-train.svg`, the torque from its shaft through each stage to the joint with the load, against what the load needs there, and whether it holds with the power on and off. The numbers are the check's.
424
425
 
425
426
  ### Building it
@@ -663,6 +664,8 @@ moving bodies in blue and the flexures in orange, drawn bent, holding a moment a
663
664
 
664
665
  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.
665
666
 
667
+ An assembly with a motor, or with gears that follow a joint, plays its drive: `cad animate <project>/<assembly>` writes `<assembly>-drive.svg`, the gears cut across their shafts through their teeth (up to three cuts side by side, a compound planetary's two rings each in its own), each part turning and moving as it does, the part with the load picked out. It turns the drive until the slowest part has moved about 60° (one to six turns; `--turns n` to choose). Each part's outline is drawn once and moved, so a gearbox stays a few hundred kilobytes.
668
+
666
669
  ## Checks
667
670
 
668
671
  - **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
@@ -55,9 +55,11 @@ const HELP = `cad: JSCAD designs you can trace, check, share and print (rulecad)
55
55
  cad add fit|joint|item|loop|pose <project>/<assembly> --a … --b … --min … add to an assembly, keeping its layout
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
- cad preview <project>/<object> six views as a PNG in .preview/ (prints the path)
58
+ cad preview <project>/<object> six views as a PNG in .preview/ (prints the path); an assembly with a motor also gets
59
+ its curve and its train as SVGs, and --check labels the torque at each joint it drives
59
60
  cad animate <project>/<object> a lamina mechanism's sequence, or an assembly's gait, start to finish, in .preview/: an animated SVG, the
60
- data (shapes, forces, energies, strains each frame, JSON) and a page that plays it
61
+ data (shapes, forces, energies, strains each frame, JSON) and a page that plays it; an
62
+ assembly with a motor or gears: the drive turning them, cut across the shafts [--turns n]
61
63
  cad optimise <project>/<problem> the stiffest layout for a problem in the project's problems/ (name:variant for a
62
64
  variant): a picture in .preview/, the result kept for designs [--fresh] [--json]
63
65
  [--watch [port]: a live view of it at http://127.0.0.1:8090/, with a stop button]
@@ -117,7 +119,7 @@ const HELP = `cad: JSCAD designs you can trace, check, share and print (rulecad)
117
119
  // Every command and option there is: a misspelt one is refused by name, not passed over
118
120
  const COMMANDS = ['new', 'import-kle', 'clone', 'agents', 'trust', 'rules', 'values', 'set', 'add', 'why', 'check', 'preview', 'animate', 'optimise', 'optimize', 'export',
119
121
  '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',
122
+ const OPTIONS = ['table', 'calibrate', 'check', 'turns', 'preview', 'gap', 'no-steps', 'all', 'along', 'at', 'bump', 'depth', 'dry-run', 'explode', 'force', 'fresh', 'json', 'licence', 'license', 'long', 'm', 'material', 'md', 'name', 'new',
121
123
  'no-models', 'no-pictures', 'no-rules', 'note', 'open', 'part', 'place', 'pose', 'progress', 'push', 'result', 'rules', 'samples', 'set', 'short', 'source', 'steps',
122
124
  'sweep', 'tol', 'trailer', 'ttl', 'version', 'watch', 'line',
123
125
  'unit', 'rule', 'label', 'from', 'out', // cad set, cad rules
@@ -130,7 +132,7 @@ const USAGE = { add: 'fit|joint|item|loop|pose <project>/<assembly> --key value
130
132
  const args = process.argv.slice(2);
131
133
  // Options that stand alone. Every other takes the value after it: --name value, or -m for one-letter names
132
134
  // (--sweep and --watch take one or not).
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'];
135
+ const FLAGS = ['table', 'calibrate', 'check', 'preview', 'no-steps', 'all', 'dry-run', 'explode', 'force', 'fresh', 'json', 'long', 'md', 'new', 'no-models', 'no-pictures', 'no-rules', 'open', 'progress', 'push', 'short'];
134
136
  const opt = (k) => {
135
137
  const i = args.findIndex((a) => a === `--${k}` || (k.length === 1 && a === `-${k}`));
136
138
  if (i < 0) return undefined;
@@ -666,7 +668,12 @@ async function assembly(cmd, ref) {
666
668
  return;
667
669
  }
668
670
  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`);
671
+ if (!s.gait) { // a motor turning what it drives: the gears cut across their shafts, the load's part turning with them
672
+ const { driveSvg } = await import('../lib/drive.mjs'), out = paths.preview(s.project, `${s.name}-drive.svg`);
673
+ fs.mkdirSync(path.dirname(out), { recursive: true });
674
+ fs.writeFileSync(out, driveSvg(s, { title, ...(opt('turns') ? { turns: Number(opt('turns')) } : {}) }));
675
+ return console.log(out);
676
+ }
670
677
  const { gaitSvg, gaitData } = await import('../lib/animate.mjs'), { framesOf } = await import('../lib/gait.mjs'), r = framesOf(s);
671
678
  if (!r.frames.length) throw new Error(`${ref}'s gait has nothing to play: ${r.findings.map((x) => x.text).join('; ')}`);
672
679
  const svg = paths.preview(s.project, `${s.name}-gait.svg`), json = paths.preview(s.project, `${s.name}-gait.json`);
@@ -675,13 +682,19 @@ async function assembly(cmd, ref) {
675
682
  console.log(svg); return console.log(json);
676
683
  }
677
684
  if (cmd === 'preview') {
678
- const out = paths.preview(s.project, `${s.name}${pose ? `-${pose}` : ''}${opt('explode') ? '-exploded' : ''}.png`);
685
+ const check = !!opt('check'); // the check view: each motor's torque labelled at its joints, never on the rest view
686
+ const out = paths.preview(s.project, `${s.name}${pose ? `-${pose}` : ''}${opt('explode') ? '-exploded' : ''}${check ? '-check' : ''}.png`);
687
+ let marks = null;
688
+ if (check) {
689
+ if (!s.motion?.drives?.length) throw new Error(`${ref} has no motor: cad preview --check labels the torque a motor sends through its joints`);
690
+ marks = (await import('../lib/motorsvg.mjs')).workMarks(s);
691
+ }
679
692
  const size = (await import('@rulecad/printcheck')).bounds(s.triangles).size.map((n) => fmt(n)).join(' × ');
680
693
  const faint = [...new Set(s.parts.filter((p) => p.role !== 'part').map((p) => `${p.object || p.item}${p.role === 'support' ? ' supports' : ''}`))]; // each kind once
681
- await preview([...s.parts, ...wireTubesOf(s)], { title, meta: `${size} mm · ${versions}${faint.length ? ` · faint: ${faint.join(', ')}` : ''}`, out, explode: !!opt('explode') });
694
+ await preview([...s.parts, ...wireTubesOf(s)], { title: check ? `${title}: the motor at work` : title, meta: `${size} mm · ${versions}${faint.length ? ` · faint: ${faint.join(', ')}` : ''}`, out, explode: !!opt('explode'), marks });
682
695
  // each motor at work beside it: its curve with the working point, and the torque through its train (said before
683
696
  // the picture, which stays the last line, for whatever reads it)
684
- if (s.motion?.drives?.length && !pose && !opt('explode')) {
697
+ if (s.motion?.drives?.length && !pose && !opt('explode') && !check) {
685
698
  const { motorWork, workCurve, trainSvg } = await import('../lib/motorsvg.mjs');
686
699
  for (const w of motorWork(s)) {
687
700
  for (const [kind, svg] of [['curve', workCurve(w)], ['train', trainSvg(w)]]) {
package/lib/drive.mjs ADDED
@@ -0,0 +1,133 @@
1
+ // A motor turning what it drives, as one animated SVG: the gears cut across their shafts, each part's outline drawn
2
+ // once and moved as a rigid body (a turn and a slide per frame), so a gearbox of fine teeth stays small. A section is
3
+ // taken at the middle of each gear (rings, suns, planets) and of the part with the load, up to three, side by side.
4
+ import { jointValues, placeItems, mul } from '@rulecad/model-link';
5
+ import { axisFrame, sliceAt } from './seats.mjs';
6
+ import { loops } from './mesh.mjs';
7
+ import { trainFrom, axisOf } from './motors.mjs';
8
+
9
+ const fmt = (n) => +Number(n).toFixed(3);
10
+ const esc = (s) => String(s).replace(/[<>&"]/g, (c) => ({ '<': '&lt;', '>': '&gt;', '&': '&amp;', '"': '&quot;' })[c]);
11
+ const rowsAt = (W, p) => [0, 1, 2].map((k) => W[4 * k] * p[0] + W[4 * k + 1] * p[1] + W[4 * k + 2] * p[2] + W[4 * k + 3]);
12
+ const COLOUR = { still: '#c9ccd1', moves: '#2f6fb3', load: '#e07a1f', bought: '#e9eaec' };
13
+
14
+ /**
15
+ * What the drive moves and where to cut: the joint the motor turns (or a gearbox's input), the joint with the load, the
16
+ * levels across the axis to section at, and how far to turn so the slowest part moves a readable amount.
17
+ */
18
+ export function drivePlan(s, { turns } = {}) {
19
+ const motion = s.motion, d = (motion.drives || []).find((x) => x.joint);
20
+ const root = d?.joint ?? motion.joints.find((j) => !j.follow && motion.joints.some((x) => x.follow?.[0] === j.id))?.id;
21
+ if (!root) return null;
22
+ const load = (motion.loads || []).find((l) => l.joint)?.joint ?? motion.joints.filter((j) => trainFrom(motion, j.id).root === root && j.id !== root).sort((a, b) => trainFrom(motion, b.id).ratio - trainFrom(motion, a.id).ratio)[0]?.id ?? root;
23
+ const ratio = Math.abs(trainFrom(motion, load).ratio) || 1;
24
+ const n = turns ?? Math.min(6, Math.max(1, (ratio * 60) / 360)); // the slowest part through about 60°, in one to six turns
25
+ return { root, load, motor: d?.id ?? null, ratio, turns: n };
26
+ }
27
+
28
+ export function driveSvg(s, { turns, title = '' } = {}) {
29
+ const plan = drivePlan(s, { turns });
30
+ if (!plan) throw new Error(`${s.name} has nothing driven to animate: give it a "motor" item that "drives" a joint, or gears that follow one`);
31
+ const motion = s.motion, rootJ = motion.joints.find((j) => j.id === plan.root);
32
+ const v0 = jointValues(motion, motion.pose ?? undefined), W0 = placeItems(motion, v0);
33
+ const { O, Z } = axisOf(motion, W0, rootJ, mul), F = axisFrame(O, Z);
34
+ const indexOf = new Map(s.items.map((it, k) => [it.id, k]));
35
+ const loadItem = motion.joints.find((j) => j.id === plan.load)?.child;
36
+ // Every part, in the axis's frame at rest: what's cut, and what it belongs to
37
+ const parts = s.parts.map((p) => ({ p, k: indexOf.get(p.item), world: p.triangles.map((t) => t.map(F)) })).filter((x) => x.k != null && x.world.length);
38
+ const span = (x) => { let lo = Infinity, hi = -Infinity; for (const t of x.world) for (const q of t) { lo = Math.min(lo, q[2]); hi = Math.max(hi, q[2]); } return [lo, hi]; };
39
+ // Where to cut: through each gear's teeth (the height whose section has the most edges, the middle of that run),
40
+ // rings named in a planetary included, and through the middle of what carries the load
41
+ const geared = new Set([...(motion.meshes || []).flatMap((m) => [m.joint, ...(m.members || [])]), ...motion.joints.filter((j) => j.follow).flatMap((j) => [j.id, j.follow[0]])]);
42
+ const childOf = new Map(motion.joints.map((j) => [j.id, j.child]));
43
+ const ringItems = new Set((s.a.planetary || []).flatMap((g) => [g.ring, g.output?.ring]).filter(Boolean).map((id) => indexOf.get(id)));
44
+ const gearItems = new Set([...[...geared].map((id) => childOf.get(id)), ...ringItems].filter((k) => k != null));
45
+ const teethAt = (x) => {
46
+ const [lo, hi] = span(x), n = Math.min(160, Math.max(8, Math.round((hi - lo) / 0.25))), counts = [];
47
+ for (let i = 1; i < n; i++) { const z = lo + ((hi - lo) * i) / n; counts.push([z, sliceAt(x.world, z).length]); }
48
+ const top = Math.max(...counts.map((c) => c[1])), run = counts.filter((c) => c[1] >= top * 0.9).map((c) => c[0]);
49
+ return run.length ? (run[0] + run.at(-1)) / 2 : (lo + hi) / 2;
50
+ };
51
+ const want = [];
52
+ for (const k of gearItems) { const own = parts.filter((x) => x.k === k && x.p.role === 'part'); if (own.length) want.push({ z: teethAt({ world: own.flatMap((x) => x.world) }), ring: ringItems.has(k) }); }
53
+ if (loadItem != null && !gearItems.has(loadItem)) { const own = parts.filter((x) => x.k === loadItem && x.p.role === 'part'); if (own.length) { const [lo, hi] = span({ world: own.flatMap((x) => x.world) }); want.push({ z: (lo + hi) / 2, ring: false }); } }
54
+ want.sort((a, b) => b.ring - a.ring || a.z - b.z);
55
+ const levels = [];
56
+ for (const { z } of want) if (!levels.some((l) => Math.abs(l - z) < 1.5)) levels.push(z);
57
+ const picked = levels.slice(0, 3).sort((a, b) => a - b); // rings first, then the rest, three at most
58
+ // The frames: the root turned through its turns, each item's rigid move in the plane from two points on it
59
+ const N = Math.min(240, Math.max(24, Math.round(plan.turns * 40))), base = v0[plan.root]?.[0] ?? 0;
60
+ const ks = [...new Set(parts.map((x) => x.k))], moves = new Map(ks.map((k) => [k, []]));
61
+ for (let f = 0; f <= N; f++) {
62
+ const W = f ? placeItems(motion, jointValues(motion, { ...Object.fromEntries(Object.entries(v0).filter(([id]) => !motion.joints.find((j) => j.id === id)?.follow)), [plan.root]: [base + (360 * plan.turns * f) / N] })) : W0;
63
+ for (const k of ks) {
64
+ const a = F(rowsAt(W[k], [0, 0, 0])), local = invRows(W0[k]), axisLocal = rotOnly(local, Z), e = perp(axisLocal);
65
+ const b = F(rowsAt(W[k], e)), a0 = F(rowsAt(W0[k], [0, 0, 0])), b0 = F(rowsAt(W0[k], e));
66
+ const th = Math.atan2(b[1] - a[1], b[0] - a[0]) - Math.atan2(b0[1] - a0[1], b0[0] - a0[0]);
67
+ const list = moves.get(k), prev = list.length ? list.at(-1).th : 0;
68
+ let t = th; while (t - prev > Math.PI) t -= 2 * Math.PI; while (t - prev < -Math.PI) t += 2 * Math.PI; // turned on, not back
69
+ const c = Math.cos(t), sn = Math.sin(t);
70
+ list.push({ th: t, tx: a[0] - (c * a0[0] - sn * a0[1]), ty: a[1] - (sn * a0[0] + c * a0[1]) });
71
+ }
72
+ }
73
+ const still = (k) => moves.get(k).every((m) => Math.abs(m.th) < 1e-6 && Math.abs(m.tx) < 1e-6 && Math.abs(m.ty) < 1e-6);
74
+ // Each panel: the cut through every part that crosses it, at rest; the moving ones animated
75
+ const panels = picked.map((z) => {
76
+ const cuts = [];
77
+ for (const x of parts) {
78
+ const outlines = loops(sliceAt(x.world, z)).filter((o) => o.length > 2);
79
+ if (outlines.length) cuts.push({ ...x, d: outlines.map((o) => `M${o.map(([u, w]) => `${fmt(u)} ${fmt(w)}`).join('L')}Z`).join('') });
80
+ }
81
+ const names = [...new Set(cuts.filter((c) => c.p.role === 'part').map((c) => c.p.item))];
82
+ return { z, cuts, names };
83
+ }).filter((p) => p.cuts.length);
84
+ if (!panels.length) throw new Error(`${s.name}: no part crosses the planes through its gears`);
85
+ // The view: everything every frame reaches, in each panel
86
+ let r = 0;
87
+ for (const pn of panels) for (const c of pn.cuts) for (const t of c.world) for (const q of t) if (Math.abs(q[2] - pn.z) < 50) r = Math.max(r, Math.hypot(q[0], q[1]));
88
+ const cell = 2 * r * 1.1, gap = cell * 0.08, cap = cell * 0.16, W = panels.length * cell + (panels.length + 1) * gap, H = cell + cap * 2 + gap;
89
+ const dur = `${fmt(Math.max(4, Math.min(12, plan.turns * 2)))}s`;
90
+ const anim = (k) => {
91
+ const m = moves.get(k);
92
+ return { t: `<animateTransform attributeName="transform" type="translate" values="${m.map((x) => `${fmt(x.tx)} ${fmt(x.ty)}`).join(';')}" dur="${dur}" repeatCount="indefinite"/>`,
93
+ r: `<animateTransform attributeName="transform" type="rotate" values="${m.map((x) => fmt((x.th * 180) / Math.PI)).join(';')}" dur="${dur}" repeatCount="indefinite"/>` };
94
+ };
95
+ const colour = (c) => (c.p.role !== 'part' ? COLOUR.bought : c.k === loadItem ? COLOUR.load : still(c.k) ? COLOUR.still : COLOUR.moves);
96
+ const art = panels.map((pn, i) => {
97
+ const cx = gap + i * (cell + gap) + cell / 2, cy = cap + gap + cell / 2;
98
+ const order = [...pn.cuts].sort((a, b) => (a.p.role !== 'part') - (b.p.role !== 'part') || still(b.k) - still(a.k)); // bought faint at the back, still parts under moving ones
99
+ const shapes = order.map((c) => {
100
+ const fill = `<path d="${c.d}" fill="${colour(c)}" fill-rule="evenodd" stroke="#1a1a1a" stroke-width="${fmt(cell / 900)}"/>`;
101
+ if (still(c.k)) return fill;
102
+ const a = anim(c.k);
103
+ return `<g>${a.t}<g>${a.r}${fill}</g></g>`;
104
+ }).join('');
105
+ const size = cap * 0.3, room = Math.floor(cell / (size * 0.55)), text = `at ${fmt(pn.z)} mm: ${pn.names.join(', ')}`;
106
+ const label = `<text x="${fmt(cx - cell / 2)}" y="${fmt(cap * 0.75)}" font-size="${fmt(size)}" font-family="system-ui, sans-serif" fill="#333">${esc(text.length > room ? `${text.slice(0, room - 1)}…` : text)}</text>`;
107
+ return `${label}<g transform="translate(${fmt(cx)} ${fmt(cy)}) scale(1 -1)">${shapes}</g>`;
108
+ }).join('\n');
109
+ const times = (n) => (n === 1 ? 'once' : `${fmt(n)} times`), along = `cut across ${plan.root}'s axis`;
110
+ const out = plan.ratio !== 1 ? `${along}: ${plan.load} turns ${fmt((360 * plan.turns) / plan.ratio)}° while ${plan.root} turns ${times(plan.turns)} (${fmt(plan.ratio)}:1)` : `${along}: ${plan.root} turned ${times(plan.turns)}`;
111
+ const KEY = [['moves', 'moves'], ['load', 'carries the load'], ['still', 'held still'], ['bought', 'bought']];
112
+ const ks2 = Math.min(cap * 0.3, (W - 2 * gap) / (KEY.reduce((n, [, t]) => n + t.length * 0.55 + 3.2, 0))), outSize = Math.min(cap * 0.34, (W - 2 * gap) / (out.length * 0.55));
113
+ let kx = gap;
114
+ const key = KEY.map(([k, t]) => { const x = kx; kx += ks2 * (t.length * 0.55 + 3.2); return `<rect x="${fmt(x)}" y="${fmt(H - cap * 0.95)}" width="${fmt(ks2 * 1.2)}" height="${fmt(ks2 * 1.2)}" fill="${COLOUR[k]}" stroke="#1a1a1a" stroke-width="${fmt(cell / 900)}"/><text x="${fmt(x + ks2 * 1.6)}" y="${fmt(H - cap * 0.95 + ks2)}" font-size="${fmt(ks2)}" font-family="system-ui, sans-serif" fill="#555">${t}</text>`; }).join('');
115
+ return `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 ${fmt(W)} ${fmt(H)}" width="${Math.min(1400, 480 * panels.length)}">
116
+ <title>${esc(title || s.a.title || s.name)}</title>
117
+ <rect width="${fmt(W)}" height="${fmt(H)}" fill="#fff"/>
118
+ ${art}
119
+ <text x="${fmt(gap)}" y="${fmt(H - cap * 1.25)}" font-size="${fmt(outSize)}" font-family="system-ui, sans-serif" fill="#333">${esc(out)}</text>
120
+ ${key}
121
+ </svg>
122
+ `;
123
+ }
124
+
125
+ // Helpers on the flat row-major 4 × 4 matrices placeItems gives
126
+ function invRows(W) { // a rigid move's inverse: the turn transposed, the shift turned back
127
+ const R = [[W[0], W[1], W[2]], [W[4], W[5], W[6]], [W[8], W[9], W[10]]], t = [W[3], W[7], W[11]];
128
+ const o = new Array(16).fill(0);
129
+ for (let i = 0; i < 3; i++) { for (let j = 0; j < 3; j++) o[4 * i + j] = R[j][i]; o[4 * i + 3] = -(R[0][i] * t[0] + R[1][i] * t[1] + R[2][i] * t[2]); }
130
+ o[15] = 1; return o;
131
+ }
132
+ const rotOnly = (W, v) => [0, 1, 2].map((k) => W[4 * k] * v[0] + W[4 * k + 1] * v[1] + W[4 * k + 2] * v[2]);
133
+ const perp = (z) => { const n = Math.hypot(...z) || 1, u = z.map((c) => c / n), seed = Math.abs(u[0]) < 0.9 ? [1, 0, 0] : [0, 1, 0]; const c = [seed[1] * u[2] - seed[2] * u[1], seed[2] * u[0] - seed[0] * u[2], seed[0] * u[1] - seed[1] * u[0]], m = Math.hypot(...c); return c.map((x) => (x / m) * 10); };
package/lib/motors.mjs CHANGED
@@ -7,6 +7,13 @@ import { motorModel, motorParts, mountModel, performance } from '@rulecad/motors
7
7
  import { stageEfficiency } from '@rulecad/gears';
8
8
  import { named } from './parts.mjs';
9
9
  import { referenceBuilt } from './bought.mjs';
10
+ import crypto from 'node:crypto';
11
+ import { grid as makeGrid, analyse, positions } from '@rulecad/fea';
12
+ import { threadsBackend } from '@rulecad/fea/threads';
13
+ import { host } from './host.mjs';
14
+ import { paths, printerOf } from './workspace.mjs';
15
+ import { peekRuleSet } from './rules.mjs';
16
+ import { solidFill } from './optimise.mjs';
10
17
 
11
18
  const require = createRequire(import.meta.url);
12
19
  const n3 = (x, d = 3) => String(Number(x.toFixed(d)));
@@ -194,7 +201,7 @@ export function motorChecks(s, f, helpers, materialName) {
194
201
  const slideRate = main.x.type === 'prismatic' ? (speedOut * 360 * main.t.slide) / 60 : null, span = slideRate ? main.x.dofs[0][1] - main.x.dofs[0][0] : 0, time = slideRate ? span / slideRate : 60 / speedOut; // along a slide's travel, or a turn
195
202
  f('info', `${main.x.id} moves at ${slideRate ? `${n3(slideRate, 2)} mm/s` : `${n3(speedOut, 2)} rpm`} with ${d.id} at ${n3(motorSpeed, 1)} rpm: ${slideRate ? 'its whole range' : 'a turn'} in ${n3(time, 1)} s`, null, { code: 'motor.speed', at: at(main.x), values: { rpm: speedOut, time } });
196
203
  }
197
- mountCheck(s, d, f, W, avail, materialName);
204
+ mountCheck(s, d, f, W, avail, materialName, { worlds, mul });
198
205
  // Does it hold?
199
206
  const fig = (k) => m.figures[k]?.value, kt = m.type === 'brushless' ? 60 / (2 * Math.PI * fig('kv')) : 0;
200
207
  const on = atCurrent(m, d.spec, fig('holding_torque') ?? fig('stall_torque') ?? (kt ? kt * fig('rated_current') : 0)), off_ = fig('detent_torque') ?? fig('friction_torque') ?? null, brake = lines.map((l) => motion.joints.find((x) => x.id === l.x.id)?.brake).find(Boolean) ?? motion.joints.find((x) => x.id === d.joint)?.brake;
@@ -216,8 +223,8 @@ export function motorChecks(s, f, helpers, materialName) {
216
223
  }
217
224
 
218
225
  // The part a motor is fastened to, under the motor's full torque as a reaction at its screws: how thick it is at the
219
- // holes (read from the part as drawn), and the screws' bearing on the plastic. Not yet: how far the whole part bends.
220
- function mountCheck(s, d, f, W, avail, materialName) {
226
+ // holes (read from the part as drawn), the screws' bearing on the plastic, and how far the whole part bends (mountBends).
227
+ function mountCheck(s, d, f, W, avail, materialName, frame) {
221
228
  const m = d.model, top = (n) => String(n).split(/[.@]/)[0], fit = s.fits.find((x) => x.fastens && [top(x.a), top(x.b)].includes(d.id));
222
229
  if (!fit || !m.mount.holes.length) return;
223
230
  const other = top(fit.a) === d.id ? top(fit.b) : top(fit.a), parts = s.parts.filter((p) => p.item === other || p.leaf === other);
@@ -230,6 +237,132 @@ function mountCheck(s, d, f, W, avail, materialName) {
230
237
  const here = mountModel(m, { plate: +plate.toFixed(2), ...(d.spec.screw ? { screw: d.spec.screw } : {}) }), mat = material(materialName) || material('pla'), radius = Math.max(...m.mount.holes.map(([x, y]) => Math.hypot(x, y))), each = avail / (m.mount.holes.length * radius / 1000), bearing = each / (hd * t), margin = mat.strength / bearing;
231
238
  for (const x of here.findings) f(x.level, `${d.id} on ${other}: ${x.text}`, x.level === 'pass' ? null : `${d.id}: ${x.code.split('.')[1]}`, { code: 'motor.mount' });
232
239
  f(margin < 2 ? 'fail' : 'pass', `${d.id} on ${other}: ${n3(plate, 2)} mm of plate at the screws, each taking ${n3(each, 1)} N against the torque (bearing ${n3(bearing, 1)} MPa, ${n3(margin, 0)} times under ${mat.name.toUpperCase()}'s ${mat.strength} MPa)`, margin < 2 ? `${d.id}: screws pull through` : null, { code: 'motor.mount', values: { plate, bearing, margin } });
240
+ mountBends(s, d, f, W, avail, mat, { other, parts, inv, plate, hd, ...frame });
241
+ }
242
+
243
+ // ---------- the mount, bent ----------
244
+ // The part as a whole under the motor: its weight (gravity as the assembly has it, in the pose it's checked in) at its
245
+ // centre and its full torque about the shaft, both carried into the part where the screws clamp it, by FE on the part as
246
+ // drawn (cubes, two across the plate at the screws). The part is held where it meets the printed parts it's fastened to,
247
+ // or at the joint it turns on; failing both, where it stands (its lowest face). Reported: how far the shaft's tip moves,
248
+ // against the printer's fit clearance (what the parts it drives are drawn with), and the peak stress against the
249
+ // material's strength. Kept in .cache, like the other FE checks.
250
+ const sub3 = (a, b) => [a[0] - b[0], a[1] - b[1], a[2] - b[2]], add3 = (a, b) => [a[0] + b[0], a[1] + b[1], a[2] + b[2]];
251
+ const len3 = (a) => Math.hypot(a[0], a[1], a[2]);
252
+ function box3(pts) { const lo = [Infinity, Infinity, Infinity], hi = [-Infinity, -Infinity, -Infinity]; for (const p of pts) for (let k = 0; k < 3; k++) { if (p[k] < lo[k]) lo[k] = p[k]; if (p[k] > hi[k]) hi[k] = p[k]; } return { lo, hi }; }
253
+ // A small dense solve (Gaussian elimination, partial pivoting); a pivot near nothing is held at a hair, not divided by
254
+ function solveSmall(A, b) {
255
+ const n = b.length, M = A.map((r, i) => [...r, b[i]]), big = Math.max(1e-30, ...A.map((r, i) => Math.abs(r[i])));
256
+ for (let c = 0; c < n; c++) {
257
+ let p = c; for (let r = c + 1; r < n; r++) if (Math.abs(M[r][c]) > Math.abs(M[p][c])) p = r;
258
+ [M[c], M[p]] = [M[p], M[c]]; if (Math.abs(M[c][c]) < 1e-12 * big) M[c][c] = 1e-12 * big;
259
+ for (let r = 0; r < n; r++) if (r !== c) { const k = M[r][c] / M[c][c]; for (let q = c; q <= n; q++) M[r][q] -= k * M[c][q]; }
260
+ }
261
+ return M.map((r, i) => r[n] / r[i]);
262
+ }
263
+
264
+ /**
265
+ * The FE itself, in the motor's frame (the mounting face at z = 0, the shaft along z). tris: the part; holes: the screws'
266
+ * [x, y]; hole: their diameter; held: boxes ({ lo, hi }) and balls ({ at, r }) where the part is held, or null for its
267
+ * lowest face along `down`; weight: N at `centre`, along `down`; torque: N mm about z; tip: the shaft's tip.
268
+ * @returns {{ deflection: number, stress: number, atHoles: boolean, cell: number, across: number, held: string } | { missing: string }}
269
+ */
270
+ export function mountFE({ tris, holes, hole, plate, side, held, down, weight, centre, torque, tip, ref = null, E, nu, budget = 9000 }) {
271
+ const key = crypto.createHash('sha256').update(JSON.stringify([3, tris, holes, hole, plate, side, held, down, weight, centre, torque, tip, ref, E, nu, budget])).digest('hex').slice(0, 24), file = paths.cache('mount', `${key}.json`);
272
+ if (!process.env.CAD_NO_CACHE && host.exists(file)) return JSON.parse(host.readText(file));
273
+ const { lo, hi } = box3(tris.flat()), span = sub3(hi, lo);
274
+ let cell = Math.max(0.4, plate / 2);
275
+ const count = (h) => span.reduce((t, x) => t * Math.max(1, Math.ceil(x / h)), 1);
276
+ while (count(cell) > budget) cell *= 1.1;
277
+ const n = span.map((x) => Math.max(1, Math.ceil(x / cell))), gr = { nx: n[0], ny: n[1], nz: n[2], h: cell };
278
+ const density = solidFill(tris, gr, lo), g = makeGrid(gr), at = positions(g), pos = (id) => add3(lo, at[id]), onPart = new Uint8Array(g.nodes);
279
+ for (let e = 0; e < density.length; e++) if (density[e] >= 0.5) for (let k = 0; k < 8; k++) onPart[g.edof[e * 24 + 3 * k] / 3] = 1;
280
+ // Clamped: the plate round each screw, under its head (about twice the hole across), through the plate's thickness
281
+ const grip = hole / 2 + Math.max(hole / 2, 1.5 * cell), clamp = [], hold = [];
282
+ const inHeld = (p) => held.some((b) => (b.r != null ? len3(sub3(p, b.at)) <= Math.max(b.r, 2.5 * cell) : p.every((x, k) => x >= b.lo[k] - cell && x <= b.hi[k] + cell)));
283
+ let lowest = Infinity; if (!held) for (const t of tris) for (const p of t) lowest = Math.min(lowest, -(p[0] * down[0] + p[1] * down[1] + p[2] * down[2]));
284
+ for (let id = 0; id < g.nodes; id++) {
285
+ if (!onPart[id]) continue;
286
+ const p = pos(id), z = p[2] * side; // (the screws' clamp first: a part held all over its face is still loaded at them)
287
+ if (z >= -cell && z <= plate + cell && holes.some(([x, y]) => Math.hypot(p[0] - x, p[1] - y) <= grip)) clamp.push(id);
288
+ else if (held ? inHeld(p) : -(p[0] * down[0] + p[1] * down[1] + p[2] * down[2]) <= lowest + cell * 0.75) hold.push(id);
289
+ }
290
+ const heldBy = !held ? 'on its lowest face' : held.some((b) => b.r != null) ? 'at the joint that carries it' : 'where it is fastened';
291
+ if (!hold.length) return { missing: `nothing of it is held ${heldBy}` };
292
+ if (!clamp.length) return { missing: 'the screws are where it is held', cell };
293
+ // The motor's weight and torque, shared over the clamped nodes as a rigid body would put them there
294
+ const P = clamp.map(pos), c = P.reduce((t, p) => add3(t, p), [0, 0, 0]).map((x) => x / P.length), R = P.map((p) => sub3(p, c));
295
+ const J = [[0, 0, 0], [0, 0, 0], [0, 0, 0]]; for (const r of R) { const rr = r[0] * r[0] + r[1] * r[1] + r[2] * r[2]; for (let a = 0; a < 3; a++) for (let b = 0; b < 3; b++) J[a][b] += (a === b ? rr : 0) - r[a] * r[b]; }
296
+ const Fw = down.map((x) => x * weight), arm = sub3(centre, c), Mw = cross(arm, Fw);
297
+ const loads = [1, -1].map((sign) => {
298
+ const M = [Mw[0], Mw[1], Mw[2] + sign * torque], w = solveSmall(J, M), out = new Float64Array(g.dofs);
299
+ clamp.forEach((id, i) => { const t = cross(w, R[i]); for (let k = 0; k < 3; k++) out[3 * id + k] = Fw[k] / clamp.length + t[k]; });
300
+ return out;
301
+ });
302
+ const fixed = new Uint8Array(g.dofs); for (const id of hold) for (let k = 0; k < 3; k++) fixed[3 * id + k] = 1;
303
+ let a; try { a = analyse({ grid: g, density, material: { E, nu }, fixed, loads, backend: threadsBackend }); } catch (e) { return { missing: e.code === 'fea.unheld' ? `it isn't held still ${heldBy}` : e.message, cell }; }
304
+ // The motor moves as a rigid body with the clamped plate: the best fit of a shift and a small turn, at the shaft's tip
305
+ // Where the driven joint stands on this same part, the shaft is measured against the part there (they move together)
306
+ let base = null;
307
+ if (ref) { let best = Infinity; for (let id = 0; id < g.nodes; id++) if (onPart[id]) best = Math.min(best, len3(sub3(pos(id), ref))); base = []; for (let id = 0; id < g.nodes; id++) if (onPart[id] && len3(sub3(pos(id), ref)) <= best + cell) base.push(id); }
308
+ const rigid = (u) => {
309
+ const A = Array.from({ length: 6 }, () => new Array(6).fill(0)), b = new Array(6).fill(0);
310
+ clamp.forEach((id, i) => {
311
+ const [x, y, z] = R[i], rows = [[1, 0, 0, 0, z, -y], [0, 1, 0, -z, 0, x], [0, 0, 1, y, -x, 0]]; // u = t + θ × r
312
+ rows.forEach((row, k) => { for (let p = 0; p < 6; p++) { b[p] += row[p] * u[3 * id + k]; for (let q = 0; q < 6; q++) A[p][q] += row[p] * row[q]; } });
313
+ });
314
+ const s6 = solveSmall(A, b), moved = add3(s6.slice(0, 3), cross(s6.slice(3), sub3(tip, c)));
315
+ return len3(base ? sub3(moved, [0, 1, 2].map((q) => base.reduce((t, id) => t + u[3 * id + q], 0) / base.length)) : moved);
316
+ };
317
+ const deflection = Math.max(...a.u.map(rigid));
318
+ // A cell's stress is read at its centre, inside the surface: across k cells, bending reads (k - 1) / k of the surface's
319
+ const across = Math.max(2, Math.round(plate / cell)), lift = across / (across - 1);
320
+ let stress = 0, atHoles = false;
321
+ for (const st of a.stress) for (let e = 0; e < density.length; e++) {
322
+ if (density[e] < 0.5 || st[e] * lift <= stress) continue;
323
+ const p = add3(lo, [((e % n[0]) + 0.5) * cell, ((Math.floor(e / n[0]) % n[1]) + 0.5) * cell, (Math.floor(e / (n[0] * n[1])) + 0.5) * cell]);
324
+ stress = st[e] * lift; atHoles = holes.some(([x, y]) => Math.hypot(p[0] - x, p[1] - y) <= grip + cell);
325
+ }
326
+ const out = { deflection, relative: !!base, stress, atHoles, cell, across, held: heldBy, cells: g.cells };
327
+ host.writeText(file, JSON.stringify(out)); return out;
328
+ }
329
+
330
+ function mountBends(s, d, f, W, avail, mat, { other, parts, inv, plate, hd, worlds, mul }) {
331
+ const m = d.model, top = (x) => String(x).split(/[.@]/)[0], motion = s.motion, ids = motion.items.map((x) => x[0]);
332
+ if (!(mat?.modulus > 0) || !(mat?.strength > 0)) return;
333
+ const tris = parts.filter((p) => p.role !== 'support').flatMap((p) => p.triangles.map((t) => t.map(inv)));
334
+ // Where it's held: at the joint it hangs from, if it's carried by one (fixed to a link, or turning on a joint); else at
335
+ // the printed parts it's fastened to that sit below it (along gravity), not the motor nor anything bought
336
+ const g = motion.gravity || [0, 0, -1], gl = Math.hypot(...g) || 1, down = [0, 1, 2].map((r) => (W[r] * g[0] + W[4 + r] * g[1] + W[8 + r] * g[2]) / gl);
337
+ const k = ids.indexOf(other), from = motion.joints.find((j) => j.child === k), boxes = [];
338
+ if (from && worlds) boxes.push({ at: inv(axisOf(motion, worlds, from, mul).O), r: 8 });
339
+ else {
340
+ const motors = new Set((motion.drives || []).map((x) => x.id)), mine = box3(tris.flat()), depth = (b) => [0, 1, 2].reduce((t, q) => t + ((b.lo[q] + b.hi[q]) / 2) * down[q], 0);
341
+ for (const x of s.fits) {
342
+ if (!x.fastens || ![top(x.a), top(x.b)].includes(other)) continue;
343
+ const them = top(x.a) === other ? top(x.b) : top(x.a); if (them === d.id || motors.has(them)) continue;
344
+ const theirs = s.parts.filter((p) => (p.item === them || p.leaf === them) && p.role !== 'reference' && p.role !== 'support');
345
+ const b = theirs.length && box3(theirs.flatMap((p) => p.triangles.flat().map(inv)));
346
+ if (b && depth(b) > depth(mine)) boxes.push(b);
347
+ }
348
+ }
349
+ const fig = (x) => m.figures[x]?.value, hold = atCurrent(m, d.spec, fig('holding_torque') ?? fig('stall_torque') ?? 0), T = Math.max(avail, hold); // N m: the most it can put on its screws
350
+ const side = m.mount.side, centre = [m.body.centre[0], m.body.centre[1], (-side * m.body.length) / 2], tip = m.anchors.tip?.origin ?? [0, 0, m.shaft.tip];
351
+ const driven = motion.joints.find((j) => j.id === d.joint), ref = driven && driven.parent === k && worlds ? inv(axisOf(motion, worlds, driven, mul).O) : null;
352
+ const fe = mountFE({ tris, holes: m.mount.holes, hole: hd, plate, side, held: boxes.length ? boxes : null, down, weight: (m.mass ?? 0) * G, centre, torque: T * 1000, tip, ref, E: mat.modulus, nu: mat.poisson ?? 0.36 });
353
+ const S = rowsAt(W, tip), refs = { item: d.id, part: other }, name = mat.name.toUpperCase();
354
+ if (fe.missing) return f('warn', `${d.id} on ${other}: couldn't bend the part under the motor: ${fe.missing}. Fasten it to what holds it (a "fastens" fit)`, `${d.id}: mount not solved`, { code: 'motor.mount', at: S, refs });
355
+ let limit = 0.2; try { limit = d.spec.deflection != null ? s.num(d.spec.deflection) : peekRuleSet(printerOf(s.project)).rules.fit?.value ?? 0.2; } catch {}
356
+ const bend = limit / Math.max(fe.deflection, 1e-9), strong = mat.strength / Math.max(fe.stress, 1e-9), margin = Math.min(bend, strong), K = 2, bad = margin < K;
357
+ const where = fe.atHoles ? 'at the screw holes' : 'in the part, away from the screws';
358
+ const how = `FE on ${n3(fe.cell, 2)} mm cubes, ${fe.across} across the plate, held ${fe.held}; an estimate: cells this coarse read a plate 10 to 20% stiffer than it is`;
359
+ const said = `${d.id} on ${other}: under the motor's ${n3((m.mass ?? 0) * 1000, 0)} g and ${n3(T, 3)} N m, the shaft's tip moves ${n3(fe.deflection, 3)} mm${fe.relative ? ` against ${d.joint}'s seat on ${other}` : ''}, ${bend >= 1 ? `${n3(bend, 1)} times inside` : `${n3(1 / bend, 1)} times`} the ${n3(limit, 2)} mm fit the parts it drives are drawn with, and the stress peaks at ${n3(fe.stress, 2)} MPa ${where}, ${strong >= 1 ? `${n3(strong, 1)} times under` : `${n3(1 / strong, 1)} times`} ${name}'s ${mat.strength} MPa (${how})`;
360
+ let fix = '';
361
+ if (bad) {
362
+ const grow = Math.max(bend < K ? Math.cbrt(K / bend) : 1, strong < K ? Math.sqrt(K / strong) : 1), want = Math.ceil(plate * grow * 5) / 5; // bending goes with the cube of the thickness, stress with its square
363
+ fix = `. A plate about ${n3(want, 1)} mm thick where it bends (${n3(plate, 2)} mm at the screws now), or ribs under it, or a stiffer material (${bend < K ? `${n3((K / bend), 1)} times ${name}'s ${mat.modulus} MPa modulus` : `${n3((mat.strength * K) / strong, 0)} MPa strength or more`}), or hold it closer to the motor`;
364
+ }
365
+ f(bad ? 'fail' : 'pass', said + fix, bad ? `${d.id}: mount ${bend < strong ? 'bends' : 'overstressed'} ${n3(margin, 1)}×` : null, { code: 'motor.mount', at: S, refs, values: { deflection: fe.deflection, relative: fe.relative, limit, stress: fe.stress, strength: mat.strength, margin, cell: fe.cell, held: fe.held } });
233
366
  }
234
367
 
235
368
  // A "shaft" fit: a motor's shaft in the bore of a part. Reads the bore from the part as drawn: a slice across the
package/lib/motorsvg.mjs CHANGED
@@ -2,7 +2,7 @@
2
2
  // through its train, a bar for each stage, against what the load needs there. The numbers are the check's own.
3
3
  import { mul, jointValues, placeItems } from '@rulecad/model-link';
4
4
  import { curve } from '@rulecad/motors/diagram';
5
- import { motorChecks, trainFrom } from './motors.mjs';
5
+ import { motorChecks, trainFrom, axisOf } from './motors.mjs';
6
6
  import { materialOf } from './list.mjs';
7
7
 
8
8
  const esc = (s) => String(s).replace(/&/g, '&amp;').replace(/</g, '&lt;');
@@ -71,3 +71,26 @@ export function trainSvg(w, { title = '' } = {}) {
71
71
  const height = y + 8;
72
72
  return `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 ${width} ${height}" width="${width}" height="${height}">${out.join('')}</svg>\n`;
73
73
  }
74
+
75
+ // Labels for a check view: at each joint the motor's torque passes through, what reaches it and the margin; at the
76
+ // joint with the load, whether it holds with the power off. Never drawn on the rest view.
77
+ export function workMarks(s, works = motorWork(s)) {
78
+ const motion = s.motion, worlds = placeItems(motion, s.jointValues ?? jointValues(motion, motion.pose ?? undefined)), out = [];
79
+ for (const w of works) {
80
+ const stages = [...w.train.stages].reverse(), atMotor = w.available / (w.train.ratio * w.train.efficiency);
81
+ const where = (id) => { const j = motion.joints.find((x) => x.id === id); return j ? axisOf(motion, worlds, j, mul).O : null; };
82
+ const first = where(w.drive.joint);
83
+ if (first && stages.length) out.push({ at: first, text: `${w.id}: ${fig(atMotor)} N m at the shaft`, level: 'info' });
84
+ let have = atMotor;
85
+ for (const [k, st] of stages.entries()) {
86
+ const slide = w.train.slide != null && k === stages.length - 1;
87
+ have = slide ? w.available : have * (1 / Math.abs(st.ratio)) * st.efficiency;
88
+ const at = where(st.joint), last = k === stages.length - 1;
89
+ if (!at) continue;
90
+ const off = last ? w.holds.find((h) => /power off|no figure/.test(h.text)) : null;
91
+ out.push({ at, text: `${st.joint}: ${fig(have)} ${slide ? 'N' : 'N m'}${last ? `, ${fig(w.margin)}× the load${off ? `; unpowered ${off.level === 'pass' ? 'holds' : off.level === 'fail' ? 'slips' : 'unknown'}` : ''}` : ''}`, level: last ? w.level : 'info' });
92
+ }
93
+ if (!stages.length && first) out.push({ at: first, text: `${w.joint}: ${fig(w.available)} N m, ${fig(w.margin)}× the load`, level: w.level });
94
+ }
95
+ return out;
96
+ }
@@ -66,7 +66,30 @@ views.forEach(([name, pos], i) => {
66
66
  renderer.render(scene, cam);
67
67
  const l = document.createElement('div'); l.className = 'label'; l.textContent = name;
68
68
  l.style.left = `${x + 32}px`; l.style.top = `${(i < 3 ? 112 : V + 24)}px`; document.body.append(l);
69
+ if (data.marks?.length && (name === '3/4' || name === 'front')) marks(cam, x, i < 3 ? 0 : V);
69
70
  });
71
+
72
+ // A check view's labels: a dot at each point, a line to its text, the texts stacked along the foot of the view in
73
+ // the order their points are, so none sits on another or on its point
74
+ function marks(cam, x0, top) {
75
+ const NS = 'http://www.w3.org/2000/svg', svg = document.createElementNS(NS, 'svg');
76
+ document.body.append(svg); // in the page first, so text can be measured
77
+ svg.setAttribute('width', W); svg.setAttribute('height', H); svg.style.position = 'absolute'; svg.style.left = '0'; svg.style.top = '0';
78
+ const colour = { pass: '#7bd88f', warn: '#f0b44c', fail: '#ff6b5b', info: '#d0d0d0' };
79
+ const pts = data.marks.map((m) => { const v = new THREE.Vector3(m.at[0], m.at[2], -m.at[1]).sub(center).project(cam); return { ...m, px: x0 + ((v.x + 1) / 2) * V, py: top + ((1 - v.y) / 2) * V }; }).sort((a, b) => a.py - b.py);
80
+ const gapY = 30, right = x0 + V - 16;
81
+ pts.forEach((p, k) => { p.row = top + V - 28 - (pts.length - 1 - k) * gapY; }); // stacked along the view's foot, in their points' order
82
+ for (const p of pts) {
83
+ const y = p.row;
84
+ const c = colour[p.level] || colour.info, add = (tag, a) => { const e = document.createElementNS(NS, tag); for (const [k, v] of Object.entries(a)) e.setAttribute(k, v); svg.append(e); return e; };
85
+ // the text right-aligned in the view, on a dark backing so it reads over a part; the line to its left end
86
+ const t = add('text', { x: right, y: y + 5, fill: c, 'font-size': 15, 'text-anchor': 'end', 'font-family': '-apple-system, Helvetica Neue, sans-serif' }); t.textContent = p.text;
87
+ const w = t.getComputedTextLength(), left = right - w;
88
+ const back = add('rect', { x: left - 6, y: y - 11, width: w + 12, height: 22, rx: 4, fill: '#000', 'fill-opacity': 0.82 }); svg.insertBefore(back, t);
89
+ add('polyline', { points: `${p.px},${p.py} ${left - 10},${y} ${left - 6},${y}`, fill: 'none', stroke: c, 'stroke-width': 1.5 });
90
+ add('circle', { cx: p.px, cy: p.py, r: 5, fill: c });
91
+ }
92
+ }
70
93
  document.body.dataset.ready = '1';
71
94
  </script>
72
95
  </body></html>
package/lib/preview.mjs CHANGED
@@ -18,9 +18,9 @@ const CHROME = process.env.CAD_CHROME || [
18
18
  ].find((f) => fs.existsSync(f));
19
19
  const THREE = path.dirname(createRequire(import.meta.url).resolve('three')); // wherever npm put it
20
20
 
21
- export async function preview(parts, { title = '', meta = '', out, explode = false }) {
21
+ export async function preview(parts, { title = '', meta = '', out, explode = false, marks = null }) {
22
22
  const flat = (tris) => { const positions = []; for (const t of tris) for (let i = 1; i < t.length - 1; i++) positions.push(...t[0], ...t[i], ...t[i + 1]); return positions; };
23
- const data = JSON.stringify({ title, meta, explode, parts: parts.map((p) => ({ name: p.name, role: p.role, label: p.label, item: p.object || p.item, positions: flat(p.triangles) })) });
23
+ const data = JSON.stringify({ title, meta, explode, marks, parts: parts.map((p) => ({ name: p.name, role: p.role, label: p.label, item: p.object || p.item, positions: flat(p.triangles) })) });
24
24
  const server = http.createServer((req, res) => {
25
25
  const u = new URL(req.url, 'http://x').pathname;
26
26
  const send = (type, body) => { res.writeHead(200, { 'Content-Type': type }); res.end(body); };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@rulecad/cad",
3
- "version": "0.7.45",
3
+ "version": "0.7.47",
4
4
  "description": "The cad command: JSCAD designs from traceable rules, checked for printing and fit, versioned by what fits, shared as links and exported as Bambu 3MF.",
5
5
  "type": "module",
6
6
  "bin": {