@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.
@@ -0,0 +1,87 @@
1
+ // A bench exists so measurements replace estimates and the predictions move. cad measured writes a measured value where
2
+ // the estimate was (in the workspace's copy of the rule set), or a measurement of something a check predicts (a figure
3
+ // no rule holds, like the pen's error at the far corner), runs the assembly's checks either side, says what moved, and
4
+ // keeps a ledger of predicted against measured beside prints.jsonl.
5
+ import fs from 'node:fs';
6
+ import path from 'node:path';
7
+ import { setAt } from './jsonedit.mjs';
8
+ import { CadError } from './errors.mjs';
9
+ import { paths, WS } from './workspace.mjs';
10
+ import { loadRuleSet } from './rules.mjs';
11
+ import { buildAssembly, checkAssembly, assemblyPath } from './assembly.mjs';
12
+
13
+ const today = () => new Date().toISOString().slice(0, 10), n = (x) => String(Number(Number(x).toFixed(4)));
14
+ export const ledgerFile = (project) => path.join(paths.project(project), 'ledger.jsonl');
15
+ export const readLedger = (project) => { const f = ledgerFile(project); return fs.existsSync(f) ? fs.readFileSync(f, 'utf8').split('\n').filter(Boolean).map((l) => JSON.parse(l)) : []; };
16
+
17
+ const findingsOf = async (ref) => checkAssembly(await buildAssembly(ref));
18
+ const keyOf = (x) => `${x.code}|${JSON.stringify(x.refs ?? {})}`;
19
+ // A prediction's name, as cad measured takes it: the check's code, and the part or joint it's about if there are several
20
+ export const predictionsOf = (findings) => findings.filter((x) => x.predict);
21
+
22
+ function ruleFile(name) {
23
+ const dot = name.indexOf('.');
24
+ if (dot < 1) throw new CadError('measured.name', `"${name}": name a rule as <set>.<rule> (x1c.press), or a prediction by its check's code (task.accuracy)`);
25
+ const set = name.slice(0, dot), rule = name.slice(dot + 1);
26
+ const data = loadRuleSet(set); // (copies the tool's set into the workspace, the first time: the measurement goes in your copy)
27
+ return { set, rule, data, file: path.join(WS, 'rules', `${set}.json`) };
28
+ }
29
+
30
+ /**
31
+ * Write measurements back.
32
+ * @param {string} ref project/assembly
33
+ * @param {Record<string, number>} values name → measured value
34
+ * @param {{ unit?: string, source?: string, rule?: string, date?: string }} [options]
35
+ * @returns {Promise<{ entries: object[], moved: { from: string, to: string }[] }>}
36
+ */
37
+ export async function recordMeasured(ref, values, { unit, source, rule, date = today() } = {}) {
38
+ const [project, name] = String(ref).split('/');
39
+ if (!project || !name || !fs.existsSync(assemblyPath(ref))) throw new CadError('measured.assembly', `no assembly "${ref}": give <project>/<assembly>, the one whose predictions it moves`);
40
+ if (!Object.keys(values).length) throw new CadError('measured.usage', 'usage: cad measured <project>/<assembly> <name>=<value> … [--unit mm] [--source "how it was measured"]');
41
+ const before = await findingsOf(ref), entries = [], predictions = predictionsOf(before);
42
+ for (const [k, value] of Object.entries(values)) {
43
+ if (!Number.isFinite(value)) throw new CadError('measured.value', `${k}: a measurement is a number (got ${value})`);
44
+ const named = predictions.filter((x) => x.code === k || x.predict.name === k);
45
+ if (named.length) {
46
+ const p = named[0].predict;
47
+ entries.push({ date, assembly: name, name: k, code: named[0].code, figure: p.figure, unit: p.unit, predicted: p.value, measured: value, ratio: p.value ? value / p.value : null, ...(source ? { source } : {}) });
48
+ continue;
49
+ }
50
+ const { set, rule: key, data, file } = ruleFile(k);
51
+ const old = data.rules?.[key];
52
+ if (!old && !rule) throw new CadError('measured.rule', `${set} has no rule "${key}" (and no check here predicts "${k}"): --rule "what it is" to add it (checks: ${[...new Set(predictions.map((x) => x.code))].join(', ') || 'none'})`);
53
+ if (unit && old?.unit && unit !== old.unit) throw new CadError('measured.unit', `${k} is in ${old.unit}, and this is in ${unit}: give it in ${old.unit}`);
54
+ const entry = { value, unit: unit ?? old?.unit ?? '', rule: rule ?? old.rule, kind: 'measured', source: source || 'measured on the bench', checked: date };
55
+ fs.writeFileSync(file, setAt(fs.readFileSync(file, 'utf8'), ['rules', key], entry));
56
+ entries.push({ date, assembly: name, name: k, figure: entry.rule, unit: entry.unit, predicted: typeof old?.value === 'number' ? old.value : null, was: old?.kind ?? null, measured: value, ratio: typeof old?.value === 'number' && old.value ? value / old.value : null, ...(source ? { source } : {}) });
57
+ }
58
+ const after = await findingsOf(ref), was = new Map(before.map((x) => [keyOf(x), x])), moved = [];
59
+ for (const x of after) {
60
+ const y = was.get(keyOf(x));
61
+ if (x.predict && y?.predict && Math.abs(x.predict.value - y.predict.value) > 1e-9) moved.push({ code: x.code, figure: x.predict.figure, unit: x.predict.unit, from: y.predict.value, to: x.predict.value });
62
+ else if (y && y.text !== x.text && !x.predict) moved.push({ code: x.code, text: x.text, was: y.text });
63
+ }
64
+ fs.appendFileSync(ledgerFile(project), entries.map((e) => JSON.stringify({ ...e, moved: moved.filter((m) => m.figure) })).join('\n') + '\n');
65
+ return { entries, moved, findings: after };
66
+ }
67
+
68
+ // What the kit assumes, as a Markdown table: each rule used that is only an estimate, what measures it, and what it feeds
69
+ export async function assumptionsTable(ref) {
70
+ const findings = await findingsOf(ref), estimates = findings.find((x) => x.code === 'rules.estimate')?.refs?.rules ?? [], preds = predictionsOf(findings);
71
+ const rows = estimates.map((name) => {
72
+ let rule = ''; try { const [u, k] = name.split('.'); rule = loadRuleSet(u).rules[k]?.rule ?? ''; } catch {}
73
+ return `| \`${name}\` | ${rule} | estimate | \`cad measured ${ref} ${name}=<value>\` |`;
74
+ });
75
+ const out = ['| What the kit assumes | What it is | Trust | How to settle it |', '|---|---|---|---|', ...rows,
76
+ ...preds.map((x) => `| ${x.predict.figure} | ${n(x.predict.value)} ${x.predict.unit}, predicted by \`${x.code}\` | prediction | \`cad measured ${ref} ${x.predict.name ?? x.code}=<value>\` |`)];
77
+ return out.join('\n');
78
+ }
79
+ // A table kept in a file, between two markers: the rest of the file stays as written
80
+ export const MARK = ['<!-- cad measured: start -->', '<!-- cad measured: end -->'];
81
+ export function writeTable(file, table) {
82
+ const text = fs.existsSync(file) ? fs.readFileSync(file, 'utf8') : '', a = text.indexOf(MARK[0]), b = text.indexOf(MARK[1]);
83
+ const block = `${MARK[0]}\n${table}\n${MARK[1]}`;
84
+ fs.writeFileSync(file, a >= 0 && b > a ? text.slice(0, a) + block + text.slice(b + MARK[1].length) : `${text}${text && !text.endsWith('\n') ? '\n' : ''}\n${block}\n`);
85
+ }
86
+
87
+ export const ledgerLines = (entries) => entries.map((e) => `${e.date} ${e.assembly} ${e.name}: measured ${n(e.measured)} ${e.unit || ''}`.trimEnd() + (e.predicted != null ? `, predicted ${n(e.predicted)}${e.was ? ` (${e.was})` : ''}${e.ratio != null ? `, ratio ${n(e.ratio)}` : ''}` : '') + (e.source ? ` [${e.source}]` : ''));
package/lib/motors.mjs CHANGED
@@ -2,11 +2,11 @@
2
2
  // slider is the motor turning), and the assembly can say what it has to do: "loads" on joints or masses on links.
3
3
  // From those, what reaches each loaded joint through the meshes and planetaries, whether the joint holds with the
4
4
  // power on and off, and whether the shaft and its mount are fit for it.
5
- import crypto from 'node:crypto';
6
5
  import { createRequire } from 'node:module';
7
6
  import { motorModel, motorParts, mountModel, performance } from '@rulecad/motors';
8
7
  import { stageEfficiency } from '@rulecad/gears';
9
8
  import { named } from './parts.mjs';
9
+ import { referenceBuilt } from './bought.mjs';
10
10
 
11
11
  const require = createRequire(import.meta.url);
12
12
  const n3 = (x, d = 3) => String(Number(x.toFixed(d)));
@@ -22,9 +22,7 @@ export function motorBuilt(spec, num, id) {
22
22
  const anchors = Object.fromEntries(Object.entries(model.anchors).map(([k, a]) => [k, { at: a.origin, axis: a.axis }]));
23
23
  const values = Object.fromEntries(Object.entries(model.figures).filter(([, f]) => typeof f.value === 'number').map(([k, f]) => [k, f.value]));
24
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 };
25
+ return referenceBuilt({ id, key: 'motor', objName: `motor:${model.name}`, name: model.name, parts, anchors, entries, values, extra: { motor: model, spec, bought: { set: model.name, variant: null, part: 'motor', mass: model.mass ?? null } } });
28
26
  }
29
27
 
30
28
  // Which joint each motor drives, checked by name; a servo's range and a stepper's step go on the joint. The shaft
@@ -37,7 +35,8 @@ export function motorDrives(a, placed, joints, num) {
37
35
  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
36
  const j = joints.find((x) => x.id === id);
39
37
  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`);
38
+ if (j.type === 'prismatic' && (it.motor.leadscrew || it.motor.belt)) j.slide = slideDrive(it.motor, what, j, num);
39
+ else 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, or give "leadscrew" or "belt"`);
41
40
  if (j.follow) throw new Error(`${what}: ${j.id} follows ${j.follow[0]}: a motor drives the joint that leads the train`);
42
41
  if (taken.has(id)) throw new Error(`${what}: ${id} is driven by ${taken.get(id)} already: one motor to a joint`);
43
42
  taken.set(id, c.id);
@@ -53,6 +52,19 @@ export function motorDrives(a, placed, joints, num) {
53
52
  return drives;
54
53
  }
55
54
 
55
+ // A motor driving a slide directly, through a lead screw or a belt: mm per turn, how much power gets through, and whether
56
+ // it holds with the power off. A screw locks when its lead angle is under its friction angle
57
+ function slideDrive(spec, what, j, num) {
58
+ if (spec.leadscrew) {
59
+ const lead = num(spec.leadscrew.lead), d = num(spec.leadscrew.diameter ?? 8), mu = num(spec.leadscrew.friction ?? 0.2), lambda = Math.atan(lead / (Math.PI * d)), phi = Math.atan(mu);
60
+ if (!(lead > 0)) throw new Error(`${what}: a lead screw's lead is above 0 mm (got ${lead})`);
61
+ return { kind: 'screw', mmPerTurn: lead, efficiency: Math.tan(lambda) / Math.tan(lambda + phi), locks: lambda < phi ? `the lead screw (its ${n3((lambda * 180) / Math.PI, 1)}° lead is under the ${n3((phi * 180) / Math.PI, 1)}° friction angle)` : null, detail: `a ${lead} mm lead` };
62
+ }
63
+ const pitch = num(spec.belt.pitch ?? 2), teeth = num(spec.belt.teeth);
64
+ if (!(teeth > 0)) throw new Error(`${what}: a belt needs its pulley's "teeth"`);
65
+ return { kind: 'belt', mmPerTurn: teeth * pitch, efficiency: 0.95, locks: null, detail: `a ${teeth} T pulley`, stretch: spec.belt.stiffness != null ? { k: num(spec.belt.stiffness), width: num(spec.belt.width ?? 6), length: num(spec.belt.length ?? 300), load: num(spec.belt.load ?? 5) } : null };
66
+ }
67
+
56
68
  // The fits a motor brings with it, in the assembly's own shape
57
69
  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
70
 
@@ -71,9 +83,10 @@ export function loadsOf(a, anchor, num, joints) {
71
83
  // ---------- the train from a motor to a joint ----------
72
84
  // 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
85
  // (or per mm, where the joint slides), the share of power that gets through, what's in the way.
74
- function trainFrom(motion, id) {
86
+ export function trainFrom(motion, id) {
75
87
  const stages = [], meshes = motion.meshes || [];
76
88
  let j = motion.joints.find((x) => x.id === id), ratio = 1, efficiency = 1, slide = j.type === 'prismatic' ? 1 : null, locks = null;
89
+ if (j.slide) return { root: j.id, ratio: 1, efficiency: j.slide.efficiency, stages: [{ joint: j.id, kind: j.slide.kind, ratio: 1, efficiency: j.slide.efficiency }], slide: j.slide.mmPerTurn / 360, locks: j.slide.locks };
77
90
  while (j.follow) {
78
91
  const [lead, r] = j.follow, m = meshes.find((x) => x.joint === j.id) || meshes.find((x) => x.planetary && (x.members || []).includes(j.id));
79
92
  const kind = m?.kind === 'external' ? 'spur' : m?.kind || 'spur';
@@ -89,7 +102,7 @@ function trainFrom(motion, id) {
89
102
 
90
103
  // World axis of a joint and the world position of a point on an item
91
104
  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]] }; };
105
+ export 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
106
  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
107
  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
108
 
@@ -122,8 +135,11 @@ function worstLoad(motion, loads, j, drive, { placeItems, jointValues, mul }) {
122
135
  return { torque: Math.abs(worst), where };
123
136
  }
124
137
 
138
+ // What a stepper gives at the current it's set to: torque goes with the current, up to its rating
139
+ export const atCurrent = (m, spec, torque) => (m.type === 'stepper' && spec.current != null && m.figures.rated_current?.value ? torque * Math.min(1, spec.current / m.figures.rated_current.value) : torque);
140
+
125
141
  // 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) {
142
+ export function workingSpeed(model, spec) {
127
143
  if (spec.speed != null) return spec.speed;
128
144
  const p = performance(model, {});
129
145
  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;
@@ -135,7 +151,7 @@ const material = (name) => { const n = String(name || 'pla').toLowerCase().split
135
151
  export function motorChecks(s, f, helpers, materialName) {
136
152
  const motion = s.motion, drives = motion?.drives || [], loads = motion?.loads || [], { placeItems, jointValues, mul } = helpers;
137
153
  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));
154
+ const worlds = placeItems(motion, s.jointValues ?? jointValues(motion, motion.pose ?? undefined));
139
155
  for (const d of drives) {
140
156
  const m = d.model, grams = n3(m.mass * 1000, 1), K = d.spec.margin != null ? d.spec.margin : 2, W = worlds[d.item];
141
157
  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 } });
@@ -168,7 +184,7 @@ export function motorChecks(s, f, helpers, materialName) {
168
184
  back += (atLead / reduction) * ηback; backOn += atLead / reduction;
169
185
  lines.push({ x, t, load, unit, reduction, atLead, η });
170
186
  }
171
- const speedOut = motorSpeed / loaded[0].t.ratio, rated = performance(m, { speed: motorSpeed }), avail = rated.motor.torque, margin = need ? avail / need : Infinity;
187
+ const speedOut = motorSpeed / loaded[0].t.ratio, rated = performance(m, { speed: motorSpeed }), avail = atCurrent(m, d.spec, rated.motor.torque), margin = need ? avail / need : Infinity;
172
188
  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
189
  const trust = rated.rests.filter((k) => k !== 'spec' && k !== 'measured'), caveat = trust.length ? ` (rests on ${trust.join(' and ')} figures: measure it)` : '';
174
190
  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` : '';
@@ -181,7 +197,7 @@ export function motorChecks(s, f, helpers, materialName) {
181
197
  mountCheck(s, d, f, W, avail, materialName);
182
198
  // Does it hold?
183
199
  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;
200
+ const on = atCurrent(m, d.spec, fig('holding_torque') ?? fig('stall_torque') ?? (kt ? kt * fig('rated_current') : 0)), off_ = fig('detent_torque') ?? fig('friction_torque') ?? null, brake = lines.map((l) => motion.joints.find((x) => x.id === l.x.id)?.brake).find(Boolean) ?? motion.joints.find((x) => x.id === d.joint)?.brake;
185
201
  const backS = n3(back), pmargin = backOn ? on / backOn : Infinity;
186
202
  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
203
  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) });
@@ -193,8 +209,8 @@ export function motorChecks(s, f, helpers, materialName) {
193
209
  const mat = material(materialName), rise = fig('temperature_rise');
194
210
  if (mat?.softening != null && rise != null) {
195
211
  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 } }); }
212
+ 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, refs: { item: d.id }, values: { case: caseT, softening: mat.softening } });
213
+ 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, refs: { item: d.id }, values: { case: caseT, softening: mat.softening } }); }
198
214
  }
199
215
  }
200
216
  }
@@ -222,7 +238,7 @@ export function shaftFit(x, s, f, { placeItems, jointValues, mul, materialName,
222
238
  // (a printed hole comes out holeComp smaller across, so a drawn bore is that much tighter on the real shaft)
223
239
  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
240
  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;
241
+ const worlds = placeItems(motion, s.jointValues ?? jointValues(motion, motion.pose ?? undefined)), W = worlds[d.item], m = d.model, S = m.shaft, r = S.diameter / 2;
226
242
  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
243
  const parts = s.parts.filter((p) => p.item === other || p.leaf === other);
228
244
  if (!parts.length) return f('fail', `${label}: no part "${other}"`, null, { code: 'shaft.part' });
package/lib/order.mjs ADDED
@@ -0,0 +1,242 @@
1
+ // The order a machine goes together in, worked out from the assembly: a part fastened into another comes after it, a
2
+ // bearing goes in before its shaft, a part goes where nothing placed yet stands in its way (a nut trapped by a wall goes
3
+ // in before its neighbour). Found by taking it apart: a part is free to leave when a straight line takes it clear of
4
+ // everything still there, and no part left depends on it. Taking parts away only ever frees others, so if nothing can leave
5
+ // no order exists, and that is a finding, assembly.order. A fit with "access": "<item>.<anchor>" names where a screw's
6
+ // tool comes from (its anchor's z points out along the screw): whatever stands on that line must go on after it.
7
+ // Works on the assembly's top-level items; a component (an assembly used as an item) is one step.
8
+ import crypto from 'node:crypto';
9
+ import path from 'node:path';
10
+ import fs from 'node:fs';
11
+ import { placeItems, jointValues, mul } from '@rulecad/model-link';
12
+ import { host } from './host.mjs';
13
+ import { paths } from './workspace.mjs';
14
+
15
+ const top = (n) => String(n).split(/[.@]/)[0];
16
+ const round = (v) => v.map((x) => (Math.abs(x) < 1e-9 ? 0 : +x.toFixed(6)));
17
+ const SIDES = [[0, 0, 1], [0, 0, -1], [1, 0, 0], [-1, 0, 0], [0, 1, 0], [0, -1, 0]];
18
+ const dot = (a, b) => a[0] * b[0] + a[1] * b[1] + a[2] * b[2];
19
+ const fan = (poly) => poly.slice(1, -1).map((_, i) => [poly[0], poly[i + 1], poly[i + 2]]);
20
+ function basis(d) {
21
+ const a = Math.abs(d[0]) < 0.9 ? [1, 0, 0] : [0, 1, 0], u = [d[1] * a[2] - d[2] * a[1], d[2] * a[0] - d[0] * a[2], d[0] * a[1] - d[1] * a[0]], l = Math.hypot(...u), n = u.map((x) => x / l);
22
+ return [n, [d[1] * n[2] - d[2] * n[1], d[2] * n[0] - d[0] * n[2], d[0] * n[1] - d[1] * n[0]]];
23
+ }
24
+
25
+ // One thing that gets placed: its triangles, its box, what a part is known as
26
+ function groups(s) {
27
+ const by = new Map();
28
+ s.parts.forEach((p, order) => {
29
+ if (!by.has(p.item)) by.set(p.item, { id: p.item, order, parts: [], tris: [] });
30
+ const g = by.get(p.item); g.parts.push(p);
31
+ for (const t of p.triangles) g.tris.push(...fan(t));
32
+ });
33
+ const objs = new Map(s.objects.map((o) => [o.id, o]));
34
+ for (const g of by.values()) { const o = objs.get(g.id); g.object = o?.objName ?? null; g.bought = o?.bought ?? null; g.motor = !!o?.motor; }
35
+ return [...by.values()];
36
+ }
37
+
38
+ // A part seen along a direction: for each cell of a grid across it, the nearest and furthest of it along the direction
39
+ function raster(g, d, h) {
40
+ const [u, v] = basis(d), cells = new Map();
41
+ let uLo = Infinity, uHi = -Infinity, vLo = Infinity, vHi = -Infinity, sLo = Infinity, sHi = -Infinity;
42
+ const k = (i, j) => (i + 1048576) * 2097152 + (j + 1048576);
43
+ for (const t of g.tris) {
44
+ const P = t.map((p) => [dot(p, u), dot(p, v), dot(p, d)]);
45
+ const lo = [Math.min(P[0][0], P[1][0], P[2][0]), Math.min(P[0][1], P[1][1], P[2][1])], hi = [Math.max(P[0][0], P[1][0], P[2][0]), Math.max(P[0][1], P[1][1], P[2][1])];
46
+ uLo = Math.min(uLo, lo[0]); uHi = Math.max(uHi, hi[0]); vLo = Math.min(vLo, lo[1]); vHi = Math.max(vHi, hi[1]); sLo = Math.min(sLo, P[0][2], P[1][2], P[2][2]); sHi = Math.max(sHi, P[0][2], P[1][2], P[2][2]);
47
+ const det = (P[1][1] - P[2][1]) * (P[0][0] - P[2][0]) + (P[2][0] - P[1][0]) * (P[0][1] - P[2][1]);
48
+ if (Math.abs(det) < 1e-9) continue; // a face seen edge-on covers no cell: the faces either side of it do
49
+ for (let i = Math.floor(lo[0] / h); i <= Math.floor(hi[0] / h); i++) for (let j = Math.floor(lo[1] / h); j <= Math.floor(hi[1] / h); j++) {
50
+ const x = (i + 0.5) * h, y = (j + 0.5) * h, a = ((P[1][1] - P[2][1]) * (x - P[2][0]) + (P[2][0] - P[1][0]) * (y - P[2][1])) / det, b = ((P[2][1] - P[0][1]) * (x - P[2][0]) + (P[0][0] - P[2][0]) * (y - P[2][1])) / det, c = 1 - a - b;
51
+ if (a < -1e-9 || b < -1e-9 || c < -1e-9) continue; // (exact: a slack in these fractions grows with the triangle)
52
+ const z = a * P[0][2] + b * P[1][2] + c * P[2][2];
53
+ const key = k(i, j), now = cells.get(key);
54
+ if (now) { if (z < now[0]) now[0] = z; if (z > now[1]) now[1] = z; } else cells.set(key, [z, z]);
55
+ }
56
+ }
57
+ return { cells, uLo, uHi, vLo, vHi, sLo, sHi, key: k };
58
+ }
59
+
60
+ // Blocked when, in a cell they share, the other has something further along than this part's rearmost: this part, moved
61
+ // on, runs into it. Parts meet at their edges, so this part is thinned by a cell; a thing narrower than that keeps its cells.
62
+ function blockers(p, q, d, h, rasterOf) {
63
+ const A = rasterOf(p, d), B = rasterOf(q, d);
64
+ if (A.uHi < B.uLo || B.uHi < A.uLo || A.vHi < B.vLo || B.vHi < A.vLo || B.sHi <= A.sLo + 0.2) return false;
65
+ const inner = [...A.cells].filter(([key]) => {
66
+ const j = key % 2097152, i = (key - j) / 2097152;
67
+ return [[1, 0], [-1, 0], [0, 1], [0, -1]].every(([a, b]) => A.cells.has((i + a) * 2097152 + (j + b)));
68
+ });
69
+ for (const [key, a] of inner.length ? inner : [...A.cells]) { const b = B.cells.get(key); if (b && b[1] > a[0] + 0.2) return true; }
70
+ return false;
71
+ }
72
+
73
+ // A pair meant to overlap (a press fit) tells nothing about what stands in whose way
74
+ const names = (x) => [x].flat().map(top);
75
+ const allowedPair = (s, a, b) => s.fits.some((x) => x.min != null && x.num(x.min) < 0 && ((names(x.a).includes(a.id) && names(x.b).includes(b.id)) || (names(x.a).includes(b.id) && names(x.b).includes(a.id))));
76
+
77
+ function hitsAlong(origin, dir, tris) {
78
+ for (const t of tris) {
79
+ const e1 = [t[1][0] - t[0][0], t[1][1] - t[0][1], t[1][2] - t[0][2]], e2 = [t[2][0] - t[0][0], t[2][1] - t[0][1], t[2][2] - t[0][2]];
80
+ const p = [dir[1] * e2[2] - dir[2] * e2[1], dir[2] * e2[0] - dir[0] * e2[2], dir[0] * e2[1] - dir[1] * e2[0]], det = dot(e1, p);
81
+ if (Math.abs(det) < 1e-12) continue;
82
+ const s = [origin[0] - t[0][0], origin[1] - t[0][1], origin[2] - t[0][2]], u = dot(s, p) / det;
83
+ if (u < 0 || u > 1) continue;
84
+ const q = [s[1] * e1[2] - s[2] * e1[1], s[2] * e1[0] - s[0] * e1[2], s[0] * e1[1] - s[1] * e1[0]], v = dot(dir, q) / det;
85
+ if (v < 0 || u + v > 1) continue;
86
+ if (dot(e2, q) / det > 0.05) return true;
87
+ }
88
+ return false;
89
+ }
90
+
91
+ /**
92
+ * The order to put an assembly together, as data.
93
+ * @param {object} s a built assembly
94
+ * @returns {{ steps: { n: number, items: string[], object: string|null, dir: number[], fasteners: {fit: string, fastener?: string, count?: number}[], text: string }[], stuck: object|null }}
95
+ */
96
+ export function assemblyOrder(s) {
97
+ const all = groups(s).filter((g) => g.bought || g.motor || g.parts.some((p) => p.role === 'part' || p.role == null) || s.fits.some((x) => [x.a, x.b].flat().some((n) => top(n) === g.id)));
98
+ if (!all.length) return { steps: [], stuck: null };
99
+ const by = new Map(all.map((g) => [g.id, g])), ids = all.map((g) => g.id), joints = s.motion.joints, items = s.motion.items.map((x) => x[0]);
100
+ const bearing = (id) => by.get(id)?.bought?.part === 'bearing';
101
+ // How far each part is from the base along joints and fastenings: nearer goes first
102
+ const links = new Map(ids.map((id) => [id, new Set()])), tie = (a, b) => { if (links.has(a) && links.has(b) && a !== b) { links.get(a).add(b); links.get(b).add(a); } };
103
+ const fastening = s.fits.filter((x) => x.fastens || x.seat != null || x.shaft != null || x.engage != null);
104
+ for (const x of fastening) for (const a of [x.a].flat()) for (const b of [x.b].flat()) tie(top(a), top(b));
105
+ for (const j of joints) if (j.parent >= 0) tie(items[j.parent], items[j.child]);
106
+ const base = items.find((id) => by.has(id)) ?? ids[0], level = new Map([[base, 0]]);
107
+ for (let queue = [base]; queue.length;) { const id = queue.shift(); for (const o of links.get(id)) if (!level.has(o)) { level.set(o, level.get(id) + 1); queue.push(o); } }
108
+ const lv = (id) => level.get(id) ?? 1e6;
109
+ const rank = (id) => [lv(id), by.get(id).order], earlier = (a, b) => { const [x, y] = [rank(a), rank(b)]; return x[0] - y[0] || x[1] - y[1]; };
110
+ // Constraints: [u, v, why]: u before v
111
+ const before = new Map(ids.map((id) => [id, new Map()])), add = (u, v, why) => { if (by.has(u) && by.has(v) && u !== v) before.get(u).set(v, why); };
112
+ for (const j of joints) if (j.parent >= 0) add(items[j.parent], items[j.child], `${items[j.child]} turns on ${items[j.parent]}`);
113
+ for (const x of fastening) for (const A of [x.a].flat()) for (const B of [x.b].flat()) {
114
+ const a = top(A), b = top(B), [u, v] = earlier(a, b) <= 0 ? [a, b] : [b, a];
115
+ if (x.seat != null && (bearing(a) || bearing(b))) { const [h, r] = bearing(a) ? [b, a] : [a, b]; add(h, r, `${r} is pressed into ${h}`); continue; }
116
+ if ((x.shaft != null || x.engage != null) && (bearing(a) || bearing(b))) { const [r, shaft] = bearing(a) ? [a, b] : [b, a]; add(r, shaft, `${r} goes in before ${shaft}`); continue; }
117
+ if (x.fastens) add(u, v, x.note || `${v} fastens to ${u}`);
118
+ }
119
+ // Screws: what stands on the tool's line goes on after the screw, and if it must already be there, nothing can
120
+ const worlds = placeItems(s.motion, s.jointValues), marks = s.motion.marks, reaches = (u, v, seen = new Set()) => { if (u === v) return true; if (seen.has(u)) return false; seen.add(u); return [...before.get(u).keys()].some((w) => reaches(w, v, seen)); };
121
+ const R = 1.5, bad = [];
122
+ for (const x of s.fits.filter((f) => f.access)) {
123
+ const [id, name] = String(x.access).split('.'), m = marks.find((k) => k.id === id && k.name === name);
124
+ if (!m) throw new Error(`fit ${x.note || `${x.a} / ${x.b}`}: access: no anchor "${x.access}" (give <item>.<anchor>${items.includes(id) ? `; ${id} has ${marks.filter((k) => k.id === id).map((k) => k.name).join(', ') || 'none'}` : ''})`);
125
+ const W = mul(worlds[m.item], m.frame), O = [W[3], W[7], W[11]], D = [W[2], W[6], W[10]], [u, v] = basis(D), starts = [[0, 0], [R, 0], [-R, 0], [0, R], [0, -R]].map(([a, b]) => O.map((c, k) => c + a * u[k] + b * v[k]));
126
+ const screwed = [top(x.a), top(x.b)].filter((t) => by.has(t)), later = [...screwed].sort(earlier).at(-1);
127
+ for (const q of all) {
128
+ if (screwed.includes(q.id) || !starts.some((p) => hitsAlong(p, D, q.tris))) continue;
129
+ if (later && reaches(q.id, later)) bad.push({ fit: x, wall: q.id, at: O, later });
130
+ else if (later) add(later, q.id, `${q.id} covers the screw of ${x.note || later}`);
131
+ }
132
+ }
133
+ const box = (g) => { const p = g.tris.flat(); return [0, 1, 2].map((k) => { const v = p.map((x) => x[k]); return (Math.min(...v) + Math.max(...v)) / 2; }); };
134
+ if (bad.length) {
135
+ const b = bad[0], label = b.fit.note || `${b.fit.a} to ${b.fit.b}`;
136
+ return { steps: [], stuck: { item: b.later, screw: label, wall: b.wall, at: b.at, text: `the screw of "${label}" can't be reached in any order: ${b.wall} stands over it and goes on first (${[...before.get(b.wall)].slice(0, 1).map(([, why]) => why)})` } };
137
+ }
138
+ let span = 1;
139
+ for (const g of all) for (const t of g.tris) for (const p of t) for (const c of p) span = Math.max(span, Math.abs(c) * 2);
140
+ const h = Math.max(0.4, Math.min(1.5, span / 300)), memo = new Map(), rasterOf = (g, d) => { const key = `${g.id}|${d.join(',')}`; if (!memo.has(key)) memo.set(key, raster(g, d, h)); return memo.get(key); };
141
+ const free = (p, rest, d) => { for (const q of rest) if (q !== p && !allowedPair(s, p, q) && blockers(p, q, d, h, rasterOf)) return false; return true; };
142
+ const dirsFor = (p) => { // along its own axes first: a part on a joint goes on along that joint, then from above, then round the sides
143
+ const own = [];
144
+ for (const j of joints) if (items[j.child] === p.id) { const P = j.parent < 0 ? j.a : mul(worlds[j.parent], j.a); own.push([P[2], P[6], P[10]]); }
145
+ for (const m of marks) if (m.id === p.id) { const W = mul(worlds[m.item], m.frame); own.push([W[2], W[6], W[10]]); }
146
+ const list = [...own.flatMap((a) => [round(a), round(a.map((x) => -x))]), ...SIDES];
147
+ return [...new Map(list.map((d) => [d.map((x) => x.toFixed(3)).join(','), d])).values()];
148
+ };
149
+ // What stays together if a part can't leave alone: its joint parent and all that hangs from it (planets on their carrier)
150
+ const below = (a) => { const out = new Set([a]); for (let grew = true; grew;) { grew = false; for (const j of joints) if (j.parent >= 0 && out.has(items[j.parent]) && by.has(items[j.child]) && !out.has(items[j.child])) { out.add(items[j.child]); grew = true; } } return out; };
151
+ const parentOf = (id) => { const j = joints.find((x) => items[x.child] === id); return j && j.parent >= 0 ? items[j.parent] : null; };
152
+ // Take a set of parts apart, the last-attached first: [{ p, d }] or [{ group, d, sub }] (a set that leaves as one, then apart)
153
+ function takeApart(start) {
154
+ let rest = [...start].sort((a, b) => earlier(b.id, a.id));
155
+ const off = [], waits = (p, set) => [...before.get(p.id).keys()].some((v) => set.some((q) => q.id === v));
156
+ while (rest.length) {
157
+ let pick = null;
158
+ for (const p of rest) {
159
+ if (waits(p, rest)) continue;
160
+ if (rest.length === 1) { pick = { p, d: [0, 0, 1] }; break; }
161
+ const d = dirsFor(p).find((x) => free(p, rest, x));
162
+ if (d) { pick = { p, d }; break; }
163
+ }
164
+ if (!pick) for (const p of rest) { // nothing leaves alone: try what's joined to it, as one
165
+ for (let a = parentOf(p.id); a && a !== base && rest.some((q) => q.id === a) && !pick; a = parentOf(a)) {
166
+ const names = below(a), group = rest.filter((q) => names.has(q.id)), others = rest.filter((q) => !names.has(q.id));
167
+ if (group.length < 2 || !others.length || group.length === rest.length || group.some((q) => waits(q, others))) continue;
168
+ const d = dirsFor(by.get(a)).find((x) => group.every((q) => others.every((o) => allowedPair(s, q, o) || !blockers(q, o, x, h, rasterOf))));
169
+ if (d) { const sub = takeApart(group); if (sub.stuck) return sub; pick = { group, d, sub }; }
170
+ }
171
+ if (pick) break;
172
+ }
173
+ if (!pick) {
174
+ const stuckBy = rest.filter((p) => !waits(p, rest))[0] ?? rest[0];
175
+ const holders = [...new Set(SIDES.flatMap((d) => rest.filter((q) => q !== stuckBy && !allowedPair(s, stuckBy, q) && blockers(stuckBy, q, d, h, rasterOf)).map((q) => q.id)))];
176
+ const ringed = rest.filter((p) => waits(p, rest)).map((p) => p.id);
177
+ return { stuck: { item: stuckBy.id, wall: holders[0] ?? null, holders, at: box(stuckBy), text: holders.length ? `${stuckBy.id} can't be reached in any order: ${holders.join(' and ')} ${holders.length > 1 ? 'hold' : 'holds'} it in from every side` : `${ringed.join(', ')} each have to go on before the next, in a ring` } };
178
+ }
179
+ off.push(pick); const gone = pick.group ?? [pick.p]; rest = rest.filter((g) => !gone.includes(g));
180
+ }
181
+ return { off };
182
+ }
183
+ const apart = takeApart(all);
184
+ if (apart.stuck) return { steps: [], stuck: apart.stuck };
185
+ // Put together: last off is first on, a set built up on its own and then fitted as one
186
+ const seq = [], lay = (off) => { for (const x of [...off].reverse()) { if (x.group) { lay(x.sub.off); seq.push({ group: x.group, d: x.d }); } else seq.push(x); } };
187
+ lay(apart.off);
188
+ const at = new Map(), steps = [];
189
+ seq.forEach((x, i) => { for (const g of x.group ?? [x.p]) at.set(g.id, i); });
190
+ for (const [i, x] of seq.entries()) {
191
+ if (x.group) { steps.push({ items: x.group.map((g) => g.id), object: null, dir: round(x.d), fasteners: [], together: true }); continue; }
192
+ const { p, d } = x, list = [...new Set(s.fits.filter((f) => [...names(f.a), ...names(f.b)].includes(p.id) && (f.fastens || f.seat != null || f.fastener) && [...names(f.a), ...names(f.b)].every((n) => (at.get(n) ?? 0) <= i)))];
193
+ steps.push({ items: [p.id], object: p.object, dir: round(d), fasteners: list.map((f) => ({ fit: f.note || f.label || `${f.a} to ${f.b}`, ...(f.fastener ? { fastener: f.fastener } : {}), ...(f.count != null ? { count: f.num(f.count) } : {}) })) });
194
+ }
195
+ // Copies of one thing fitted the same way, one after another, are one step
196
+ const merged = [];
197
+ for (const st of steps) {
198
+ const last = merged.at(-1);
199
+ if (last && st.object && !st.together && last.object === st.object && last.dir.join() === st.dir.join() && JSON.stringify(last.fasteners.map((f) => f.fit)) === JSON.stringify(st.fasteners.map((f) => f.fit))) last.items.push(...st.items);
200
+ else merged.push({ items: [...st.items], object: st.object, dir: st.dir, fasteners: st.fasteners, ...(st.together ? { together: true } : {}) });
201
+ }
202
+ merged.forEach((st, i) => { st.n = i + 1; st.text = `${st.items.join(', ')}${st.object && !st.items.includes(st.object) ? ` (${st.object})` : ''}${st.together ? ' go on as one' : i ? ` goes on${st.items.length > 1 ? ', one by one' : ''}` : ' first'}${st.fasteners.length ? `: ${st.fasteners.map((f) => `${f.fit}${f.fastener ? ` (${f.count != null ? `${f.count} × ` : ''}${f.fastener})` : ''}`).join('; ')}` : ''}`; });
203
+ return { steps: merged, stuck: null };
204
+ }
205
+
206
+ // Cached by what the parts are and where they are, with everything else that changes the answer
207
+ function orderFile(s) {
208
+ const key = crypto.createHash('sha256').update(JSON.stringify([4, s.parts.map((p) => [p.item, p.hash ?? p.shape, Array.from(p.m ?? []).map((x) => +x.toFixed(4))]), s.fits.map(({ num, ...x }) => x), s.motion.joints.map((j) => [j.id, j.child, j.parent])])).digest('hex');
209
+ return paths.cache('order', `${key}.json`);
210
+ }
211
+ export function orderOf(s) {
212
+ if (s.orderSteps) return s.orderSteps;
213
+ const file = orderFile(s);
214
+ if (!process.env.CAD_NO_CACHE && host.exists(file)) return (s.orderSteps = JSON.parse(host.readText(file)));
215
+ const r = assemblyOrder(s);
216
+ try { fs.mkdirSync(path.dirname(file), { recursive: true }); host.writeText(file, JSON.stringify(r)); } catch {} // (only slower without it)
217
+ return (s.orderSteps = r);
218
+ }
219
+
220
+ // Whether an assembly is something that goes together with fastenings: anything else has no steps to find
221
+ export const isBuilt = (s) => s.a.kind !== 'plate' && s.fits.some((x) => x.fastens || x.seat != null || x.shaft != null || x.access);
222
+
223
+ /** assembly.order, in the assembly's findings shape. */
224
+ export function orderChecks(s, f) {
225
+ if (!isBuilt(s) || (s.pose != null && s.pose !== s.motion.pose)) return;
226
+ const r = orderOf(s);
227
+ if (r.stuck) f('fail', r.stuck.text, `${r.stuck.item}: can't be reached`, { code: 'assembly.order', at: r.stuck.at, refs: { item: r.stuck.item, ...(r.stuck.wall ? { wall: r.stuck.wall } : {}), ...(r.stuck.screw ? { screw: r.stuck.screw } : {}), ...(r.stuck.holders ? { holders: r.stuck.holders } : {}) } });
228
+ else f('pass', `goes together in ${r.steps.length} step${r.steps.length === 1 ? '' : 's'}, ${r.steps[0]?.items[0]} first, nothing trapped`, null, { code: 'assembly.order', values: { steps: r.steps.length }, refs: { first: r.steps[0]?.items[0] } });
229
+ }
230
+
231
+ /** Each step's picture: what's there, and the new part held off along the way it goes on. @returns {object[][]} parts lists, for preview() */
232
+ export function stepPictures(s, r) {
233
+ let off = 40;
234
+ for (const p of s.parts) for (const t of p.triangles) for (const v of t) off = Math.max(off, Math.abs(v[0]), Math.abs(v[1]), Math.abs(v[2]));
235
+ off *= 0.5;
236
+ return r.steps.map((st, i) => {
237
+ const shown = new Set(r.steps.slice(0, i + 1).flatMap((x) => x.items)), now = new Set(st.items);
238
+ return s.parts.filter((p) => shown.has(p.item)).map((p) => (now.has(p.item) ? { ...p, role: 'part', triangles: p.triangles.map((t) => t.map((v) => v.map((c, k) => c + st.dir[k] * off))) } : { ...p, role: 'reference' }));
239
+ });
240
+ }
241
+
242
+ export const orderText = (ref, r) => (r.stuck ? `${ref}: ${r.stuck.text}` : [`${ref}: how it goes together`, ...r.steps.map((st) => ` ${String(st.n).padStart(2)}. ${st.text}`)].join('\n'));
package/lib/plates.mjs ADDED
@@ -0,0 +1,108 @@
1
+ // A machine's printed parts on beds: each object in its print orientation (as it's drawn, Z up, on the bed), grouped by
2
+ // filament, spaced by the first-layer rule, and written as plate assemblies, so check and export treat them as prints.
3
+ // Each plate remembers what's on it by the build's hash ("packed"): a changed part re-packs only its plate.
4
+ import fs from 'node:fs';
5
+ import path from 'node:path';
6
+ import { bounds, check as printCheck } from '@rulecad/printcheck';
7
+ import { locate, build } from './design.mjs';
8
+ import { paths, printerOf } from './workspace.mjs';
9
+ import { peekRuleSet } from './rules.mjs';
10
+ import { CadError } from './errors.mjs';
11
+ import { assemblyPath, buildAssembly, checkAssembly } from './assembly.mjs';
12
+ import { printedParts } from './list.mjs';
13
+
14
+ const n3 = (x) => +x.toFixed(3);
15
+
16
+ // The gap between parts on a plate: what two parts need to print apart at the first layer (print_gap, plus the first
17
+ // layer's spread each side), up to whole lines of the nozzle
18
+ function rulesOf(project, gap) {
19
+ const r = peekRuleSet(printerOf(project)).rules, num = (k, f) => { const v = r[k]?.value; return typeof v === 'number' ? v : f; }, bed = num('bed', 256), line = num('line', 0.42), need = num('print_gap', 0.3) + 2 * num('foot', 0.15);
20
+ return { bed, gap: gap ?? n3(Math.ceil((need - 1e-6) / line) * line), need };
21
+ }
22
+
23
+ // Every printed thing to go on a plate: built as printed, its filaments, how big
24
+ async function plateParts(s) {
25
+ const out = [];
26
+ for (const o of s.objects) {
27
+ if (o.unplaced || o.role !== 'part' || !o.objName) continue;
28
+ const d = locate(`${s.project}/${o.objName}`), b = await build({ ...d, ...(o.variant ? { variant: o.variant } : {}) }, o.set || {}), tris = b.parts.flatMap((p) => p.triangles), { lo, hi } = bounds(tris);
29
+ const fil = [...new Set(b.parts.filter((p) => p.role !== 'support').map((p) => p.filament || 'base'))].sort().join('+') || 'base';
30
+ out.push({ id: o.id.replace(/\./g, '_'), source: o.id, object: o.objName, variant: o.variant, set: o.set || {}, filament: fil, hash: b.hash, lo, size: [hi[0] - lo[0], hi[1] - lo[1]], height: hi[2] - lo[2] });
31
+ }
32
+ return out;
33
+ }
34
+
35
+ // Shelves on a bed, largest first: as many plates as it takes
36
+ function pack(parts, { bed, gap }) {
37
+ const sorted = [...parts].sort((a, b) => b.size[1] - a.size[1] || b.size[0] - a.size[0] || a.id.localeCompare(b.id)), beds = [];
38
+ const room = bed - 2 * gap;
39
+ for (const p of sorted) {
40
+ let done = false;
41
+ for (const b of beds) {
42
+ const shelf = b.shelves.at(-1);
43
+ if (shelf.x + p.size[0] <= room && p.size[1] <= shelf.h) { b.items.push({ p, x: shelf.x, y: shelf.y }); shelf.x += p.size[0] + gap; done = true; break; }
44
+ const y = shelf.y + shelf.h + gap;
45
+ if (y + p.size[1] <= room && p.size[0] <= room) { b.shelves.push({ y, h: p.size[1], x: p.size[0] + gap }); b.items.push({ p, x: 0, y }); done = true; break; }
46
+ }
47
+ if (!done) beds.push({ shelves: [{ y: 0, h: p.size[1], x: p.size[0] + gap }], items: [{ p, x: 0, y: 0 }] });
48
+ }
49
+ return beds;
50
+ }
51
+
52
+ const plateFile = (project, name) => assemblyPath(`${project}/${name}`);
53
+ function existing(s) {
54
+ const dir = path.join(paths.project(s.project), 'assemblies'), out = [];
55
+ for (const f of fs.existsSync(dir) ? fs.readdirSync(dir) : []) { if (!f.endsWith('.json')) continue; let a; try { a = JSON.parse(fs.readFileSync(path.join(dir, f), 'utf8')); } catch { continue; } if (a.packed?.of === s.name) out.push({ name: f.slice(0, -5), a }); }
56
+ return out.sort((a, b) => a.name.localeCompare(b.name, undefined, { numeric: true }));
57
+ }
58
+ const nameOf = (s, filament, k) => `${s.name}-${filament.replace(/\+/g, '-')}-${k}`;
59
+
60
+ function plateJson(s, plate, { bed, gap }) {
61
+ const origin = (bed - 2 * gap) / 2;
62
+ return { title: `${s.a.title || s.name}: ${plate.filament}, plate ${plate.n}`, kind: 'plate', note: `Generated by cad plates from ${s.name}. Hand edits are replaced when a part on it changes.`,
63
+ packed: { of: s.name, filament: plate.filament, gap, parts: Object.fromEntries(plate.items.map(({ p }) => [p.id, p.hash])) },
64
+ items: plate.items.map(({ p, x, y }) => ({ id: p.id, object: p.object, ...(p.variant ? { variant: p.variant } : {}), ...(Object.keys(p.set).length ? { set: p.set } : {}), at: [n3(x - origin - p.lo[0]), n3(y - origin - p.lo[1]), n3(-p.lo[2])] })) };
65
+ }
66
+
67
+ /**
68
+ * The plates of an assembly: a stale plate (a part on it changed or gone) and any new part packed again, every other plate left alone.
69
+ * @param {object} s a built assembly @param {{ write?: boolean, gap?: number }} [options]
70
+ * @returns {Promise<{ plates: object[], touched: string[], removed: string[], gap: number, bed: number, findings: object[] }>}
71
+ */
72
+ export async function platesOf(s, { write = false, gap: asked } = {}) {
73
+ const parts = await plateParts(s), { bed, gap } = rulesOf(s.project, asked), findings = [], plates = [], touched = [], removed = [];
74
+ if (!parts.length) throw new CadError('plates.empty', `${s.project}/${s.name} has nothing printed to put on a plate`);
75
+ const big = parts.filter((p) => p.size[0] > bed - 2 * gap || p.size[1] > bed - 2 * gap);
76
+ for (const p of big) findings.push({ level: 'fail', text: `${p.id} (${p.object}) is ${Number(p.size[0].toFixed(1))} × ${Number(p.size[1].toFixed(1))} mm: bigger than the ${bed} mm bed, so it has no plate: split it or turn it`, code: 'plate.bed', refs: { item: p.id }, values: { size: p.size, bed } });
77
+ const by = new Map(parts.filter((p) => !big.includes(p)).map((p) => [p.id, p])), had = existing(s), kept = new Set(), used = new Set();
78
+ // A plate stands if everything on it is still there and unchanged
79
+ for (const e of had) {
80
+ const on = Object.entries(e.a.packed.parts || {}), ok = on.length && on.every(([id, h]) => by.get(id)?.hash === h) && e.a.packed.gap === gap;
81
+ if (!ok) continue;
82
+ kept.add(e.name); on.forEach(([id]) => used.add(id)); plates.push({ name: e.name, filament: e.a.packed.filament, a: e.a, items: e.a.items.map((it) => { const p = by.get(it.id), origin = (bed - 2 * gap) / 2; return { p, x: it.at[0] + p.lo[0] + origin, y: it.at[1] + p.lo[1] + origin }; }), stood: true });
83
+ }
84
+ // Everything else, packed by filament; names reused from the plates that are going, so a changed part keeps its name
85
+ const free = [...by.values()].filter((p) => !used.has(p.id)), byFilament = new Map();
86
+ for (const p of free) { if (!byFilament.has(p.filament)) byFilament.set(p.filament, []); byFilament.get(p.filament).push(p); }
87
+ const goingNames = had.filter((e) => !kept.has(e.name)).map((e) => e.name);
88
+ for (const [filament, list] of byFilament) {
89
+ const beds = pack(list, { bed, gap }); let k = 0;
90
+ const next = () => { const reuse = goingNames.find((n) => had.find((e) => e.name === n)?.a.packed.filament === filament); if (reuse) { goingNames.splice(goingNames.indexOf(reuse), 1); return reuse; } let name; do name = nameOf(s, filament, ++k); while (kept.has(name) || plates.some((x) => x.name === name)); return name; };
91
+ for (const b of beds) { const name = next(), n = Number(name.match(/-(\d+)$/)?.[1]) || 1, plate = { name, filament, n, items: b.items }; plate.a = plateJson(s, plate, { bed, gap }); plates.push(plate); touched.push(name); }
92
+ }
93
+ for (const n of goingNames) removed.push(n);
94
+ plates.sort((a, b) => a.name.localeCompare(b.name, undefined, { numeric: true }));
95
+ if (write) {
96
+ const dir = path.join(paths.project(s.project), 'assemblies'); fs.mkdirSync(dir, { recursive: true });
97
+ for (const p of plates) if (!p.stood) fs.writeFileSync(plateFile(s.project, p.name), `${JSON.stringify(p.a, null, 2)}\n`);
98
+ for (const n of removed) fs.rmSync(plateFile(s.project, n), { force: true });
99
+ }
100
+ const grams = new Map(printedParts(s).map((x) => [x.id.replace(/\./g, '_'), x]));
101
+ return { bed, gap, touched, removed, findings, plates: plates.map((p) => ({ name: p.name, filament: p.filament, parts: p.items.map(({ p: q, x, y }) => ({ id: q.id, object: q.object, x: n3(x + gap), y: n3(y + gap), w: n3(q.size[0]), d: n3(q.size[1]) })), grams: n3(p.items.reduce((t, { p: q }) => t + (grams.get(q.id)?.grams ?? 0), 0)), minutes: p.items.reduce((t, { p: q }) => t + (grams.get(q.id)?.minutes ?? 0), 0), stood: !!p.stood })) };
102
+ }
103
+
104
+ /** Each plate's checks: what check says of a plate, the print check over the whole bed included. */
105
+ export async function checkPlate(ref) {
106
+ const s = await buildAssembly(ref), printer = printerOf(s.project), rules = Object.fromEntries(Object.keys(peekRuleSet(printer).rules).map((k) => [k, s.num(`${printer}.${k}`)])), printed = s.parts.filter((p) => p.role !== 'reference');
107
+ return [...checkAssembly(s), ...printCheck(printed.flatMap((p) => p.triangles), rules, { parts: printed })];
108
+ }
package/lib/power.mjs ADDED
@@ -0,0 +1,31 @@
1
+ // Drivers and supplies in an assembly: each stepper's driver is named by the bought item it plugs into, the current it is
2
+ // set to is checked and the trimmer's voltage said, and the supply is held against the whole machine's draw.
3
+ import { driver as driverModel, setting, powerBudget } from '@rulecad/motors';
4
+
5
+ const n3 = (x, d = 2) => String(Number(x.toFixed(d)));
6
+
7
+ function itemById(s, id) { return s.objects.find((o) => o.id === id); }
8
+
9
+ export function powerChecks(s, f) {
10
+ const drives = s.motion?.drives ?? [], supplies = s.objects.filter((o) => o.bought?.part === 'supply');
11
+ const psu = supplies[0]?.built.values, voltage = psu?.output_voltage, draws = [];
12
+ for (const d of drives) {
13
+ const m = d.model, refs = { item: d.id, ...(d.joint ? { joint: d.joint } : {}) };
14
+ if (m.type === 'stepper') {
15
+ const rated = m.figures.rated_current?.value, current = d.spec.current ?? rated, R = m.figures.resistance?.value;
16
+ draws.push({ name: d.id, current, resistance: R, ...(d.spec.duty != null ? { duty: d.spec.duty } : {}) });
17
+ if (!d.spec.driver) { if (s.task) f('warn', `${d.id} has no "driver": nothing checks the current it's set to (name a bought driver item)`, `${d.id}: no driver`, { code: 'motor.driver', refs }); continue; }
18
+ const o = itemById(s, d.spec.driver);
19
+ if (!o || o.bought?.part !== 'driver') { f('fail', `${d.id}: driver "${d.spec.driver}" isn't a bought driver item`, `${d.id}: no such driver`, { code: 'motor.driver', refs }); continue; }
20
+ const model = driverModel(o.bought.set, { variant: o.bought.variant ?? undefined }), { vref, findings } = setting(model, current, { cooled: !!d.spec.cooled, supply: voltage, microsteps: d.spec.microsteps });
21
+ for (const x of findings) f(x.level, `${d.id}: ${x.text}`, `${d.id}: driver`, { code: x.code, values: x.values, refs });
22
+ if (!findings.some((x) => x.level === 'fail')) f('pass', `${d.id} on ${model.name}: set the trimmer to ${n3(vref, 3)} V for ${n3(current, 2)} A per coil (${model.formula}${model.uart ? `, or set it over UART` : ''}), ${model.sense} ohm sense resistors: read yours before trusting this`, null, { code: 'motor.driver', refs, values: { vref, current, sense: model.sense } });
23
+ } else if (m.type === 'servo') {
24
+ draws.push({ name: d.id, current: 0.7, voltage: m.figures.rated_voltage?.value ?? 5, duty: d.spec.duty ?? 0.2 });
25
+ }
26
+ }
27
+ if (!draws.length || !supplies.length) { if (draws.length && s.task) f('warn', 'there is no "supply" among the bought items: nothing checks the power', 'no supply', { code: 'power.supply' }); return; }
28
+ const o = supplies[0], I = psu.output_current, extra = s.objects.filter((x) => x.bought?.part === 'board').map((x) => ({ name: x.id, current: 0.1, voltage: 5, duty: 1 }));
29
+ const r = powerBudget([...draws, ...extra], { voltage, current: I, margin: s.a.power?.margin ?? 1.25 });
30
+ for (const x of r.findings) f(x.level, `${o.id} (${o.bought.variant ?? o.bought.set}): ${x.text}`, x.level === 'pass' ? null : `${o.id}: too small`, { code: x.code, values: x.values, refs: { item: o.id } });
31
+ }