@rulecad/cad 0.7.41 → 0.7.43
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/AGENTS.md +21 -0
- package/EXAMPLES.md +4252 -4
- package/README.md +13 -0
- package/bin/cad.mjs +120 -8
- package/lib/animate.mjs +41 -0
- package/lib/assembly.mjs +49 -8
- package/lib/bought.mjs +105 -0
- package/lib/buildpage.mjs +81 -0
- package/lib/gait.mjs +66 -0
- package/lib/grip.mjs +23 -0
- package/lib/links.mjs +11 -2
- package/lib/list.mjs +58 -0
- package/lib/loads.mjs +224 -0
- package/lib/machine.mjs +92 -0
- package/lib/measured.mjs +87 -0
- package/lib/motors.mjs +30 -14
- package/lib/order.mjs +242 -0
- package/lib/plates.mjs +108 -0
- package/lib/power.mjs +31 -0
- package/lib/rules.mjs +6 -0
- package/lib/seats.mjs +128 -0
- package/lib/sheet.mjs +146 -16
- package/lib/task.mjs +203 -0
- package/lib/wires.mjs +131 -0
- package/package.json +7 -6
- package/schemas/assembly.schema.json +14 -1
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
// What a machine's model link adds to the model, all read from the same assembly the checks read: the task (the pen, the
|
|
2
|
+
// plane, the margins' figures), a step file, the wires' routes, and the build page (shopping list, plates, wiring sheet,
|
|
3
|
+
// assembly steps, machine settings).
|
|
4
|
+
import fs from 'node:fs';
|
|
5
|
+
import path from 'node:path';
|
|
6
|
+
import { sheetFrame } from '@rulecad/robots';
|
|
7
|
+
import { compactSteps } from '@rulecad/model-link';
|
|
8
|
+
import { paths } from './workspace.mjs';
|
|
9
|
+
import { host } from './host.mjs';
|
|
10
|
+
import { accuracyOf, sample, chainOf } from './task.mjs';
|
|
11
|
+
import { machineOf } from './machine.mjs';
|
|
12
|
+
import { shoppingList } from './list.mjs';
|
|
13
|
+
import { wiresFor, wireRoutesOf } from './assembly.mjs';
|
|
14
|
+
import { orderOf, isBuilt } from './order.mjs';
|
|
15
|
+
import { platesOf } from './plates.mjs';
|
|
16
|
+
import { wiringSheet } from './wires.mjs';
|
|
17
|
+
import { readLedger } from './measured.mjs';
|
|
18
|
+
import { fmt } from './rules.mjs';
|
|
19
|
+
|
|
20
|
+
const guard = async (fn) => { try { return await fn(); } catch (e) { return { error: e.message }; } };
|
|
21
|
+
const r = (x) => +Number(x).toFixed(6);
|
|
22
|
+
|
|
23
|
+
// The plane the pen moves on: the sheet, or the middle of a region or a volume
|
|
24
|
+
function planeOf(t) {
|
|
25
|
+
if (t.sheet) { const f = sheetFrame(t.sheet); return { at: f.at, u: f.u, v: f.v, n: f.n, width: f.width, height: f.height }; }
|
|
26
|
+
const area = t.region ?? t.volume, xr = area.x ?? [area.lo[0], area.hi[0]], yr = area.y ?? [area.lo[1], area.hi[1]], zr = area.z != null ? (Array.isArray(area.z) ? area.z : [area.z, area.z]) : area.lo ? [area.lo[2] ?? 0, area.hi?.[2] ?? area.lo[2] ?? 0] : [0, 0];
|
|
27
|
+
// The two longest sides are the plane the page draws on: a volume can be flat in any of its axes, or a single point
|
|
28
|
+
const at = [(xr[0] + xr[1]) / 2, (yr[0] + yr[1]) / 2, (zr[0] + zr[1]) / 2], side = [xr[1] - xr[0], yr[1] - yr[0], zr[1] - zr[0]], thin = side.indexOf(Math.min(...side));
|
|
29
|
+
const [a, b] = [0, 1, 2].filter((k) => k !== thin), axis = (k) => [0, 1, 2].map((m) => (m === k ? 1 : 0)), n = [0, 1, 2].map((m) => (m === thin ? (thin === 1 ? -1 : 1) : 0));
|
|
30
|
+
return { at, u: axis(a), v: axis(b), n, width: Math.max(side[a], 1), height: Math.max(side[b], 1) };
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/** The task as the page reads it. @param {object} s a built assembly with a task @param {object[]} findings from checkAssembly */
|
|
34
|
+
export function taskData(s, findings) {
|
|
35
|
+
const t = s.task, { elbow } = sample(s), plane = planeOf(t);
|
|
36
|
+
const terms = t.accuracy != null ? accuracyOf(s).list.flatMap((j, i) => j.terms.map((x) => [i, x.term, r(x.value), x.kind ?? ''])) : [];
|
|
37
|
+
const loads = (s.motion.loads || []).map((l) => (l.mass != null ? { item: l.item, at: [l.frame[3], l.frame[7], l.frame[11]].map(r), mass: l.mass } : { joint: l.joint, value: l.value }));
|
|
38
|
+
const torque = findings.filter((x) => x.code === 'motor.torque' && x.values?.available != null).map((x) => ({ joint: x.refs.joint, available: r(x.values.available) }));
|
|
39
|
+
const hot = findings.filter((x) => x.code === 'motor.heat' && x.values?.case != null).sort((a, b) => (b.values.case / b.values.softening) - (a.values.case / a.values.softening))[0];
|
|
40
|
+
return { tool: t.tool, item: t.item, point: t.point.map(r), plane: { at: plane.at.map(r), u: plane.u.map(r), v: plane.v.map(r), n: plane.n.map(r), width: r(plane.width), height: r(plane.height) },
|
|
41
|
+
...(elbow ? { elbow } : {}), ...(t.speed != null ? { speed: t.speed } : {}), ...(t.accuracy != null ? { accuracy: t.accuracy } : {}), ...(t.deflection ? { deflection: t.deflection } : {}),
|
|
42
|
+
...(terms.length ? { terms } : {}), ...(loads.length ? { loads, gravity: s.motion.gravity } : {}), ...(torque.length ? { torque } : {}), ...(hot ? { heat: { motor: hot.refs?.item ?? '', case: r(hot.values.case), softening: hot.values.softening } } : {}) };
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/** A step file for the link: the one asked for, or the newest cad plot wrote for this assembly. @returns {object|null} the compact form */
|
|
46
|
+
export function stepsData(s, asked) {
|
|
47
|
+
const dir = paths.exports(s.project), base = `${s.name}-`;
|
|
48
|
+
let file = typeof asked === 'string' ? asked : null;
|
|
49
|
+
if (!file && asked !== false && fs.existsSync(dir)) file = fs.readdirSync(dir).filter((f) => f.startsWith(base) && f.endsWith('.steps.json')).map((f) => path.join(dir, f)).sort((a, b) => fs.statSync(b).mtimeMs - fs.statSync(a).mtimeMs)[0] ?? null;
|
|
50
|
+
if (!file) return null;
|
|
51
|
+
if (!host.exists(file)) throw new Error(`no step file "${file}": cad plot writes them to exports/`);
|
|
52
|
+
const steps = compactSteps(JSON.parse(fs.readFileSync(file, 'utf8'))), names = chainOf(s).names;
|
|
53
|
+
if (names.join() !== steps.names.join()) throw new Error(`the step file ${path.basename(file)} is for joints ${steps.names.join(', ')}, and this machine's are ${names.join(', ')}: plot it again`);
|
|
54
|
+
return steps;
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/** The build page. @param {object} s a built assembly */
|
|
58
|
+
export async function buildData(s) {
|
|
59
|
+
const list = await guard(() => shoppingList(s));
|
|
60
|
+
const wires = await guard(() => (s.wires?.length ? wiresFor(s).map(({ route, ...w }) => w) : null));
|
|
61
|
+
const plates = await guard(() => platesOf(s).then(({ bed, gap, plates: p, findings }) => ({ bed, gap, plates: p, findings })));
|
|
62
|
+
const order = isBuilt(s) ? await guard(() => orderOf(s)) : null;
|
|
63
|
+
const machine = s.task ? await guard(() => machineOf(s)) : null;
|
|
64
|
+
return { build: { list, wires, plates, order, machine } };
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
// The ledger, in the rules sheet's own rows: each prediction the bench can measure, the measurement once it's in
|
|
68
|
+
export function ledgerRows(s, findings) {
|
|
69
|
+
const entries = readLedger(s.project).filter((e) => e.assembly === s.name), rows = [], done = new Set();
|
|
70
|
+
for (const e of entries) { done.add(e.name); rows.push(['Predicted against measured', e.name, fmt(e.measured), e.unit || '', `predicted ${e.predicted != null ? `${fmt(e.predicted)}${e.was ? ` (${e.was})` : ''}` : 'nothing'}${e.ratio != null ? `, ratio ${fmt(+e.ratio.toFixed(3))}` : ''}${e.figure ? `, ${e.figure}` : ''}`, '', 'measured', e.source ?? '', e.date ?? '']); }
|
|
71
|
+
for (const x of findings) if (x.predict && !done.has(x.predict.name ?? x.code)) rows.push(['Predicted against measured', x.predict.name ?? x.code, fmt(x.predict.value), x.predict.unit ?? '', `${x.predict.figure}: nobody has measured it yet (cad measured ${s.project}/${s.name} ${x.predict.name ?? x.code}=<value>)`, '', 'prediction']);
|
|
72
|
+
return rows.map((row) => row.map(String));
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
/** The wiring sheet in the exports: <assembly>.wiring.md. @returns {string|null} the file */
|
|
76
|
+
export function writeWiring(s) {
|
|
77
|
+
if (!s.wires?.length) return null;
|
|
78
|
+
const dir = paths.exports(s.project), file = path.join(dir, `${s.name}.wiring.md`);
|
|
79
|
+
fs.mkdirSync(dir, { recursive: true }); fs.writeFileSync(file, `# ${s.project}/${s.name}: wiring\n\n${wiringSheet(wiresFor(s))}\n`);
|
|
80
|
+
return file;
|
|
81
|
+
}
|
package/lib/gait.mjs
ADDED
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
// A gait in an assembly: poses in time. Each leg is the chain from the body to its foot; the cycle comes from
|
|
2
|
+
// @rulecad/robots, and the checks run through it: stability, the swing foot's clearance, each joint's torque against its
|
|
3
|
+
// motor, and the sweep along the sequence for one leg hitting another or the body.
|
|
4
|
+
// "gait": { "legs": ["fl.foot.tip", …], "pattern": "trot", "stride": 40, "lift": 15, "period": 1.2, "height": 120, "mass": 1.5 }
|
|
5
|
+
import { chainFromMotion, fk, gait } from '@rulecad/robots';
|
|
6
|
+
import { performance } from '@rulecad/motors';
|
|
7
|
+
import { trainFrom, workingSpeed, atCurrent } from './motors.mjs';
|
|
8
|
+
|
|
9
|
+
const n3 = (x, d = 2) => String(Number(x.toFixed(d)));
|
|
10
|
+
|
|
11
|
+
/** The gait as written, its legs as chains, refused by name when the assembly is built. */
|
|
12
|
+
export function gaitOf(a, motion, num) {
|
|
13
|
+
const g = a.gait; if (!g) return null;
|
|
14
|
+
if (!Array.isArray(g.legs) || !g.legs.length) throw new Error('gait: legs is a list of feet, <item>.<anchor>');
|
|
15
|
+
const legs = g.legs.map((ref) => {
|
|
16
|
+
const [id, name] = String(ref).split('.'), mark = motion.marks.find((m) => m.id === id && m.name === name);
|
|
17
|
+
if (!mark) throw new Error(`gait: no anchor "${ref}" (items: ${[...new Set(motion.marks.map((m) => m.id))].join(', ')})`);
|
|
18
|
+
// A leg's gearbox sits beside its links, so the foot's plane is not the hip anchor's: it stands in its own plane, over the hip
|
|
19
|
+
const c = chainFromMotion(motion, { tip: id, tool: [mark.frame[3], mark.frame[7], mark.frame[11]] }), zero = fk(c, c.names.map(() => 0)), hip = zero.frames[0].at;
|
|
20
|
+
return { name: id, chain: c, at: [hip[0], zero.position[1], hip[2]] };
|
|
21
|
+
});
|
|
22
|
+
const out = { legs, pattern: g.pattern, stride: num(g.stride), lift: num(g.lift), period: num(g.period), height: num(g.height), mass: num(g.mass), ...(g.steps ? { steps: num(g.steps) } : {}), ...(g.com ? { com: g.com.map(num) } : {}) };
|
|
23
|
+
return out;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
// The joint values of a frame of the cycle, in the assembly's terms
|
|
27
|
+
export const frameValues = (s, frame, jointValues) => { // a joint behind a gearbox is moved by the motor's shaft it follows
|
|
28
|
+
const set = {};
|
|
29
|
+
for (const e of frame.feet) { const l = s.gait.legs.find((x) => x.name === e.leg); l.chain.names.forEach((n, i) => { let j = s.motion.joints.find((x) => x.id === n), v = e.q[i]; while (j.follow) { const [lead, r = 1, o = 0] = j.follow; v = (v - o) / r; j = s.motion.joints.find((x) => x.id === lead); } set[j.id] = [v]; }); }
|
|
30
|
+
return jointValues(s.motion, set);
|
|
31
|
+
};
|
|
32
|
+
export const framesOf = (s) => (s.gaitRun ??= gait(s.gait));
|
|
33
|
+
|
|
34
|
+
export function gaitChecks(s, f, { jointValues, placeItems, sweepOne }) {
|
|
35
|
+
if (!s.gait) return;
|
|
36
|
+
const r = framesOf(s);
|
|
37
|
+
for (const x of r.findings) f(x.level, `gait: ${x.text}`, x.level === 'pass' || x.level === 'info' ? null : 'gait: fails', { code: x.code, values: x.values, refs: x.refs });
|
|
38
|
+
if (!r.summary?.torque) return;
|
|
39
|
+
const lift = r.summary.clearance, min = s.a.gait.clearance != null ? s.num(s.a.gait.clearance) : s.gait.lift * 0.5;
|
|
40
|
+
f(lift >= min ? 'pass' : 'fail', `gait: the swing foot clears the ground by ${n3(lift, 1)} mm (wanted ${n3(min, 1)})`, lift >= min ? null : 'gait: foot drags', { code: 'gait.clearance', values: { lift, min } });
|
|
41
|
+
// Each driven joint's torque through the cycle, against its motor
|
|
42
|
+
const motion = s.motion;
|
|
43
|
+
for (const [id, t] of Object.entries(r.summary.torque)) {
|
|
44
|
+
const j = motion.joints.find((x) => x.id === id), tr = j && trainFrom(motion, id), d = tr && motion.drives.find((x) => x.joint === tr.root);
|
|
45
|
+
if (!d) { f('warn', `gait: nothing drives ${id}, so its ${n3(t, 3)} N m through the cycle isn't checked`, `gait: ${id} undriven`, { code: 'gait.torque', refs: { joint: id } }); continue; }
|
|
46
|
+
const speed = workingSpeed(d.model, d.spec), avail = atCurrent(d.model, d.spec, performance(d.model, { speed }).motor.torque) * tr.ratio * tr.efficiency, margin = avail / t, level = margin < 1 ? 'fail' : margin < 2 ? 'warn' : 'pass';
|
|
47
|
+
f(level, `gait: ${id} needs ${n3(t, 3)} N m at its worst in the cycle, and ${d.id} gives ${n3(avail, 3)} N m there, ${n3(margin, 1)} times over`, level === 'pass' ? null : `gait: ${id} ${n3(margin, 1)}×`, { code: 'motor.torque', refs: { joint: id, item: d.id }, values: { needed: t, available: avail, margin } });
|
|
48
|
+
}
|
|
49
|
+
// Leg against leg, leg against body: the cycle as a sweep
|
|
50
|
+
const every = Math.max(1, Math.floor(r.frames.length / 12)); let clashes = null, first = null;
|
|
51
|
+
for (const [k, frame] of r.frames.entries()) { if (k % every) continue; const c = sweepOne(frameValues(s, frame, jointValues)); if (c.length && !clashes) { clashes = c; first = frame.t; } }
|
|
52
|
+
if (clashes) f('fail', `gait: at ${n3(first * 100, 0)}% of the cycle ${clashes.slice(0, 3).map(([a, b]) => `${a} hits ${b}`).join(', ')}`, 'gait: clash', { code: 'gait.sweep', refs: { at: first } });
|
|
53
|
+
else f('pass', `gait: nothing collides through the cycle (${Math.ceil(r.frames.length / every)} poses of it)`, null, { code: 'gait.sweep' });
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
// A gait as joint values through its cycle, for the viewer's Motion panel and cad animate: the joints that lead
|
|
57
|
+
// (a motor's shaft in place of a gearbox's output), and their values at each frame
|
|
58
|
+
export function gaitSequence(s) {
|
|
59
|
+
if (!s.gait) return null;
|
|
60
|
+
const r = framesOf(s); if (!r.frames.length) return null;
|
|
61
|
+
const leads = (id) => { let j = s.motion.joints.find((x) => x.id === id); while (j.follow) j = s.motion.joints.find((x) => x.id === j.follow[0]); return j.id; };
|
|
62
|
+
const names = [...new Set(s.gait.legs.flatMap((l) => l.chain.names).map(leads))];
|
|
63
|
+
const toLead = (id, q) => { let j = s.motion.joints.find((x) => x.id === id), v = q; while (j.follow) { const [lead, ratio = 1, offset = 0] = j.follow; v = (v - offset) / ratio; j = s.motion.joints.find((x) => x.id === lead); } return v; };
|
|
64
|
+
const round = (x) => Number(x.toFixed(4));
|
|
65
|
+
return { kind: 'gait', period: s.gait.period, names, q: r.frames.map((f) => names.map((n) => { for (const e of f.feet) { const l = s.gait.legs.find((x) => x.name === e.leg); const i = l.chain.names.findIndex((m) => leads(m) === n); if (i >= 0) return round(toLead(l.chain.names[i], e.q[i])); } return 0; })) };
|
|
66
|
+
}
|
package/lib/grip.mjs
ADDED
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
// A compliant gripper's grip: a servo through its horn closes two fingers on leaf flexures. What the servo gives, less what
|
|
2
|
+
// bending the leaves takes, is the grip; the payload is held by friction against gravity and the arm's acceleration.
|
|
3
|
+
// "grip": { "servo": "gripper_servo", "horn": 12, "leaf": { "length": 30, "thickness": 1.2, "width": 8 }, "travel": 6, "friction": 0.4 }
|
|
4
|
+
import { leafModel } from '@rulecad/flexures';
|
|
5
|
+
import { peekRuleSet } from './rules.mjs';
|
|
6
|
+
import { materialOf } from './list.mjs';
|
|
7
|
+
|
|
8
|
+
const G = 9.80665, n3 = (x, d = 2) => String(Number(x.toFixed(d)));
|
|
9
|
+
|
|
10
|
+
export function gripChecks(s, f) {
|
|
11
|
+
const g = s.a.task?.grip; if (!g) return;
|
|
12
|
+
const code = 'tool.grip', d = s.motion.drives.find((x) => x.id === g.servo), payload = s.task.payload ?? 0;
|
|
13
|
+
if (!d) throw new Error(`task.grip: servo "${g.servo}" isn't a motor item (${s.motion.drives.map((x) => x.id).join(', ') || 'none'})`);
|
|
14
|
+
if (d.model.type !== 'servo') throw new Error(`task.grip: ${g.servo} is a ${d.model.type}: the grip is worked out for a servo through its horn`);
|
|
15
|
+
const name = String(g.material ?? materialOf(s.project).name).toLowerCase(), rules = peekRuleSet(name).rules, E = rules.modulus.value, strength = rules.strength.value;
|
|
16
|
+
const horn = s.num(g.horn), travel = s.num(g.travel), lever = g.lever != null ? s.num(g.lever) : 1, mu = s.num(g.friction ?? 0.4), L = { length: s.num(g.leaf.length), thickness: s.num(g.leaf.thickness), width: s.num(g.leaf.width) }, m = leafModel(L, { E });
|
|
17
|
+
const torque = d.model.figures.stall_torque.value * (g.torque_share != null ? s.num(g.torque_share) : 0.6), pull = ((torque * 1000) / horn / 2) * lever, spring = m.stiffness * travel, grip = pull - spring, accel = (s.task.accel ?? 0) / 1000, need = payload * (G + accel);
|
|
18
|
+
const held = 2 * mu * grip, margin = need > 0 ? held / need : Infinity, want = g.margin != null ? s.num(g.margin) : 2, stress = m.stress(travel), strain = stress / strength, values = { grip, pull, spring, held, need, margin, stress };
|
|
19
|
+
if (grip <= 0) f('fail', `the grip: the servo pulls each finger with ${n3(pull)} N and the leaves take ${n3(spring)} N to close: it can't close them. A longer or thinner leaf`, 'grip: too stiff', { code, values });
|
|
20
|
+
else if (margin < 1) f('fail', `the grip: ${n3(grip)} N a finger holds ${n3(held)} N at μ ${mu}, and the payload needs ${n3(need)} N: it drops`, 'grip: drops', { code, values });
|
|
21
|
+
else f(margin < want ? 'warn' : 'pass', `the grip: ${n3(grip)} N a finger (${n3(pull)} N from the servo at ${n3(torque, 3)} N m, less ${n3(spring)} N to bend the leaves) holds ${n3(held)} N at μ ${mu}, against ${n3(need)} N for ${n3(payload * 1000, 0)} g: ${n3(margin, 1)} times over`, margin < want ? `grip: ${n3(margin, 1)}×` : null, { code, values });
|
|
22
|
+
f(strain > 1 ? 'fail' : strain > 0.6 ? 'warn' : 'pass', `the fingers at full close: ${n3(stress, 1)} MPa in a ${name.toUpperCase()} leaf, ${n3(strain * 100, 0)}% of its ${strength} MPa`, strain > 0.6 ? `finger ${n3(strain * 100, 0)}% strength` : null, { code: 'tool.strain', values: { stress, strength } });
|
|
23
|
+
}
|
package/lib/links.mjs
CHANGED
|
@@ -6,8 +6,9 @@ import { fmt } from './rules.mjs';
|
|
|
6
6
|
import { paths, config } from './workspace.mjs';
|
|
7
7
|
import { host, readJson } from './host.mjs';
|
|
8
8
|
import { pcbEngine } from './design.mjs';
|
|
9
|
-
import { shapes, motionData } from './assembly.mjs';
|
|
9
|
+
import { shapes, motionData, checkAssembly, wireRoutesOf } from './assembly.mjs';
|
|
10
10
|
import { slotOf } from './threemf.mjs';
|
|
11
|
+
import { taskData, stepsData, buildData, ledgerRows } from './buildpage.mjs';
|
|
11
12
|
|
|
12
13
|
/** The project's filaments: { base: { slot: 1, … }, legend: { slot: 2, … } } in project.json. @param {string} project */
|
|
13
14
|
export const filaments = (project) => readJson(path.join(paths.project(project), 'project.json')).filaments || {};
|
|
@@ -53,7 +54,7 @@ export async function objectModel(b, { title, version, src, set, filaments: fil
|
|
|
53
54
|
}
|
|
54
55
|
|
|
55
56
|
/** A built assembly as a model: each shape once and placed (nine keys cost one keycap), its boards' views, its joints. */
|
|
56
|
-
export async function assemblyModel(s, { title, versions, filaments: fil = {}, noRules = false }) {
|
|
57
|
+
export async function assemblyModel(s, { title, versions, filaments: fil = {}, noRules = false, steps }) {
|
|
57
58
|
const placed = shapes(s.parts), list = placed.shapes.length ? placed.place.map(([i, ...m], n) => { const p = placed.shapes[i].part; return { shape: i, role: p.role, label: p.object || p.label, slot: slotOf(fil, p.filament), triangles: triangles(placed.shapes[i].triangles), matrix: m, name: s.parts[n].name }; }) : [];
|
|
58
59
|
// A pose that sets items' variables draws some parts differently (a flexure bent): each such part's shape in that
|
|
59
60
|
// pose goes in the link as a "pose" part, placed as the part is, to be swapped in when the page shows the pose
|
|
@@ -87,5 +88,13 @@ export async function assemblyModel(s, { title, versions, filaments: fil = {}, n
|
|
|
87
88
|
model.motion.swap = {};
|
|
88
89
|
alts.forEach((x, i) => (model.motion.swap[x.pose] ||= []).push([x.of, list.length - alts.length + i]));
|
|
89
90
|
}
|
|
91
|
+
// A machine's link carries the rest of the project: its task, a drawing to play, its wires' routes, the build page
|
|
92
|
+
if (s.wires?.length) model.wires = wireRoutesOf(s);
|
|
93
|
+
if (s.task || s.wires?.length || s.objects.some((o) => o.bought || o.motor)) {
|
|
94
|
+
const findings = s.task ? checkAssembly(s) : [];
|
|
95
|
+
if (s.task && model.motion) { model.task = taskData(s, findings); const carried = stepsData(s, steps); if (carried) model.steps = carried; }
|
|
96
|
+
Object.assign(model, await buildData(s));
|
|
97
|
+
if (!noRules && s.task) { const rows = ledgerRows(s, findings); if (rows.length) model.sheet = [...rows, ...(model.sheet ?? [])]; }
|
|
98
|
+
}
|
|
90
99
|
return model;
|
|
91
100
|
}
|
package/lib/list.mjs
ADDED
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
// What a machine takes to build, in numbers: the bought items by rule set with quantities, fasteners from the fits that
|
|
2
|
+
// name them, wires by gauge, and the printed parts with their grams and an estimate of the minutes.
|
|
3
|
+
import { peekRuleSet as loadRuleSet } from './rules.mjs';
|
|
4
|
+
import { paths } from './workspace.mjs';
|
|
5
|
+
import { readJson } from './host.mjs';
|
|
6
|
+
import path from 'node:path';
|
|
7
|
+
import { volume } from './mesh.mjs';
|
|
8
|
+
import { wiresFor } from './assembly.mjs';
|
|
9
|
+
|
|
10
|
+
const n = (x, d = 1) => Number(x.toFixed(d));
|
|
11
|
+
|
|
12
|
+
export function materialOf(project) {
|
|
13
|
+
let name = 'pla';
|
|
14
|
+
try { name = String(readJson(path.join(paths.project(project), 'project.json')).material || 'pla').toLowerCase().split(/\s/)[0]; } catch {}
|
|
15
|
+
try { return { name, density: loadRuleSet(name).rules.density.value }; } catch { return { name, density: 1.25, assumed: true }; }
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
// Every printed thing in the assembly, once for each copy: its volume, grams and minutes
|
|
19
|
+
export function printedParts(s) {
|
|
20
|
+
const mat = materialOf(s.project); let flow = 12;
|
|
21
|
+
try { flow = loadRuleSet('x1c').rules.print_flow?.value ?? flow; } catch {}
|
|
22
|
+
const by = new Map();
|
|
23
|
+
for (const p of s.parts) {
|
|
24
|
+
if (p.role !== 'part' && p.role != null) continue;
|
|
25
|
+
const key = p.leaf ?? p.item, mm3 = volume(p.triangles), o = by.get(key) ?? { id: key, object: p.object ?? null, volume: 0 };
|
|
26
|
+
o.volume += mm3; by.set(key, o);
|
|
27
|
+
}
|
|
28
|
+
return [...by.values()].map((o) => ({ ...o, volume: n(o.volume, 0), grams: n((o.volume / 1000) * mat.density), minutes: n(o.volume / flow / 60, 0) }));
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/** The whole list. @returns {{ bought: object[], fasteners: object[], wires: object[], printed: object[], totals: object }} */
|
|
32
|
+
export function shoppingList(s) {
|
|
33
|
+
const mat = materialOf(s.project), printed = printedParts(s), bought = new Map(), fasteners = new Map();
|
|
34
|
+
for (const o of s.objects) if (o.bought && !o.unplaced) {
|
|
35
|
+
const key = `${o.bought.set}|${o.bought.variant ?? ''}`, line = bought.get(key) ?? { set: o.bought.set, variant: o.bought.variant, part: o.bought.part, qty: 0, grams: o.bought.mass != null ? o.bought.mass * 1000 : null, items: [] };
|
|
36
|
+
line.qty++; line.items.push(o.id); bought.set(key, line);
|
|
37
|
+
}
|
|
38
|
+
for (const x of s.fits) if (x.fastener) {
|
|
39
|
+
const count = x.count != null ? x.num(x.count) : 1, line = fasteners.get(x.fastener) ?? { fastener: x.fastener, qty: 0, from: [] };
|
|
40
|
+
line.qty += count; line.from.push(x.note || `${x.a} / ${x.b}`); fasteners.set(x.fastener, line);
|
|
41
|
+
}
|
|
42
|
+
const rows = s.wires?.length ? wiresFor(s) : [], wires = new Map();
|
|
43
|
+
for (const w of rows) { const key = w.gauge ?? 'gauge not given', l = wires.get(key) ?? { gauge: w.gauge, conductors: 0, length: 0, runs: [] }; l.length += w.length * w.conductors; l.conductors += w.conductors; l.runs.push(w.id); wires.set(key, l); }
|
|
44
|
+
const boughtList = [...bought.values()].map((b) => ({ ...b, grams: b.grams != null ? n(b.grams) : null })).sort((a, b) => a.part.localeCompare(b.part) || a.set.localeCompare(b.set));
|
|
45
|
+
const printedGrams = printed.reduce((t, p) => t + p.grams, 0), boughtGrams = boughtList.reduce((t, b) => t + (b.grams ?? 0) * b.qty, 0), unknown = boughtList.filter((b) => b.grams == null).map((b) => b.set);
|
|
46
|
+
return { bought: boughtList, fasteners: [...fasteners.values()], wires: [...wires.values()], printed, totals: { printedGrams: n(printedGrams), boughtGrams: n(boughtGrams), machineGrams: n(printedGrams + boughtGrams), minutes: n(printed.reduce((t, p) => t + p.minutes, 0), 0), material: mat.name, ...(mat.assumed ? { densityAssumed: true } : {}), ...(unknown.length ? { noMassFor: unknown } : {}) } };
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
export function listText(ref, l) {
|
|
50
|
+
const out = [`${ref}: what it takes to build`];
|
|
51
|
+
const row = (a) => out.push(a.join(' '));
|
|
52
|
+
if (l.bought.length) { out.push('', 'Bought'); for (const b of l.bought) row([` ${String(b.qty).padStart(3)} ×`, `${b.set}${b.variant ? ` (${b.variant})` : ''}`, `a ${b.part}`, b.grams != null ? `${b.grams} g each` : 'mass not given', b.items.join(', ')]); }
|
|
53
|
+
if (l.fasteners.length) { out.push('', 'Fasteners'); for (const f of l.fasteners) row([` ${String(f.qty).padStart(3)} ×`, f.fastener, f.from.join('; ')]); }
|
|
54
|
+
if (l.wires.length) { out.push('', 'Wire'); for (const w of l.wires) row([` ${w.length} mm of`, w.gauge ?? 'gauge not given', `in ${w.runs.join(', ')}`]); }
|
|
55
|
+
if (l.printed.length) { out.push('', `Printed (${l.totals.material})`); for (const p of l.printed) row([` ${String(p.grams).padStart(7)} g`, `about ${p.minutes} min`, `${p.id}${p.object && p.object !== p.id ? ` (${p.object})` : ''}`]); }
|
|
56
|
+
out.push('', `Total: ${l.totals.printedGrams} g printed, about ${l.totals.minutes} min of printing (an estimate from volume and the printer's flow), ${l.totals.machineGrams} g as a machine${l.totals.noMassFor ? ` (no mass given for ${l.totals.noMassFor.join(', ')})` : ''}`);
|
|
57
|
+
return out.join('\n');
|
|
58
|
+
}
|
package/lib/loads.mjs
ADDED
|
@@ -0,0 +1,224 @@
|
|
|
1
|
+
// What the machine's own weight and its payload do to it: the force and tipping moment each joint's bearing or printed
|
|
2
|
+
// location takes, how far the links bend, how fast the arm rings, and what acceleration the motors can give it. Masses come
|
|
3
|
+
// from the parts as drawn (volume and density) and the bought parts' rules. Findings in the assembly's shape.
|
|
4
|
+
import crypto from 'node:crypto';
|
|
5
|
+
import { grid as makeGrid, analyse, positions } from '@rulecad/fea';
|
|
6
|
+
import { jacobian } from '@rulecad/robots';
|
|
7
|
+
import { performance } from '@rulecad/motors';
|
|
8
|
+
import { host } from './host.mjs';
|
|
9
|
+
import { paths } from './workspace.mjs';
|
|
10
|
+
import { peekRuleSet } from './rules.mjs';
|
|
11
|
+
import { solidFill } from './optimise.mjs';
|
|
12
|
+
import { materialOf } from './list.mjs';
|
|
13
|
+
import { axisOf, trainFrom, workingSpeed, atCurrent } from './motors.mjs';
|
|
14
|
+
import { sample, chainOf } from './task.mjs';
|
|
15
|
+
|
|
16
|
+
const G = 9.80665, sub = (a, b) => [a[0] - b[0], a[1] - b[1], a[2] - b[2]], dot = (a, b) => a[0] * b[0] + a[1] * b[1] + a[2] * b[2];
|
|
17
|
+
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]], add = (a, b) => [a[0] + b[0], a[1] + b[1], a[2] + b[2]], scale = (a, k) => a.map((x) => x * k);
|
|
18
|
+
const norm = (a) => Math.hypot(a[0], a[1], a[2]), n3 = (x, d = 2) => String(Number(x.toFixed(d)));
|
|
19
|
+
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]);
|
|
20
|
+
const invAt = (W, 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]]; };
|
|
21
|
+
|
|
22
|
+
// A mesh's volume and centroid: signed tetrahedra from the origin
|
|
23
|
+
function solidOf(tris) {
|
|
24
|
+
let V = 0; const c = [0, 0, 0];
|
|
25
|
+
for (const [a, b, d] of tris) { const v = dot(a, cross(b, d)) / 6; V += v; for (let k = 0; k < 3; k++) c[k] += (v * (a[k] + b[k] + d[k])) / 4; }
|
|
26
|
+
return { volume: Math.abs(V), centroid: V ? c.map((x) => x / V) : [0, 0, 0] };
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/** Each moving thing's mass in kg and its centre in its item's frame. */
|
|
30
|
+
export function massesOf(s, { placeItems, jointValues }) {
|
|
31
|
+
const motion = s.motion, ids = motion.items.map((x) => x[0]), W = placeItems(motion, jointValues(motion, motion.pose ?? undefined)), density = materialOf(s.project).density, out = [];
|
|
32
|
+
ids.forEach((id, k) => {
|
|
33
|
+
const parts = s.parts.filter((p) => p.item === id && p.role !== 'support'); if (!parts.length) return;
|
|
34
|
+
const o = s.objects.find((x) => x.id === id || String(x.id).startsWith(`${id}.`)), reference = parts.every((p) => p.role === 'reference');
|
|
35
|
+
let total = 0, c = [0, 0, 0];
|
|
36
|
+
for (const p of parts) { const q = solidOf(p.triangles); const kg = reference ? 0 : (q.volume / 1000) * density / 1000; total += kg; c = add(c, scale(q.centroid, kg || q.volume)); }
|
|
37
|
+
const weightSum = reference ? parts.reduce((t, p) => t + solidOf(p.triangles).volume, 0) : total;
|
|
38
|
+
const bought = reference ? o?.bought?.mass ?? null : null;
|
|
39
|
+
out.push({ item: k, id, kg: reference ? bought ?? 0 : total, centre: invAt(W[k], weightSum ? scale(c, 1 / weightSum) : c), known: !reference || bought != null });
|
|
40
|
+
});
|
|
41
|
+
return out;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
// A joint's value set through its leader when it follows a motor off the chain (a gearbox's output): the model moves by its leader
|
|
45
|
+
const chainSet = (motion, names, q) => Object.fromEntries(names.map((n, i) => { const j = motion.joints.find((x) => x.id === n), lead = j?.follow && !names.includes(j.follow[0]) ? j.follow : null; return lead ? [lead[0], [(q[i] - (lead[2] ?? 0)) / (lead[1] ?? 1)]] : [n, [q[i]]]; }));
|
|
46
|
+
// A mesh's bounding box, as lo and hi: a loop, as a large part's triangles overflow Math.min(...spread)
|
|
47
|
+
function extent(tris) { const lo = [Infinity, Infinity, Infinity], hi = [-Infinity, -Infinity, -Infinity]; for (const t of tris) for (const p of t) 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 }; }
|
|
48
|
+
const beyond = (motion, j, item) => { const by = new Map(motion.joints.map((x) => [x.child, x])); for (let i = item, n = 0; i >= 0 && n < 99; n++) { const x = by.get(i); if (!x) return false; if (x === j) return true; i = x.parent; } return false; };
|
|
49
|
+
|
|
50
|
+
// Force and moment about a joint's origin, at one pose
|
|
51
|
+
function loadAt(motion, masses, payload, worlds, j, mul) {
|
|
52
|
+
const { O, Z } = axisOf(motion, worlds, j, mul), g = motion.gravity || [0, 0, -1], dir = scale(g, 1 / norm(g));
|
|
53
|
+
let F = [0, 0, 0], M = [0, 0, 0], carried = 0;
|
|
54
|
+
const addMass = (kg, X) => { const f = scale(dir, kg * G); F = add(F, f); M = add(M, scale(cross(sub(X, O), f), 1 / 1000)); carried += kg; };
|
|
55
|
+
for (const m of masses) if (beyond(motion, j, m.item)) addMass(m.kg, rowsAt(worlds[m.item], m.centre));
|
|
56
|
+
if (payload && beyond(motion, j, payload.item)) addMass(payload.kg, rowsAt(worlds[payload.item], payload.point));
|
|
57
|
+
const axial = dot(F, Z), radial = norm(sub(F, scale(Z, axial))), torque = dot(M, Z), tipping = norm(sub(M, scale(Z, torque)));
|
|
58
|
+
return { axial: Math.abs(axial), radial, tipping, torque, carried, F, O, Z };
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
// The poses the machine will be in: the task's samples, the named poses, or each joint at its ends
|
|
62
|
+
function posesOf(s, jointValues) {
|
|
63
|
+
const motion = s.motion, base = jointValues(motion, motion.pose ?? undefined), leads = Object.fromEntries(Object.entries(base).filter(([id]) => !motion.joints.find((x) => x.id === id)?.follow)), out = [];
|
|
64
|
+
for (const p of Object.keys(motion.poses || {})) out.push({ label: `pose ${p}`, values: jointValues(motion, p) });
|
|
65
|
+
if (s.task) { const { c, r } = sample(s), every = Math.max(1, Math.ceil(r.samples.length / 40)); r.samples.filter((x, i) => x.reachable && !(i % every)).forEach((x) => out.push({ label: 'on the task', point: x.point, values: jointValues(motion, { ...leads, ...chainSet(motion, c.names, x.q) }) })); }
|
|
66
|
+
if (!out.length) for (const j of motion.joints.filter((x) => !x.follow && x.dofs.length === 1)) for (const v of j.dofs[0].slice(0, 2)) out.push({ label: `${j.id} at ${n3(v, 1)}`, values: jointValues(motion, { ...leads, [j.id]: [v] }) });
|
|
67
|
+
out.push({ label: 'as drawn', values: base });
|
|
68
|
+
return out;
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
const X0 = 0.6, Y0 = 0.5; // ISO 76, a single deep-groove ball bearing's static factors
|
|
72
|
+
function bearingMargin(rows, loads) {
|
|
73
|
+
const [first] = rows, pair = rows.length >= 2;
|
|
74
|
+
const span = pair ? Math.abs(rows[1].along - rows[0].along) : (first.bore + first.outer) / 2; // mm: a pair's spacing, or the balls' pitch circle
|
|
75
|
+
const radial = pair ? loads.radial / rows.length + (loads.tipping * 1000) / span : loads.radial + (2 * loads.tipping * 1000) / span;
|
|
76
|
+
const P0 = Math.max(radial, X0 * radial + Y0 * (loads.axial / (pair ? 2 : 1)));
|
|
77
|
+
return { P0, C0: first.C0, margin: first.C0 / P0, span };
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
// A printed location's weakest clip, from FE on the part as drawn: fixed at its foot, the load at its head
|
|
81
|
+
function clipStress(tris, force, modulus, nu, cell) {
|
|
82
|
+
const key = crypto.createHash('sha256').update(JSON.stringify([tris.length, tris[0], force, modulus, cell])).digest('hex').slice(0, 20), file = paths.cache('clip', key);
|
|
83
|
+
if (!process.env.CAD_NO_CACHE && host.exists(file)) return JSON.parse(host.readText(file));
|
|
84
|
+
const { lo, hi } = extent(tris), n = hi.map((h, k) => Math.max(1, Math.ceil((h - lo[k]) / cell)));
|
|
85
|
+
const gr = { nx: n[0], ny: n[1], nz: n[2], h: cell }, density = solidFill(tris, gr, lo), g = makeGrid(gr), fixed = new Uint8Array(g.dofs), f = new Float64Array(g.dofs);
|
|
86
|
+
// nodes at the foot (the lowest two layers) are held, and the load shared over the top two layers
|
|
87
|
+
const at = positions(g), nodeZ = (id) => Math.round(at[id][2] / cell), onPart = new Uint8Array(g.nodes);
|
|
88
|
+
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;
|
|
89
|
+
const tops = []; for (let id = 0; id < g.nodes; id++) { if (!onPart[id]) continue; const z = nodeZ(id); if (z <= 1) for (let k = 0; k < 3; k++) fixed[3 * id + k] = 1; if (z >= n[2] - 1) tops.push(id); }
|
|
90
|
+
if (!tops.length) return { stress: 0, thin: true };
|
|
91
|
+
for (const id of tops) for (let k = 0; k < 3; k++) f[3 * id + k] = force[k] / tops.length;
|
|
92
|
+
const a = analyse({ grid: g, density, material: { E: modulus, nu }, fixed, loads: [f] });
|
|
93
|
+
let most = 0; for (let e = 0; e < density.length; e++) if (density[e] >= 0.5 && a.stress[0][e] > most) most = a.stress[0][e];
|
|
94
|
+
const out = { stress: most, deflection: a.deflection[0].most }; host.writeText(file, JSON.stringify(out)); return out;
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
export function momentChecks(s, f, helpers, masses, payload) {
|
|
98
|
+
const motion = s.motion, { placeItems, mul, jointValues } = helpers, specs = new Map((s.a.joints || []).map((j) => [j.id, j])), poses = posesOf(s, jointValues), out = {};
|
|
99
|
+
const mat = (() => { const n = materialOf(s.project).name; try { return Object.fromEntries(Object.entries(peekRuleSet(n).rules).map(([k, r]) => [k, r.value])); } catch { return null; } })();
|
|
100
|
+
for (const j of motion.joints) {
|
|
101
|
+
if (j.type !== 'revolute' && j.type !== 'prismatic') continue;
|
|
102
|
+
let worst = null;
|
|
103
|
+
for (const p of poses) { const w = placeItems(motion, p.values), L = loadAt(motion, masses, payload, w, j, mul); if (!worst || L.tipping + L.radial / 50 > worst.L.tipping + worst.L.radial / 50) worst = { L, p, w }; }
|
|
104
|
+
if (!worst || !worst.L.carried) continue;
|
|
105
|
+
const { L, p } = worst, spec = specs.get(j.id) ?? {}, at = L.O, refs = { joint: j.id }, say = `${n3(L.carried * 1000, 0)} g carried: ${n3(L.tipping, 3)} N m tipping, ${n3(L.radial, 2)} N across and ${n3(L.axial, 2)} N along it, worst ${p.label}`, values = { axial: L.axial, radial: L.radial, tipping: L.tipping, carried: L.carried };
|
|
106
|
+
out[j.id] = { ...values, pose: p.label };
|
|
107
|
+
if (spec.support?.bearings?.length) {
|
|
108
|
+
const rows = spec.support.bearings.map((id) => { const o = s.objects.find((x) => x.id === id); if (!o || !['bearing', 'linear_bearing'].includes(o.bought?.part)) throw new Error(`joint ${j.id}: support names "${id}", which isn't a bought bearing`); const v = o.built.values, W = worst.w[motion.items.findIndex((x) => x[0] === id)]; return { id, bore: v.bore, outer: v.outer_diameter, C0: v.static_rating, along: dot(sub([W[3], W[7], W[11]], L.O), L.Z) }; });
|
|
109
|
+
const m = bearingMargin(rows, L), level = m.margin < 1 ? 'fail' : m.margin < 2 ? 'warn' : 'pass';
|
|
110
|
+
f(level, `${j.id}: ${say}. ${rows.map((r) => r.id).join(' and ')} take ${n3(m.P0, 1)} N equivalent against ${n3(m.C0, 0)} N static, ${n3(m.margin, 1)} times over`, level === 'pass' ? null : `${j.id}: bearing ${n3(m.margin, 1)}×`, { code: 'joint.moment', at, refs: { ...refs, bearings: rows.map((r) => r.id) }, values: { ...values, equivalent: m.P0, rating: m.C0, margin: m.margin } });
|
|
111
|
+
} else if (spec.support?.clips?.length) {
|
|
112
|
+
const clips = spec.support.clips, D = s.num(spec.support.pitch ?? 40) / 2, share = L.axial / clips.length + (L.tipping * 1000 * 2) / (clips.length * D), cell = s.num(spec.support.cell ?? 0.8);
|
|
113
|
+
let worstClip = null;
|
|
114
|
+
for (const id of clips) {
|
|
115
|
+
const parts = s.parts.filter((x) => x.item === id || x.leaf === id); if (!parts.length) throw new Error(`joint ${j.id}: support names a clip "${id}", which isn't a part`);
|
|
116
|
+
const tris = parts.flatMap((x) => x.triangles), r = clipStress(tris, scale(L.Z, -share), mat?.modulus ?? 2500, mat?.poisson ?? 0.36, cell);
|
|
117
|
+
if (!worstClip || r.stress > worstClip.stress) worstClip = { id, ...r };
|
|
118
|
+
}
|
|
119
|
+
const strength = mat?.strength ?? 30, margin = strength / worstClip.stress, level = margin < 1 ? 'fail' : margin < 2 ? 'warn' : 'pass';
|
|
120
|
+
f(level, `${j.id}: ${say}. ${clips.length} printed clips, the worst (${worstClip.id}) at ${n3(worstClip.stress, 2)} MPa against ${strength} MPa (FE on ${cell} mm cells, an estimate), ${n3(margin, 1)} times over`, level === 'pass' ? null : `${j.id}: clip ${n3(margin, 1)}×`, { code: 'joint.moment', at, refs: { ...refs, clips }, values: { ...values, stress: worstClip.stress, strength, margin } });
|
|
121
|
+
} else f(s.task && (s.a.gravity || s.task.payload != null) ? 'warn' : 'info', `${j.id}: ${say}, and nothing named takes it: give the joint a "support" (bearings, or printed clips)`, `${j.id}: no support named`, { code: 'joint.moment', at, refs, values });
|
|
122
|
+
}
|
|
123
|
+
return out;
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
// A link bent: held at its parent joint, the carried weight at its far end. δ from the FE, the tilt from a cantilever's
|
|
127
|
+
// relation (1.5 δ / L), carried on to the tool. Kept in .cache, as this is the slow part.
|
|
128
|
+
function linkFE(tris, O, far, force, E, nu, cell) {
|
|
129
|
+
const key = crypto.createHash('sha256').update(JSON.stringify([tris.length, tris.slice(0, 4), O, far, force, E, cell])).digest('hex').slice(0, 20), file = paths.cache('link', key);
|
|
130
|
+
if (!process.env.CAD_NO_CACHE && host.exists(file)) return JSON.parse(host.readText(file));
|
|
131
|
+
const { lo, hi } = extent(tris), n = hi.map((h, k) => Math.max(1, Math.ceil((h - lo[k]) / cell)));
|
|
132
|
+
const gr = { nx: n[0], ny: n[1], nz: n[2], h: cell }, density = solidFill(tris, gr, lo), g = makeGrid(gr), fixed = new Uint8Array(g.dofs), f = new Float64Array(g.dofs), onPart = new Uint8Array(g.nodes);
|
|
133
|
+
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;
|
|
134
|
+
const nodeAt = positions(g), pos = (id) => [lo[0] + nodeAt[id][0], lo[1] + nodeAt[id][1], lo[2] + nodeAt[id][2]];
|
|
135
|
+
const R = 3 * cell, held = [], near = [];
|
|
136
|
+
for (let id = 0; id < g.nodes; id++) if (onPart[id]) { const p = pos(id); if (norm(sub(p, O)) <= R + 4) held.push(id); if (norm(sub(p, far)) <= R + 4) near.push(id); }
|
|
137
|
+
if (!held.length || !near.length) return { deflection: 0, cell, missing: true };
|
|
138
|
+
for (const id of held) for (let k = 0; k < 3; k++) fixed[3 * id + k] = 1;
|
|
139
|
+
for (const id of near) for (let k = 0; k < 3; k++) f[3 * id + k] = force[k] / near.length;
|
|
140
|
+
const size = norm(force), a = analyse({ grid: g, density, material: { E, nu }, fixed, loads: [f] }), out = { deflection: size ? a.compliance[0] / size : 0, stress: Array.from(a.stress[0]).reduce((m, x, e) => (density[e] >= 0.5 && x > m ? x : m), 0), cell };
|
|
141
|
+
host.writeText(file, JSON.stringify(out)); return out;
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
export function deflectionChecks(s, f, helpers, masses, payload) {
|
|
145
|
+
if (!s.task) return 0;
|
|
146
|
+
const motion = s.motion, { placeItems, mul, jointValues } = helpers, { c, r } = sample(s), ids = motion.items.map((x) => x[0]), mat = (() => { try { return Object.fromEntries(Object.entries(peekRuleSet(materialOf(s.project).name).rules).map(([k, x]) => [k, x.value])); } catch { return {}; } })(), E = mat.modulus ?? 2500, nu = mat.poisson ?? 0.36;
|
|
147
|
+
const reached = r.samples.filter((x) => x.reachable); if (!reached.length) return 0;
|
|
148
|
+
const lever = (x) => norm(sub(x.point, rowsAt(placeItems(motion, jointValues(motion, motion.pose ?? undefined))[0] || [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0], [0, 0, 0])));
|
|
149
|
+
const far = reached.reduce((a, b) => (lever(b) > lever(a) ? b : a)), near = reached.reduce((a, b) => (lever(b) < lever(a) ? b : a));
|
|
150
|
+
const links = motion.joints.filter((j) => c.names.includes(j.id));
|
|
151
|
+
const at = (x, label) => {
|
|
152
|
+
const v = jointValues(motion, chainSet(motion, c.names, x.q)), W = placeItems(motion, v), rows = [];
|
|
153
|
+
let total = 0, carried = 0, tool = x.point, dir = (() => { const g = motion.gravity || [0, 0, -1], l = norm(g); return g.map((q) => q / l); })();
|
|
154
|
+
links.forEach((j, i) => {
|
|
155
|
+
const group = new Set([j.child]); for (let more = true; more;) { more = false; for (const x of motion.joints) if (x.type === 'fixed' && group.has(x.parent) && !group.has(x.child)) { group.add(x.child); more = true; } } // the link is everything bolted to the joint's child
|
|
156
|
+
const parts = s.parts.filter((p) => group.has(ids.indexOf(p.item)) && p.role !== 'support' && p.role !== 'reference'); if (!parts.length) return;
|
|
157
|
+
const m = masses.filter((q) => beyond(motion, j, q.item)).reduce((t, q) => t + q.kg, 0) + (payload && beyond(motion, j, payload.item) ? payload.kg : 0);
|
|
158
|
+
if (!m) return;
|
|
159
|
+
const O = axisOf(motion, W, j, mul).O, nextJ = links[i + 1], end = nextJ ? axisOf(motion, W, nextJ, mul).O : tool, Wc = W[j.child];
|
|
160
|
+
const local = parts.flatMap((p) => { const Wp = W[ids.indexOf(p.item)]; return p.localTriangles && Wp ? p.localTriangles.map((t) => t.map((q) => invAt(Wc, rowsAt(Wp, q)))) : p.triangles.map((t) => t.map((q) => invAt(Wc, q))); }), Lo = invAt(Wc, O), Le = invAt(Wc, end), F = [dir[0] * Wc[0] + dir[1] * Wc[4] + dir[2] * Wc[8], dir[0] * Wc[1] + dir[1] * Wc[5] + dir[2] * Wc[9], dir[0] * Wc[2] + dir[1] * Wc[6] + dir[2] * Wc[10]].map((q) => q * m * G);
|
|
161
|
+
const e = extent(local), box = [0, 1, 2].map((k) => e.hi[k] - e.lo[k]), sup = s.a.joints?.find((x) => x.id === j.id)?.support, cell = sup?.cell != null ? s.num(sup.cell) : Math.max(1, Math.min(4, Math.min(...box) / 3)), fe = linkFE(local, Lo, Le, F, E, nu, cell), L = norm(sub(Lo, Le)) || 1, beyondLength = norm(sub(tool, end)), drop = fe.deflection + (1.5 * fe.deflection * beyondLength) / L;
|
|
162
|
+
total += drop; carried = Math.max(carried, m); rows.push({ link: ids[j.child], deflection: fe.deflection, at_tool: drop, cell: fe.cell, stress: fe.stress });
|
|
163
|
+
});
|
|
164
|
+
return { label, total, carried, rows };
|
|
165
|
+
};
|
|
166
|
+
const stretch = at(far, 'at full stretch'), folded = at(near, 'folded'), worst = stretch.total >= folded.total ? stretch : folded;
|
|
167
|
+
if (!worst.rows.length) return 0;
|
|
168
|
+
f('info', `the tool drops ${n3(worst.total, 3)} mm ${worst.label}: ${worst.rows.map((x) => `${x.link} ${n3(x.at_tool, 3)} mm`).join(', ')} (FE from the parts as drawn, cells ${worst.rows.map((x) => n3(x.cell, 1)).join(', ')} mm: a person can refine with "cell" on the joint's support)`, null, { code: 'link.deflection', predict: { name: 'link.deflection', figure: `drop at ${s.task.tool}`, value: worst.total, unit: 'mm' }, values: { total: worst.total, rows: worst.rows, label: worst.label } });
|
|
169
|
+
const finds = [stretch, folded].filter((x) => x.rows.length).map((x) => { const k = (x.carried * G) / (x.total || 1e-9), Hz = Math.sqrt((k * 1000) / x.carried) / (2 * Math.PI); return { ...x, Hz }; }), low = finds.reduce((a, b) => (b.Hz < a.Hz ? b : a));
|
|
170
|
+
const rings = s.task.speed != null ? ` Expect visible ringing past about ${n3(Math.max(20, low.Hz * 3), 0)} mm/s.` : '';
|
|
171
|
+
f('info', `the lowest mode is about ${n3(low.Hz, 0)} Hz ${low.label}, from the tool's stiffness and the mass it carries.${rings}`, null, { code: 'assembly.frequency', values: { Hz: low.Hz, label: low.label } });
|
|
172
|
+
return worst.total;
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
// What the motors can do to the arm's inertia: the worst acceleration at the tool, and the time a move across the task takes
|
|
176
|
+
export function accelChecks(s, f, helpers, masses, payload) {
|
|
177
|
+
const motion = s.motion, { placeItems, jointValues, mul } = helpers; if (!motion.drives?.length) return null;
|
|
178
|
+
const c = s.task ? chainOf(s) : null, names = c ? c.names : motion.joints.filter((j) => !j.follow).map((j) => j.id), base = placeItems(motion, jointValues(motion, motion.pose ?? undefined)), limits = [];
|
|
179
|
+
for (const id of names) {
|
|
180
|
+
const j = motion.joints.find((x) => x.id === id), t = trainFrom(motion, id), d = motion.drives.find((x) => x.joint === t.root); if (!d) { limits.push(null); continue; }
|
|
181
|
+
const axis = axisOf(motion, base, j, mul);
|
|
182
|
+
let I = 0, gravity = 0; // kg mm² about the joint
|
|
183
|
+
for (const m of masses) if (beyond(motion, j, m.item)) { const X = rowsAt(base[m.item], m.centre), r = sub(X, axis.O), rad = norm(sub(r, scale(axis.Z, dot(r, axis.Z)))); I += m.kg * rad * rad; }
|
|
184
|
+
if (payload && beyond(motion, j, payload.item)) { const X = rowsAt(base[payload.item], payload.point), r = sub(X, axis.O), rad = norm(sub(r, scale(axis.Z, dot(r, axis.Z)))); I += payload.kg * rad * rad; }
|
|
185
|
+
for (const p of posesOf(s, jointValues).slice(0, 30)) gravity = Math.max(gravity, Math.abs(loadAt(motion, masses, payload, placeItems(motion, p.values), j, mul).torque));
|
|
186
|
+
const m = d.model, speed = workingSpeed(m, d.spec), ratio = t.ratio, eff = t.efficiency, rotor = (m.figures.rotor_inertia?.value ?? 0) * 0.1, kgmm2 = I / (ratio * ratio * eff) + rotor; // kg mm²
|
|
187
|
+
const avail = atCurrent(m, d.spec, performance(m, { speed }).motor.torque), left = avail - gravity / (ratio * eff), refs = { joint: id, item: d.id }, at = axis.O;
|
|
188
|
+
if (left <= 0) { f('fail', `${id} stalls: ${d.id} gives ${n3(avail, 3)} N m at ${n3(speed, 0)} rpm, and the load takes ${n3(gravity / (ratio * eff), 3)} N m of it through ${n3(ratio, 1)}:1`, `${id}: stalls`, { code: 'motor.accel', at, refs, values: { available: avail, gravity } }); limits.push(0); continue; }
|
|
189
|
+
const alphaMotor = (left * 1e6) / kgmm2, alpha = (alphaMotor / ratio) * (180 / Math.PI); // rad/s² at the motor, deg/s² at the joint
|
|
190
|
+
limits.push(alpha);
|
|
191
|
+
f('info', `${id} can accelerate at ${n3(alpha, 0)} °/s² (reflected inertia ${n3(kgmm2, 1)} kg mm², ${n3(left, 3)} N m left after the load)`, null, { code: 'motor.accel', at, refs, values: { alpha, inertia: kgmm2, torque: left } });
|
|
192
|
+
}
|
|
193
|
+
if (!s.task || limits.some((x) => x == null)) return limits;
|
|
194
|
+
const { r } = sample(s), frame = s.task.sheet ? s.task : null;
|
|
195
|
+
let worst = Infinity;
|
|
196
|
+
for (const x of r.samples) if (x.reachable) {
|
|
197
|
+
const J = jacobian(c, x.q), N = names.length, rows = J.map((row) => row.slice(0, N));
|
|
198
|
+
for (let d = 0; d < 12; d++) { const th = (d * Math.PI) / 6, v = [Math.cos(th), Math.sin(th), 0], lam = pinv2(rows, v); if (!lam) continue; let k = Infinity; for (let i = 0; i < N; i++) if (Math.abs(lam[i]) > 1e-12) k = Math.min(k, limits[i] / Math.abs(lam[i])); worst = Math.min(worst, k); }
|
|
199
|
+
}
|
|
200
|
+
if (worst === Infinity) return limits;
|
|
201
|
+
const accel = 0.7 * worst; s.task.accel = s.a.task.accel != null ? s.num(s.a.task.accel) : accel; void frame;
|
|
202
|
+
if (s.task.speed != null) {
|
|
203
|
+
const L = s.task.sheet ? Math.hypot(...(() => { const c0 = r.summary.corners; const a = c0[0].point, b = c0[2].point; return sub(a, b); })()) : 100, v = s.task.speed, a = s.task.accel, t = L > (v * v) / a ? v / a + L / v : 2 * Math.sqrt(L / a);
|
|
204
|
+
f('info', `a move across the task (${n3(L, 0)} mm) takes ${n3(t, 2)} s, at up to ${n3(worst, 0)} mm/s² at the tool, planned at ${n3(s.task.accel, 0)}`, null, { code: 'task.time', values: { time: t, accel: s.task.accel, limit: worst } });
|
|
205
|
+
}
|
|
206
|
+
return limits;
|
|
207
|
+
}
|
|
208
|
+
function pinv2(J, v) {
|
|
209
|
+
// Minimum-norm joint rates for a tool velocity, from a 2-row or 3-row Jacobian
|
|
210
|
+
const R = J.map((r) => r), n = R.length, M = R.map((a) => R.map((b) => a.reduce((t, x, i) => t + x * b[i], 0)));
|
|
211
|
+
const y = solveN(M.map((row, i) => [...row, v[i]])); return y && J[0].map((_, i) => R.reduce((t, r, k) => t + r[i] * y[k], 0));
|
|
212
|
+
function solveN(A) { const m = A.length; for (let c = 0; c < m; c++) { let p = c; for (let r = c + 1; r < m; r++) if (Math.abs(A[r][c]) > Math.abs(A[p][c])) p = r; [A[c], A[p]] = [A[p], A[c]]; if (Math.abs(A[c][c]) < 1e-9) { A[c][c] = 1e-9; } for (let r = 0; r < m; r++) if (r !== c) { const f = A[r][c] / A[c][c]; for (let k = c; k <= m; k++) A[r][k] -= f * A[c][k]; } } return A.map((r, i) => r[m] / r[i]); }
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
export function loadChecks(s, f, helpers) {
|
|
216
|
+
const motion = s.motion;
|
|
217
|
+
if (!motion?.joints?.length || !(s.task || s.a.gravity)) return;
|
|
218
|
+
const masses = massesOf(s, helpers), payload = s.task?.payload ? { kg: s.task.payload, item: motion.items.findIndex((x) => x[0] === s.task.item), point: s.task.point } : null;
|
|
219
|
+
const unknown = masses.filter((m) => !m.known).map((m) => m.id);
|
|
220
|
+
if (unknown.length && s.task) f('warn', `no mass known for ${unknown.join(', ')}: their rule sets give none, so they weigh nothing here`, 'masses unknown', { code: 'joint.moment.mass', refs: { items: unknown } });
|
|
221
|
+
s.jointLoads = momentChecks(s, f, helpers, masses, payload);
|
|
222
|
+
if (s.task?.payload != null || s.a.gravity) { const d = deflectionChecks(s, f, helpers, masses, payload); if (d && s.a.task?.deflection == null) s.task.deflection = d; }
|
|
223
|
+
accelChecks(s, f, helpers, masses, payload);
|
|
224
|
+
}
|
package/lib/machine.mjs
ADDED
|
@@ -0,0 +1,92 @@
|
|
|
1
|
+
// One description of a machine, read from its assembly: the axes with the steps they take, where each comes from, and
|
|
2
|
+
// the task. cad plot plans a drawing on it, checks it against the task, and shows the result before anything moves.
|
|
3
|
+
import fs from 'node:fs';
|
|
4
|
+
import path from 'node:path';
|
|
5
|
+
import { svgToStrokes, orderStrokes, planToolpath, stepBlocks, estimate, sheetFrame, fk } from '@rulecad/robots';
|
|
6
|
+
import { trainFrom, workingSpeed } from './motors.mjs';
|
|
7
|
+
import { chainOf, accuracyOf, sample, jacobianError } from './task.mjs';
|
|
8
|
+
import { paths } from './workspace.mjs';
|
|
9
|
+
|
|
10
|
+
const r6 = (x) => +Number(x).toFixed(6), n3 = (x, d = 2) => String(Number(x.toFixed(d)));
|
|
11
|
+
|
|
12
|
+
/** The machine as plain data. Every figure's origin is said in _why, by the name of the figure. @param {object} s a built assembly with a task */
|
|
13
|
+
export function machineOf(s) {
|
|
14
|
+
if (!s.task) throw new Error(`${s.project}/${s.name} has no "task": a machine says what it is for`);
|
|
15
|
+
const c = chainOf(s), motion = s.motion, specs = new Map((s.a.joints || []).map((j) => [j.id, j]));
|
|
16
|
+
const axes = c.names.map((id) => {
|
|
17
|
+
const t = trainFrom(motion, id), d = motion.drives.find((x) => x.joint === t.root), j = motion.joints.find((x) => x.id === id), spec = specs.get(id) ?? {};
|
|
18
|
+
if (!d?.model.stepAngle) throw new Error(`${s.project}/${s.name}: joint ${id} has no stepper driving it, and a step file needs one`);
|
|
19
|
+
const micro = d.spec.microsteps ?? 16, per = (360 / d.model.stepAngle) * micro, stepsPerUnit = j.type === 'prismatic' ? (per * t.ratio) / t.slide / 360 : (per * t.ratio) / 360;
|
|
20
|
+
const rpm = workingSpeed(d.model, d.spec), maxRate = (rpm / 60) * per, home = spec.home;
|
|
21
|
+
const homing = home ? { endstop: home.endstop, direction: home.direction ?? -1, rate: Math.round(maxRate / 8), back: Math.round(stepsPerUnit * 3) } : null;
|
|
22
|
+
return { name: id, joint: id, motor: d.id, model: d.model.name, driver: d.spec.driver ?? null, stepAngle: d.model.stepAngle, microsteps: micro, ratio: r6(t.ratio), stepsPerUnit: r6(stepsPerUnit), unit: j.type === 'prismatic' ? 'mm' : 'deg', limits: (j.limits ?? j.dofs[0].slice(0, 2)).map(r6), maxRate: Math.round(maxRate), homing,
|
|
23
|
+
_why: { stepAngle: `${d.model.name}.step_angle`, microsteps: d.spec.microsteps != null ? `the motor item's "microsteps" (resolution only, not accuracy)` : 'the default, 1/16 (resolution only, not accuracy)', ratio: t.stages.length ? `the train from ${t.root} to ${id}` : 'direct', maxRate: `${n3(rpm, 1)} rpm, ${d.spec.speed != null ? 'the motor item\'s speed' : `the working speed of a ${d.model.name}`}` } };
|
|
24
|
+
});
|
|
25
|
+
const kinematics = c.names.length === 2 && motion.joints.filter((j) => c.names.includes(j.id)).every((j) => j.type === 'revolute') ? 'scara' : motion.joints.filter((j) => c.names.includes(j.id)).every((j) => j.type === 'prismatic') ? 'cartesian' : 'serial';
|
|
26
|
+
const pen = s.a.task.pen ?? null;
|
|
27
|
+
return { format: 'rulecad.machine/1', name: `${s.project}/${s.name}`, kinematics, tool: s.task.tool, elbow: sample(s).elbow, axes, task: { sheet: s.a.task.sheet ?? null, region: s.a.task.region ?? null, volume: s.a.task.volume ?? null, speed: s.task.speed, accuracy: s.task.accuracy, accel: s.task.accel ?? 500 }, ...(pen ? { pen } : {}) };
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
// A drawing's size against the sheet: the first stroke that leaves it, named
|
|
31
|
+
function fitsSheet(strokes, frame) {
|
|
32
|
+
const off = [];
|
|
33
|
+
for (const st of strokes) {
|
|
34
|
+
let worst = 0;
|
|
35
|
+
for (const p of st.points) worst = Math.max(worst, -p[0], p[0] - frame.width, -p[1], p[1] - frame.height);
|
|
36
|
+
if (worst > 1e-6) off.push({ stroke: st.name, by: worst });
|
|
37
|
+
}
|
|
38
|
+
return off.sort((a, b) => b.by - a.by);
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
export const CALIBRATION = (w, h) => {
|
|
42
|
+
const cx = w / 2, cy = h / 2, side = Math.min(100, Math.min(w, h) - 20), r = Math.min(15, (Math.min(w, h) - side) / 4 + 10);
|
|
43
|
+
const at = [[cx, cy], [cx - (side / 2 - r), cy - (side / 2 - r)], [cx + (side / 2 - r), cy + (side / 2 - r)]];
|
|
44
|
+
return `<svg xmlns="http://www.w3.org/2000/svg" width="${w}mm" height="${h}mm" viewBox="0 0 ${w} ${h}"><rect id="square" x="${cx - side / 2}" y="${cy - side / 2}" width="${side}" height="${side}" fill="none" stroke="black"/>${at.map(([x, y], i) => `<circle id="circle-${i + 1}" cx="${x}" cy="${y}" r="${r}" fill="none" stroke="black"/>`).join('')}</svg>`;
|
|
45
|
+
};
|
|
46
|
+
|
|
47
|
+
/**
|
|
48
|
+
* Plan a drawing on a machine. Refused (ok: false, nothing written) if it leaves the sheet or can't be reached.
|
|
49
|
+
* @param {object} s a built assembly with a task and a sheet @param {string} svg the drawing @param {{ tolerance?: number, name: string }} o
|
|
50
|
+
*/
|
|
51
|
+
export function plot(s, svg, { tolerance, name } = {}) {
|
|
52
|
+
if (!s.task?.sheet) throw new Error(`${s.project}/${s.name}: plot draws on a "sheet", and the task has none`);
|
|
53
|
+
const m = machineOf(s), frame = sheetFrame(s.task.sheet), c = chainOf(s), tol = tolerance ?? Math.min(0.1, (s.task.accuracy ?? 0.3) / 3);
|
|
54
|
+
const page = svgToStrokes(svg, { tolerance: tol }), findings = [...page.findings], ok = () => findings.every((x) => x.level !== 'fail');
|
|
55
|
+
if (!page.strokes.length) return { ok: false, findings: [...findings, { level: 'fail', text: 'the drawing has no strokes', code: 'plot.empty' }] };
|
|
56
|
+
const off = fitsSheet(page.strokes, frame);
|
|
57
|
+
if (off.length) { findings.push({ level: 'fail', text: `stroke ${off[0].stroke} leaves the ${n3(frame.width, 0)} × ${n3(frame.height, 0)} mm sheet by ${n3(off[0].by)} mm${off.length > 1 ? `, and ${off.length - 1} more` : ''}: the drawing is larger than the sheet`, code: 'plot.sheet', refs: { stroke: off[0].stroke }, values: { by: off[0].by, count: off.length } }); return { ok: false, findings }; }
|
|
58
|
+
const ordered = orderStrokes(page, {}), plan = planToolpath(c, ordered, { tolerance: tol, elbow: m.elbow, sheet: s.task.sheet });
|
|
59
|
+
findings.push(...plan.findings);
|
|
60
|
+
if (!plan.ok) return { ok: false, findings, plan };
|
|
61
|
+
const speed = s.task.speed ?? 50, accel = m.task.accel, axes = m.axes.map((a) => ({ name: a.name, stepsPerUnit: a.stepsPerUnit, maxRate: a.maxRate }));
|
|
62
|
+
const steps = stepBlocks(plan, { axes, speed, accel, travelSpeed: speed * 2 });
|
|
63
|
+
// The pen-down lines, with what the budget predicts along them
|
|
64
|
+
const { list } = s.task.accuracy != null ? accuracyOf(s) : { list: null }, drawn = plan.moves.filter((x) => x.kind === 'draw').map((x) => ({ stroke: x.stroke, name: x.name, points: x.points.map((p) => p.map(r6)), error: list ? x.q.map((q) => +jacobianError(c, q, list, s.task.deflection).toFixed(4)) : null }));
|
|
65
|
+
const time = estimate(steps), out = { ...steps, machine: m.name, drawing: name, drawn };
|
|
66
|
+
findings.push(...steps.findings, { level: 'info', text: `${ordered.strokes?.length ?? ordered.length} strokes, ${n3(plan.length.draw, 0)} mm drawn, ${n3(plan.length.travel, 0)} mm of travel, ${n3(time.time, 1)} s, with tool speed ${speed} mm/s`, code: 'plot.time', values: { time: time.time, draw: plan.length.draw, travel: plan.length.travel } });
|
|
67
|
+
return { ok: ok(), findings, plan, steps: out, machine: m, time };
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
// An animated SVG: the sheet, the drawing appearing, the arm sweeping over it
|
|
71
|
+
export function animation(s, result) {
|
|
72
|
+
const { c } = sample(s), f = sheetFrame(s.task.sheet), plan = result.plan, moves = plan.moves, toS = (p) => { const d = p.map((x, k) => x - f.at[k]); return [r6(d[0] * f.u[0] + d[1] * f.u[1] + d[2] * f.u[2]), r6(-(d[0] * f.v[0] + d[1] * f.v[1] + d[2] * f.v[2]))]; };
|
|
73
|
+
const speed = s.task.speed ?? 50, frames = [];
|
|
74
|
+
let t = 0;
|
|
75
|
+
for (const m of moves) for (let i = 1; i < m.points.length; i++) { const dt = Math.hypot(...m.points[i].map((x, k) => x - m.points[i - 1][k])) / speed; frames.push({ t: t + dt, q: m.q[i], kind: m.kind }); t += dt; }
|
|
76
|
+
const every = Math.max(1, Math.floor(frames.length / 240)), keep = frames.filter((_, i) => !(i % every)), last = frames.at(-1) || { t: 1 }, T = last.t || 1;
|
|
77
|
+
const arm = (q) => armPoints(c, q).map(toS).map((p) => p.join(',')).join(' ');
|
|
78
|
+
const pts = [...moves.flatMap((m) => m.points.map(toS)), ...armPoints(c, moves[0].q[0]).map(toS)], lo = [0, 1].map((k) => Math.min(-f.width / 2 * (k ? f.height / f.width : 1), ...pts.map((p) => p[k]))), hi = [0, 1].map((k) => Math.max((k ? f.height : f.width) / 2, ...pts.map((p) => p[k])));
|
|
79
|
+
const m = 10, draw = result.steps.drawn;
|
|
80
|
+
const lines = draw.map((d, i) => { const len = d.points.reduce((a, p, j) => (j ? a + Math.hypot(...p.map((x, k) => x - d.points[j - 1][k])) : 0), 0), start = moves.slice(0, moves.findIndex((x) => x.kind === 'draw' && x.stroke === d.stroke)).reduce((a, x) => a + x.points.reduce((b, p, j) => (j ? b + Math.hypot(...p.map((v, k) => v - x.points[j - 1][k])) : 0), 0), 0) / speed; return `<polyline points="${d.points.map(toS).map((p) => p.join(',')).join(' ')}" fill="none" stroke="#135" stroke-width="0.5" stroke-dasharray="${len}" stroke-dashoffset="${len}"><animate attributeName="stroke-dashoffset" from="${len}" to="0" begin="${n3(start, 2)}s" dur="${n3(len / speed, 2)}s" fill="freeze"/></polyline>`; }).join('');
|
|
81
|
+
const values = keep.map((x) => arm(x.q)).join(';');
|
|
82
|
+
return `<svg xmlns="http://www.w3.org/2000/svg" viewBox="${lo[0] - m} ${lo[1] - m} ${hi[0] - lo[0] + 2 * m} ${hi[1] - lo[1] + 2 * m}" width="${Math.round((hi[0] - lo[0] + 2 * m) * 3)}" height="${Math.round((hi[1] - lo[1] + 2 * m) * 3)}"><rect x="${-f.width / 2}" y="${-f.height / 2}" width="${f.width}" height="${f.height}" fill="#fff" stroke="#333" stroke-width="0.4"/>${lines}<polyline points="${arm(moves[0].q[0])}" fill="none" stroke="#c33" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><animate attributeName="points" dur="${n3(T, 2)}s" fill="freeze" values="${values}"/></polyline></svg>\n`;
|
|
83
|
+
}
|
|
84
|
+
const armPoints = (c, q) => { const F = fk(c, q); return [...F.frames.map((x) => x.at), F.position]; };
|
|
85
|
+
|
|
86
|
+
export function writePlot(s, result, base) {
|
|
87
|
+
const dir = paths.exports(s.project); fs.mkdirSync(dir, { recursive: true }); const file = path.join(dir, `${base}.steps.json`);
|
|
88
|
+
fs.writeFileSync(file, JSON.stringify(result.steps));
|
|
89
|
+
const prev = paths.preview(s.project, `${base}-plot.svg`); fs.mkdirSync(path.dirname(prev), { recursive: true }); fs.writeFileSync(prev, animation(s, result));
|
|
90
|
+
return { file, preview: prev };
|
|
91
|
+
}
|
|
92
|
+
export function writeMachine(s, m) { const dir = paths.exports(s.project); fs.mkdirSync(dir, { recursive: true }); const file = path.join(dir, `${s.name}.machine.json`); fs.writeFileSync(file, `${JSON.stringify(m, null, 2)}\n`); return file; }
|