@rulecad/cad 0.7.56 → 0.7.58
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 +103 -1
- package/CHANGELOG.md +241 -0
- package/EXAMPLES.md +782 -2
- package/README.md +719 -8
- package/TUTORIAL.md +2 -0
- package/bin/cad.mjs +135 -29
- package/lib/assembly.mjs +83 -17
- package/lib/beams.mjs +46 -13
- package/lib/bought.mjs +41 -5
- package/lib/buildpage.mjs +8 -3
- package/lib/edit.mjs +10 -4
- package/lib/fasten.mjs +279 -47
- package/lib/fittings.mjs +313 -0
- package/lib/framebuild.mjs +463 -0
- package/lib/framecheck.mjs +831 -0
- package/lib/framegen.mjs +111 -0
- package/lib/frameheat.mjs +94 -0
- package/lib/frameprint.mjs +277 -0
- package/lib/frames.mjs +5 -3
- package/lib/framesize.mjs +261 -0
- package/lib/guides.mjs +354 -0
- package/lib/jigs.mjs +240 -0
- package/lib/joins.mjs +263 -0
- package/lib/kit.mjs +190 -0
- package/lib/links.mjs +11 -3
- package/lib/list.mjs +28 -8
- package/lib/loads.mjs +12 -4
- package/lib/measured.mjs +86 -17
- package/lib/motors.mjs +7 -3
- package/lib/optimise.mjs +18 -3
- package/lib/order.mjs +28 -14
- package/lib/panels.mjs +220 -0
- package/lib/plates.mjs +37 -16
- package/lib/services.mjs +132 -0
- package/lib/sheet.mjs +15 -1
- package/lib/slotnuts.mjs +159 -0
- package/lib/task.mjs +43 -3
- package/lib/wires.mjs +2 -1
- package/package.json +6 -6
- package/schemas/assembly.schema.json +34 -9
package/lib/kit.mjs
ADDED
|
@@ -0,0 +1,190 @@
|
|
|
1
|
+
// A kit: one folder that holds everything a person needs to build an assembly, to hand to someone who never opens the
|
|
2
|
+
// model. exports/<project>/<assembly>-kit/:
|
|
3
|
+
// README.md the build page: what the checks say, what to buy, what to print, the cut list, the drilling
|
|
4
|
+
// and tapping, and the build in numbered steps with the torques and the diagonals to measure
|
|
5
|
+
// buy.csv the shopping list as a table: bars, bought parts, screws, nuts and inserts in packs
|
|
6
|
+
// print/<plate>.3mf each plate of printed parts, by material (cad plates), and the beams' jigs on their own plates
|
|
7
|
+
// sheets/beam-<m>.svg each mark of beam's cut-and-drill sheet, to scale (print at 100%)
|
|
8
|
+
// pictures/ with --pictures: the whole, and each step of the build that shows something
|
|
9
|
+
// Written only for an assembly that cad check passes with nothing failing: a kit of a failing design is refused by name.
|
|
10
|
+
import fs from 'node:fs';
|
|
11
|
+
import path from 'node:path';
|
|
12
|
+
import { paths, WS } from './workspace.mjs';
|
|
13
|
+
import { CadError } from './errors.mjs';
|
|
14
|
+
import { buildAssembly } from './assembly.mjs';
|
|
15
|
+
import { shoppingList } from './list.mjs';
|
|
16
|
+
import { platesOf, checkPlate } from './plates.mjs';
|
|
17
|
+
import { cutListOf, writeBeamSheets } from './beams.mjs';
|
|
18
|
+
import { writeJigs } from './jigs.mjs';
|
|
19
|
+
import { frameBuild, frameStepPictures } from './framebuild.mjs';
|
|
20
|
+
import { orderOf, isBuilt } from './order.mjs';
|
|
21
|
+
import { withPreload } from './slotnuts.mjs';
|
|
22
|
+
import { threemf, slotOf } from './threemf.mjs';
|
|
23
|
+
import { companions } from './fittings.mjs';
|
|
24
|
+
|
|
25
|
+
const mm = (x) => String(+Number(x).toFixed(2));
|
|
26
|
+
const plural = (n, one, many = `${one}s`) => `${n} ${n === 1 ? one : many}`;
|
|
27
|
+
const cell = (x) => String(x ?? '').replace(/\|/g, '\\|').replace(/\n/g, ' ');
|
|
28
|
+
// The upright beams (placed by their ends, running up z) and the corner each stands at, seen from above: left and right
|
|
29
|
+
// by x, front and back by y (the front the side of least y), where the uprights stand in two rows that way
|
|
30
|
+
function uprightPlan(s, marks) {
|
|
31
|
+
const isVec = (v) => Array.isArray(v) && v.length === 3 && v.every((x) => typeof x === 'number' && Number.isFinite(x));
|
|
32
|
+
const ups = (s.items ?? []).filter((it) => it.beam && isVec(it.from) && isVec(it.to) && Math.abs(it.from[0] - it.to[0]) < 1e-6 && Math.abs(it.from[1] - it.to[1]) < 1e-6 && Math.abs(it.to[2] - it.from[2]) > 1e-6);
|
|
33
|
+
if (ups.length < 2) return null;
|
|
34
|
+
const xs = [...new Set(ups.map((u) => +u.from[0].toFixed(3)))].sort((a, b) => a - b), ys = [...new Set(ups.map((u) => +u.from[1].toFixed(3)))].sort((a, b) => a - b);
|
|
35
|
+
const side = (v, list, lo, hi) => (list.length === 2 ? (Math.abs(v - list[0]) < 1e-3 ? lo : hi) : null);
|
|
36
|
+
const rows = ups.map((u) => {
|
|
37
|
+
const fb = side(u.from[1], ys, 'front', 'back'), lr = side(u.from[0], xs, 'left', 'right');
|
|
38
|
+
return [u.id, [fb, lr].filter(Boolean).join(' ') || 'see x, y', `${mm(u.from[0])}, ${mm(u.from[1])}`, marks.find((m) => m.items.includes(u.id))?.mark ?? ''];
|
|
39
|
+
});
|
|
40
|
+
const down = ups.every((u) => u.from[2] < u.to[2]) ? ' Each upright stands with its end a down.' : '';
|
|
41
|
+
return { rows, said: `Seen from above, x to the right and y away from you: the front is the side nearest you (least y), the left the side of least x.${down}` };
|
|
42
|
+
}
|
|
43
|
+
const table = (heads, rows) => [`| ${heads.join(' | ')} |`, `|${heads.map(() => '---').join('|')}|`, ...rows.map((r) => `| ${r.map(cell).join(' | ')} |`)];
|
|
44
|
+
const csv = (rows) => rows.map((r) => r.map((x) => { const t = String(x ?? ''); return /[",\n]/.test(t) ? `"${t.replace(/"/g, '""')}"` : t; }).join(',')).join('\n');
|
|
45
|
+
|
|
46
|
+
/** The kit's folder for an assembly: exports/<project>/<assembly>-kit. @param {object} s a built assembly */
|
|
47
|
+
export const kitDir = (s) => paths.exports(s.project, `${s.name}-kit`);
|
|
48
|
+
|
|
49
|
+
// A plate assembly's printed parts as a 3MF: one object per printed thing, a part per part, each in its filament (as
|
|
50
|
+
// cad export writes a plate)
|
|
51
|
+
async function plate3mf(ref, file) {
|
|
52
|
+
const { filaments, slots } = await import('./links.mjs');
|
|
53
|
+
const s = await buildAssembly(ref), fil = filaments(s.project), things = new Map();
|
|
54
|
+
for (const p of s.parts.filter((q) => q.role !== 'reference')) { if (!things.has(p.leaf)) things.set(p.leaf, []); things.get(p.leaf).push({ name: p.label, triangles: p.triangles, slot: slotOf(fil, p.filament) }); }
|
|
55
|
+
fs.writeFileSync(file, await threemf([...things].map(([name, parts]) => ({ name, parts })), { filaments: slots(fil) }));
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/**
|
|
59
|
+
* Write an assembly's kit. Refused by name (kit.check) where cad check fails, and (kit.empty) where there is nothing to
|
|
60
|
+
* build from: no beams, nothing printed and nothing bought.
|
|
61
|
+
* @param {object} s a built assembly @param {object[]} findings checkAssembly's
|
|
62
|
+
* @param {{ pictures?: boolean, preview?: Function }} [o] pictures: draw the whole and each step (needs Chrome; preview is lib/preview.mjs's)
|
|
63
|
+
* @returns {Promise<{ dir: string, files: string[], plates: object[], jigs: object | null, sheets: object[], steps: number, findings: object[] }>}
|
|
64
|
+
*/
|
|
65
|
+
export async function writeKit(s, findings, { pictures = false, preview = null } = {}) {
|
|
66
|
+
const ref = `${s.project}/${s.name}`, fails = findings.filter((f) => f.level === 'fail');
|
|
67
|
+
if (fails.length) throw new CadError('kit.check', `${ref}: cad check fails ${plural(fails.length, 'check')} (${fails.slice(0, 3).map((f) => f.text).join('; ')}${fails.length > 3 ? '; ..' : ''}), and a kit is written only for a design that checks with nothing failing: cad check ${ref}`);
|
|
68
|
+
const dir = kitDir(s), files = [], rel = (f) => path.relative(dir, f).split(path.sep).join('/'), put = (f, text) => { fs.mkdirSync(path.dirname(f), { recursive: true }); fs.writeFileSync(f, text); files.push(rel(f)); };
|
|
69
|
+
fs.rmSync(dir, { recursive: true, force: true }); // (the kit is written whole each time: nothing stale is left in it)
|
|
70
|
+
fs.mkdirSync(dir, { recursive: true });
|
|
71
|
+
|
|
72
|
+
// What to print: the plates (cad plates' own, each written as its 3MF) and the beams' jigs
|
|
73
|
+
let pl = null;
|
|
74
|
+
try { pl = await platesOf(s, { write: true }); } catch (e) { if (e.code !== 'plates.empty') throw e; }
|
|
75
|
+
const plates = [];
|
|
76
|
+
for (const p of pl?.plates ?? []) {
|
|
77
|
+
const file = path.join(dir, 'print', `${p.name}.3mf`); fs.mkdirSync(path.dirname(file), { recursive: true });
|
|
78
|
+
await plate3mf(`${s.project}/${p.name}`, file); files.push(rel(file));
|
|
79
|
+
const bad = (await checkPlate(`${s.project}/${p.name}`)).filter((f) => (f.level === 'fail' || f.level === 'warn') && f.code !== 'rules.estimate');
|
|
80
|
+
plates.push({ ...p, file: rel(file), issues: bad.map((f) => `${f.level}: ${f.text}`) });
|
|
81
|
+
}
|
|
82
|
+
const cut = cutListOf(s), jigs = cut ? await writeJigs(s) : null;
|
|
83
|
+
if (jigs) for (const p of jigs.plates) { const file = path.join(dir, 'print', path.basename(p.file)); fs.copyFileSync(p.file, file); files.push(rel(file)); p.kit = rel(file); }
|
|
84
|
+
// The sheets: each mark's, as cad beams writes them
|
|
85
|
+
const sheets = cut ? writeBeamSheets(s).map((x) => { const file = path.join(dir, 'sheets', `beam-${x.mark}.svg`); fs.mkdirSync(path.dirname(file), { recursive: true }); fs.copyFileSync(x.file, file); files.push(rel(file)); return { ...x, kit: rel(file), was: x.file }; }) : [];
|
|
86
|
+
// What to buy, and how it goes together
|
|
87
|
+
const list = shoppingList(s), frame = s.joins?.length ? frameBuild(s) : null, order = !frame && isBuilt(s) ? withPreload(s, orderOf(s)) : null;
|
|
88
|
+
if (!cut && !plates.length && !list.bought.length && !list.fasteners.length) throw new CadError('kit.empty', `${ref} has nothing to build a kit from: no beams, nothing printed and nothing bought`);
|
|
89
|
+
if (frame?.stuck || order?.stuck) throw new CadError('kit.order', `${ref}: ${(frame ?? order).stuck.text}`);
|
|
90
|
+
// a sheet named in a step by its file in exports/ is named by its file in the kit
|
|
91
|
+
const local = (t) => sheets.reduce((x, sh) => x.split(path.relative(WS, sh.was)).join(sh.kit).split(path.relative(WS, sh.was).split(path.sep).join('/')).join(sh.kit), t);
|
|
92
|
+
|
|
93
|
+
// Pictures: the whole, and each step that shows something
|
|
94
|
+
const pics = new Map();
|
|
95
|
+
if (pictures) {
|
|
96
|
+
if (!preview) throw new CadError('kit.pictures', 'cad kit --pictures draws with lib/preview.mjs, and was given none');
|
|
97
|
+
const whole = path.join(dir, 'pictures', `${s.name}.png`);
|
|
98
|
+
await preview(s.parts.map((p) => ({ name: p.name, label: p.label, role: p.role, item: p.item, triangles: p.triangles })), { title: s.a.title || s.name, meta: 'as built', out: whole }); files.push(rel(whole));
|
|
99
|
+
if (frame) for (const { n, parts } of frameStepPictures(s, frame)) { const st = frame.steps[n - 1], out = path.join(dir, 'pictures', `step-${String(n).padStart(2, '0')}.png`); await preview(parts, { title: `${s.a.title || s.name}: step ${n} of ${frame.steps.length}`, meta: st.text, out }); files.push(rel(out)); pics.set(n, rel(out)); }
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
// buy.csv: one row a line to buy
|
|
103
|
+
const rows = [['kind', 'quantity', 'what', 'buy', 'for']];
|
|
104
|
+
for (const st of list.cut?.stock ?? []) for (const b of st.buy) rows.push(['bar', b.count, `${st.profile} x ${mm(b.length)} mm`, `${b.count} x ${mm(b.length)} mm`, `the cut list's marks ${[...new Set(st.bars.flatMap((x) => x.cuts.map((c) => c.mark)))].join(', ')}`]);
|
|
105
|
+
for (const b of list.bought.filter((x) => x.part !== 'beam')) rows.push(['bought', b.qty, `${b.set}${b.variant ? ` (${b.variant})` : ''}${b.size ? ` cut ${b.size[0]} x ${b.size[1]} mm` : ''}`, b.cost != null ? `${b.cost} ${b.currency} each` : '', b.items.join(' ')]);
|
|
106
|
+
for (const f of list.fasteners) rows.push([f.kind ?? 'fixing', f.qty, f.fastener, f.packs ? `${f.packs} pack${f.packs > 1 ? 's' : ''} of ${list.totals.pack.size}` : '', f.from.join('; ')]);
|
|
107
|
+
put(path.join(dir, 'buy.csv'), `${csv(rows)}\n`);
|
|
108
|
+
|
|
109
|
+
// README.md: the build page
|
|
110
|
+
const title = s.a.title || s.name, out = [`# ${title}: the kit`, '', `Everything needed to build ${title}, made from the assembly \`${ref}\` by \`cad kit\`. The design checks with nothing failing; this folder is enough to buy, print, cut, drill and put it together without opening the model.`, ''];
|
|
111
|
+
out.push('## In this folder', '', ...table(['File', 'What it is'], [
|
|
112
|
+
['README.md', 'This page: what the checks say, what to buy, what to print, the cut list, the drilling and tapping, and the build step by step'],
|
|
113
|
+
['buy.csv', 'The shopping list as a table: bars, bought parts, screws, nuts and inserts, each with how many to buy'],
|
|
114
|
+
...plates.map((p) => [p.file, `A plate to print in ${p.material.toUpperCase()}: ${plural(p.parts.length, 'part')}, ${mm(p.grams)} g, about ${p.minutes} min. Open it in the slicer as it is`]),
|
|
115
|
+
...(jigs?.plates ?? []).map((p) => [p.kit, `Jigs for cutting, drilling, tapping and squaring the beams, in ${String(p.material).toUpperCase()}: ${plural(p.parts.length, 'part')}`]),
|
|
116
|
+
...sheets.map((x) => [x.kit, `Mark ${x.mark}'s cut-and-drill sheet (${x.items.join(', ')}), to scale: print it at 100%`]),
|
|
117
|
+
...(pictures ? [[`pictures/${s.name}.png`, 'The whole, as built, from six sides'], ...[...pics].map(([n, f]) => [f, `Step ${n}, what is on the bench then`])] : []),
|
|
118
|
+
]), '');
|
|
119
|
+
|
|
120
|
+
// what the checks say: the warnings, and what the frame's own checks found, each with what it rests on
|
|
121
|
+
const warns = findings.filter((f) => f.level === 'warn'), passes = findings.filter((f) => f.level === 'pass').length;
|
|
122
|
+
const said = findings.filter((f) => /^frame\.(deflection|stress|buckling|rack|frequency|square)$/.test(f.code ?? '') || f.code === 'mass.parts');
|
|
123
|
+
out.push('## What the checks say', '', `\`cad check ${ref}\`: ${plural(passes, 'check')} pass, none fail${warns.length ? `, ${plural(warns.length, 'warning')}` : ', none warn'}.`, '');
|
|
124
|
+
for (const f of warns) out.push(`- Warning: ${f.text}`);
|
|
125
|
+
for (const f of said) out.push(`- ${f.text}`);
|
|
126
|
+
out.push('');
|
|
127
|
+
|
|
128
|
+
// what to buy
|
|
129
|
+
out.push('## What to buy', '');
|
|
130
|
+
if (list.cut) {
|
|
131
|
+
out.push('### Bars', '', `Cut to the cut list below. Each cut takes the saw's ${mm(list.cut.rules.kerf.value)} mm kerf, and ${mm(list.cut.rules.trim.value)} mm is trimmed off each bar's first end.`, '');
|
|
132
|
+
out.push(...table(['Profile', 'Buy', 'Left over, mm'], list.cut.stock.map((st) => [st.profile, st.buy.map((b) => `${b.count} x ${mm(b.length)} mm`).join(', '), mm(st.offcut ?? 0)])), '');
|
|
133
|
+
}
|
|
134
|
+
const bought = list.bought.filter((b) => b.part !== 'beam');
|
|
135
|
+
if (bought.length) out.push('### Bought parts', '', ...table(['Qty', 'Part', 'What', 'Price each', 'Where it goes'], bought.map((b) => [b.qty, `${b.set}${b.variant ? ` (${b.variant})` : ''}${b.size ? `, cut ${b.size[0]} x ${b.size[1]} mm` : ''}`, b.part, b.cost != null ? `${b.cost} ${b.currency}` : 'not given', b.items.join(', ')])), '');
|
|
136
|
+
if (list.fasteners.length) out.push('### Screws, nuts and inserts', '', ...table(['Qty', 'Fixing', 'Buy', 'Where it goes'], list.fasteners.map((f) => [f.qty, f.fastener, f.packs ? `${plural(f.packs, 'pack')} of ${list.totals.pack.size}, ${f.spare} spare` : '', f.from.join('; ')])), '');
|
|
137
|
+
if (list.totals.pack) out.push(`Packs of ${list.totals.pack.size} are ${list.totals.pack.kind === 'estimate' ? 'an estimate' : `${list.totals.pack.kind}`} (${list.totals.pack.rule}).`, '');
|
|
138
|
+
|
|
139
|
+
// what to print
|
|
140
|
+
if (plates.length || jigs?.jigs.length) {
|
|
141
|
+
out.push('## What to print', '');
|
|
142
|
+
if (plates.length) {
|
|
143
|
+
out.push(...table(['Plate', 'Material', 'Parts', 'Grams', 'Minutes', 'Prints'], plates.map((p) => [p.file, p.material.toUpperCase(), p.parts.map((x) => x.id).join(', '), mm(p.grams), p.minutes, p.issues.length ? p.issues.join('; ') : 'clean'])), '');
|
|
144
|
+
const companions = list.printed.filter((x) => x.with);
|
|
145
|
+
if (companions.length) out.push(`${companions.map((x) => x.id).join(', ')} ${companions.length === 1 ? 'is' : 'are'} printed beside the part ${companions.length === 1 ? 'it goes' : 'they go'} with (${[...new Set(companions.map((x) => x.with))].join(', ')}) and screwed in by hand once that is on.`, '');
|
|
146
|
+
out.push(`About ${mm(list.totals.printedGrams)} g of ${list.totals.material.toUpperCase()} and ${list.totals.minutes} min of printing (an estimate from each part's volume and the printer's flow).`, '');
|
|
147
|
+
}
|
|
148
|
+
if (jigs?.jigs.length) {
|
|
149
|
+
out.push('### Jigs', '', 'Printed tools for making the beams, each marked with the marks it is for. Print them first.', '');
|
|
150
|
+
out.push(...table(['Jig', 'Mark', 'For', 'Grams', 'Margin at its load'], jigs.jigs.map((x) => [x.name, x.mark, x.kind === 'length-stop' ? `cutting ${x.for.map((w) => `mark ${w.mark}`).join(', ')} to length against one stop` : x.kind === 'square-corner' ? x.for.map((w) => w.text).join('; ') : x.for.map((w) => `${w.label ?? w.mark} (${w.items.join(', ')}): ${w.line}`).join('; '), mm(x.grams), `${mm(x.margin)} x`])), '');
|
|
151
|
+
for (const f of jigs.findings) out.push(`- ${f.level === 'warn' ? 'Warning: ' : ''}${f.text}`);
|
|
152
|
+
if (jigs.findings.length) out.push('');
|
|
153
|
+
}
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
// the cut list and the drilling
|
|
157
|
+
if (list.cut) {
|
|
158
|
+
out.push('## Cut', '', 'Beams that are the same share a mark. Write the item on each beam as it is cut.', '');
|
|
159
|
+
out.push(...table(['Mark', 'Qty', 'Profile', 'Length, mm', 'Items'], list.cut.marks.map((m) => [m.mark, m.count, m.profile, mm(m.length), m.items.join(', ')])), '');
|
|
160
|
+
for (const st of list.cut.stock) { out.push(`${st.profile}, the cuts on each bar in order:`, ''); st.bars.forEach((b, i) => out.push(`${i + 1}. A ${mm(b.length)} mm bar: ${b.cuts.map((c) => `${c.mark} ${mm(c.length)} (${c.item})`).join(', ')}; ${mm(b.offcut)} mm left`)); out.push(''); }
|
|
161
|
+
out.push('## Drill and tap', '', 'Each mark\'s work, every hole dimensioned from end a on its sheet.', '');
|
|
162
|
+
out.push(...table(['Mark', 'Work', 'Sheet'], list.cut.marks.map((m) => [m.mark, m.ops.length ? m.ops.join('; ') : 'cut square, nothing else', sheets.find((x) => x.mark === m.mark)?.kit ?? ''])), '');
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
// where each upright stands: a plan of the frame's corners, so the build is followed without the pictures
|
|
166
|
+
const plan = uprightPlan(s, list.cut?.marks ?? []);
|
|
167
|
+
if (frame && plan) out.push('## Where the uprights stand', '', plan.said, '', ...table(['Upright', 'Corner', 'x, y (mm, its centre line)', 'Mark'], plan.rows), '');
|
|
168
|
+
|
|
169
|
+
// the build
|
|
170
|
+
const pads = companions(s);
|
|
171
|
+
if (frame) {
|
|
172
|
+
out.push('## Build', '', 'From bars to a square frame, then the rest mounted on it. Snug joins are tightened to their torque once their bay is square.', '');
|
|
173
|
+
for (const st of frame.steps) {
|
|
174
|
+
out.push(`${st.n}. ${local(st.text)}`);
|
|
175
|
+
for (const l of st.lines ?? []) out.push(` - ${local(l)}`);
|
|
176
|
+
for (const c of pads.filter((x) => st.items?.includes(x.of))) out.push(` - Then screw ${c.id} (printed beside it) into ${c.of} by hand, as far as levels the frame`);
|
|
177
|
+
if (pics.has(st.n)) out.push('', ` })`, '');
|
|
178
|
+
}
|
|
179
|
+
out.push('');
|
|
180
|
+
for (const x of frame.notFlat ?? []) out.push(`The bay of ${x.name} is built on the frame, not flat: ${x.why}.`, '');
|
|
181
|
+
if (frame.torques.length) out.push('### Tightening, by kind of join', '', ...table(['Join', 'Joins', 'Screws', 'Key', 'N m', 'Why'], frame.torques.map((t) => [t.kind, t.joins, t.fasteners.join(', '), t.key, mm(t.torque), t.why])), '');
|
|
182
|
+
if (frame.bays.length) out.push('### Diagonals', '', 'Measure both diagonals of each bay, inside corner to inside corner. Where they differ by more than the last column, push the corners of the long diagonal together, tighten and measure again.', '', ...table(['Bay', 'Opening, mm', 'Each diagonal, mm', 'Accept a difference up to, mm'], frame.bays.map((b) => [b.name, `${mm(b.width)} x ${mm(b.height)}`, mm(b.square.diagonal), mm(b.square.accept)])), '');
|
|
183
|
+
} else if (order) {
|
|
184
|
+
out.push('## Build', '');
|
|
185
|
+
for (const st of order.steps) { out.push(`${st.n}. ${st.text}`); for (const l of st.load ?? []) out.push(` - First, ${l}`); }
|
|
186
|
+
out.push('');
|
|
187
|
+
}
|
|
188
|
+
put(path.join(dir, 'README.md'), `${out.join('\n').replace(/\n{3,}/g, '\n\n').trimEnd()}\n`);
|
|
189
|
+
return { dir, files: files.sort(), plates, jigs: jigs ? { count: jigs.jigs.length, plates: jigs.plates.map((p) => ({ file: p.kit, material: p.material, parts: p.parts.length })), findings: jigs.findings } : null, sheets: sheets.map((x) => ({ mark: x.mark, file: x.kit, items: x.items })), steps: frame?.steps.length ?? order?.steps.length ?? 0, findings: warns };
|
|
190
|
+
}
|
package/lib/links.mjs
CHANGED
|
@@ -9,6 +9,8 @@ import { pcbEngine } from './design.mjs';
|
|
|
9
9
|
import { shapes, motionData, checkAssembly, wireRoutesOf } from './assembly.mjs';
|
|
10
10
|
import { slotOf } from './threemf.mjs';
|
|
11
11
|
import { taskData, stepsData, buildData, ledgerRows } from './buildpage.mjs';
|
|
12
|
+
import { beamSheet } from '@rulecad/frames';
|
|
13
|
+
import { cutListOf } from './beams.mjs';
|
|
12
14
|
|
|
13
15
|
/** The project's filaments: { base: { slot: 1, … }, legend: { slot: 2, … } } in project.json. @param {string} project */
|
|
14
16
|
export const filaments = (project) => readJson(path.join(paths.project(project), 'project.json')).filaments || {};
|
|
@@ -57,11 +59,11 @@ export async function objectModel(b, { title, version, src, set, filaments: fil
|
|
|
57
59
|
// Each board's fab zip (cad export's: Gerbers, drill files, BOM, placement), for the page to offer as a download. A
|
|
58
60
|
// board whose files can't be made here (one that needs KiCad, without it) goes without, and says why
|
|
59
61
|
async function fabOf(boards) {
|
|
60
|
-
const pcb = await pcbEngine(), { zip } = await import('@rulecad/model-link'), fab = [];
|
|
62
|
+
const pcb = await pcbEngine(), { zip, fabName } = await import('@rulecad/model-link'), fab = [];
|
|
61
63
|
for (const [name, version, b] of boards) {
|
|
62
64
|
try {
|
|
63
65
|
const files = await pcb.fabFiles(b.circuit, name, { source: b.source });
|
|
64
|
-
fab.push({ name: `${name}${version ? `@${version}` : ''}-fab
|
|
66
|
+
fab.push({ name: fabName(`${name}${version ? `@${version}` : ''}-fab`), zip: Buffer.from(await zip(Object.entries(files))).toString('base64') });
|
|
65
67
|
} catch (e) { console.error(` ${name}: no fab zip in the link (${String(e.message || e).split('\n')[0]})`); }
|
|
66
68
|
}
|
|
67
69
|
return fab.length ? { fab } : {};
|
|
@@ -69,7 +71,10 @@ async function fabOf(boards) {
|
|
|
69
71
|
|
|
70
72
|
/** A built assembly as a model: each shape once and placed (nine keys cost one keycap), its boards' views, its joints. */
|
|
71
73
|
export async function assemblyModel(s, { title, versions, filaments: fil = {}, noRules = false, steps }) {
|
|
72
|
-
|
|
74
|
+
// a beam is labelled by its mark (beams that are the same share one, as the cut list and the sheets name them), so the
|
|
75
|
+
// parts list groups them and a beam picked shows its mark
|
|
76
|
+
const marks = new Map(s.objects.filter((o) => o.mark).map((o) => [o.id, o.mark])), labelOf = (q, p) => (marks.has(q.item) ? `mark ${marks.get(q.item)}: ${String(q.label).replace(/^[^:]*: mark \w+, /, '')}` : p.object || p.label);
|
|
77
|
+
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: labelOf(s.parts[n], p), slot: slotOf(fil, p.filament), triangles: triangles(placed.shapes[i].triangles), matrix: m, name: s.parts[n].name }; }) : [];
|
|
73
78
|
// A pose that sets items' variables draws some parts differently (a flexure bent): each such part's shape in that
|
|
74
79
|
// pose goes in the link as a "pose" part, placed as the part is, to be swapped in when the page shows the pose
|
|
75
80
|
const alts = [];
|
|
@@ -96,6 +101,9 @@ export async function assemblyModel(s, { title, versions, filaments: fil = {}, n
|
|
|
96
101
|
})()),
|
|
97
102
|
...fromShapes(list),
|
|
98
103
|
};
|
|
104
|
+
// each mark's cut-and-drill sheet, as a 2D view (Beams: A, B ..): a beam picked in the model opens its own
|
|
105
|
+
const cut = marks.size ? cutListOf(s) : null;
|
|
106
|
+
if (cut) model.views = [...(model.views ?? []), ...cut.marks.map((m) => [`Beams: ${m.mark}`, beamSheet(m.beam, { mark: m.mark, items: m.items, grams: m.grams }).svg])];
|
|
99
107
|
Object.assign(model, motionData(s));
|
|
100
108
|
if (alts.length) { // the shapes parts take in other poses, on the same items, and which pose shows which
|
|
101
109
|
model.motion.part.push(...alts.map((x) => model.motion.part[x.of]));
|
package/lib/list.mjs
CHANGED
|
@@ -12,15 +12,16 @@ import { readJson } from './host.mjs';
|
|
|
12
12
|
import path from 'node:path';
|
|
13
13
|
import { volume } from './mesh.mjs';
|
|
14
14
|
import { wiresFor } from './assembly.mjs';
|
|
15
|
+
import { companions } from './fittings.mjs';
|
|
15
16
|
import { cutListOf, cutListData } from './beams.mjs';
|
|
16
|
-
import { cutListText } from '@rulecad/frames';
|
|
17
|
+
import { cutListText, printedCost } from '@rulecad/frames';
|
|
17
18
|
|
|
18
19
|
const n = (x, d = 1) => Number(x.toFixed(d));
|
|
19
20
|
|
|
20
21
|
export function materialOf(project) {
|
|
21
22
|
let name = 'pla';
|
|
22
23
|
try { name = String(readJson(path.join(paths.project(project), 'project.json')).material || 'pla').toLowerCase().split(/\s/)[0]; } catch {}
|
|
23
|
-
try { return { name, density:
|
|
24
|
+
try { const set = loadRuleSet(name); return { name, density: set.rules.density.value, ...(set.rules.cost ? { cost: set.rules.cost } : {}) }; } catch { return { name, density: 1.25, assumed: true }; }
|
|
24
25
|
}
|
|
25
26
|
|
|
26
27
|
// Every printed thing in the assembly, once for each copy: its volume, grams and minutes
|
|
@@ -30,9 +31,12 @@ export function printedParts(s) {
|
|
|
30
31
|
const by = new Map();
|
|
31
32
|
for (const p of s.parts) {
|
|
32
33
|
if (p.role !== 'part' && p.role != null) continue;
|
|
33
|
-
|
|
34
|
+
// (a printed beam's part is drawn solid and printed with walls and infill: its fill is the share of plastic laid)
|
|
35
|
+
const key = p.leaf ?? p.item, mm3 = volume(p.triangles) * (p.fill ?? 1), o = by.get(key) ?? { id: key, object: p.object ?? null, volume: 0 };
|
|
34
36
|
o.volume += mm3; by.set(key, o);
|
|
35
37
|
}
|
|
38
|
+
// and what comes with a placed part, printed beside it (a levelling foot's pad), by its model's grams
|
|
39
|
+
for (const c of companions(s)) if (c.grams > 0) by.set(c.id, { id: c.id, object: null, volume: (c.grams / mat.density) * 1000, with: c.of });
|
|
36
40
|
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) }));
|
|
37
41
|
}
|
|
38
42
|
|
|
@@ -41,8 +45,9 @@ export function shoppingList(s) {
|
|
|
41
45
|
const mat = materialOf(s.project), printed = printedParts(s), bought = new Map(), fasteners = new Map();
|
|
42
46
|
for (const o of s.objects) if (o.bought && !o.unplaced) {
|
|
43
47
|
// (a beam by its profile and length: one line for each length cut, lib/beams.mjs)
|
|
44
|
-
|
|
45
|
-
const
|
|
48
|
+
// (a panel by its sheet and size: lib/panels.mjs)
|
|
49
|
+
const len = o.bought.length != null ? Number(o.bought.length.toFixed(2)) : null, size = o.bought.size ?? null, key = `${o.bought.set}|${o.bought.variant ?? ''}|${len ?? ''}|${size ?? ''}`;
|
|
50
|
+
const line = bought.get(key) ?? { set: o.bought.set, variant: o.bought.variant, part: o.bought.part, ...(len != null ? { length: len } : {}), ...(size ? { size } : {}), qty: 0, grams: o.bought.mass != null ? o.bought.mass * 1000 : null, ...(o.bought.cost ? { cost: o.bought.cost.value, currency: o.bought.cost.unit } : {}), items: [] };
|
|
46
51
|
line.qty++; line.items.push(o.id); bought.set(key, line);
|
|
47
52
|
}
|
|
48
53
|
// fasten.count: the hardware a fasten placed (a component's too), one part a piece; a motor's mounting screws; and a fit
|
|
@@ -53,6 +58,8 @@ export function shoppingList(s) {
|
|
|
53
58
|
let grams = null; try { grams = screwModel(m.thread, { length: m.length, head: m.head, anyLength: true }).mass; } catch {}
|
|
54
59
|
add(m.name, m.count, `${m.item} on ${m.other} (its mount, a fit that fastens)`, { kind: 'screw', thread: m.thread, length: m.length, head: m.head, grams });
|
|
55
60
|
}
|
|
61
|
+
// what a printed fitting takes besides its screws: a hinge's pin and its nut, a catch's magnet and strike (lib/fittings.mjs)
|
|
62
|
+
for (const o of s.objects) if (o.fitting?.hardware && !o.unplaced) for (const h of o.fitting.hardware) add(h.name, h.count ?? 1, `${o.id} (${h.why ?? 'its fitting'})`, { kind: h.kind, thread: h.thread ?? null, length: h.length ?? null, head: h.head ?? null, grams: null });
|
|
56
63
|
for (const x of s.fits) if (x.fastener && x.fasten == null) add(x.fastener, x.count != null ? x.num(x.count) : 1, x.note || `${x.a} / ${x.b}`);
|
|
57
64
|
// Rounded up to whole packs (packs.pack), the spares said
|
|
58
65
|
let pack = null; try { const r = loadRuleSet('packs').rules.pack; pack = { size: r.value, rule: 'packs.pack', kind: r.kind }; } catch {}
|
|
@@ -64,13 +71,19 @@ export function shoppingList(s) {
|
|
|
64
71
|
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);
|
|
65
72
|
const cut = cutListData(cutListOf(s));
|
|
66
73
|
const fixingsGrams = fixings.reduce((t, f) => t + (f.mass ?? 0), 0);
|
|
67
|
-
|
|
74
|
+
// what it costs, where prices are given: the bought items' by their sets, the printed parts' plastic by the material's
|
|
75
|
+
// price a kilogram; fixings and bars are not priced, and the list says which lines have no price
|
|
76
|
+
const priced = boughtList.filter((b) => b.cost != null), currencies = [...new Set(priced.map((b) => b.currency))];
|
|
77
|
+
const plastic = printedGrams > 0 ? printedCost(printedGrams, { name: mat.name, rules: mat.cost ? { cost: mat.cost } : {} }) : null;
|
|
78
|
+
const cost = priced.length || plastic ? { bought: priced.length && currencies.length === 1 ? n(priced.reduce((t, b) => t + b.cost * b.qty, 0), 2) : null, currency: currencies.length === 1 ? currencies[0] : plastic?.unit ?? null, ...(currencies.length > 1 ? { currencies } : {}),
|
|
79
|
+
unpriced: [...new Set(boughtList.filter((b) => b.cost == null).map((b) => b.set))], printed: plastic ? n(plastic.value, 2) : null, ...(plastic ? { printedUnit: plastic.unit, printedRule: plastic.rule } : {}) } : null;
|
|
80
|
+
return { bought: boughtList, fasteners: fixings, wires: [...wires.values()], printed, cut, ...(cost ? { cost } : {}), totals: { printedGrams: n(printedGrams), boughtGrams: n(boughtGrams), fixingsGrams: n(fixingsGrams), machineGrams: n(printedGrams + boughtGrams + fixingsGrams), ...(pack && fixings.some((f) => f.packs) ? { pack } : {}), minutes: n(printed.reduce((t, p) => t + p.minutes, 0), 0), material: mat.name, ...(mat.assumed ? { densityAssumed: true } : {}), ...(unknown.length ? { noMassFor: unknown } : {}) } };
|
|
68
81
|
}
|
|
69
82
|
|
|
70
83
|
export function listText(ref, l) {
|
|
71
84
|
const out = [`${ref}: what it takes to build`];
|
|
72
85
|
const row = (a) => out.push(a.join(' '));
|
|
73
|
-
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})` : ''}${b.length != null ? ` x ${b.length} mm` : ''}`, `a ${b.part}`, b.grams != null ? `${b.grams} g each` : 'mass not given', b.items.join(', ')]); }
|
|
86
|
+
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})` : ''}${b.length != null ? ` x ${b.length} mm` : ''}${b.size ? ` cut ${b.size[0]} x ${b.size[1]} mm` : ''}`, `a ${b.part}`, b.grams != null ? `${b.grams} g each` : 'mass not given', ...(b.cost != null ? [`${b.cost} ${b.currency} each`] : []), b.items.join(', ')]); }
|
|
74
87
|
if (l.cut) { out.push('', `Cut list (kerf ${l.cut.rules.kerf.value} mm, trim ${l.cut.rules.trim.value} mm; a sheet for each mark: cad beams ${ref})`, ...cutListText(l.cut)); }
|
|
75
88
|
if (l.fasteners.length) {
|
|
76
89
|
out.push('', 'Fasteners');
|
|
@@ -78,7 +91,14 @@ export function listText(ref, l) {
|
|
|
78
91
|
if (l.totals.pack) out.push(` (packs of ${l.totals.pack.size}: ${l.totals.pack.rule}, ${/^[aeiou]/.test(l.totals.pack.kind) ? 'an' : 'a'} ${l.totals.pack.kind}; masses are estimates from each piece's outline)`);
|
|
79
92
|
}
|
|
80
93
|
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(', ')}`]); }
|
|
81
|
-
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})` : ''}`]); }
|
|
94
|
+
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})` : ''}${p.with ? ` (comes with ${p.with}: printed beside it, screwed into it by hand)` : ''}`]); }
|
|
82
95
|
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.fixingsGrams ? `${l.totals.fixingsGrams} g of fixings, ` : ''}${l.totals.machineGrams} g as a machine${l.totals.noMassFor ? ` (no mass given for ${l.totals.noMassFor.join(', ')})` : ''}`);
|
|
96
|
+
if (l.cost) {
|
|
97
|
+
const c = l.cost, parts = [];
|
|
98
|
+
if (c.bought != null) parts.push(`${c.bought} ${c.currency} bought${c.unpriced.length ? ` (no price given for ${c.unpriced.join(', ')})` : ''}`);
|
|
99
|
+
else if (c.currencies) parts.push(`bought items priced in ${c.currencies.join(' and ')}, not added together`);
|
|
100
|
+
if (c.printed != null) parts.push(`${c.printed} ${c.printedUnit} of ${l.totals.material} printed (the plastic alone)`);
|
|
101
|
+
out.push(`Cost: ${parts.join(', ')}; fixings and bars are not priced. Prices are each set's, on the date it was checked`);
|
|
102
|
+
}
|
|
83
103
|
return out.join('\n');
|
|
84
104
|
}
|
package/lib/loads.mjs
CHANGED
|
@@ -12,6 +12,7 @@ import { solidFill } from './optimise.mjs';
|
|
|
12
12
|
import { materialOf } from './list.mjs';
|
|
13
13
|
import { axisOf, trainFrom, workingSpeed, atCurrent } from './motors.mjs';
|
|
14
14
|
import { sample, chainOf } from './task.mjs';
|
|
15
|
+
import { carriageChecks } from './guides.mjs';
|
|
15
16
|
|
|
16
17
|
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
18
|
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);
|
|
@@ -45,7 +46,8 @@ export function massesOf(s, { placeItems, jointValues }) {
|
|
|
45
46
|
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
47
|
// A mesh's bounding box, as lo and hi: a loop, as a large part's triangles overflow Math.min(...spread)
|
|
47
48
|
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
|
-
|
|
49
|
+
/** Whether an item moves with a joint: the joint is on its chain to the base. */
|
|
50
|
+
export 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
51
|
|
|
50
52
|
// Force and moment about a joint's origin, at one pose
|
|
51
53
|
function loadAt(motion, masses, payload, worlds, j, mul) {
|
|
@@ -59,7 +61,8 @@ function loadAt(motion, masses, payload, worlds, j, mul) {
|
|
|
59
61
|
}
|
|
60
62
|
|
|
61
63
|
// The poses the machine will be in: the task's samples, the named poses, or each joint at its ends
|
|
62
|
-
|
|
64
|
+
/** The poses the machine will be in: the task's samples, the named poses, or each joint at its ends; and as drawn. */
|
|
65
|
+
export function posesOf(s, jointValues) {
|
|
63
66
|
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
67
|
for (const p of Object.keys(motion.poses || {})) out.push({ label: `pose ${p}`, values: jointValues(motion, p) });
|
|
65
68
|
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) }) })); }
|
|
@@ -99,6 +102,7 @@ export function momentChecks(s, f, helpers, masses, payload) {
|
|
|
99
102
|
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
103
|
for (const j of motion.joints) {
|
|
101
104
|
if (j.type !== 'revolute' && j.type !== 'prismatic') continue;
|
|
105
|
+
if (specs.get(j.id)?._guide) continue; // (a guide's carriage: carriageChecks holds it to its ratings)
|
|
102
106
|
let worst = null;
|
|
103
107
|
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
108
|
if (!worst || !worst.L.carried) continue;
|
|
@@ -158,14 +162,15 @@ export function deflectionChecks(s, f, helpers, masses, payload) {
|
|
|
158
162
|
if (!m) return;
|
|
159
163
|
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
164
|
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
|
-
|
|
165
|
+
// the link's own cell: a clip's "cell" (a 2 mm clip at 0.5 mm) on a 170 mm link was 130 000 cells, 3 GB and ten minutes
|
|
166
|
+
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?.linkCell != null ? s.num(sup.linkCell) : 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
167
|
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
168
|
});
|
|
164
169
|
return { label, total, carried, rows };
|
|
165
170
|
};
|
|
166
171
|
const stretch = at(far, 'at full stretch'), folded = at(near, 'folded'), worst = stretch.total >= folded.total ? stretch : folded;
|
|
167
172
|
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 "
|
|
173
|
+
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 "linkCell" 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
174
|
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
175
|
const rings = s.task.speed != null ? ` Expect visible ringing past about ${n3(Math.max(20, low.Hz * 3), 0)} mm/s.` : '';
|
|
171
176
|
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 } });
|
|
@@ -214,6 +219,9 @@ function pinv2(J, v) {
|
|
|
214
219
|
|
|
215
220
|
export function loadChecks(s, f, helpers) {
|
|
216
221
|
const motion = s.motion;
|
|
222
|
+
// a guide's carriages are held to their ratings whether or not the machine has a task: they carry what is on them
|
|
223
|
+
// (the masses' centres read against the frames of the pose the parts were built at, which a pose's own check is)
|
|
224
|
+
if (s.guides?.length && motion?.joints?.length) carriageChecks(s, f, helpers, { masses: massesOf(s, { ...helpers, jointValues: (m, p) => s.jointValues ?? helpers.jointValues(m, p) }), beyond, poses: posesOf(s, helpers.jointValues) });
|
|
217
225
|
if (!motion?.joints?.length || !(s.task || s.a.gravity)) return;
|
|
218
226
|
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
227
|
const unknown = masses.filter((m) => !m.known).map((m) => m.id);
|
package/lib/measured.mjs
CHANGED
|
@@ -2,18 +2,24 @@
|
|
|
2
2
|
// the estimate was (in the workspace's copy of the rule set), or a measurement of something a check predicts (a figure
|
|
3
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
4
|
// keeps a ledger of predicted against measured beside prints.jsonl. The rules the fixings coupon measures (a pilot or an
|
|
5
|
-
// insert hole per thread, the nut fits, the thread gap and flank form)
|
|
6
|
-
// each is comes from here; a slot's figures go in the workspace's copy of its set,
|
|
5
|
+
// insert hole per thread, the nut fits, the thread gap and flank form), the slot coupon's fits and a slot nut's hold
|
|
6
|
+
// along its slot need no --rule: what each is comes from here; a slot's figures go in the workspace's copy of its set,
|
|
7
|
+
// checked as a slot. A drop measured on the joint rig (join.drop's <beam>.drop) also writes the join's spring, worked
|
|
8
|
+
// out from it, to the rule the spring came from: the joins set (the workspace's copy, started from @rulecad/frames'
|
|
9
|
+
// estimates), a bought fitting's set, or a printed fitting's share of its finite-element figure. The beam coupon's sag
|
|
10
|
+
// and the mass it broke at (beam.coupon's <beam>.sag and <beam>.break) write the modulus and strength a printed beam has
|
|
11
|
+
// to its plastic's set (beam_modulus, beam_strength; _z standing up).
|
|
7
12
|
import fs from 'node:fs';
|
|
8
13
|
import path from 'node:path';
|
|
9
14
|
import { setAt } from './jsonedit.mjs';
|
|
10
15
|
import { CadError } from './errors.mjs';
|
|
11
16
|
import { paths, WS, RULE_DIRS, printerOf } from './workspace.mjs';
|
|
12
|
-
import { loadRuleSet } from './rules.mjs';
|
|
17
|
+
import { loadRuleSet, peekRuleSet } from './rules.mjs';
|
|
13
18
|
import { buildAssembly, checkAssembly, assemblyPath } from './assembly.mjs';
|
|
14
|
-
import { slotModel } from '@rulecad/frames';
|
|
19
|
+
import { slotModel, JOIN_SET, joinRuleSet } from '@rulecad/frames';
|
|
15
20
|
import { fixingsContext } from './design.mjs';
|
|
16
21
|
import { fixingsFor, threads } from '@rulecad/fixings';
|
|
22
|
+
import { couponFigure } from './frameprint.mjs';
|
|
17
23
|
|
|
18
24
|
const today = () => new Date().toISOString().slice(0, 10), n = (x) => String(Number(Number(x).toFixed(4)));
|
|
19
25
|
export const ledgerFile = (project) => path.join(paths.project(project), 'ledger.jsonl');
|
|
@@ -24,12 +30,17 @@ const keyOf = (x) => `${x.code}|${JSON.stringify(x.refs ?? {})}`;
|
|
|
24
30
|
// 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
|
|
25
31
|
export const predictionsOf = (findings) => findings.filter((x) => x.predict);
|
|
26
32
|
|
|
33
|
+
// A rule's set, read and not written: its text as it starts (the workspace's copy, else the kit's, else for the joins
|
|
34
|
+
// set @rulecad/frames' estimates), so nothing is written until every value has been checked
|
|
27
35
|
function ruleFile(name) {
|
|
28
36
|
const dot = name.indexOf('.');
|
|
29
37
|
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)`);
|
|
30
38
|
const set = name.slice(0, dot), rule = name.slice(dot + 1);
|
|
31
|
-
const
|
|
32
|
-
|
|
39
|
+
const file = path.join(WS, 'rules', `${set}.json`), from = RULE_DIRS.map((d) => path.join(d, `${set}.json`)).find((f) => fs.existsSync(f));
|
|
40
|
+
// the joins set has no file in the kit: the workspace's copy starts from @rulecad/frames' estimates
|
|
41
|
+
if (set === JOIN_SET && !from) { const text = JSON.stringify(joinRuleSet(), null, 2) + '\n'; return { set, rule, data: JSON.parse(text), file, text, copied: `started rules/${set}.json from @rulecad/frames' estimates: yours to keep and edit` }; }
|
|
42
|
+
const data = peekRuleSet(set); // (the measurement goes in your copy: the tool's set is copied there when it is written)
|
|
43
|
+
return { set, rule, data, file, text: fs.readFileSync(from, 'utf8'), copied: from === file ? null : `copied the ${set} rule set into rules/${set}.json: yours to keep and edit` };
|
|
33
44
|
}
|
|
34
45
|
|
|
35
46
|
// The slot coupon (examples/bench/projects/benchmarks/MEASURE.md, rows 29 to 33): the two fits it measures, which a
|
|
@@ -47,6 +58,40 @@ function slotRule(project, set, key, data) {
|
|
|
47
58
|
return null;
|
|
48
59
|
}
|
|
49
60
|
|
|
61
|
+
// The joint rig (examples/bench/projects/benchmarks/MEASURE.md, rows 34 to 37): a join's bending spring, written to the
|
|
62
|
+
// joins set or a bought fitting's set, and a slot nut's hold along its slot, which no maker publishes, so a nut's set
|
|
63
|
+
// has no rule for it until it is measured
|
|
64
|
+
const RIG = 'the joint rig (examples/bench/projects/benchmarks/MEASURE.md)';
|
|
65
|
+
function rigRule(set, key, data) {
|
|
66
|
+
if (data.part === 'slot_nut' && key === 'hold_along') return { unit: 'N', predicted: null, was: 'no figure: no maker publishes it', source: `${RIG}, a luggage scale`,
|
|
67
|
+
rule: `The pull along its slot at which this nut slips, its screw tightened as its maker says (or firmly by hand with a hex key where it says nothing): the reading on ${RIG}'s luggage scale as the nut moved` };
|
|
68
|
+
// what a spring measured on the rig is, in place of the estimate's sentence ("a working guess ... until the joint rig
|
|
69
|
+
// measures it"); the drop it came from goes in its source
|
|
70
|
+
const how = `measured on ${RIG}: a beam held out by the join, the drop of its end under a hung mass less the beam's own bending (F L² / that)`;
|
|
71
|
+
const turn = (who) => ({ bending: `How stiffly ${who} holds the end of a beam against turning across its axis`, twist: `How stiffly ${who} holds the end of a beam against twisting about its own axis` });
|
|
72
|
+
if (set === JOIN_SET) {
|
|
73
|
+
const j = key.match(/^(.+)_(bending|twist|printed_share)$/), kind = j?.[1].replace(/_/g, '-');
|
|
74
|
+
if (!j) return { source: RIG };
|
|
75
|
+
return { source: RIG, measuredRule: j[2] === 'printed_share' ? `A ${kind} join with a printed fitting, as a share of the fitting's own bending stiffness by finite elements: the join's spring ${how}, over the fitting's figure`
|
|
76
|
+
: `${turn(`a ${kind} join`)[j[2]]}, for a 20 mm series profile: ${how}` };
|
|
77
|
+
}
|
|
78
|
+
if (data.part === 'fitting' && /_stiffness$/.test(key)) { const k = key.replace(/_stiffness$/, ''); return { source: RIG, ...(turn('this fitting')[k] ? { measuredRule: `${turn('this fitting')[k]}, its screws tight: ${how}` } : {}) }; }
|
|
79
|
+
return null;
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
// The beam coupon (examples/bench/projects/benchmarks/MEASURE.md, rows 38 and 39): the modulus a printed beam bends at
|
|
83
|
+
// and the stress it breaks at, which no plastic's data sheet gives for a beam of walls and infill, so a plastic's set has
|
|
84
|
+
// no rule for them until the coupon is measured
|
|
85
|
+
const BEAM_COUPON = 'the beam coupon (examples/bench/projects/benchmarks/MEASURE.md)';
|
|
86
|
+
function couponRule(set, key, data) {
|
|
87
|
+
const m = key.match(/^beam_(modulus|strength)(_z)?$/);
|
|
88
|
+
if (!m || data.rules?.density == null) return null;
|
|
89
|
+
const how = m[2] ? 'printed standing up, bent across its layers' : 'printed lying down, its layers along it';
|
|
90
|
+
return { unit: 'MPa', source: BEAM_COUPON, predicted: data.rules?.[m[2] && data.rules[`${m[1]}_z`] ? `${m[1]}_z` : m[1]]?.value ?? null, was: `${set}.${m[1]}${m[2] && data.rules[`${m[1]}_z`] ? '_z' : ''}, the data sheet's`,
|
|
91
|
+
measuredRule: m[1] === 'modulus' ? `The modulus a printed beam of ${set.toUpperCase()} bends at, ${how}, with its section counted from its walls and infill (@rulecad/frames printedSection): the sag of ${BEAM_COUPON} under a hung mass, measured with a dial, and the solve's sag scaled to it. A printed beam takes it before the plastic's own modulus`
|
|
92
|
+
: `The stress a printed beam of ${set.toUpperCase()} breaks at in bending, ${how}, its section counted from its walls and infill: the mass ${BEAM_COUPON} broke at, as the stress the solve gives under it. A printed beam takes it before the plastic's own strength, and its creep limit follows it` };
|
|
93
|
+
}
|
|
94
|
+
|
|
50
95
|
// The printer's rules the fixings read that a printer's set may not hold yet, each measured on the fixings coupon
|
|
51
96
|
// (examples/bench/projects/benchmarks/MEASURE.md): what it is, its unit, and what the kit drew before it was measured,
|
|
52
97
|
// so the ledger shows predicted against measured. A pilot or an insert hole is per thread, and may name a plastic
|
|
@@ -94,28 +139,52 @@ export async function recordMeasured(ref, values, { unit, source, rule, date = t
|
|
|
94
139
|
if (!Object.keys(values).length) throw new CadError('measured.usage', 'usage: cad measured <project>/<assembly> <name>=<value> … [--unit mm] [--source "how it was measured"]');
|
|
95
140
|
const before = await findingsOf(ref), entries = [], predictions = predictionsOf(before);
|
|
96
141
|
const writes = [], slots = new Map(); // (every value is checked before any is written, so a refusal leaves the rule sets as they were)
|
|
142
|
+
// a rule's new value, checked before anything is written (a refusal leaves the rule sets as they were)
|
|
143
|
+
const writeRule = (k, value, { from = null, unit: u = unit } = {}) => {
|
|
144
|
+
const { set, rule: key, data, file, text, copied } = ruleFile(k);
|
|
145
|
+
const old = data.rules?.[key], known = slotRule(project, set, key, data) ?? rigRule(set, key, data) ?? couponRule(set, key, data) ?? fixingsRule(project, set, key) ?? (old ? null : kitRule(set, key));
|
|
146
|
+
if (known?.allowed && !known.allowed.includes(value)) throw new CadError('measured.value', `${k} is ${known.allowed.join(' or ')}: the flank forms the coupon prints (got ${value})`);
|
|
147
|
+
if (!old && !rule && !known) 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'})`);
|
|
148
|
+
const had = old ?? known, prior = typeof had?.value === 'number' ? had.value : known?.predicted ?? null;
|
|
149
|
+
if (u && had?.unit && u !== had.unit) throw new CadError('measured.unit', `${k} is in ${had.unit}, and this is in ${u}: give it in ${had.unit}`);
|
|
150
|
+
// its sentence: what was measured, never the estimate's "until it is measured": the one given, else the rig's, else the rule's own
|
|
151
|
+
const entry = { value, unit: u ?? had?.unit ?? '', rule: (from ? null : rule) ?? known?.measuredRule ?? had.rule, kind: 'measured', source: [source || known?.source || 'measured on the bench', from].filter(Boolean).join(': '), checked: date };
|
|
152
|
+
if (data.part === 'slot') slots.set(set, { data, change: { ...slots.get(set)?.change, [key]: value } });
|
|
153
|
+
writes.push({ file, key, entry, text, copied, set });
|
|
154
|
+
entries.push({ date, assembly: name, name: k, figure: entry.rule, unit: entry.unit, predicted: prior, was: old ? old.kind : known?.was ?? known?.kind ?? null, measured: value, ratio: prior ? value / prior : null, ...(source ? { source } : {}) });
|
|
155
|
+
};
|
|
97
156
|
for (const [k, value] of Object.entries(values)) {
|
|
98
157
|
if (!Number.isFinite(value)) throw new CadError('measured.value', `${k}: a measurement is a number (got ${value})`);
|
|
99
158
|
const named = predictions.filter((x) => x.code === k || x.predict.name === k);
|
|
100
159
|
if (named.length) {
|
|
101
160
|
const p = named[0].predict;
|
|
102
161
|
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 } : {}) });
|
|
162
|
+
// a drop on the joint rig: what the beam bends of it is the beam's own; the rest is the join turning, so its spring
|
|
163
|
+
if (p.rig) {
|
|
164
|
+
const r = p.rig, n = (x) => String(Number(Number(x).toFixed(3)));
|
|
165
|
+
if (!(value > r.beam)) throw new CadError('measured.value', `${k}: ${n(value)} mm is no more than the ${n(r.beam)} mm the beam bends by itself under ${n(r.force)} N at ${n(r.arm)} mm, so the join would be stiffer than solid metal: read the drop again, from the dial's reading with the mass hung less its reading without`);
|
|
166
|
+
const spring = (r.force * r.arm * r.arm) / (value - r.beam), figure = Number((spring * r.per).toPrecision(4));
|
|
167
|
+
writeRule(r.rule, figure, { unit: r.unit, from: `${n(value)} mm drop of ${k.replace(/\.drop$/, '')} under ${n(r.force)} N at ${n(r.arm)} mm (${r.join}), less the beam's own ${n(r.beam)} mm, is a spring of ${(spring / 1e6).toFixed(3)} N·m/mrad` });
|
|
168
|
+
}
|
|
169
|
+
// the beam coupon: the modulus from its sag, the strength from the mass it broke at
|
|
170
|
+
if (p.coupon) {
|
|
171
|
+
const c = p.coupon, figure = couponFigure(c, p.value, value);
|
|
172
|
+
if (!(value > 0)) throw new CadError('measured.value', `${k}: a ${c.kind === 'modulus' ? 'sag' : 'mass'} is above 0 (got ${value})`);
|
|
173
|
+
writeRule(c.rule, figure, { unit: c.unit, from: c.kind === 'modulus' ? `${n(value)} mm sag of ${k.replace(/\.sag$/, '')} under ${c.what}, against ${n(p.value)} mm at ${n(c.base)} MPa` : `broke at ${n(value)} kg ${c.what}, ${n(c.perKg)} MPa a kilogram on its own weight's ${n(c.self)} MPa` });
|
|
174
|
+
}
|
|
103
175
|
continue;
|
|
104
176
|
}
|
|
105
|
-
|
|
106
|
-
const old = data.rules?.[key], known = slotRule(project, set, key, data) ?? fixingsRule(project, set, key) ?? (old ? null : kitRule(set, key));
|
|
107
|
-
if (known?.allowed && !known.allowed.includes(value)) throw new CadError('measured.value', `${k} is ${known.allowed.join(' or ')}: the flank forms the coupon prints (got ${value})`);
|
|
108
|
-
if (!old && !rule && !known) 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'})`);
|
|
109
|
-
const had = old ?? known, prior = typeof had?.value === 'number' ? had.value : known?.predicted ?? null;
|
|
110
|
-
if (unit && had?.unit && unit !== had.unit) throw new CadError('measured.unit', `${k} is in ${had.unit}, and this is in ${unit}: give it in ${had.unit}`);
|
|
111
|
-
const entry = { value, unit: unit ?? had?.unit ?? '', rule: rule ?? had.rule, kind: 'measured', source: source || known?.source || 'measured on the bench', checked: date };
|
|
112
|
-
if (data.part === 'slot') slots.set(set, { data, change: { ...slots.get(set)?.change, [key]: value } });
|
|
113
|
-
writes.push([file, key, entry]);
|
|
114
|
-
entries.push({ date, assembly: name, name: k, figure: entry.rule, unit: entry.unit, predicted: prior, was: old ? old.kind : known?.was ?? known?.kind ?? null, measured: value, ratio: prior ? value / prior : null, ...(source ? { source } : {}) });
|
|
177
|
+
writeRule(k, value);
|
|
115
178
|
}
|
|
116
179
|
// a slot's figures together still make a slot (an opening narrower than its cavity, lips thinner than it is deep)
|
|
117
180
|
for (const [set, { data, change }] of slots) { try { slotModel(data, change); } catch (e) { throw new CadError('measured.value', `${set}: ${e.message.replace(/^slotModel: /, '')}`); } }
|
|
118
|
-
|
|
181
|
+
// every value checked: now each set is written, the workspace's copy made from where it started where there is none
|
|
182
|
+
const texts = new Map();
|
|
183
|
+
for (const w of writes) texts.set(w.file, { ...w, text: setAt(texts.get(w.file)?.text ?? w.text, ['rules', w.key], w.entry) });
|
|
184
|
+
for (const [file, w] of texts) {
|
|
185
|
+
fs.mkdirSync(path.dirname(file), { recursive: true }); fs.writeFileSync(file, w.text);
|
|
186
|
+
if (w.copied) console.error(w.copied);
|
|
187
|
+
}
|
|
119
188
|
const after = await findingsOf(ref), was = new Map(before.map((x) => [keyOf(x), x])), moved = [];
|
|
120
189
|
for (const x of after) {
|
|
121
190
|
const y = was.get(keyOf(x));
|
package/lib/motors.mjs
CHANGED
|
@@ -223,9 +223,13 @@ export function motorChecks(s, f, helpers, materialName) {
|
|
|
223
223
|
// The case, against what it's bolted to
|
|
224
224
|
const mat = material(materialName), rise = fig('temperature_rise');
|
|
225
225
|
if (mat?.softening != null && rise != null) {
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
226
|
+
// (the rise is the maker's at rated current; the heat goes as the current squared, so a driver set lower runs cooler)
|
|
227
|
+
const I = fig('rated_current'), set = d.spec.current != null && I ? Math.min(1, (d.spec.current / I) ** 2) : 1;
|
|
228
|
+
const duty = d.spec.duty != null ? d.spec.duty : 1, room = 25, caseT = room + rise * duty * set, ok = caseT <= mat.softening, name = mat.name.toUpperCase();
|
|
229
|
+
const how = [set < 1 ? `at ${n3(d.spec.current, 2)} A` : null, duty < 1 ? `at ${n3(duty * 100, 0)}% duty` : null].filter(Boolean).join(' and ') || 'at rated current';
|
|
230
|
+
const est = `an estimate: ${m.name}'s ${n3(rise, 1)} °C rise at rated current${set < 1 ? ', scaled by the current squared (its copper loss)' : ''}${duty < 1 ? ', by the duty' : ''}, over a ${room} °C room`;
|
|
231
|
+
if (ok) f('pass', `${d.id}'s case reaches at most ${n3(caseT, 1)} °C ${how}, under ${name}'s ${mat.softening} °C (${est})`, null, { code: 'motor.heat', at: S, refs: { item: d.id }, values: { case: caseT, softening: mat.softening, rise, room, scale: set * duty } });
|
|
232
|
+
else { const k = Math.sqrt((mat.softening - room) / (rise * duty)); f('warn', `${d.id}'s case can reach ${n3(caseT, 1)} °C ${how} (${est}), 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, rise, room, scale: set * duty } }); }
|
|
229
233
|
}
|
|
230
234
|
}
|
|
231
235
|
}
|