@rulecad/cad 0.7.57 → 0.7.59
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 +48 -3
- package/CHANGELOG.md +213 -0
- package/EXAMPLES.md +421 -3
- package/README.md +391 -11
- package/bin/cad.mjs +105 -22
- package/lib/assembly.mjs +15 -2
- package/lib/beams.mjs +44 -11
- package/lib/buildpage.mjs +1 -1
- package/lib/design.mjs +3 -0
- package/lib/fasten.mjs +31 -9
- package/lib/fittings.mjs +50 -8
- package/lib/framebuild.mjs +62 -6
- 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 +2 -1
- package/lib/framesize.mjs +261 -0
- package/lib/jigs.mjs +18 -15
- package/lib/joins.mjs +7 -3
- package/lib/kit.mjs +190 -0
- package/lib/links.mjs +12 -3
- package/lib/list.mjs +6 -2
- package/lib/loads.mjs +3 -2
- package/lib/measured.mjs +24 -2
- package/lib/optimise.mjs +18 -3
- package/lib/order.mjs +10 -4
- package/lib/panels.mjs +1 -1
- package/lib/plates.mjs +31 -17
- package/lib/preview.mjs +4 -3
- package/lib/sheet.mjs +15 -1
- package/lib/task.mjs +39 -1
- package/package.json +5 -5
- package/schemas/assembly.schema.json +9 -5
|
@@ -0,0 +1,261 @@
|
|
|
1
|
+
// A frame's sizing (@rulecad/fea/frame's sizing): "frame": { "size": { "profiles": [...] } } chooses, for each group of
|
|
2
|
+
// beams that must match (a pair of rails, the four posts), the lightest profile from a list that meets the frame's own
|
|
3
|
+
// limits: the sag allowed at each load, named point and guide (as frame.deflection holds it), each beam's stress against
|
|
4
|
+
// its alloy with frame.margin to spare, with the joins' springs and with them rigid (as frame.stress), the whole frame's
|
|
5
|
+
// first buckling factor and each grouped beam against Euler's load with the same margin (as frame.buckling), and the
|
|
6
|
+
// lowest mode against what the task's moves shake it at, twice over (as frame.frequency), or a floor of the assembly's
|
|
7
|
+
// own. The frame is the one frameModelOf builds, solved in every pose; only the beams' sections, alloys, mass and roll
|
|
8
|
+
// change. The result is a table: each group's profile, the limit that set it (the one its next lighter profile breaks)
|
|
9
|
+
// and the margin, written into the assembly by cad frame --size --write.
|
|
10
|
+
// Units: mm, N, MPa, kg, Hz.
|
|
11
|
+
import { sizing } from '@rulecad/fea/frame';
|
|
12
|
+
import { profileModel, profileChoices } from '@rulecad/frames';
|
|
13
|
+
import { frameModelOf, FRAME_CHECK, excitesOf } from './framecheck.mjs';
|
|
14
|
+
import { framesContext } from './beams.mjs';
|
|
15
|
+
import { givenFor } from './frames.mjs';
|
|
16
|
+
|
|
17
|
+
const shown = (v) => (v === undefined ? 'nothing' : JSON.stringify(v));
|
|
18
|
+
const n3 = (x, d = 3) => String(+Number(x).toFixed(d)), r3 = (x) => +Number(x).toFixed(3);
|
|
19
|
+
|
|
20
|
+
/** The working figures of the frame's sizing, each with what it rests on. */
|
|
21
|
+
export const FRAME_SIZING = {
|
|
22
|
+
profiles: { value: ['2020-misumi-hfs5', '2040-misumi-hfs5', '2060-misumi-hfs5', '3030-misumi-hfs6', '3060-misumi-hfs6', '4040-misumi-hfs8', '4080-misumi-hfs8'], unit: '', rule: 'Where frame.size gives no profiles, the list each group is chosen from: one maker\'s series from 20 to 40 mm, so the slot nuts and fittings stay within three slot sizes. Each that is not square is tried lying as drawn and turned a quarter', kind: 'default', source: 'A working list of @rulecad/cad, from the profile sets in @rulecad/rules (MISUMI HFS5, HFS6 and HFS8)', checked: '2026-11-20' },
|
|
23
|
+
match: { value: 0.5, unit: 'mm', rule: 'Beams not named in frame.size.groups are grouped by themselves: beams of one profile lying the same way whose lengths agree within this much must match (a pair of rails, four posts)', kind: 'default', source: 'A working figure of @rulecad/cad: under any cut tolerance in the kit\'s profile sets', checked: '2026-11-20' },
|
|
24
|
+
};
|
|
25
|
+
|
|
26
|
+
const SIZE_KEYS = ['profiles', 'groups', 'limits', 'by'];
|
|
27
|
+
const LIMIT_KEYS = ['deflection', 'stress', 'buckling', 'frequency'];
|
|
28
|
+
|
|
29
|
+
/**
|
|
30
|
+
* frame.size read and refused by name: { profiles, groups, limits, by }.
|
|
31
|
+
* @param {object} s a built assembly @returns {{ profiles: string[], groups: Record<string, string[]>, limits: Record<string, number>, by: 'mass' | 'cost' } | null}
|
|
32
|
+
*/
|
|
33
|
+
export function sizeOption(s) {
|
|
34
|
+
const o = s.a.frame?.size;
|
|
35
|
+
if (o == null) return null;
|
|
36
|
+
if (typeof o !== 'object' || Array.isArray(o)) throw new Error(`frame.size is { "profiles": ["2020-misumi-hfs5", "2040-misumi-hfs5"], "groups": { "legs": ["z1", "z2"] }, "limits": { "deflection": 1 } } (got ${shown(o)})`);
|
|
37
|
+
for (const k of Object.keys(o)) if (!SIZE_KEYS.includes(k)) throw new Error(`frame.size has no "${k}": it takes ${SIZE_KEYS.join(', ')}`);
|
|
38
|
+
const profiles = o.profiles ?? FRAME_SIZING.profiles.value;
|
|
39
|
+
if (!Array.isArray(profiles) || !profiles.length || !profiles.every((p) => typeof p === 'string' && p)) throw new Error(`frame.size.profiles is a list of profile sets by name, to choose each group's from (got ${shown(o.profiles)})`);
|
|
40
|
+
const groups = o.groups ?? {};
|
|
41
|
+
if (typeof groups !== 'object' || Array.isArray(groups)) throw new Error(`frame.size.groups is { "legs": ["z1", "z2", "z3", "z4"] }: beams that must take one profile, by name (got ${shown(o.groups)})`);
|
|
42
|
+
for (const [g, list] of Object.entries(groups)) if (!Array.isArray(list) || !list.length || !list.every((x) => typeof x === 'string')) throw new Error(`frame.size.groups.${g} is a list of beams by name (got ${shown(list)})`);
|
|
43
|
+
const limits = o.limits ?? {};
|
|
44
|
+
if (typeof limits !== 'object' || Array.isArray(limits)) throw new Error(`frame.size.limits is { "deflection": mm, "stress": margin, "buckling": factor, "frequency": Hz } (got ${shown(o.limits)})`);
|
|
45
|
+
for (const k of Object.keys(limits)) if (!LIMIT_KEYS.includes(k)) throw new Error(`frame.size.limits has no "${k}": it takes deflection (mm), stress (a margin), buckling (a factor) and frequency (Hz)`);
|
|
46
|
+
const out = {};
|
|
47
|
+
for (const [k, v] of Object.entries(limits)) { const x = s.num(v); if (!(x > 0)) throw new Error(`frame.size.limits.${k} is above 0 (got ${shown(v)})`); out[k] = x; }
|
|
48
|
+
if (o.by != null && !['mass', 'cost'].includes(o.by)) throw new Error(`frame.size.by is mass or cost (got ${shown(o.by)})`);
|
|
49
|
+
if (o.by === 'cost') throw new Error('frame.size.by is cost, and no profile set in the kit gives a price per metre: size by mass');
|
|
50
|
+
return { profiles, groups, limits: out, by: o.by ?? 'mass' };
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/**
|
|
54
|
+
* The frame's sizing: frameModelOf's frame, its beams grouped, each group given the lightest profile from the list that
|
|
55
|
+
* meets the frame's limits. Null where the assembly has no frame to solve. Refused by name: frame.size as sizeOption
|
|
56
|
+
* refuses it, a group naming no beam of the frame or a beam twice, a profile set that does not exist or has no modulus.
|
|
57
|
+
* @param {object} s a built assembly @param {{ placeItems: Function, jointValues: Function, mul: Function }} helpers
|
|
58
|
+
* @param {object} [given] frame.size in place of the assembly's own
|
|
59
|
+
* @returns {null | { ok: boolean, rows: object[], limits: object[], total: number, drawn: number, tried: number, search: string, sized: object, fm: object }}
|
|
60
|
+
*/
|
|
61
|
+
export function frameSizing(s, helpers, given) {
|
|
62
|
+
const opt = given ?? sizeOption(s) ?? sizeOption({ ...s, a: { ...s.a, frame: { ...s.a.frame, size: {} } } });
|
|
63
|
+
const fm = frameModelOf(s, helpers);
|
|
64
|
+
if (!fm || fm.empty) return null;
|
|
65
|
+
// the groups: named ones, then the rest by direction, profile and length
|
|
66
|
+
const groups = {}, taken = new Map();
|
|
67
|
+
for (const [g, list] of Object.entries(opt.groups)) {
|
|
68
|
+
for (const id of list) {
|
|
69
|
+
if (!fm.beams.has(id)) throw new Error(`frame.size.groups.${g}: ${id} is not a beam of the frame (its beams: ${[...fm.beams.keys()].join(', ')})`);
|
|
70
|
+
if (taken.has(id)) throw new Error(`frame.size.groups: ${id} is in ${taken.get(id)} and in ${g}: a beam takes one profile`);
|
|
71
|
+
taken.set(id, g);
|
|
72
|
+
}
|
|
73
|
+
groups[g] = list;
|
|
74
|
+
}
|
|
75
|
+
const near = FRAME_SIZING.match.value, auto = [];
|
|
76
|
+
for (const b of fm.beams.values()) {
|
|
77
|
+
if (taken.has(b.id)) continue;
|
|
78
|
+
const mate = auto.find((x) => x.profile === b.m.profile.name && Math.abs(x.L - b.L) <= near && Math.abs(Math.abs(x.u[0] * b.u[0] + x.u[1] * b.u[1] + x.u[2] * b.u[2]) - 1) < 1e-6);
|
|
79
|
+
if (mate) mate.ids.push(b.id); else auto.push({ profile: b.m.profile.name, L: b.L, u: b.u, ids: [b.id] });
|
|
80
|
+
}
|
|
81
|
+
for (const x of auto) groups[x.ids.join(', ')] = x.ids;
|
|
82
|
+
// the choices, from the workspace's sets before the kit's
|
|
83
|
+
const context = framesContext(), choices = [];
|
|
84
|
+
for (const name of opt.profiles) {
|
|
85
|
+
let m;
|
|
86
|
+
try { m = profileModel(name, {}, givenFor(context, name)); } catch (e) { throw new Error(`frame.size.profiles: ${String(e.message).replace(/^profileModel: /, '')}`); }
|
|
87
|
+
try { choices.push(...profileChoices(m)); } catch (e) { throw new Error(`frame.size.profiles: ${String(e.message).replace(/^profileChoices: /, '')}`); }
|
|
88
|
+
}
|
|
89
|
+
// the limits: the frame checks' own, or the assembly's in their place
|
|
90
|
+
const margin = FRAME_CHECK.margin.value, deflection = [], limitRows = [];
|
|
91
|
+
const limitOf = (b, own) => (opt.limits.deflection != null ? { value: opt.limits.deflection, from: 'frame.size.limits.deflection' } : own ? { value: own.value, from: own.from }
|
|
92
|
+
: s.a.frame?.limit != null ? { value: s.num(s.a.frame.limit), from: 'frame.limit' } : s.task?.accuracy != null ? { value: s.task.accuracy, from: 'the task\'s accuracy' }
|
|
93
|
+
: { value: b.L / FRAME_CHECK.sag.value, from: `${b.id}'s span over ${FRAME_CHECK.sag.value} (frame.sag)` });
|
|
94
|
+
for (const l of fm.loads) {
|
|
95
|
+
const b = l.beam ?? l.mount.beam, lim = limitOf(b);
|
|
96
|
+
// a load that moves with a joint is held to its limit wherever along the beam it is; a still one at its node
|
|
97
|
+
if (l.beam || !l.mount.mover) { const n = fm.nodeAt(b, l.beam ? l.z : fm.mountStation(l.mount, fm.cases[0].values)); deflection.push({ node: n, limit: lim.value, along: fm.down }); limitRows.push({ limit: 'deflection', where: n, what: l.where, value: lim.value, from: lim.from }); }
|
|
98
|
+
else { deflection.push({ member: b.id, limit: lim.value, along: fm.down }); limitRows.push({ limit: 'deflection', where: b.id, what: `${l.where}, anywhere it moves`, value: lim.value, from: lim.from }); }
|
|
99
|
+
}
|
|
100
|
+
for (const p of fm.points) { const n = fm.nodeAt(p.beam, p.z), lim = limitOf(p.beam); deflection.push({ node: n, limit: lim.value, along: fm.down }); limitRows.push({ limit: 'deflection', where: n, what: p.where, value: lim.value, from: lim.from }); }
|
|
101
|
+
for (const g of fm.guides) {
|
|
102
|
+
const lim = limitOf(g.beam, g.tolerance ? { value: g.tolerance.value, from: `the rail's own parallelism (${g.tolerance.note ?? g.tolerance.term})` } : null);
|
|
103
|
+
deflection.push({ member: g.beam.id, from: g.from, to: g.to, limit: lim.value, along: fm.down });
|
|
104
|
+
limitRows.push({ limit: 'deflection', where: g.beam.id, what: `under guide ${g.id}`, value: lim.value, from: lim.from });
|
|
105
|
+
}
|
|
106
|
+
const stress = opt.limits.stress ?? margin, factor = opt.limits.buckling ?? margin;
|
|
107
|
+
limitRows.push({ limit: 'stress', where: 'each beam', value: stress, from: opt.limits.stress != null ? 'frame.size.limits.stress' : 'frame.margin' });
|
|
108
|
+
limitRows.push({ limit: 'buckling', where: 'the frame and each grouped beam (Euler, K 1)', value: factor, from: opt.limits.buckling != null ? 'frame.size.limits.buckling' : 'frame.margin' });
|
|
109
|
+
const moves = excitesOf(s).filter((x) => x.kind === 'move'), Hz = opt.limits.frequency ?? (moves.length ? Math.max(...moves.map((x) => x.Hz)) * margin : null);
|
|
110
|
+
if (Hz != null) limitRows.push({ limit: 'frequency', where: 'the frame', value: Hz, from: opt.limits.frequency != null ? 'frame.size.limits.frequency' : `twice the task's moves (frame.frequency)` });
|
|
111
|
+
const limits = { ...(deflection.length ? { deflection } : {}), stress: { margin: stress }, buckling: { factor, euler: FRAME_CHECK.euler.value }, ...(Hz != null ? { frequency: { Hz } } : {}) };
|
|
112
|
+
// every beam's alloy carries its strength, so the beams outside the groups are held to it too
|
|
113
|
+
const withStrength = (model) => ({ ...model, materials: Object.fromEntries(Object.entries(model.materials).map(([k, v]) => [k, fm.beams.get(k)?.strength ? { ...v, strength: fm.beams.get(k).strength } : v])) });
|
|
114
|
+
const cases = fm.cases.map((c) => ({ label: c.label, loads: fm.nodeLoads(c.values), inertia: fm.nodeMasses(c.values) }));
|
|
115
|
+
const sized = sizing([withStrength(fm.model), withStrength(fm.rigid)], { groups, choices, limits, cases, by: opt.by });
|
|
116
|
+
const byName = new Map(choices.map((c) => [c.name, c]));
|
|
117
|
+
const rows = sized.groups.map((g) => {
|
|
118
|
+
const c = byName.get(g.choice), drawn = [...new Set(g.members.map((id) => fm.beams.get(id).m.profile.name.replace(/^profile-/, '')))];
|
|
119
|
+
const drawnKg = g.members.reduce((t, id) => t + fm.beams.get(id).grams / 1000, 0);
|
|
120
|
+
return { group: g.name, beams: g.members, profile: c.profile, roll: c.roll, choice: g.choice, drawn, length: r3(g.length), kg: r3(g.mass), drawnKg: r3(drawnKg), lighter: g.lighter,
|
|
121
|
+
governs: g.governs ? { limit: g.governs.limit, where: g.governs.where, value: r3(g.governs.value), allowed: r3(g.governs.allowed), case: g.governs.case, lighter: g.governs.lighter, broken: r3(g.governs.broken) } : null, margin: g.margin == null ? null : r3(g.margin) };
|
|
122
|
+
});
|
|
123
|
+
const drawn = [...fm.beams.values()].filter((b) => sized.groups.some((g) => g.members.includes(b.id))).reduce((t, b) => t + b.grams / 1000, 0);
|
|
124
|
+
return { ok: sized.ok, rows, limits: limitRows, total: r3(sized.total), drawn: r3(drawn), tried: sized.tried, search: sized.search, worst: sized.worst, sized, fm };
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
// a limit's figure in words: what a lighter profile does there
|
|
128
|
+
const unitOf = { deflection: 'mm', stress: 'MPa', buckling: 'x', frequency: 'Hz' };
|
|
129
|
+
const sayLimit = (g) => {
|
|
130
|
+
if (!g) return 'the lightest in the list';
|
|
131
|
+
const u = unitOf[g.limit], what = g.limit === 'deflection' ? `the sag at ${g.where}` : g.limit === 'stress' ? `the stress in ${g.where}` : g.limit === 'buckling' ? (g.where === 'frame' ? 'the frame\'s buckling factor' : `${g.where.replace(' (Euler)', '')}'s Euler margin`) : 'the lowest mode';
|
|
132
|
+
return `${g.limit}: with ${g.lighter}, ${what} breaks its limit ${n3(g.broken, 2)} times over`;
|
|
133
|
+
};
|
|
134
|
+
|
|
135
|
+
/**
|
|
136
|
+
* The sizing as a table, one line a group. @param {object} r frameSizing's @returns {string[]}
|
|
137
|
+
*/
|
|
138
|
+
export function sizingText(r) {
|
|
139
|
+
const lines = [`${r.ok ? 'sized' : 'no profile in the list meets every limit; nearest'}: ${n3(r.total, 3)} kg of grouped beams (drawn ${n3(r.drawn, 3)} kg), ${r.tried} designs solved (${r.search === 'every' ? 'every design ranked by mass' : 'by steps'})`];
|
|
140
|
+
lines.push('group | profile | kg | set by | margin');
|
|
141
|
+
for (const x of r.rows) lines.push(`${x.group} | ${x.choice}${x.drawn.length === 1 && x.drawn[0] === x.choice ? '' : ` (drawn ${x.drawn.join(', ')})`} | ${n3(x.kg, 3)} | ${sayLimit(x.governs)} | ${x.margin == null ? '-' : `${n3(x.margin, 2)}x`}`);
|
|
142
|
+
lines.push(`limits: ${r.limits.map((l) => `${l.limit} ${l.limit === 'deflection' ? `${n3(l.value, 3)} mm at ${l.what ?? l.where}` : l.limit === 'frequency' ? `${n3(l.value, 1)} Hz` : `${n3(l.value, 2)}x`} (${l.from})`).join('; ')}`);
|
|
143
|
+
return lines;
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
/**
|
|
147
|
+
* frame.size as a finding: info with the table where every limit is met, warn where none of the profiles meets them.
|
|
148
|
+
* @param {object} s @param {Function} f the findings' sink @param {object} helpers
|
|
149
|
+
*/
|
|
150
|
+
export function sizeChecks(s, f, helpers) {
|
|
151
|
+
if (s.a.frame?.size == null) return;
|
|
152
|
+
let r;
|
|
153
|
+
try { r = frameSizing(s, helpers); } catch (e) { f('fail', `frame.size: ${e.message}`, 'frame.size: refused', { code: 'frame.size' }); return; }
|
|
154
|
+
if (!r) return;
|
|
155
|
+
const text = r.rows.map((x) => `${x.group}: ${x.choice}, ${n3(x.kg, 3)} kg, ${x.governs ? `set by ${sayLimit(x.governs)}, ${n3(x.margin, 2)} times inside it as chosen` : 'the lightest in the list'}`).join('; ');
|
|
156
|
+
f(r.ok ? 'info' : 'warn', `${r.ok ? 'sized' : `no profile in the list meets every limit: the nearest breaks ${r.worst.limit} at ${r.worst.where} ${n3(r.worst.ratio, 2)} times over`}: ${text}. ${n3(r.total, 3)} kg of grouped beams against ${n3(r.drawn, 3)} kg drawn (cad frame --size --write writes the profiles in)`, r.ok ? null : 'frame.size: not met',
|
|
157
|
+
{ code: 'frame.size', values: { kg: r.total, drawn: r.drawn, tried: r.tried }, refs: { groups: r.rows, limits: r.limits, search: r.search } });
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
/**
|
|
161
|
+
* The assembly with the sizing's profiles written in: each grouped beam's profile (and a quarter roll where it was
|
|
162
|
+
* turned), and each printed end fitting on it drawn for the new profile. Each beam keeps its line (its axis), so a
|
|
163
|
+
* deeper profile stands about its middle; where a beam's end butts against another's face and that face moves with
|
|
164
|
+
* the other's new size, the end moves with it (the beam's length follows). A generated frame's rings keep their outer faces (a table's top
|
|
165
|
+
* stays level with its legs' tops); a drawn beam whose new size would stand past the end of the beam it meets moves
|
|
166
|
+
* along that beam by as much, if the move fits at its other end, and otherwise nothing is written (refused by name). A blind or end-tap join whose end now
|
|
167
|
+
* has several bores (a 20 x 40) becomes one join a bore, each at its own place on the beam it meets. A generated frame
|
|
168
|
+
* is written out expanded, as cad frame --expand does, as its generator takes one profile.
|
|
169
|
+
* @param {object} raw the assembly as read @param {object} expanded the generated frame expanded (expandFrame's) @param {object} r frameSizing's
|
|
170
|
+
* @returns {object}
|
|
171
|
+
*/
|
|
172
|
+
export function writeSizing(raw, expanded, r) {
|
|
173
|
+
const out = structuredClone(raw.frame?.kind != null ? expanded : raw), by = new Map(), context = framesContext();
|
|
174
|
+
for (const x of r.rows) for (const id of x.beams) by.set(id, x);
|
|
175
|
+
const models = new Map(), modelOf = (name) => { if (!models.has(name)) models.set(name, profileModel(name, {}, givenFor(context, name))); return models.get(name); };
|
|
176
|
+
// each beam's section axes in the world, as drawn and as written: x across its width, y up its height, u along it
|
|
177
|
+
const axes = (b, roll) => { const X = [b.W[0], b.W[4], b.W[8]], Y = [b.W[1], b.W[5], b.W[9]], c = Math.cos(roll * Math.PI / 180), sn = Math.sin(roll * Math.PI / 180); return { X: X.map((v, k) => c * v + sn * Y[k]), Y: Y.map((v, k) => c * v - sn * X[k]), u: b.u }; };
|
|
178
|
+
const dot = (p, q) => p[0] * q[0] + p[1] * q[1] + p[2] * q[2];
|
|
179
|
+
const was = (id) => { const b = r.fm.beams.get(id); return { b, profile: modelOf(b.m.profile.name), ax: axes(b, 0) }; };
|
|
180
|
+
const now = (id) => { const x = by.get(id), w = was(id); return x ? { b: w.b, profile: modelOf(x.profile), ax: axes(w.b, x.roll) } : w; };
|
|
181
|
+
const half = (q, dir) => (Math.abs(dot(dir, q.ax.X)) * q.profile.width + Math.abs(dot(dir, q.ax.Y)) * q.profile.height) / 2;
|
|
182
|
+
const items = new Map((out.items ?? []).map((it) => [it.id, it])), numeric = (it) => Array.isArray(it?.from) && Array.isArray(it?.to) && [...it.from, ...it.to].every((v) => typeof v === 'number');
|
|
183
|
+
// a generated frame's rings keep their outer faces: the top ring its top (a table's top stays flat and level with its
|
|
184
|
+
// legs' tops), the bottom ring of a box its bottom, the rings between their middles; a drawn frame keeps every line
|
|
185
|
+
const lift = new Map();
|
|
186
|
+
if (raw.frame?.kind != null) {
|
|
187
|
+
const up = r.fm.down.map((v) => -v), flat = [...by.keys()].map((id) => r.fm.beams.get(id)).filter((b) => Math.abs(dot(b.u, up)) < 1e-6);
|
|
188
|
+
const height = (b) => dot(b.A, up), all = [...r.fm.beams.values()].filter((b) => Math.abs(dot(b.u, up)) < 1e-6).map(height), top = Math.max(...all), low = Math.min(...all);
|
|
189
|
+
for (const b of flat) {
|
|
190
|
+
const side = Math.abs(height(b) - top) < 1e-6 ? 1 : Math.abs(height(b) - low) < 1e-6 && !['table', 'portal'].includes(raw.frame.kind) ? -1 : 0;
|
|
191
|
+
if (!side) continue;
|
|
192
|
+
const d = side * (half(was(b.id), up) - half(now(b.id), up));
|
|
193
|
+
if (Math.abs(d) > 1e-9) lift.set(b.id, up.map((v) => v * d));
|
|
194
|
+
}
|
|
195
|
+
}
|
|
196
|
+
// a beam whose end meets another's face keeps its line, unless its new size would stand past that beam's end (a
|
|
197
|
+
// rail flush with its legs' tops, now deeper): then it moves across its length, along the beam it meets, by as much,
|
|
198
|
+
// so its face there stays where it was. The move must fit at every end it has (its other end's beam), else it stays
|
|
199
|
+
// and the guard below refuses
|
|
200
|
+
for (const id of by.keys()) {
|
|
201
|
+
if (lift.has(id) || !numeric(items.get(id))) continue;
|
|
202
|
+
const b = r.fm.beams.get(id), ends = new Map();
|
|
203
|
+
for (const j of out.joins ?? []) {
|
|
204
|
+
const ma = /^([\w-]+)\.([ab])(?:\.\d+)?$/.exec(String(j.a ?? '')), mb = /^([\w-]+)\.[a-z]+(?:\.\d+)?@/.exec(String(j.b ?? ''));
|
|
205
|
+
if (!ma || ma[1] !== id || !mb || !r.fm.beams.has(mb[1]) || mb[1] === id) continue;
|
|
206
|
+
// where this end's line meets the other beam, along it, and how far the beam stands each way of it, as drawn and as sized
|
|
207
|
+
const post = r.fm.beams.get(mb[1]), P = ma[2] === 'a' ? b.A : b.A.map((v, k) => v + b.u[k] * b.L), at = dot(P.map((v, k) => v - post.A[k]), post.u);
|
|
208
|
+
const hw = half(was(id), post.u), hn = half(now(id), post.u);
|
|
209
|
+
ends.set(`${ma[2]} ${mb[1]}`, { post, at, hn, lo: Math.min(0, at - hw), hi: Math.max(post.L, at + hw) });
|
|
210
|
+
}
|
|
211
|
+
const fits = (e, d) => e.at + d + e.hn <= e.hi + 1e-6 && e.at + d - e.hn >= e.lo - 1e-6;
|
|
212
|
+
const need = [...ends.values()].find((e) => !fits(e, 0));
|
|
213
|
+
if (!need) continue;
|
|
214
|
+
const d = need.at + need.hn > need.hi ? need.hi - (need.at + need.hn) : need.lo - (need.at - need.hn), v = need.post.u.map((x) => x * d);
|
|
215
|
+
if ([...ends.values()].every((e) => fits(e, dot(v, e.post.u)))) lift.set(id, v);
|
|
216
|
+
}
|
|
217
|
+
for (const [id, v] of lift) { const it = items.get(id); if (numeric(it)) { it.from = it.from.map((x, k) => r3(x + v[k])); it.to = it.to.map((x, k) => r3(x + v[k])); } else lift.delete(id); }
|
|
218
|
+
for (const j of out.joins ?? []) {
|
|
219
|
+
const ma = /^([\w-]+)\./.exec(String(j.a ?? '')), mb = /^([\w-]+)\.([a-z]+(?:\.\d+)?)@(-?[\d.]+)$/.exec(String(j.b ?? ''));
|
|
220
|
+
if (ma && mb && lift.has(ma[1]) && r.fm.beams.has(mb[1])) j.b = `${mb[1]}.${mb[2]}@${r3(Number(mb[3]) + dot(lift.get(ma[1]), r.fm.beams.get(mb[1]).u))}`;
|
|
221
|
+
}
|
|
222
|
+
// ends against faces: each moves as the face it meets moves
|
|
223
|
+
for (const j of out.joins ?? []) {
|
|
224
|
+
const ma = /^([\w-]+)\.([ab])(\.\d+)?$/.exec(String(j.a ?? '')), mb = /^([\w-]+)\.[a-z]+(\.\d+)?@/.exec(String(j.b ?? ''));
|
|
225
|
+
if (!ma || !mb || !r.fm.beams.has(ma[1]) || !r.fm.beams.has(mb[1]) || !by.has(mb[1])) continue;
|
|
226
|
+
const it = items.get(ma[1]);
|
|
227
|
+
if (!numeric(it)) continue;
|
|
228
|
+
const a = r.fm.beams.get(ma[1]), out_ = ma[2] === 'a' ? a.u.map((v) => -v) : a.u, shift = half(was(mb[1]), out_) - half(now(mb[1]), out_);
|
|
229
|
+
if (Math.abs(shift) < 1e-9 || it._moved?.[ma[2]]) continue;
|
|
230
|
+
const key = ma[2] === 'a' ? 'from' : 'to';
|
|
231
|
+
it[key] = it[key].map((v, k) => r3(v + out_[k] * shift));
|
|
232
|
+
(it._moved ??= {})[ma[2]] = true;
|
|
233
|
+
}
|
|
234
|
+
for (const it of out.items ?? []) {
|
|
235
|
+
delete it._moved;
|
|
236
|
+
const x = by.get(it.id);
|
|
237
|
+
if (x && it.beam) {
|
|
238
|
+
it.beam = { ...it.beam, profile: x.profile };
|
|
239
|
+
if (x.roll) it.roll = ((typeof it.roll === 'number' ? it.roll : 0) + x.roll) % 360;
|
|
240
|
+
}
|
|
241
|
+
const on = typeof it.at === 'string' ? by.get(it.at.split('.')[0]) : null;
|
|
242
|
+
if (on && it.fitting?.profile) it.fitting = { ...it.fitting, profile: on.profile };
|
|
243
|
+
}
|
|
244
|
+
// a blind or end-tap join at an end that now has several bores: one join a bore, each where its bore meets the face
|
|
245
|
+
if (out.joins) out.joins = out.joins.flatMap((j) => {
|
|
246
|
+
const ma = /^([\w-]+)\.([ab])$/.exec(String(j.a ?? '')), mb = /^([\w-]+)\.([a-z]+(?:\.\d+)?)@(-?[\d.]+)$/.exec(String(j.b ?? ''));
|
|
247
|
+
if (!ma || !mb || !['blind', 'end-tap'].includes(j.kind) || !by.has(ma[1]) || !r.fm.beams.has(mb[1])) return [j];
|
|
248
|
+
const q = now(ma[1]), bores = q.profile.bores;
|
|
249
|
+
if (bores.length < 2) return [j];
|
|
250
|
+
const post = r.fm.beams.get(mb[1]);
|
|
251
|
+
return bores.map((bo, k) => { const o = q.ax.X.map((v, c) => v * bo.at[0] + q.ax.Y[c] * bo.at[1]); return { ...j, a: `${ma[1]}.${ma[2]}.${k + 1}`, b: `${mb[1]}.${mb[2]}@${r3(Number(mb[3]) + dot(o, post.u))}` }; });
|
|
252
|
+
});
|
|
253
|
+
// nothing is written that would not build: every join's place on the beam it meets lies on that beam
|
|
254
|
+
for (const j of out.joins ?? []) {
|
|
255
|
+
const mb = /^([\w-]+)\.[a-z]+(?:\.\d+)?@(-?[\d.]+)$/.exec(String(j.b ?? ''));
|
|
256
|
+
if (!mb || !r.fm.beams.has(mb[1])) continue;
|
|
257
|
+
const it = items.get(mb[1]), L = numeric(it) ? Math.hypot(...it.to.map((v, k) => v - it.from[k])) : r.fm.beams.get(mb[1]).L, s = Number(mb[2]), at = mb[2].startsWith('-') ? L + s : s;
|
|
258
|
+
if (at < -1e-6 || at > L + 1e-6) throw new Error(`the sized profiles do not fit as drawn, so nothing is written: join ${j.a} would meet ${mb[1]} at ${n3(at)} mm, past its ${n3(L)} mm (a deeper beam there stands past the end of the one it meets, and its ends do not agree on a move); give that group a profile no deeper (frame.size.groups and profiles), or move the beam by hand`);
|
|
259
|
+
}
|
|
260
|
+
return out;
|
|
261
|
+
}
|
package/lib/jigs.mjs
CHANGED
|
@@ -9,7 +9,7 @@
|
|
|
9
9
|
import fs from 'node:fs';
|
|
10
10
|
import path from 'node:path';
|
|
11
11
|
import jscad from '@jscad/modeling';
|
|
12
|
-
import { JOINS, beamSheet, drillGuideModel, drillGuide, tapGuideModel, tapGuide, lengthStopModel, lengthStop, squareCornerModel, squareCorner, JIG_KINDS } from '@rulecad/frames';
|
|
12
|
+
import { JOINS, beamSheet, workOrder, drillGuideModel, drillGuide, tapGuideModel, tapGuide, lengthStopModel, lengthStop, squareCornerModel, squareCorner, JIG_KINDS } from '@rulecad/frames';
|
|
13
13
|
import { placeItems } from '@rulecad/model-link';
|
|
14
14
|
import { text } from '@rulecad/shapes';
|
|
15
15
|
import { check as printCheck } from '@rulecad/printcheck';
|
|
@@ -17,6 +17,7 @@ import { paths, printerOf } from './workspace.mjs';
|
|
|
17
17
|
import { peekRuleSet } from './rules.mjs';
|
|
18
18
|
import { threemf } from './threemf.mjs';
|
|
19
19
|
import { cutListOf } from './beams.mjs';
|
|
20
|
+
import { plasticOf } from './fittings.mjs';
|
|
20
21
|
|
|
21
22
|
const { measureBoundingBox } = jscad.measurements, { translate } = jscad.transforms, { geom3 } = jscad.geometries;
|
|
22
23
|
const mm = (x) => String(+Number(x).toFixed(2)), r3 = (x) => +x.toFixed(3);
|
|
@@ -80,29 +81,31 @@ function cornerFit(m, F, ai, bi, beams, worlds) {
|
|
|
80
81
|
* @returns {{ jigs: { kind: string, name: string, model: object, for: object[], label: string }[], findings: object[] }}
|
|
81
82
|
*/
|
|
82
83
|
export function jigsOf(s) {
|
|
83
|
-
const c = cutListOf(s), jigs = new Map(), findings = [], printer = printerFor(s.project).set ?? undefined;
|
|
84
|
+
const c = cutListOf(s), jigs = new Map(), findings = [], printer = printerFor(s.project).set ?? undefined, fx = { ...(printer ? { printer } : {}), material: plasticOf(s.project) }; // (printed in the project's plastic, as its fittings are)
|
|
84
85
|
const warn = (code, txt, refs) => findings.push({ level: 'warn', code, text: txt, refs });
|
|
85
86
|
const add = (key, kind, model, who) => { if (!jigs.has(key)) jigs.set(key, { kind, name: model.name, model, for: [] }); jigs.get(key).for.push(who); };
|
|
86
87
|
if (!c) return { jigs: [], findings };
|
|
87
88
|
for (const mk of c.marks) {
|
|
88
89
|
const b = mk.beam, sheet = beamSheet(b, { mark: mk.mark, items: mk.items });
|
|
90
|
+
// (each operation by its number on the sheet, the order it is done in; i is its index in the model's ops)
|
|
91
|
+
const order = workOrder(b), step = (i) => order.indexOf(i) + 1;
|
|
89
92
|
b.ops.forEach((x, i) => {
|
|
90
|
-
const who = { mark: mk.mark, items: mk.items, op:
|
|
93
|
+
const n = step(i), who = { mark: mk.mark, items: mk.items, op: n, at: x.at, line: x.line };
|
|
91
94
|
if (HOLES.includes(x.op)) {
|
|
92
95
|
try {
|
|
93
|
-
const m = drillGuideModel(b, i,
|
|
94
|
-
const dim = sheet.dimensions.find((d) => d.op ===
|
|
95
|
-
add(`drill|${m.name}|${m.profile}|${m.plate.span.join(',')}`, 'drill-guide', m, { ...who, label: `${mk.mark}${
|
|
96
|
-
} catch (e) { warn('jig.drill', `mark ${mk.mark} (${mk.items.join(', ')}), operation ${
|
|
96
|
+
const m = drillGuideModel(b, i, fx), z = r3(m.fit[6] * m.bush.at[1] + m.fit[14]); // (the bush's axis, fitted: its distance from end a)
|
|
97
|
+
const dim = sheet.dimensions.find((d) => d.op === n);
|
|
98
|
+
add(`drill|${m.name}|${m.profile}|${m.plate.span.join(',')}`, 'drill-guide', m, { ...who, label: `${mk.mark}${n}`, from: m.from, distance: m.bush.at[1], bush: z, sheet: dim ? dim.distance : null, sheetText: dim ? dim.text : null });
|
|
99
|
+
} catch (e) { warn('jig.drill', `mark ${mk.mark} (${mk.items.join(', ')}), operation ${n}: no drill guide: ${strip(e)}`, { mark: mk.mark, op: n }); }
|
|
97
100
|
}
|
|
98
101
|
if (x.op === 'tap') {
|
|
99
102
|
try {
|
|
100
|
-
const m = tapGuideModel(b, i,
|
|
101
|
-
add(`tap|${m.name}|${m.profile}|${JSON.stringify(m.bores)}`, 'tap-guide', m, { ...who, label: `${mk.mark}${
|
|
102
|
-
} catch (e) { warn('jig.tap', `mark ${mk.mark} (${mk.items.join(', ')}), operation ${
|
|
103
|
+
const m = tapGuideModel(b, i, fx);
|
|
104
|
+
add(`tap|${m.name}|${m.profile}|${JSON.stringify(m.bores)}`, 'tap-guide', m, { ...who, label: `${mk.mark}${n}`, end: x.end, bores: x.bores });
|
|
105
|
+
} catch (e) { warn('jig.tap', `mark ${mk.mark} (${mk.items.join(', ')}), operation ${n}: no tap guide: ${strip(e)}`, { mark: mk.mark, op: n }); }
|
|
103
106
|
}
|
|
104
107
|
});
|
|
105
|
-
const m = lengthStopModel(b.profile, b.length,
|
|
108
|
+
const m = lengthStopModel(b.profile, b.length, fx);
|
|
106
109
|
add(`length|${b.profile.name}|${b.length}`, 'length-stop', m, { mark: mk.mark, items: mk.items, label: `${mk.mark} ${mm(b.length)}`, length: b.length });
|
|
107
110
|
}
|
|
108
111
|
// a squaring corner for each square join: on a face of each beam in one plane, of the hand whose arm b lies on b, its
|
|
@@ -122,7 +125,7 @@ export function jigsOf(s) {
|
|
|
122
125
|
if (dot(fa.n, fb.n) < 1 - 1e-6 || Math.abs(dot(fa.n, fa.at.map((v, k) => v - fb.at[k]))) > 0.05) continue;
|
|
123
126
|
const out = dot(fa.n, fb.at.map((v, k) => v - middle[k])), edge = dot(fb.along, away) > 0 ? 'hi' : 'lo';
|
|
124
127
|
for (const hand of ['right', 'left']) {
|
|
125
|
-
const m = corner({ profile: A.profile, face: pa.name, end, length: A.length }, { profile: B.profile, face: pb.name, edge }, { hand, ...
|
|
128
|
+
const m = corner({ profile: A.profile, face: pa.name, end, length: A.length }, { profile: B.profile, face: pb.name, edge }, { hand, ...fx });
|
|
126
129
|
tried.push({ pa, pb, hand, out, m, fit: mul(colMajor(Wa), m.fit), ...cornerFit(m, mul(colMajor(Wa), m.fit), ai, bi, beams, worlds) });
|
|
127
130
|
}
|
|
128
131
|
}
|
|
@@ -196,7 +199,7 @@ export const jigFile = (s, n, of) => paths.exports(s.project, `${s.name}.jigs${o
|
|
|
196
199
|
export async function writeJigs(s, { write = true } = {}) {
|
|
197
200
|
const { jigs, findings } = jigsOf(s), { check } = printerFor(s.project), dir = paths.exports(s.project), base = `${s.name}.jigs`;
|
|
198
201
|
if (write && fs.existsSync(dir)) for (const f of fs.readdirSync(dir)) if (f.startsWith(base) && f.endsWith('.3mf')) fs.rmSync(path.join(dir, f));
|
|
199
|
-
const parts = [], rows = [];
|
|
202
|
+
const parts = [], rows = [], material = () => { const p = plasticOf(s.project); return typeof p === 'string' ? p : p.name; };
|
|
200
203
|
for (const x of jigs) {
|
|
201
204
|
const made = jigParts(x), checks = [];
|
|
202
205
|
for (const p of made) {
|
|
@@ -207,7 +210,7 @@ export async function writeJigs(s, { write = true } = {}) {
|
|
|
207
210
|
for (const f of issues) findings.push({ level: f.level, code: 'jig.print', text: `${p.name}: ${f.text}`, refs: { jig: x.name, check: f.code } });
|
|
208
211
|
}
|
|
209
212
|
const m = x.model;
|
|
210
|
-
rows.push({ kind: x.kind, name: x.name, mark: x.label, for: x.for, grams: m.grams, margin: m.margin, size: m.size, checks, findings: m.findings.map(({ level, code, text: t, values }) => ({ level, code, text: t, ...(values ? { values } : {}) })) });
|
|
213
|
+
rows.push({ kind: x.kind, name: x.name, mark: x.label, for: x.for, material: m.material, grams: m.grams, margin: m.margin, size: m.size, checks, findings: m.findings.map(({ level, code, text: t, values }) => ({ level, code, text: t, ...(values ? { values } : {}) })) });
|
|
211
214
|
}
|
|
212
215
|
const gap = Math.max(2, Math.ceil((check.print_gap + 2 * check.foot) / check.line - 1e-6) * check.line), beds = parts.length ? pack(parts, check.bed, gap) : [];
|
|
213
216
|
const plates = [];
|
|
@@ -215,7 +218,7 @@ export async function writeJigs(s, { write = true } = {}) {
|
|
|
215
218
|
const file = jigFile(s, n + 1, beds.length), half = check.bed / 2 - gap;
|
|
216
219
|
const objects = b.parts.map((p) => ({ name: p.name, parts: [{ name: p.name, triangles: p.tris.map((t) => t.map((v) => [v[0] + p.at[0] - half, v[1] + p.at[1] - half, v[2]])), slot: 1 }] }));
|
|
217
220
|
if (write) { fs.mkdirSync(dir, { recursive: true }); fs.writeFileSync(file, await threemf(objects, { title: `${s.a.title || s.name}: jigs` })); }
|
|
218
|
-
plates.push({ file, parts: b.parts.map((p) => p.name), objects });
|
|
221
|
+
plates.push({ file, material: material(), parts: b.parts.map((p) => p.name), objects });
|
|
219
222
|
}
|
|
220
223
|
return { jigs: rows, plates: plates.map(({ objects, ...p }) => p), findings, parts: plates.flatMap((p) => p.objects) };
|
|
221
224
|
}
|
package/lib/joins.mjs
CHANGED
|
@@ -12,7 +12,7 @@ import { placeItems } from '@rulecad/model-link';
|
|
|
12
12
|
import { beamOf, beamPlace, framesContext } from './beams.mjs';
|
|
13
13
|
import { joinFitting, fittedStiffness } from './fittings.mjs';
|
|
14
14
|
|
|
15
|
-
const KEYS = ['kind', 'a', 'b', 'fitting', 'screw', 'brace', 'load', 'nut', 'note'];
|
|
15
|
+
const KEYS = ['kind', 'a', 'b', 'fitting', 'screw', 'brace', 'load', 'nut', 'face', 'shape', 'note'];
|
|
16
16
|
const shown = (v) => (v === undefined ? 'nothing' : JSON.stringify(v));
|
|
17
17
|
const mm = (x) => String(+Number(x).toFixed(2)), r3 = (x) => +x.toFixed(3);
|
|
18
18
|
const dot = (a, b) => a[0] * b[0] + a[1] * b[1] + a[2] * b[2], sub = (a, b) => [a[0] - b[0], a[1] - b[1], a[2] - b[2]];
|
|
@@ -66,6 +66,9 @@ export function expandJoins(a, num, context = framesContext(), material = 'pla')
|
|
|
66
66
|
catch (e) { throw new Error(`${what}: ${String(e.message).replace(/^(joinModel|beamAnchor): /, '')}`); }
|
|
67
67
|
for (const [side, ops] of [['a', m.a.ops], ['b', m.b.ops]]) { const id = ends[side].id; if (ops.length) extra.set(id, [...(extra.get(id) || []), ...ops]); }
|
|
68
68
|
const label = j.note || `${j.kind} join of ${j.a} to ${j.b}`, mine = [];
|
|
69
|
+
if (j.face != null && !(j.kind === 'gusset' && j.fitting === 'printed')) throw new Error(`${what}: face names the face of b a printed gusset lies on: give it on a gusset join with "fitting": "printed", or leave face out`);
|
|
70
|
+
if (j.shape != null && !(j.kind === 'gusset' && j.fitting === 'printed')) throw new Error(`${what}: shape names a printed gusset's shape (L or T): give it on a gusset join with "fitting": "printed", or leave shape out`);
|
|
71
|
+
if (j.shape != null && !['L', 'T'].includes(j.shape)) throw new Error(`${what}: shape is a printed gusset's shape, L or T (got ${JSON.stringify(j.shape)})`);
|
|
69
72
|
for (const k of ['brace', 'load', 'nut']) if (j[k] != null && !(m.fitting?.printed && j.fitting === 'printed')) throw new Error(`${what}: ${k} is for a printed fitting: give "fitting": "printed" on a ${Object.keys(JOINS).filter((x) => JOINS[x].printed).join(', ')} join, or leave ${k} out`);
|
|
70
73
|
// a printed fitting: its item, placed from where the beams are, and a fasten for each leg into its beam's slot
|
|
71
74
|
let fitted = null;
|
|
@@ -86,12 +89,13 @@ export function expandJoins(a, num, context = framesContext(), material = 'pla')
|
|
|
86
89
|
for (const sc of m.screws) { mine.push(first + fasten.length); fasten.push({ screw: sc.screw, through: [ends.b.id], into: ends.a.id, at: [`${ends.a.id}.${sc.bore}`], note: label, join: i, ...(lips ? { lips } : {}) }); }
|
|
87
90
|
joins.push({ index: i, kind: j.kind, a: j.a, b: j.b, items: [ends.a.id, ends.b.id], end: ends.a.rest, address: ends.b.rest, label, fitting: j.fitting ?? null, model: m, fasten: mine, ...(fitted ? { fitted: { item: fitted.item.id, model: fitted.model } } : {}) });
|
|
88
91
|
});
|
|
89
|
-
// each beam's own ops first; a join's op where the beam has none like it at that place (a tap
|
|
92
|
+
// each beam's own ops first; a join's op where the beam has none like it at that place (a tap of the whole end a
|
|
93
|
+
// covers a tap at a.1; a tap at a.1 does not cover one at a.2, a 20 x 40's other bore)
|
|
90
94
|
const withOps = items.map((it) => {
|
|
91
95
|
const add = extra.get(it.id);
|
|
92
96
|
if (!add) return it;
|
|
93
97
|
const own = it.beam.ops || [], ops = [...own];
|
|
94
|
-
for (const op of add) if (!ops.some((g) => g?.op === op.op && (sameAt(g.at, op.at) || (op.op === 'tap' && String(g.at).trim()[0]
|
|
98
|
+
for (const op of add) if (!ops.some((g) => g?.op === op.op && (sameAt(g.at, op.at) || (op.op === 'tap' && (String(g.at).trim() === op.at[0] || (op.at.length === 1 && String(g.at).trim()[0] === op.at)))))) ops.push(op);
|
|
95
99
|
return { ...it, beam: { ...it.beam, ops } };
|
|
96
100
|
});
|
|
97
101
|
return { a: { ...a, items: [...withOps, ...added], ...(fasten.length ? { fasten: [...(a.fasten || []), ...fasten] } : {}) }, joins };
|
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
|
+
}
|