@rulecad/cad 0.7.37 → 0.7.40
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 +423 -1
- package/README.md +14 -0
- package/bin/cad.mjs +31 -1
- package/lib/assembly.mjs +40 -11
- package/lib/design.mjs +4 -3
- package/lib/motors.mjs +265 -0
- package/lib/sandbox-hooks.mjs +2 -2
- package/lib/sandbox-run.mjs +2 -1
- package/lib/sandbox.mjs +1 -1
- package/lib/sheet.mjs +136 -0
- package/package.json +5 -4
- package/schemas/assembly.schema.json +6 -0
- package/schemas/rules.schema.json +3 -0
package/lib/assembly.mjs
CHANGED
|
@@ -30,8 +30,9 @@ import { bounds } from '@rulecad/printcheck';
|
|
|
30
30
|
import { closest, closestAt, inside, distanceToFace, overlapAt } from '@rulecad/fit';
|
|
31
31
|
import { keys as keyCentres, readLayout, hasLayout } from './layout.mjs';
|
|
32
32
|
import { DOFS, frame, turn, mul, pathLength, jointValues, placeItems, jointMatrix } from '@rulecad/model-link';
|
|
33
|
-
import { gearModel, internalModel, rackModel, mesh as meshOf, phase, rackPhase, contact, wormModel, wormMesh, bevelModel, bevelMesh } from '@rulecad/gears';
|
|
33
|
+
import { gearModel, internalModel, rackModel, mesh as meshOf, phase, rackPhase, contact, wormModel, wormMesh, bevelModel, bevelMesh, compoundEfficiency } from '@rulecad/gears';
|
|
34
34
|
import { ops as booleans } from '@rulecad/shapes';
|
|
35
|
+
import { motorBuilt, motorDrives, shaftFits, loadsOf, motorChecks, shaftFit } from './motors.mjs';
|
|
35
36
|
|
|
36
37
|
export const assemblyPath = (ref) => { const [project, name] = String(ref).split('/'); return path.join(paths.project(project || ''), 'assemblies', `${name || ''}.json`); };
|
|
37
38
|
export const isAssembly = (ref) => String(ref).includes('/') && host.exists(assemblyPath(ref.split('@')[0]));
|
|
@@ -94,6 +95,7 @@ export async function buildAssembly(ref, stack = [], overrides = {}, opts = {})
|
|
|
94
95
|
for (const [k, r] of Object.entries(a.requires || {})) requires.push({ object: k, range: r, from: ref });
|
|
95
96
|
const built = new Map(); // each object or component is built once per set of values, however many copies are placed
|
|
96
97
|
const source = async (it, extra) => {
|
|
98
|
+
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); }
|
|
97
99
|
// from: inputs worked out from items built before this one ({ "usb_y": "board.pcb.pico_y" }): numbers, in this
|
|
98
100
|
// assembly's names, so a part can take a value only another part knows once it's built
|
|
99
101
|
const from = Object.fromEntries(Object.entries(it.from || {}).map(([k, x]) => [k, num(x)]));
|
|
@@ -130,7 +132,7 @@ export async function buildAssembly(ref, stack = [], overrides = {}, opts = {})
|
|
|
130
132
|
let builtCount = 0;
|
|
131
133
|
for (const it of a.items || []) {
|
|
132
134
|
if (!/^[a-z][\w-]*$/.test(it.id || '')) throw new Error(`each item needs an id (letters, digits, - or _): got ${JSON.stringify(it.id)}`);
|
|
133
|
-
if (
|
|
135
|
+
if ([it.object, it.assembly, it.motor].filter(Boolean).length !== 1) throw new Error(`item ${it.id}: give one of "object", "assembly" or "motor"`);
|
|
134
136
|
// Copies: one, a grid from repeat x/y, or a layout's keys. Each: { id, offset (from at), extra (values to set) }
|
|
135
137
|
const rx = it.repeat?.x, ry = it.repeat?.y, rl = it.repeat?.layout, copies = [];
|
|
136
138
|
if (rl) {
|
|
@@ -184,6 +186,7 @@ export async function buildAssembly(ref, stack = [], overrides = {}, opts = {})
|
|
|
184
186
|
for (const c of copies) { placed.push([it, c]); ids.push(c.id); }
|
|
185
187
|
}
|
|
186
188
|
const motion = motionOf(a, placed, num, ref);
|
|
189
|
+
fits.push(...shaftFits(motion.drives, motion.joints, placed.map(([, c]) => c.id)).map((x) => ({ ...x, num })));
|
|
187
190
|
for (const [it, c] of placed) {
|
|
188
191
|
const src = c.src, id = c.id;
|
|
189
192
|
if (src.sub) {
|
|
@@ -339,7 +342,7 @@ function motionOf(a, placed, num, ref) {
|
|
|
339
342
|
joints.push({ id: j.id, type: j.type, parent: p.item, child: c.item, a: p.frame, b: c.frame, dofs,
|
|
340
343
|
...(j.label ? { label: j.label } : {}), ...(path ? { path } : {}), ...(j.cone != null ? { cone: num(j.cone) } : {}),
|
|
341
344
|
...(j.follow ? { follow: [j.follow, j.ratio != null ? num(j.ratio) : 1, j.offset != null ? num(j.offset) : 0] } : {}),
|
|
342
|
-
...(j.mesh ? { meshSpec: j.mesh } : {}) });
|
|
345
|
+
...(j.mesh ? { meshSpec: j.mesh } : {}), ...(j.brake ? { brake: j.brake } : {}) });
|
|
343
346
|
}
|
|
344
347
|
for (const j of joints) if (j.follow) {
|
|
345
348
|
const l = joints.find((x) => x.id === j.follow[0]);
|
|
@@ -353,6 +356,7 @@ function motionOf(a, placed, num, ref) {
|
|
|
353
356
|
return [c.id, ...rows(translate(base, rotate(rot, translate([c.offset[0], c.offset[1], 0], jscad.geometries.geom3.create()))).transforms)];
|
|
354
357
|
});
|
|
355
358
|
const meshes = [...gearMeshes(joints, items, num), ...planetaries(a.planetary || [], joints, items, num)];
|
|
359
|
+
const drives = motorDrives(a, placed, joints, num), loads = loadsOf(a, anchor, num, joints);
|
|
356
360
|
const poses = Object.fromEntries(Object.entries(a.poses || {}).map(([n, set]) => [n, Object.fromEntries(Object.entries(set).filter(([id]) => !id.includes('.')).map(([id, v]) => {
|
|
357
361
|
if (!joints.some((j) => j.id === id)) throw new Error(`pose ${n}: no joint "${id}"`);
|
|
358
362
|
return [id, Array.isArray(v) ? v.map(num) : num(v)];
|
|
@@ -364,7 +368,7 @@ function motionOf(a, placed, num, ref) {
|
|
|
364
368
|
const marks = placed.flatMap(([, c], k) => Object.entries(c.src?.b?.object.anchors || {}).map(([name, spec]) => {
|
|
365
369
|
try { return { item: k, id: c.id, name, frame: frameOf(spec, evalIn(c.src.b.values, `${c.src.objName} anchor ${name}`)) }; } catch { return null; }
|
|
366
370
|
})).filter(Boolean);
|
|
367
|
-
return { items, joints, poses, pose: a.pose || Object.keys(poses)[0], loops, ref, marks, meshes };
|
|
371
|
+
return { items, joints, poses, pose: a.pose || Object.keys(poses)[0], loops, ref, marks, meshes, drives, loads, gravity: (a.gravity || [0, 0, -1]).map(num) };
|
|
368
372
|
}
|
|
369
373
|
|
|
370
374
|
// A pair measured from its drawn teeth (@rulecad/gears contact: backlash, transmission error, interference), kept in
|
|
@@ -429,15 +433,16 @@ function planetaries(list, joints, items, num) {
|
|
|
429
433
|
// the third's rotation for the driver's: from the relation, with the held one still
|
|
430
434
|
const rot = (d) => { const r = { [held[0]]: 0, [drive]: sg[drive] * d }; r[third] = (sigma0 - coef[drive] * r[drive]) / coef[third]; return r; };
|
|
431
435
|
// a straight line in the driver's value (f: degrees in, radians out): [ratio, offset in degrees]
|
|
432
|
-
const lin = (f) => { const a = f(0), b = f(1); return [(b - a) / DEG,
|
|
436
|
+
const lin = (f) => { const a = f(0), b = f(1), o = a / DEG; return [(b - a) / DEG, ((o + 180) % 360 + 360) % 360 - 180]; }; // (the offset a part-turn: a whole turn is the same place)
|
|
437
|
+
const free = (j) => { j.dofs[0] = [-1e6, 1e6, j.dofs[0][2]]; }; // what follows a sun can turn past a turn
|
|
433
438
|
const [k3, o3] = lin((d) => sg[third] * rot(d * DEG)[third]);
|
|
434
|
-
follower.follow = [lead.id, k3, o3];
|
|
439
|
+
follower.follow = [lead.id, k3, o3]; free(follower);
|
|
435
440
|
const findings = [], f = (level, text, code, between) => findings.push({ level, text, code, ...(between ? { between } : {}) });
|
|
436
441
|
pl.forEach((p, i) => {
|
|
437
442
|
// the planet's first tooth from the sun's mesh: π = −(S/P) σ + β (1 + S/P) + π − π/P, β the planet's place
|
|
438
443
|
const tooth = (d) => { const r = rot(d * DEG), beta = p.beta + r.carrier; return -(S / P) * r.sun + beta * (1 + S / P) + Math.PI - Math.PI / P; };
|
|
439
444
|
const [kp, op] = lin((d) => p.s * (tooth(d) - p.gamma - rot(d * DEG).carrier));
|
|
440
|
-
p.joint.follow = [lead.id, kp, op];
|
|
445
|
+
p.joint.follow = [lead.id, kp, op]; free(p.joint);
|
|
441
446
|
// and with the ring: in phase with it too, or it can't go there
|
|
442
447
|
const ringTooth = (P / R) * tooth(0) + p.beta * (1 - P / R) - Math.PI / R, pitch = (2 * Math.PI) / R;
|
|
443
448
|
const miss = (((ringTooth - gr) % pitch) + pitch * 1.5) % pitch - pitch / 2;
|
|
@@ -451,7 +456,25 @@ function planetaries(list, joints, items, num) {
|
|
|
451
456
|
}
|
|
452
457
|
});
|
|
453
458
|
const ratioText = `the ${drive} drives the ${third}${held[0] === 'carrier' ? '' : ' and the planets'} (the ${held[0]} held): ${Number(Math.abs(k3).toFixed(4))} turns of the ${third} for each turn of the ${drive}, ${k3 * sg[drive] * sg[third] < 0 ? 'opposite ways' : 'the same way'}`;
|
|
454
|
-
out.push({ joint: follower.id, with: lead.id, kind: 'planetary', text: ratioText, findings, between: [O, O], planetary: true });
|
|
459
|
+
out.push({ joint: follower.id, with: lead.id, kind: 'planetary', text: ratioText, findings, between: [O, O], planetary: true, members: [follower.id, ...planetJoints.map((j) => j.id)] });
|
|
460
|
+
// A second ring, on the planets' second step: it follows the planets' turning as the first ring would
|
|
461
|
+
if (g.output) {
|
|
462
|
+
const k2 = index(g.output.ring, 'output ring'), j2 = moving(k2), P2 = num(g.output.planet), R2 = num(g.output.teeth), oc = { ...common };
|
|
463
|
+
if (!j2 || j2.type !== 'revolute') throw new Error(`${what}: the output ring ${g.output.ring} turns on a revolute`);
|
|
464
|
+
if (j2.follow || j2.meshSpec) throw new Error(`${what}: ${j2.id} follows the planets here: give it no follow or mesh of its own`);
|
|
465
|
+
if (R2 - P2 !== R - P) throw new Error(`${what}: the output ring and the planets' second step must differ as the first do: ${R2} - ${P2} isn't ${R} - ${P}, so one centre distance can't serve both`);
|
|
466
|
+
let p2, r2;
|
|
467
|
+
try { p2 = gearModel({ ...oc, teeth: P2 }); r2 = internalModel({ ...oc, teeth: R2 }); } catch (e) { throw new Error(`${what}: ${e.message}`); }
|
|
468
|
+
const g2 = ang(flat(col(W(k2), 0), Z), X0, Z), s2 = sign(j2), p0 = pl[0], ps = Math.PI / R2;
|
|
469
|
+
const toothAt = (d) => { const r = rot(d * DEG); return -(S / P) * r.sun + (p0.beta + r.carrier) * (1 + S / P) + Math.PI - Math.PI / P; };
|
|
470
|
+
const ring2 = (d) => { const r = rot(d * DEG); return (P2 / R2) * toothAt(d) + (p0.beta + r.carrier) * (1 - P2 / R2) - ps - g2; };
|
|
471
|
+
const [k, o] = lin((d) => s2 * ring2(d));
|
|
472
|
+
j2.follow = [lead.id, k, o]; free(j2);
|
|
473
|
+
const eff = compoundEfficiency({ planet: P, planet2: P2, ring: R, ring2: R2 }), fails = [], ff = (level, text, code) => fails.push({ level, text, code, between: [O, O] });
|
|
474
|
+
for (const x of meshOf(p2, r2, { centre: pl[0].r }).findings) ff(x.level, `${pl[0].id} and the output ring: ${x.text}`, x.code);
|
|
475
|
+
pl.forEach((p, i) => { const t2 = (P2 / R2) * ((-(S / P) * sigma0 + p.beta * (1 + S / P) + Math.PI - Math.PI / P)) + p.beta * (1 - P2 / R2) - ps, pitch2 = (2 * Math.PI) / R2, miss = (((t2 - (P2 / R2) * ((-(S / P) * sigma0 + p0.beta * (1 + S / P) + Math.PI - Math.PI / P)) - p0.beta * (1 - P2 / R2) + ps) % pitch2) + pitch2 * 1.5) % pitch2 - pitch2 / 2; if (Math.abs(miss) > 1e-6) ff('fail', `planet ${p.id} can't mesh with the output ring where it is: every tooth count a multiple of the planets puts them all in phase`, 'planetary.phase'); });
|
|
476
|
+
out.push({ joint: j2.id, with: lead.id, kind: 'planetary', efficiency: eff, text: `the second ring turns ${Number(Math.abs(k).toFixed(5))} of the ${drive}'s turn, ${k * s2 * sg[drive] < 0 ? 'the other way' : 'the same way'} (${Number((1 / Math.abs(k)).toFixed(2))}:1, about ${Math.round(eff * 100)}% efficient, an estimate)`, findings: fails, between: [O, O], planetary: true });
|
|
477
|
+
}
|
|
455
478
|
});
|
|
456
479
|
return out;
|
|
457
480
|
}
|
|
@@ -527,7 +550,7 @@ function wormDrive(j, lead, spec, teeth, common, joints, items, num) {
|
|
|
527
550
|
const m = wormMesh({ ...common, starts: teeth[0], ...(ws.diameter != null ? { diameter: num(ws.diameter) } : {}), ...(ws.hand ? { hand: ws.hand } : {}) }, { teeth: teeth[1] });
|
|
528
551
|
const c = meshOf(wheel, rackModel({ ...common, teeth: 4 }), { centre: dist - w.pitch / 2 });
|
|
529
552
|
const findings = [...m.findings, ...c.findings.filter((x) => x.code === 'mesh.centre').map((x) => ({ ...x, text: x.text.replace("centre to the rack's pitch line", "the wheel's centre to the worm's pitch cylinder") }))];
|
|
530
|
-
return { joint: j.id, with: lead.id, kind: 'worm', findings, between: [Ow.map((x, i) => x + U[i] * at), O2], text: `a worm of ${teeth[0]} start${teeth[0] > 1 ? 's' : ''}, ${Number((teeth[1] / teeth[0]).toFixed(3))} turns of the worm for one of the wheel` };
|
|
553
|
+
return { joint: j.id, with: lead.id, kind: 'worm', worm: m, findings, between: [Ow.map((x, i) => x + U[i] * at), O2], text: `a worm of ${teeth[0]} start${teeth[0] > 1 ? 's' : ''}, ${Number((teeth[1] / teeth[0]).toFixed(3))} turns of the worm for one of the wheel` };
|
|
531
554
|
}
|
|
532
555
|
|
|
533
556
|
// Gears that mesh: "mesh": { "with": <the driving joint>, "module", "teeth": [its, this one's], "shift"?, "ring"? } on
|
|
@@ -652,6 +675,9 @@ function saveOverlaps() {
|
|
|
652
675
|
}
|
|
653
676
|
|
|
654
677
|
// checkAssembly(built) -> findings, as @rulecad/printcheck: { level, text, card? } (card: a short line for the mirror)
|
|
678
|
+
// What a project prints in, for the motors' heat and press-fit checks
|
|
679
|
+
const materialOf = (project) => { try { return readJson(path.join(paths.project(project), 'project.json')).material; } catch { return null; } };
|
|
680
|
+
|
|
655
681
|
export function checkAssembly(s) {
|
|
656
682
|
const out = [], f = (level, text, card, extra) => out.push({ level, text, ...(card && { card }), ...extra }), mm = (n) => `${Number(n.toFixed(3))}`;
|
|
657
683
|
// Versions: every pin, from this assembly and its components, against every copy of that object
|
|
@@ -696,7 +722,9 @@ export function checkAssembly(s) {
|
|
|
696
722
|
for (const x of s.fits) {
|
|
697
723
|
if (x.poses && !x.poses.includes(s.pose)) continue; // a fit for some poses only: the folded screen over the keys
|
|
698
724
|
if (x.holes) { holesFit(x); continue; }
|
|
725
|
+
if (x.silent) continue; // lets a pair overlap, and has nothing to report
|
|
699
726
|
if (x.engage != null) { engageFit(x); continue; }
|
|
727
|
+
if (x.shaft != null) { shaftFit(x, s, f, { placeItems, jointValues, mul, materialName: materialOf(s.project) }); continue; }
|
|
700
728
|
const A = pickIn(x.a, x), key = x.note || `${x.a} / ${x.b}`;
|
|
701
729
|
const lo = x.min != null ? x.num(x.min) : -Infinity, hi = x.max != null ? x.num(x.max) : Infinity;
|
|
702
730
|
const reach = Math.max(2, ...[lo, hi].filter(Number.isFinite)) + 1; // look past the range, so a gap near it is measured
|
|
@@ -806,6 +834,7 @@ export function checkAssembly(s) {
|
|
|
806
834
|
}
|
|
807
835
|
}
|
|
808
836
|
}
|
|
837
|
+
motorChecks(s, f, { placeItems, jointValues, mul }, materialOf(s.project));
|
|
809
838
|
// Plates print everything: no references
|
|
810
839
|
if (s.a.kind === 'plate') {
|
|
811
840
|
const refs = s.objects.filter((o) => o.role === 'reference' && !o.unplaced); // an unplaced item only lends its numbers
|
|
@@ -898,8 +927,8 @@ export function motionData(s) {
|
|
|
898
927
|
}));
|
|
899
928
|
return { motion: {
|
|
900
929
|
items: mo.items.map(([n, ...m]) => [n, ...m.map(r)]),
|
|
901
|
-
joints: mo.joints.map(({ id, type, parent, child, a, b, dofs, label, follow, path, cone }) => ({ id, type, parent, child, a: a.map(r), b: b.map(r), dofs: dofs.map((d) => d.map(r)),
|
|
902
|
-
...(label ? { label } : {}), ...(follow ? { follow } : {}), ...(path ? { path: path.map((p) => p.map(r)) } : {}), ...(cone != null ? { cone } : {}) })),
|
|
930
|
+
joints: mo.joints.map(({ id, type, parent, child, a, b, dofs, label, follow, path, cone, step }) => ({ id, type, parent, child, a: a.map(r), b: b.map(r), dofs: dofs.map((d) => d.map(r)),
|
|
931
|
+
...(label ? { label } : {}), ...(follow ? { follow } : {}), ...(path ? { path: path.map((p) => p.map(r)) } : {}), ...(cone != null ? { cone } : {}), ...(step ? { step } : {}) })),
|
|
903
932
|
poses: mo.poses, ...(s.pose ? { pose: s.pose } : {}),
|
|
904
933
|
part: s.parts.map((p) => names.indexOf(p.item)),
|
|
905
934
|
...(allow.length ? { allow } : {}),
|
package/lib/design.mjs
CHANGED
|
@@ -33,6 +33,7 @@ import { optimised, forDesign } from './optimise.mjs';
|
|
|
33
33
|
import * as shapes from '@rulecad/shapes';
|
|
34
34
|
import * as flexures from '@rulecad/flexures';
|
|
35
35
|
import * as gears from '@rulecad/gears';
|
|
36
|
+
import * as motors from '@rulecad/motors';
|
|
36
37
|
import { engineId, packageVersion, materialise } from './versions.mjs';
|
|
37
38
|
import { satisfies } from '@rulecad/versions';
|
|
38
39
|
|
|
@@ -126,11 +127,11 @@ const CACHE = paths.cache('builds'), CACHE_VERSION = 3;
|
|
|
126
127
|
const source = (f) => fs.readFileSync(new URL(f, import.meta.url), 'utf8');
|
|
127
128
|
// What every build is made with: this code, the shape helpers and JSCAD's version (an upgrade rebuilds everything);
|
|
128
129
|
// boards also with the board engine (engineId: its code and tscircuit's version), loaded only for boards
|
|
129
|
-
const shapesDir = path.dirname(fileURLToPath(import.meta.resolve('@rulecad/shapes'))), flexuresDir = path.dirname(fileURLToPath(import.meta.resolve('@rulecad/flexures'))), gearsDir = path.dirname(fileURLToPath(import.meta.resolve('@rulecad/gears')));
|
|
130
|
+
const shapesDir = path.dirname(fileURLToPath(import.meta.resolve('@rulecad/shapes'))), flexuresDir = path.dirname(fileURLToPath(import.meta.resolve('@rulecad/flexures'))), gearsDir = path.dirname(fileURLToPath(import.meta.resolve('@rulecad/gears'))), motorsDir = path.dirname(fileURLToPath(import.meta.resolve('@rulecad/motors')));
|
|
130
131
|
// (every module of a helper package but its tests: they change nothing a design builds)
|
|
131
132
|
const helperSources = (dir) => fs.readdirSync(dir).filter((f) => f.endsWith('.mjs') && f !== 'test.mjs').sort().map((f) => source(pathToFileURL(path.join(dir, f)).href)).join('');
|
|
132
133
|
const feaDir = path.dirname(createRequire(pathToFileURL(path.join(flexuresDir, 'package.json')).href).resolve('@rulecad/fea')); // (flexures' own, wherever npm put it)
|
|
133
|
-
const own = source(import.meta.url) + helperSources(shapesDir) + helperSources(flexuresDir) + helperSources(gearsDir) + helperSources(feaDir) + packageVersion('@jscad/modeling'); // every shapes module, not just its entry
|
|
134
|
+
const own = source(import.meta.url) + helperSources(shapesDir) + helperSources(flexuresDir) + helperSources(gearsDir) + helperSources(motorsDir) + helperSources(feaDir) + packageVersion('@jscad/modeling'); // every shapes module, not just its entry
|
|
134
135
|
// A lamina's slow stages (the physics, the flood's probe) are kept apart from the builds, keyed by the library's code
|
|
135
136
|
// and their own inputs, so a build that changes only what comes after them (a strap, a check, a rule's words) has them
|
|
136
137
|
// at once: .cache/stages/. A design in the sandbox can't write them, so the sandbox hands them back and the tool writes them
|
|
@@ -220,7 +221,7 @@ export async function build(d, set = {}, { mirror = false } = {}) {
|
|
|
220
221
|
throw syntaxAt(located(e, d.js, 'design.run'), d);
|
|
221
222
|
});
|
|
222
223
|
if (typeof mod.main !== 'function') throw new Error(`${path.relative(WS, d.js)} has no exported main(v)`);
|
|
223
|
-
const w = watch(values, { shapes, flexures, gears, ops: await shapes.ops(booleans(object)), ...(pcb ? { pcb } : {}) }, optional);
|
|
224
|
+
const w = watch(values, { shapes, flexures, gears, motors, ops: await shapes.ops(booleans(object)), ...(pcb ? { pcb } : {}) }, optional);
|
|
224
225
|
read = w.read;
|
|
225
226
|
let made;
|
|
226
227
|
try { ({ shapes: made, mechanism } = unpack(await mod.main(w.v))); } catch (e) { throw Object.assign(located(e, d.js, 'design.run'), { line: lineOf(e, pathToFileURL(d.js).href) || undefined }); }
|
package/lib/motors.mjs
ADDED
|
@@ -0,0 +1,265 @@
|
|
|
1
|
+
// Motors in assemblies: an item with "motor" is drawn from @rulecad/motors, its shaft turns a joint (the assembly's
|
|
2
|
+
// slider is the motor turning), and the assembly can say what it has to do: "loads" on joints or masses on links.
|
|
3
|
+
// From those, what reaches each loaded joint through the meshes and planetaries, whether the joint holds with the
|
|
4
|
+
// power on and off, and whether the shaft and its mount are fit for it.
|
|
5
|
+
import crypto from 'node:crypto';
|
|
6
|
+
import { createRequire } from 'node:module';
|
|
7
|
+
import { motorModel, motorParts, mountModel, performance } from '@rulecad/motors';
|
|
8
|
+
import { stageEfficiency } from '@rulecad/gears';
|
|
9
|
+
import { named } from './parts.mjs';
|
|
10
|
+
|
|
11
|
+
const require = createRequire(import.meta.url);
|
|
12
|
+
const n3 = (x, d = 3) => String(Number(x.toFixed(d)));
|
|
13
|
+
const G = 9.80665; // m/s²
|
|
14
|
+
|
|
15
|
+
// A motor item, built: its parts (body and shaft), anchors from its model, its figures as values and rules
|
|
16
|
+
export function motorBuilt(spec, num, id) {
|
|
17
|
+
const what = `item ${id}: motor`;
|
|
18
|
+
if (!spec || typeof spec !== 'object' || !spec.model) throw new Error(`${what}: give { "model": "nema17", "drives": "<joint>" }`);
|
|
19
|
+
const set = Object.fromEntries(Object.entries(spec.set || {}).map(([k, v]) => { if (typeof v !== 'string') return [k, v]; try { return [k, num(v)]; } catch { return [k, v]; } }));
|
|
20
|
+
const model = motorModel(spec.model, set), { body, shaft } = motorParts(model);
|
|
21
|
+
const parts = named(shaft ? { body, shaft } : { body }, { body: { label: `${model.name} body` }, ...(shaft ? { shaft: { label: `${model.name} shaft` } } : {}) });
|
|
22
|
+
const anchors = Object.fromEntries(Object.entries(model.anchors).map(([k, a]) => [k, { at: a.origin, axis: a.axis }]));
|
|
23
|
+
const values = Object.fromEntries(Object.entries(model.figures).filter(([, f]) => typeof f.value === 'number').map(([k, f]) => [k, f.value]));
|
|
24
|
+
const entries = Object.entries(model.figures).map(([k, f]) => ({ name: `${model.name}.${k}`, value: f.value, unit: f.unit, rule: f.rule, kind: f.kind, source: f.source, checked: f.checked, set: model.name }));
|
|
25
|
+
const hash = crypto.createHash('sha256').update(JSON.stringify(model.figures)).digest('hex').slice(0, 16);
|
|
26
|
+
const b = { object: { name: model.name, title: model.name, role: 'reference', version: '0.0.0', anchors }, values, entries, deps: [], units: {}, parts, polygons: parts.flatMap((p) => p.polygons), triangles: parts.flatMap((p) => p.triangles), hash };
|
|
27
|
+
return { key: `motor:${id}:${hash}`, objName: `motor:${model.name}`, b, version: '0.0.0', role: 'reference', motor: model, spec };
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
// Which joint each motor drives, checked by name; a servo's range and a stepper's step go on the joint. The shaft
|
|
31
|
+
// turns in what it drives, so that pair may overlap: the body is still checked against everything.
|
|
32
|
+
export function motorDrives(a, placed, joints, num) {
|
|
33
|
+
const drives = [], taken = new Map();
|
|
34
|
+
placed.forEach(([it, c], k) => {
|
|
35
|
+
if (!it.motor) return;
|
|
36
|
+
const what = `item ${c.id}: motor`, id = it.motor.drives;
|
|
37
|
+
if (id == null) { drives.push({ item: k, id: c.id, model: c.src.motor, spec: it.motor, joint: null }); return; } // on the bench, turning nothing
|
|
38
|
+
const j = joints.find((x) => x.id === id);
|
|
39
|
+
if (!j) throw new Error(`${what}: drives "${id}", which isn't a joint (${joints.map((x) => x.id).join(', ') || 'none'})`);
|
|
40
|
+
if (j.type !== 'revolute') throw new Error(`${what}: a motor turns a revolute (${j.id} is a ${j.type}): drive the gear, and let the slide follow it`);
|
|
41
|
+
if (j.follow) throw new Error(`${what}: ${j.id} follows ${j.follow[0]}: a motor drives the joint that leads the train`);
|
|
42
|
+
if (taken.has(id)) throw new Error(`${what}: ${id} is driven by ${taken.get(id)} already: one motor to a joint`);
|
|
43
|
+
taken.set(id, c.id);
|
|
44
|
+
const model = c.src.motor, spec = (a.joints || []).find((x) => x.id === id);
|
|
45
|
+
if (model.range != null) {
|
|
46
|
+
const half = model.range / 2, d = j.dofs[0];
|
|
47
|
+
if (spec.min == null && spec.max == null) { d[0] = -half; d[1] = half; d[2] = Math.min(half, Math.max(-half, d[2])); }
|
|
48
|
+
else if (d[0] < -half - 1e-9 || d[1] > half + 1e-9) throw new Error(`${what}: a ${model.name} turns ${model.range}°, and ${j.id} asks for ${d[0]}° to ${d[1]}°`);
|
|
49
|
+
}
|
|
50
|
+
if (model.stepAngle) j.step = model.stepAngle;
|
|
51
|
+
drives.push({ item: k, id: c.id, model, spec: it.motor, joint: id });
|
|
52
|
+
});
|
|
53
|
+
return drives;
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
// The fits a motor brings with it, in the assembly's own shape
|
|
57
|
+
export const shaftFits = (drives, joints, ids) => drives.filter((d) => d.joint && d.model.shaft.length).map((d) => ({ a: `${d.id}.shaft`, b: ids[joints.find((j) => j.id === d.joint).child], min: -1000, silent: true }));
|
|
58
|
+
|
|
59
|
+
// "loads": [{ "joint": "elbow", "torque": 0.5 }, { "joint": "slide", "force": 12 }, { "mass": 0.2, "at": "forearm.tip" }]
|
|
60
|
+
export function loadsOf(a, anchor, num, joints) {
|
|
61
|
+
return (a.loads || []).map((l, i) => {
|
|
62
|
+
const what = `load ${i + 1}`;
|
|
63
|
+
if (l.mass != null) { if (l.at == null) throw new Error(`${what}: a mass needs "at", an anchor on what carries it`); const m = num(l.mass); if (!(m > 0)) throw new Error(`${what}: mass is above 0 kg (got ${m})`); return { mass: m, ...anchor(l.at, what), note: l.note }; }
|
|
64
|
+
const j = joints.find((x) => x.id === l.joint);
|
|
65
|
+
if (!j) throw new Error(`${what}: give a "mass" and "at", or a "joint" with its "torque" or "force" (joints: ${joints.map((x) => x.id).join(', ')})`);
|
|
66
|
+
if (j.type === 'prismatic' ? l.force == null : l.torque == null) throw new Error(`${what}: ${j.id} is a ${j.type}, so give its ${j.type === 'prismatic' ? 'force (N)' : 'torque (N m)'}`);
|
|
67
|
+
return { joint: j.id, value: num(j.type === 'prismatic' ? l.force : l.torque), note: l.note };
|
|
68
|
+
});
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
// ---------- the train from a motor to a joint ----------
|
|
72
|
+
// Walks up the follow links from a joint to the one that leads it: the turns of that lead per turn of this joint
|
|
73
|
+
// (or per mm, where the joint slides), the share of power that gets through, what's in the way.
|
|
74
|
+
function trainFrom(motion, id) {
|
|
75
|
+
const stages = [], meshes = motion.meshes || [];
|
|
76
|
+
let j = motion.joints.find((x) => x.id === id), ratio = 1, efficiency = 1, slide = j.type === 'prismatic' ? 1 : null, locks = null;
|
|
77
|
+
while (j.follow) {
|
|
78
|
+
const [lead, r] = j.follow, m = meshes.find((x) => x.joint === j.id) || meshes.find((x) => x.planetary && (x.members || []).includes(j.id));
|
|
79
|
+
const kind = m?.kind === 'external' ? 'spur' : m?.kind || 'spur';
|
|
80
|
+
const eff = m?.efficiency ?? stageEfficiency(kind, kind === 'worm' ? { worm: m.worm } : {});
|
|
81
|
+
efficiency *= eff; stages.push({ joint: j.id, kind, ratio: r, efficiency: eff });
|
|
82
|
+
if (kind === 'worm' && m.worm.locks) locks = `the worm (its ${n3(m.worm.leadAngle, 1)}° lead is under the friction angle)`;
|
|
83
|
+
if (slide != null && stages.length === 1) slide = Math.abs(r); // mm of slide for each degree of the gear
|
|
84
|
+
else ratio *= 1 / Math.abs(r);
|
|
85
|
+
j = motion.joints.find((x) => x.id === lead);
|
|
86
|
+
}
|
|
87
|
+
return { root: j.id, ratio, efficiency, stages, slide, locks };
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
// World axis of a joint and the world position of a point on an item
|
|
91
|
+
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]);
|
|
92
|
+
const axisOf = (motion, worlds, j, mul) => { const P = j.parent < 0 ? j.a : mul(worlds[j.parent], j.a); return { O: [P[3], P[7], P[11]], Z: [P[2], P[6], P[10]] }; };
|
|
93
|
+
const sub = (a, b) => a.map((x, i) => x - b[i]), dot = (a, b) => a[0] * b[0] + a[1] * b[1] + a[2] * b[2];
|
|
94
|
+
const cross = (a, b) => [a[1] * b[2] - a[2] * b[1], a[2] * b[0] - a[0] * b[2], a[0] * b[1] - a[1] * b[0]];
|
|
95
|
+
|
|
96
|
+
// The load at one joint, at one set of joint values (N m on a revolute, N on a slide), from every mass carried beyond it
|
|
97
|
+
function loadAt(motion, loads, worlds, j, mul) {
|
|
98
|
+
const { O, Z } = axisOf(motion, worlds, j, mul), byChild = new Map(motion.joints.map((x) => [x.child, x]));
|
|
99
|
+
const beyond = (k) => { for (let i = k, n = 0; i >= 0 && n < 99; n++) { const x = byChild.get(i); if (!x) return false; if (x === j) return true; i = x.parent; } return false; };
|
|
100
|
+
let total = 0;
|
|
101
|
+
for (const l of loads) {
|
|
102
|
+
if (l.joint === j.id) total += l.value;
|
|
103
|
+
else if (l.mass != null && beyond(l.item)) {
|
|
104
|
+
const X = rowsAt(worlds[l.item], [l.frame[3], l.frame[7], l.frame[11]]), g = motion.gravity || [0, 0, -1], F = g.map((c) => (c * l.mass * G) / Math.hypot(...g));
|
|
105
|
+
total += j.type === 'prismatic' ? dot(Z, F) : dot(Z, cross(sub(X, O), F)) / 1000;
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
return total;
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
// The worst load on a joint: at each named pose, and with the motor run through its range
|
|
112
|
+
function worstLoad(motion, loads, j, drive, { placeItems, jointValues, mul }) {
|
|
113
|
+
let worst = 0, where = null;
|
|
114
|
+
const look = (values, label) => { const t = loadAt(motion, loads, placeItems(motion, values), j, mul); if (Math.abs(t) > Math.abs(worst)) { worst = t; where = label; } };
|
|
115
|
+
const poses = Object.keys(motion.poses || {});
|
|
116
|
+
for (const p of poses.length ? poses : [null]) look(jointValues(motion, p ?? undefined), p);
|
|
117
|
+
const root = drive && motion.joints.find((x) => x.id === drive.joint);
|
|
118
|
+
if (root) {
|
|
119
|
+
const base = jointValues(motion, motion.pose ?? undefined), [lo, hi] = root.dofs[0];
|
|
120
|
+
for (let k = 0; k <= 24; k++) { const a = lo + ((hi - lo) * k) / 24, set = Object.fromEntries(Object.entries(base).filter(([id]) => !motion.joints.find((x) => x.id === id)?.follow)); look(jointValues(motion, { ...set, [root.id]: [a] }), `${root.id} at ${n3(a, 1)}°`); }
|
|
121
|
+
}
|
|
122
|
+
return { torque: Math.abs(worst), where };
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
// A motor's speed if the assembly doesn't say: its corner speed, its rated speed, or half its free speed
|
|
126
|
+
function workingSpeed(model, spec) {
|
|
127
|
+
if (spec.speed != null) return spec.speed;
|
|
128
|
+
const p = performance(model, {});
|
|
129
|
+
return model.type === 'dc' ? p.limit / 2 : model.figures.pull_in_torque ? p.limit : model.type === 'servo' ? p.limit : model.type === 'brushless' ? p.limit / 4 : p.limit / 5;
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
const material = (name) => { const n = String(name || 'pla').toLowerCase().split(/\s/)[0]; try { return { name: n, ...Object.fromEntries(Object.entries(require(`@rulecad/rules/${n}.json`).rules).map(([k, r]) => [k, r.value])) }; } catch { return null; } };
|
|
133
|
+
|
|
134
|
+
// The findings: f(level, text, card, extra), as the assembly's check makes them
|
|
135
|
+
export function motorChecks(s, f, helpers, materialName) {
|
|
136
|
+
const motion = s.motion, drives = motion?.drives || [], loads = motion?.loads || [], { placeItems, jointValues, mul } = helpers;
|
|
137
|
+
if (!drives.length) { if (loads.length) f('warn', `there are loads, but no motor: nothing has been checked against them (add a "motor" item that "drives" a joint)`, null, { code: 'motor.loads' }); return; }
|
|
138
|
+
const worlds = placeItems(motion, jointValues(motion, motion.pose ?? undefined));
|
|
139
|
+
for (const d of drives) {
|
|
140
|
+
const m = d.model, grams = n3(m.mass * 1000, 1), K = d.spec.margin != null ? d.spec.margin : 2, W = worlds[d.item];
|
|
141
|
+
f('info', `${d.id}: ${m.name}, ${grams} g${d.joint ? `, drives ${d.joint}` : ''}${m.stepAngle ? `, ${n3(m.stepAngle, 4)}° a step` : ''}${m.range ? `, ${m.range}° of travel` : ''}`, null, { code: 'motor.model', refs: { item: d.id, joint: d.joint }, values: { model: m.name, grams: m.mass * 1000, stepAngle: m.stepAngle } });
|
|
142
|
+
if (!d.joint) continue;
|
|
143
|
+
// Its shaft on the joint's axis
|
|
144
|
+
const j = motion.joints.find((x) => x.id === d.joint), { O, Z } = axisOf(motion, worlds, j, mul), S = rowsAt(W, m.anchors.shaft.origin), A = [W[2], W[6], W[10]];
|
|
145
|
+
const off = cross(sub(S, O), Z), apart = Math.hypot(...off), tilt = Math.abs(1 - Math.abs(dot(A, Z)));
|
|
146
|
+
if (apart > 0.05 || tilt > 1e-6) { f('fail', `${d.id}'s shaft isn't on ${d.joint}'s axis: ${n3(apart, 2)} mm off${tilt > 1e-6 ? ', and not parallel to it' : ''}`, `${d.id}: shaft off axis`, { code: 'motor.axis', at: S, refs: { item: d.id, joint: d.joint } }); continue; }
|
|
147
|
+
f('pass', `${d.id}'s shaft is on ${d.joint}'s axis`, null, { code: 'motor.axis', at: S });
|
|
148
|
+
// Everything it drives that carries a load
|
|
149
|
+
const driven = motion.joints.filter((x) => trainFrom(motion, x.id).root === d.joint).map((x) => ({ j: x, t: trainFrom(motion, x.id), load: worstLoad(motion, loads, x, d, helpers) })).filter((x) => x.load.torque > 0);
|
|
150
|
+
const motorSpeed = workingSpeed(m, d.spec), loaded = driven.length ? driven : [];
|
|
151
|
+
if (!loaded.length) {
|
|
152
|
+
const here = performance(m, { speed: motorSpeed });
|
|
153
|
+
f('info', `${d.id} gives ${n3(here.motor.torque)} N m at ${n3(motorSpeed, 1)} rpm; no loads on what it drives, so nothing to check that against (add "loads")`, null, { code: 'motor.torque' });
|
|
154
|
+
continue;
|
|
155
|
+
}
|
|
156
|
+
// Reflected to the motor's own shaft: what each load needs of it, and what it would take to hold against it
|
|
157
|
+
let need = 0, back = 0, backOn = 0;
|
|
158
|
+
const lines = [], at = (x) => axisOf(motion, worlds, x, mul).O;
|
|
159
|
+
let locked = null;
|
|
160
|
+
for (const { j: x, t, load } of loaded) {
|
|
161
|
+
// the lead's torque for a load here: a slide's force through the pinion, a revolute's torque down the ratio
|
|
162
|
+
const atLead = t.slide != null ? (load.torque * t.slide * 180) / Math.PI / 1000 : load.torque;
|
|
163
|
+
const unit = t.slide != null ? 'N' : 'N m', reduction = t.ratio;
|
|
164
|
+
const η = t.efficiency, needed = atLead / (reduction * η);
|
|
165
|
+
need += needed; const ηback = Math.max(0, 2 - 1 / η);
|
|
166
|
+
if (t.locks) locked = t.locks;
|
|
167
|
+
else if (η <= 0.5) locked = `the gears (${n3(η * 100, 0)}% forwards, under the 50% where they can't be driven backwards)`;
|
|
168
|
+
back += (atLead / reduction) * ηback; backOn += atLead / reduction;
|
|
169
|
+
lines.push({ x, t, load, unit, reduction, atLead, η });
|
|
170
|
+
}
|
|
171
|
+
const speedOut = motorSpeed / loaded[0].t.ratio, rated = performance(m, { speed: motorSpeed }), avail = rated.motor.torque, margin = need ? avail / need : Infinity;
|
|
172
|
+
const main = lines[0], what = main.unit === 'N m' ? `${n3(main.load.torque)} N m` : `${n3(main.load.torque, 2)} N`, gives = main.unit === 'N m' ? `${n3(avail * main.reduction * main.η)} N m` : `${n3((avail * main.reduction * main.η * Math.PI * 1000) / (main.t.slide * 180), 1)} N`;
|
|
173
|
+
const trust = rated.rests.filter((k) => k !== 'spec' && k !== 'measured'), caveat = trust.length ? ` (rests on ${trust.join(' and ')} figures: measure it)` : '';
|
|
174
|
+
const level = margin < 1 ? 'fail' : margin < K ? 'warn' : 'pass', fix = margin < 1 && main.t.slide == null ? ` A ratio of ${n3((main.reduction * K) / margin, 1)}:1 would give it ${K} times` : '';
|
|
175
|
+
f(level, `${d.id} into ${main.x.id}${lines.length > 1 ? ` and ${lines.length - 1} more` : ''}: ${gives} there against ${what} needed${main.load.where ? ` (worst: ${main.load.where})` : ''}, ${n3(margin, 2)} times over${caveat}.${fix}`, level === 'pass' ? null : `${d.id}: ${n3(margin, 2)}× torque`, { code: 'motor.torque', at: at(main.x), refs: { item: d.id, joint: main.x.id }, values: { available: avail * main.reduction * main.η, needed: main.load.torque, margin } });
|
|
176
|
+
if (d.spec.speed != null && performance(m, { speed: motorSpeed }).findings.some((x) => x.code === 'motor.speed')) f('fail', `${d.id} is asked for ${motorSpeed} rpm, past what a ${m.name} does`, `${d.id}: too fast`, { code: 'motor.speed', refs: { item: d.id } });
|
|
177
|
+
else {
|
|
178
|
+
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
|
|
179
|
+
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 } });
|
|
180
|
+
}
|
|
181
|
+
mountCheck(s, d, f, W, avail, materialName);
|
|
182
|
+
// Does it hold?
|
|
183
|
+
const fig = (k) => m.figures[k]?.value, kt = m.type === 'brushless' ? 60 / (2 * Math.PI * fig('kv')) : 0;
|
|
184
|
+
const on = 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;
|
|
185
|
+
const backS = n3(back), pmargin = backOn ? on / backOn : Infinity;
|
|
186
|
+
if (locked || brake) f('pass', `${main.x.id} holds with the power off: ${brake ? `its brake (${brake})` : locked} is what holds it`, null, { code: 'motor.holds', at: at(main.x) });
|
|
187
|
+
else if (off_ != null && back <= off_) f('pass', `${main.x.id} holds with the power off: ${backS} N m back at the motor against ${n3(off_)} N m of ${fig('detent_torque') != null ? 'detent' : 'gearbox friction'}`, null, { code: 'motor.holds', at: at(main.x) });
|
|
188
|
+
else if (off_ != null) f('warn', `${main.x.id} drops with the power off: ${backS} N m back at the motor against ${n3(off_)} N m of ${fig('detent_torque') != null ? 'detent' : 'gearbox friction'}. A worm, a ratchet, or more ratio`, `${main.x.id}: drops unpowered`, { code: 'motor.holds', at: at(main.x), values: { back, holds: off_ } });
|
|
189
|
+
else f('warn', `${main.x.id}: there's no figure for what holds it with the power off (${m.name} gives none): assume it can be turned back, and measure it`, `${main.x.id}: unpowered unknown`, { code: 'motor.holds', at: at(main.x) });
|
|
190
|
+
if (pmargin < 1) f('fail', `${main.x.id} slips with the power on: ${n3(backOn)} N m back at the motor against ${n3(on)} N m of ${fig('holding_torque') != null ? 'holding' : 'stall'} torque`, `${main.x.id}: slips`, { code: 'motor.holds', at: at(main.x), values: { back: backOn, holds: on } });
|
|
191
|
+
else f('pass', `${main.x.id} holds with the power on, ${n3(pmargin, 1)} times over`, null, { code: 'motor.holds', at: at(main.x), values: { margin: pmargin } });
|
|
192
|
+
// The case, against what it's bolted to
|
|
193
|
+
const mat = material(materialName), rise = fig('temperature_rise');
|
|
194
|
+
if (mat?.softening != null && rise != null) {
|
|
195
|
+
const duty = d.spec.duty != null ? d.spec.duty : 1, room = 25, caseT = room + rise * duty, ok = caseT <= mat.softening, name = mat.name.toUpperCase(), I = fig('rated_current');
|
|
196
|
+
if (ok) f('pass', `${d.id}'s case reaches at most ${n3(caseT, 1)} °C ${duty < 1 ? `at ${n3(duty * 100, 0)}% duty` : 'at rated current'}, under ${name}'s ${mat.softening} °C`, null, { code: 'motor.heat', at: S });
|
|
197
|
+
else { const k = Math.sqrt((mat.softening - room) / (rise * duty)); f('warn', `${d.id}'s case can reach ${n3(caseT, 1)} °C at rated current, past where ${name} softens (${mat.softening} °C). Set the driver to ${I ? `${n3(I * k, 2)} A` : `${n3(k * 100, 0)}% of its current`} (${n3(k * 100, 0)}% of the torque), or print the mount in a material that takes it`, `${d.id}: mount will soften`, { code: 'motor.heat', at: S, values: { case: caseT, softening: mat.softening } }); }
|
|
198
|
+
}
|
|
199
|
+
}
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
// 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
|
|
203
|
+
// holes (read from the part as drawn), and the screws' bearing on the plastic. Not yet: how far the whole part bends.
|
|
204
|
+
function mountCheck(s, d, f, W, avail, materialName) {
|
|
205
|
+
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));
|
|
206
|
+
if (!fit || !m.mount.holes.length) return;
|
|
207
|
+
const other = top(fit.a) === d.id ? top(fit.b) : top(fit.a), parts = s.parts.filter((p) => p.item === other || p.leaf === other);
|
|
208
|
+
if (!parts.length) return;
|
|
209
|
+
const inv = (p) => { const q = [p[0] - W[3], p[1] - W[7], p[2] - W[11]]; return [W[0] * q[0] + W[4] * q[1] + W[8] * q[2], W[1] * q[0] + W[5] * q[1] + W[9] * q[2], W[2] * q[0] + W[6] * q[1] + W[10] * q[2]]; };
|
|
210
|
+
const pts = parts.flatMap((p) => p.triangles.flat().map(inv)), side = m.mount.side, nominal = mountModel(m, { plate: 10 }), hd = nominal.holes[0].diameter;
|
|
211
|
+
let t = Infinity, plate = 0; // the shortest wall a hole has, and the plate round it (more, if the screw's head is sunk)
|
|
212
|
+
for (const [hx, hy] of m.mount.holes) for (const p of pts) { const r = Math.hypot(p[0] - hx, p[1] - hy), z = p[2] * side; if (r < hd / 2 + 2 && z > 0.5) { t = Math.min(t, z); plate = Math.max(plate, z); } }
|
|
213
|
+
if (t === Infinity) return f('warn', `${d.id}: couldn't find the plate at its screw holes in ${other}`, `${d.id}: mount not found`, { code: 'motor.mount' });
|
|
214
|
+
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;
|
|
215
|
+
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' });
|
|
216
|
+
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 } });
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
// 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
|
|
220
|
+
// shaft at the grip, a ray out from the axis every few degrees, the wall inside and outside.
|
|
221
|
+
export function shaftFit(x, s, f, { placeItems, jointValues, mul, materialName, holeComp = 0.1 }) {
|
|
222
|
+
// (a printed hole comes out holeComp smaller across, so a drawn bore is that much tighter on the real shaft)
|
|
223
|
+
const motion = s.motion, top = (n) => String(n).split(/[.@]/)[0], drives = motion?.drives || [], d = drives.find((y) => y.id === top(x.a) || y.id === top(x.b)), other = d && (top(x.a) === d.id ? top(x.b) : top(x.a)), label = x.note || `${d?.id ?? x.a}'s shaft in ${other ?? x.b}`;
|
|
224
|
+
if (!d) return f('fail', `${label}: neither ${x.a} nor ${x.b} is a motor`, null, { code: 'shaft.motor' });
|
|
225
|
+
const worlds = placeItems(motion, jointValues(motion, motion.pose ?? undefined)), W = worlds[d.item], m = d.model, S = m.shaft, r = S.diameter / 2;
|
|
226
|
+
const inv = (p) => { const q = [p[0] - W[3], p[1] - W[7], p[2] - W[11]]; return [W[0] * q[0] + W[4] * q[1] + W[8] * q[2], W[1] * q[0] + W[5] * q[1] + W[9] * q[2], W[2] * q[0] + W[6] * q[1] + W[10] * q[2]]; };
|
|
227
|
+
const parts = s.parts.filter((p) => p.item === other || p.leaf === other);
|
|
228
|
+
if (!parts.length) return f('fail', `${label}: no part "${other}"`, null, { code: 'shaft.part' });
|
|
229
|
+
const tris = parts.flatMap((p) => p.triangles).map((t) => t.map(inv));
|
|
230
|
+
// How far along the shaft the part reaches, near the axis
|
|
231
|
+
let lo = Infinity, hi = -Infinity; for (const t of tris) for (const p of t) if (Math.hypot(p[0], p[1]) < r + 6) { lo = Math.min(lo, p[2]); hi = Math.max(hi, p[2]); }
|
|
232
|
+
const from = Math.max(lo, S.base), to = Math.min(hi, S.tip), on = to - from;
|
|
233
|
+
if (!(on > 0.05)) return f('fail', `${label}: the part isn't on the shaft (it reaches ${n3(lo, 2)} to ${n3(hi, 2)} mm along it; the shaft runs ${n3(S.base, 2)} to ${n3(S.tip, 2)})`, `${label}: not on the shaft`, { code: 'shaft.seat' });
|
|
234
|
+
const flatFrom = S.flats ? S.tip - S.flatLength : S.tip, flatOn = Math.max(0, to - Math.max(from, flatFrom)), z = S.flats && flatOn > 0.2 ? (Math.max(from, flatFrom) + to) / 2 : (from + to) / 2;
|
|
235
|
+
// The slice at z, as segments
|
|
236
|
+
const segs = [];
|
|
237
|
+
for (const t of tris) { const c = []; for (let i = 0; i < 3; i++) { const a = t[i], b = t[(i + 1) % 3]; if ((a[2] - z) * (b[2] - z) < 0) { const u = (z - a[2]) / (b[2] - a[2]); c.push([a[0] + u * (b[0] - a[0]), a[1] + u * (b[1] - a[1])]); } } if (c.length === 2) segs.push(c); }
|
|
238
|
+
// Each ray: the nearest wall out from the axis, and the part's outside beyond it
|
|
239
|
+
const hits = (ang) => { const dx = Math.cos(ang), dy = Math.sin(ang), out = []; for (const [p, q] of segs) { const ex = q[0] - p[0], ey = q[1] - p[1], den = dx * ey - dy * ex; if (Math.abs(den) < 1e-12) continue; const t = (p[0] * ey - p[1] * ex) / den, u = (p[0] * dy - p[1] * dx) / den; if (t > 1e-6 && u >= 0 && u <= 1) out.push(t); } return out.sort((a, b) => a - b); };
|
|
240
|
+
// The shaft's section at an angle, its flat turned to psi: the shaft turns to meet the bore as it goes on, so the flat is
|
|
241
|
+
// read from the bore. Rays at every 5°; the best angle is the one that leaves the most room at the closest point.
|
|
242
|
+
const flatY = S.flats === 2 ? S.across / 2 : S.across - r;
|
|
243
|
+
const section = (ang, psi) => { const a = Math.sin(ang - psi); if (S.flats === 2) return Math.min(r, flatY / Math.abs(a || 1e-9)); if (S.flats === 1 && a > 0) return Math.min(r, flatY / a); return r; };
|
|
244
|
+
const N = 72, inner = [];
|
|
245
|
+
let minWall = Infinity;
|
|
246
|
+
for (let k = 0; k < N; k++) { const ang = (2 * Math.PI * k) / N, h = hits(ang); if (!h.length) return f('fail', `${label}: at ${n3(z, 1)} mm along the shaft, the part doesn't go round it`, `${label}: no bore`, { code: 'shaft.bore' }); inner.push([ang, h[0]]); if (h.length > 1) minWall = Math.min(minWall, h[1] - h[0]); }
|
|
247
|
+
const gapAt = (psi) => Math.min(...inner.map(([a, h]) => h - section(a, psi)));
|
|
248
|
+
let gap = S.flats ? -Infinity : gapAt(0);
|
|
249
|
+
if (S.flats) for (let k = 0; k < N; k++) gap = Math.max(gap, gapAt((2 * Math.PI * k) / N));
|
|
250
|
+
const code = (c) => ({ code: c, refs: { item: d.id, part: other } }), press = x.shaft === 'press' || gap < 0;
|
|
251
|
+
if (S.flats) {
|
|
252
|
+
const radial = inner.map(([, h]) => h);
|
|
253
|
+
if (Math.max(...radial) - Math.min(...radial) < 0.2) return f('fail', `${label}: the bore is round and the shaft has a flat: nothing turns the part but friction. Cut the flat in the bore (bore() in @rulecad/motors), or add a grub screw`, `${label}: round bore`, { ...code('shaft.flat') });
|
|
254
|
+
}
|
|
255
|
+
if (gap > 0.5) f('fail', `${label}: the bore is ${n3(gap, 2)} mm clear of the shaft at its closest: too slack to hold`, `${label}: slack`, code('shaft.bore'));
|
|
256
|
+
if (gap < -0.2) f('fail', `${label}: the bore is ${n3(-gap, 2)} mm tighter than the shaft: it won't go on`, `${label}: too tight`, code('shaft.bore'));
|
|
257
|
+
const grip = S.flats ? Math.min(flatOn, on) : on, want = S.flats ? Math.min(1.5 * S.diameter, 0.8 * S.flatLength) : 1.5 * S.diameter;
|
|
258
|
+
if (grip < want) f('warn', `${label}: only ${n3(grip, 1)} mm of ${S.flats ? 'the flat' : 'the shaft'} is in the bore: ${n3(want, 1)} mm or more, or it rocks and rounds out`, `${label}: short grip`, code('shaft.grip'));
|
|
259
|
+
else f('pass', `${label}: ${n3(grip, 1)} mm of ${S.flats ? 'the flat' : 'the shaft'} in the bore, ${n3(gap, 2)} mm of play at the closest`, null, code('shaft.grip'));
|
|
260
|
+
if (press && minWall < Infinity) {
|
|
261
|
+
const a = r, u = Math.max(0, holeComp / 2 - gap), b = a + minWall, Kf = (b * b + a * a) / (b * b - a * a), mat = material(materialName) || material('pla'), E = mat.modulus, nu = mat.poisson ?? 0.36, sigma = (E * (u / a) * Kf) / (Kf + nu), limit = mat.strength;
|
|
262
|
+
if (sigma > limit) f('fail', `${label}: pressing it on stretches a ${n3(minWall, 2)} mm wall to ${n3(sigma, 1)} MPa, past ${mat.name.toUpperCase()}'s ${limit} MPa: it splits. A thicker hub or a slide fit`, `${label}: hub splits`, { ...code('shaft.hoop'), values: { stress: sigma, strength: limit } });
|
|
263
|
+
else f('pass', `${label}: pressing it on stretches the wall to ${n3(sigma, 1)} MPa (${mat.name.toUpperCase()} takes ${limit} MPa)`, null, { ...code('shaft.hoop') });
|
|
264
|
+
}
|
|
265
|
+
}
|
package/lib/sandbox-hooks.mjs
CHANGED
|
@@ -1,11 +1,11 @@
|
|
|
1
|
-
// The sandbox's import hook: code in the design's project may import @jscad/modeling, @rulecad/shapes, @rulecad/flexures, @rulecad/gears and files of
|
|
1
|
+
// The sandbox's import hook: code in the design's project may import @jscad/modeling, @rulecad/shapes, @rulecad/flexures, @rulecad/gears, @rulecad/motors and files of
|
|
2
2
|
// its own project, nothing else (no node: modules: no files, network or processes). The tool's own modules are free.
|
|
3
3
|
import { builtinModules } from 'node:module';
|
|
4
4
|
|
|
5
5
|
let project = '';
|
|
6
6
|
export async function initialize(data) { project = data?.project || ''; }
|
|
7
7
|
|
|
8
|
-
const ALLOWED = ['@jscad/modeling', '@rulecad/shapes', '@rulecad/flexures', '@rulecad/gears'];
|
|
8
|
+
const ALLOWED = ['@jscad/modeling', '@rulecad/shapes', '@rulecad/flexures', '@rulecad/gears', '@rulecad/motors'];
|
|
9
9
|
const deny = (spec, why) => Object.assign(new Error(`designs can't import "${spec}": ${why}`), { code: 'design.sandbox' });
|
|
10
10
|
|
|
11
11
|
// The same check, for in-thread hooks (synchronous) and worker hooks (async)
|
package/lib/sandbox-run.mjs
CHANGED
|
@@ -5,6 +5,7 @@ import path from 'node:path';
|
|
|
5
5
|
import * as shapes from '@rulecad/shapes';
|
|
6
6
|
import * as flexures from '@rulecad/flexures';
|
|
7
7
|
import * as gears from '@rulecad/gears';
|
|
8
|
+
import * as motors from '@rulecad/motors';
|
|
8
9
|
import { named, faces, unpack, watch } from './parts.mjs';
|
|
9
10
|
import { lineOf } from './errors.mjs';
|
|
10
11
|
|
|
@@ -28,7 +29,7 @@ console.log = console.info = console.debug = (...a) => console.error(...a);
|
|
|
28
29
|
try {
|
|
29
30
|
const mod = await import(js);
|
|
30
31
|
if (typeof mod.main !== 'function') throw Object.assign(new Error('the design has no exported main(v)'), { code: 'design.main' });
|
|
31
|
-
const { v, read } = watch(values, { shapes, flexures, gears, ops: await shapes.ops(engine || 'jscad') }, optional);
|
|
32
|
+
const { v, read } = watch(values, { shapes, flexures, gears, motors, ops: await shapes.ops(engine || 'jscad') }, optional);
|
|
32
33
|
const { shapes: made, mechanism } = unpack(await mod.main(v));
|
|
33
34
|
const parts = named(made, meta).map(({ geometry, ...p }) => ({ ...p, solid: faces(geometry) }));
|
|
34
35
|
done({ parts, read: [...read], ...(mechanism ? { mechanism } : {}), ...(Object.keys(kept).length ? { stages: kept } : {}) });
|
package/lib/sandbox.mjs
CHANGED
|
@@ -40,7 +40,7 @@ function readable() {
|
|
|
40
40
|
// Every node_modules above the workspace and the tool (package lookups read their links), and where links lead
|
|
41
41
|
const up = (dir) => { const out = []; for (let d = dir; ; d = path.dirname(d)) { out.push(path.join(d, 'node_modules')); if (path.dirname(d) === d) return out; } };
|
|
42
42
|
const dirs = [WS, TOOL, ...[...up(WS), ...up(TOOL)].filter((d) => fs.existsSync(d)),
|
|
43
|
-
...['@jscad/modeling', '@rulecad/shapes', '@rulecad/flexures', '@rulecad/gears', '@rulecad/fea', '@rulecad/variables', 'manifold-3d'].flatMap((n) => [pkgDir(n, fromWs), pkgDir(n, fromTool)])];
|
|
43
|
+
...['@jscad/modeling', '@rulecad/shapes', '@rulecad/flexures', '@rulecad/gears', '@rulecad/motors', '@rulecad/rules/x1c.json', '@rulecad/fea', '@rulecad/variables', 'manifold-3d'].flatMap((n) => [pkgDir(n, fromWs), pkgDir(n, fromTool)])];
|
|
44
44
|
return [...new Set(dirs.filter(Boolean).flatMap((d) => [d, real(d)]).filter(Boolean))];
|
|
45
45
|
}
|
|
46
46
|
|