@rulecad/cad 0.7.56 → 0.7.57
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 +57 -0
- package/CHANGELOG.md +41 -0
- package/EXAMPLES.md +363 -1
- package/README.md +336 -5
- package/TUTORIAL.md +2 -0
- package/bin/cad.mjs +35 -11
- package/lib/assembly.mjs +69 -16
- package/lib/beams.mjs +2 -2
- package/lib/bought.mjs +41 -5
- package/lib/buildpage.mjs +8 -3
- package/lib/edit.mjs +10 -4
- package/lib/fasten.mjs +255 -45
- package/lib/fittings.mjs +271 -0
- package/lib/framebuild.mjs +407 -0
- package/lib/frames.mjs +4 -3
- package/lib/guides.mjs +354 -0
- package/lib/jigs.mjs +237 -0
- package/lib/joins.mjs +259 -0
- package/lib/list.mjs +22 -6
- package/lib/loads.mjs +9 -2
- package/lib/measured.mjs +64 -17
- package/lib/motors.mjs +7 -3
- package/lib/order.mjs +19 -11
- package/lib/panels.mjs +220 -0
- package/lib/plates.mjs +11 -4
- package/lib/services.mjs +132 -0
- package/lib/slotnuts.mjs +159 -0
- package/lib/task.mjs +4 -2
- package/lib/wires.mjs +2 -1
- package/package.json +4 -4
- package/schemas/assembly.schema.json +27 -5
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;
|
|
@@ -214,6 +218,9 @@ function pinv2(J, v) {
|
|
|
214
218
|
|
|
215
219
|
export function loadChecks(s, f, helpers) {
|
|
216
220
|
const motion = s.motion;
|
|
221
|
+
// a guide's carriages are held to their ratings whether or not the machine has a task: they carry what is on them
|
|
222
|
+
// (the masses' centres read against the frames of the pose the parts were built at, which a pose's own check is)
|
|
223
|
+
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
224
|
if (!motion?.joints?.length || !(s.task || s.a.gravity)) return;
|
|
218
225
|
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
226
|
const unknown = masses.filter((m) => !m.known).map((m) => m.id);
|
package/lib/measured.mjs
CHANGED
|
@@ -2,16 +2,19 @@
|
|
|
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.
|
|
7
10
|
import fs from 'node:fs';
|
|
8
11
|
import path from 'node:path';
|
|
9
12
|
import { setAt } from './jsonedit.mjs';
|
|
10
13
|
import { CadError } from './errors.mjs';
|
|
11
14
|
import { paths, WS, RULE_DIRS, printerOf } from './workspace.mjs';
|
|
12
|
-
import { loadRuleSet } from './rules.mjs';
|
|
15
|
+
import { loadRuleSet, peekRuleSet } from './rules.mjs';
|
|
13
16
|
import { buildAssembly, checkAssembly, assemblyPath } from './assembly.mjs';
|
|
14
|
-
import { slotModel } from '@rulecad/frames';
|
|
17
|
+
import { slotModel, JOIN_SET, joinRuleSet } from '@rulecad/frames';
|
|
15
18
|
import { fixingsContext } from './design.mjs';
|
|
16
19
|
import { fixingsFor, threads } from '@rulecad/fixings';
|
|
17
20
|
|
|
@@ -24,12 +27,17 @@ const keyOf = (x) => `${x.code}|${JSON.stringify(x.refs ?? {})}`;
|
|
|
24
27
|
// 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
28
|
export const predictionsOf = (findings) => findings.filter((x) => x.predict);
|
|
26
29
|
|
|
30
|
+
// 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
|
|
31
|
+
// set @rulecad/frames' estimates), so nothing is written until every value has been checked
|
|
27
32
|
function ruleFile(name) {
|
|
28
33
|
const dot = name.indexOf('.');
|
|
29
34
|
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
35
|
const set = name.slice(0, dot), rule = name.slice(dot + 1);
|
|
31
|
-
const
|
|
32
|
-
|
|
36
|
+
const file = path.join(WS, 'rules', `${set}.json`), from = RULE_DIRS.map((d) => path.join(d, `${set}.json`)).find((f) => fs.existsSync(f));
|
|
37
|
+
// the joins set has no file in the kit: the workspace's copy starts from @rulecad/frames' estimates
|
|
38
|
+
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` }; }
|
|
39
|
+
const data = peekRuleSet(set); // (the measurement goes in your copy: the tool's set is copied there when it is written)
|
|
40
|
+
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
41
|
}
|
|
34
42
|
|
|
35
43
|
// The slot coupon (examples/bench/projects/benchmarks/MEASURE.md, rows 29 to 33): the two fits it measures, which a
|
|
@@ -47,6 +55,27 @@ function slotRule(project, set, key, data) {
|
|
|
47
55
|
return null;
|
|
48
56
|
}
|
|
49
57
|
|
|
58
|
+
// The joint rig (examples/bench/projects/benchmarks/MEASURE.md, rows 34 to 37): a join's bending spring, written to the
|
|
59
|
+
// 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
|
|
60
|
+
// has no rule for it until it is measured
|
|
61
|
+
const RIG = 'the joint rig (examples/bench/projects/benchmarks/MEASURE.md)';
|
|
62
|
+
function rigRule(set, key, data) {
|
|
63
|
+
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`,
|
|
64
|
+
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` };
|
|
65
|
+
// what a spring measured on the rig is, in place of the estimate's sentence ("a working guess ... until the joint rig
|
|
66
|
+
// measures it"); the drop it came from goes in its source
|
|
67
|
+
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)`;
|
|
68
|
+
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` });
|
|
69
|
+
if (set === JOIN_SET) {
|
|
70
|
+
const j = key.match(/^(.+)_(bending|twist|printed_share)$/), kind = j?.[1].replace(/_/g, '-');
|
|
71
|
+
if (!j) return { source: RIG };
|
|
72
|
+
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`
|
|
73
|
+
: `${turn(`a ${kind} join`)[j[2]]}, for a 20 mm series profile: ${how}` };
|
|
74
|
+
}
|
|
75
|
+
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}` } : {}) }; }
|
|
76
|
+
return null;
|
|
77
|
+
}
|
|
78
|
+
|
|
50
79
|
// The printer's rules the fixings read that a printer's set may not hold yet, each measured on the fixings coupon
|
|
51
80
|
// (examples/bench/projects/benchmarks/MEASURE.md): what it is, its unit, and what the kit drew before it was measured,
|
|
52
81
|
// so the ledger shows predicted against measured. A pilot or an insert hole is per thread, and may name a plastic
|
|
@@ -94,28 +123,46 @@ export async function recordMeasured(ref, values, { unit, source, rule, date = t
|
|
|
94
123
|
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
124
|
const before = await findingsOf(ref), entries = [], predictions = predictionsOf(before);
|
|
96
125
|
const writes = [], slots = new Map(); // (every value is checked before any is written, so a refusal leaves the rule sets as they were)
|
|
126
|
+
// a rule's new value, checked before anything is written (a refusal leaves the rule sets as they were)
|
|
127
|
+
const writeRule = (k, value, { from = null, unit: u = unit } = {}) => {
|
|
128
|
+
const { set, rule: key, data, file, text, copied } = ruleFile(k);
|
|
129
|
+
const old = data.rules?.[key], known = slotRule(project, set, key, data) ?? rigRule(set, key, data) ?? fixingsRule(project, set, key) ?? (old ? null : kitRule(set, key));
|
|
130
|
+
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})`);
|
|
131
|
+
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'})`);
|
|
132
|
+
const had = old ?? known, prior = typeof had?.value === 'number' ? had.value : known?.predicted ?? null;
|
|
133
|
+
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}`);
|
|
134
|
+
// 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
|
|
135
|
+
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 };
|
|
136
|
+
if (data.part === 'slot') slots.set(set, { data, change: { ...slots.get(set)?.change, [key]: value } });
|
|
137
|
+
writes.push({ file, key, entry, text, copied, set });
|
|
138
|
+
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 } : {}) });
|
|
139
|
+
};
|
|
97
140
|
for (const [k, value] of Object.entries(values)) {
|
|
98
141
|
if (!Number.isFinite(value)) throw new CadError('measured.value', `${k}: a measurement is a number (got ${value})`);
|
|
99
142
|
const named = predictions.filter((x) => x.code === k || x.predict.name === k);
|
|
100
143
|
if (named.length) {
|
|
101
144
|
const p = named[0].predict;
|
|
102
145
|
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 } : {}) });
|
|
146
|
+
// 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
|
|
147
|
+
if (p.rig) {
|
|
148
|
+
const r = p.rig, n = (x) => String(Number(Number(x).toFixed(3)));
|
|
149
|
+
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`);
|
|
150
|
+
const spring = (r.force * r.arm * r.arm) / (value - r.beam), figure = Number((spring * r.per).toPrecision(4));
|
|
151
|
+
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` });
|
|
152
|
+
}
|
|
103
153
|
continue;
|
|
104
154
|
}
|
|
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 } : {}) });
|
|
155
|
+
writeRule(k, value);
|
|
115
156
|
}
|
|
116
157
|
// a slot's figures together still make a slot (an opening narrower than its cavity, lips thinner than it is deep)
|
|
117
158
|
for (const [set, { data, change }] of slots) { try { slotModel(data, change); } catch (e) { throw new CadError('measured.value', `${set}: ${e.message.replace(/^slotModel: /, '')}`); } }
|
|
118
|
-
|
|
159
|
+
// every value checked: now each set is written, the workspace's copy made from where it started where there is none
|
|
160
|
+
const texts = new Map();
|
|
161
|
+
for (const w of writes) texts.set(w.file, { ...w, text: setAt(texts.get(w.file)?.text ?? w.text, ['rules', w.key], w.entry) });
|
|
162
|
+
for (const [file, w] of texts) {
|
|
163
|
+
fs.mkdirSync(path.dirname(file), { recursive: true }); fs.writeFileSync(file, w.text);
|
|
164
|
+
if (w.copied) console.error(w.copied);
|
|
165
|
+
}
|
|
119
166
|
const after = await findingsOf(ref), was = new Map(before.map((x) => [keyOf(x), x])), moved = [];
|
|
120
167
|
for (const x of after) {
|
|
121
168
|
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
|
}
|
package/lib/order.mjs
CHANGED
|
@@ -92,7 +92,8 @@ function hitsAlong(origin, dir, tris) {
|
|
|
92
92
|
/**
|
|
93
93
|
* The order to put an assembly together, as data.
|
|
94
94
|
* @param {object} s a built assembly
|
|
95
|
-
* @returns {{ steps: { n: number, items: string[], object: string|null, dir: number[], fasteners: {fit: string, fastener?: string, count?: number}[], text: string }[], stuck: object|null }}
|
|
95
|
+
* @returns {{ steps: { n: number, items: string[], object: string|null, dir: number[], fasteners: {fit: string, fastener?: string, count?: number}[], text: string }[], stuck: object|null, covers?: { fit: string, fasten?: number, screwed: string[], wall: string }[] }}
|
|
96
|
+
* covers: each part that stands over a screw, which has to go on after the parts the screw joins
|
|
96
97
|
*/
|
|
97
98
|
export function assemblyOrder(s) {
|
|
98
99
|
const all = groups(s).filter((g) => g.bought || g.motor || g.parts.some((p) => p.role === 'part' || p.role == null) || s.fits.some((x) => [x.a, x.b].flat().some((n) => top(n) === g.id)));
|
|
@@ -119,7 +120,7 @@ export function assemblyOrder(s) {
|
|
|
119
120
|
}
|
|
120
121
|
// Screws: what stands on the tool's line goes on after the screw, and if it must already be there, nothing can
|
|
121
122
|
const worlds = placeItems(s.motion, s.jointValues), marks = s.motion.marks, reaches = (u, v, seen = new Set()) => { if (u === v) return true; if (seen.has(u)) return false; seen.add(u); return [...before.get(u).keys()].some((w) => reaches(w, v, seen)); };
|
|
122
|
-
const R = 1.5, bad = [];
|
|
123
|
+
const R = 1.5, bad = [], covers = []; // (covers: what stands over a screw, kept so another order of the same parts, a frame's build, can be held to it)
|
|
123
124
|
for (const x of s.fits.filter((f) => f.access)) {
|
|
124
125
|
const [id, name] = String(x.access).split('.'), m = marks.find((k) => k.id === id && k.name === name) ?? (s.items.find((i) => i.id === id)?.beam ? s.motion.address(String(x.access), 'access') : null); // (a beam's address: x1.top@120)
|
|
125
126
|
if (!m) throw new Error(`fit ${x.note || `${x.a} / ${x.b}`}: access: no anchor "${x.access}" (give <item>.<anchor>${items.includes(id) ? `; ${id} has ${marks.filter((k) => k.id === id).map((k) => k.name).join(', ') || 'none'}` : ''})`);
|
|
@@ -128,7 +129,7 @@ export function assemblyOrder(s) {
|
|
|
128
129
|
for (const q of all) {
|
|
129
130
|
if (screwed.includes(q.id) || !starts.some((p) => hitsAlong(p, D, q.tris))) continue;
|
|
130
131
|
if (later && reaches(q.id, later)) bad.push({ fit: x, wall: q.id, at: O, later });
|
|
131
|
-
else if (later) add(later, q.id, `${q.id} covers the screw of ${x.note || later}`);
|
|
132
|
+
else if (later) { add(later, q.id, `${q.id} covers the screw of ${x.note || later}`); covers.push({ fit: x.note || `${x.a} to ${x.b}`, screwed, wall: q.id }); }
|
|
132
133
|
}
|
|
133
134
|
}
|
|
134
135
|
// A fasten's screws (lib/fasten.mjs): what stands over a head goes on after the parts the screw joins. A part that
|
|
@@ -139,7 +140,7 @@ export function assemblyOrder(s) {
|
|
|
139
140
|
const screwed = [...rel.through, rel.into].map(top).filter((t) => by.has(t)), later = [...screwed].sort(earlier).at(-1), walls = [...new Set(acc.blockers.map((b) => b.item))];
|
|
140
141
|
const first = walls.filter((q) => !by.has(q) || screwed.includes(q) || (later && reaches(q, later)));
|
|
141
142
|
if (first.length) { if (acc.tilt == null) bad.push({ fit: { note: rel.label }, wall: first[0], at: acc.top, later, fasten: rel.index, screw: sc.index, member: screwed.includes(first[0]), fixed: !by.has(first[0]) }); continue; }
|
|
142
|
-
for (const q of walls) add(later, q, `${q} covers the screws of ${rel.label}`);
|
|
143
|
+
for (const q of walls) { add(later, q, `${q} covers the screws of ${rel.label}`); covers.push({ fasten: rel.index, fit: rel.label, screwed, wall: q }); }
|
|
143
144
|
}
|
|
144
145
|
const box = (g) => { const p = g.tris.flat(); return [0, 1, 2].map((k) => { const v = p.map((x) => x[k]); return (Math.min(...v) + Math.max(...v)) / 2; }); };
|
|
145
146
|
if (bad.length) {
|
|
@@ -214,7 +215,7 @@ export function assemblyOrder(s) {
|
|
|
214
215
|
else merged.push({ items: [...st.items], object: st.object, dir: st.dir, fasteners: st.fasteners, ...(st.together ? { together: true } : {}) });
|
|
215
216
|
}
|
|
216
217
|
merged.forEach((st, i) => { st.n = i + 1; st.text = `${st.items.join(', ')}${st.object && !st.items.includes(st.object) ? ` (${st.object})` : ''}${st.together ? ' go on as one' : i ? ` goes on${st.items.length > 1 ? ', one by one' : ''}` : ' first'}${st.fasteners.length ? `: ${st.fasteners.map(fastenerText).join('; ')}` : ''}`; });
|
|
217
|
-
return { steps: merged, stuck: null };
|
|
218
|
+
return { steps: merged, stuck: null, covers };
|
|
218
219
|
}
|
|
219
220
|
|
|
220
221
|
/** One fastening of a step as the order and the build page say it: the fit, its screws by count and name, the key and how tight. */
|
|
@@ -222,7 +223,7 @@ export const fastenerText = (f) => `${f.fit}${f.fastener ? ` (${f.count != null
|
|
|
222
223
|
|
|
223
224
|
// Cached by what the parts are and where they are, with everything else that changes the answer
|
|
224
225
|
function orderFile(s) {
|
|
225
|
-
const key = crypto.createHash('sha256').update(JSON.stringify([
|
|
226
|
+
const key = crypto.createHash('sha256').update(JSON.stringify([6, s.parts.map((p) => [p.item, p.hash ?? p.shape, Array.from(p.m ?? []).map((x) => +x.toFixed(4))]), s.fits.map(({ num, ...x }) => x), s.motion.joints.map((j) => [j.id, j.child, j.parent])])).digest('hex');
|
|
226
227
|
return paths.cache('order', `${key}.json`);
|
|
227
228
|
}
|
|
228
229
|
export function orderOf(s) {
|
|
@@ -237,12 +238,19 @@ export function orderOf(s) {
|
|
|
237
238
|
// Whether an assembly is something that goes together with fastenings: anything else has no steps to find
|
|
238
239
|
export const isBuilt = (s) => s.a.kind !== 'plate' && s.fits.some((x) => x.fastens || x.seat != null || x.shaft != null || x.access);
|
|
239
240
|
|
|
240
|
-
/**
|
|
241
|
-
|
|
241
|
+
/**
|
|
242
|
+
* assembly.order, in the assembly's findings shape. With a frame's build (frameBuild, for an assembly with joins) the
|
|
243
|
+
* steps counted are its, as cad order prints them: one count for the one sequence. @param {object} s @param {Function} f
|
|
244
|
+
* @param {{ frame?: (s: object) => object }} [o]
|
|
245
|
+
*/
|
|
246
|
+
export function orderChecks(s, f, { frame = null } = {}) {
|
|
242
247
|
if (!isBuilt(s) || (s.pose != null && s.pose !== s.motion.pose)) return;
|
|
243
248
|
const r = orderOf(s);
|
|
244
|
-
if (r.stuck) f('fail', r.stuck.text, `${r.stuck.item}: can't be reached`, { code: 'assembly.order', at: r.stuck.at, refs: { item: r.stuck.item, ...(r.stuck.wall ? { wall: r.stuck.wall } : {}), ...(r.stuck.screw ? { screw: r.stuck.screw } : {}), ...(r.stuck.holders ? { holders: r.stuck.holders } : {}) } });
|
|
245
|
-
|
|
249
|
+
if (r.stuck) return f('fail', r.stuck.text, `${r.stuck.item}: can't be reached`, { code: 'assembly.order', at: r.stuck.at, refs: { item: r.stuck.item, ...(r.stuck.wall ? { wall: r.stuck.wall } : {}), ...(r.stuck.screw ? { screw: r.stuck.screw } : {}), ...(r.stuck.holders ? { holders: r.stuck.holders } : {}) } });
|
|
250
|
+
const b = frame && s.joins?.length ? frame(s) : null;
|
|
251
|
+
if (b?.stuck) return f('fail', `no build from bars to a square frame: ${b.stuck.text}`, `${b.stuck.item}: no build`, { code: 'assembly.order', refs: { item: b.stuck.item, ...(b.stuck.place ? { place: b.stuck.place } : {}), ...(b.stuck.joins ? { joins: b.stuck.joins } : {}) } });
|
|
252
|
+
const n = b ? b.steps.length : r.steps.length, first = b ? b.steps.find((st) => st.now?.length)?.now[0] : r.steps[0]?.items[0];
|
|
253
|
+
f('pass', `goes together in ${n} step${n === 1 ? '' : 's'}${b ? ' from bars to a square frame (cad order)' : ''}, ${first} first, nothing trapped`, null, { code: 'assembly.order', values: { steps: n }, refs: { first } });
|
|
246
254
|
}
|
|
247
255
|
|
|
248
256
|
/** Each step's picture: what's there, and the new part held off along the way it goes on. @returns {object[][]} parts lists, for preview() */
|
|
@@ -256,4 +264,4 @@ export function stepPictures(s, r) {
|
|
|
256
264
|
});
|
|
257
265
|
}
|
|
258
266
|
|
|
259
|
-
export const orderText = (ref, r) => (r.stuck ? `${ref}: ${r.stuck.text}` : [`${ref}: how it goes together`, ...r.steps.
|
|
267
|
+
export const orderText = (ref, r) => (r.stuck ? `${ref}: ${r.stuck.text}` : [`${ref}: how it goes together`, ...r.steps.flatMap((st) => [...(st.load || []).map((t) => ` first, ${t}`), ` ${String(st.n).padStart(2)}. ${st.text}`])].join('\n'));
|
package/lib/panels.mjs
ADDED
|
@@ -0,0 +1,220 @@
|
|
|
1
|
+
// Panels in assemblies (@rulecad/frames' panel.mjs and door.mjs): an item with "panel" is a sheet cut to the bay of a
|
|
2
|
+
// frame it closes: { "sheet": "acrylic", "thickness": 3, "bay": ["x1", "z1", "x2", "z2"], "out": [0, -1, 0] }. The bay
|
|
3
|
+
// is four beams placed by their ends, two each way, their slotted faces that look along "out" in one plane. Before the
|
|
4
|
+
// items are built, each panel is worked out: its size from the beams' slots, the item placed on that plane, and its
|
|
5
|
+
// printed clips placed at a pitch along each edge, each with a fasten into its beam's slot. With "door" it is a door:
|
|
6
|
+
// it stands off the faces on printed hinges along one beam, turns on a revolute joint (poses <id>-shut and <id>-open),
|
|
7
|
+
// has a handle and a magnet catch, and the screws through it are fastens with their holes cut in it. Units: mm.
|
|
8
|
+
import { panelModel, panel, panelClipModel, hingeModel, latchModel, magnetCatchModel, handleModel, PANEL_DEFAULTS, DOOR_DEFAULTS } from '@rulecad/frames';
|
|
9
|
+
import { beamOf, beamPlace, framesContext } from './beams.mjs';
|
|
10
|
+
import { givenFor } from './frames.mjs';
|
|
11
|
+
import { named } from './parts.mjs';
|
|
12
|
+
import { referenceBuilt } from './bought.mjs';
|
|
13
|
+
import { ops as booleans } from '@rulecad/shapes';
|
|
14
|
+
|
|
15
|
+
const KEYS = ['sheet', 'thickness', 'bay', 'out', 'pitch', 'nut', 'load', 'door'];
|
|
16
|
+
const DOOR_KEYS = ['hinge', 'open', 'handle', 'catch', 'latch', 'load'];
|
|
17
|
+
const shown = (v) => (v === undefined ? 'nothing' : JSON.stringify(v));
|
|
18
|
+
const mm = (x) => String(+Number(x).toFixed(2)), r3 = (x) => +x.toFixed(3);
|
|
19
|
+
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]], add = (a, b, k = 1) => [a[0] + k * b[0], a[1] + k * b[1], a[2] + k * b[2]];
|
|
20
|
+
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]];
|
|
21
|
+
const unit = (v) => { const l = Math.hypot(...v); return v.map((c) => c / l); };
|
|
22
|
+
const col = (f, k) => [f[k], f[4 + k], f[8 + k]], org = (f) => [f[3], f[7], f[11]];
|
|
23
|
+
const world = (f, p) => [0, 1, 2].map((k) => f[4 * k] * p[0] + f[4 * k + 1] * p[1] + f[4 * k + 2] * p[2] + f[4 * k + 3]);
|
|
24
|
+
const turn = (f, v) => [0, 1, 2].map((k) => f[4 * k] * v[0] + f[4 * k + 1] * v[1] + f[4 * k + 2] * v[2]);
|
|
25
|
+
// a world point and direction in a frame's own coordinates (its rows' transpose)
|
|
26
|
+
const local = (f, p) => { const q = sub(p, org(f)); return [0, 1, 2].map((k) => r3(dot(col(f, k), q))); };
|
|
27
|
+
const localDir = (f, v) => [0, 1, 2].map((k) => r3(dot(col(f, k), v)));
|
|
28
|
+
const near = (a, b) => Math.abs(a - b) < 1e-6;
|
|
29
|
+
|
|
30
|
+
/** The working figures of panels in assemblies, each with what it rests on. */
|
|
31
|
+
export const PANEL_CHECK = {
|
|
32
|
+
plane: { value: 0.05, unit: 'mm', rule: 'A bay\'s four faces lie in one plane when they are within this of each other: a panel lies flat on all four', kind: 'default', source: 'A working figure of @rulecad/cad, the same as a join\'s flush', checked: '2026-11-17' },
|
|
33
|
+
latch_probe: { value: 0.5, unit: '°', rule: 'A door with its latch shut is also swept this far off shut, finer than the sweep\'s steps: the latch\'s tab stands just over the door\'s edge, so the door hits it within its first degree and a coarse step would jump past it', kind: 'default', source: 'A working figure of @rulecad/cad: the panels test sees the hit from 0.5° on a 400 x 300 mm door', checked: '2026-11-17' },
|
|
34
|
+
inset: { value: 2, unit: 'mm', rule: 'A clip or a hinge stands this far clear of the beam that crosses the end of its beam, past that beam\'s half width or the reach of its clips', kind: 'default', source: 'A working figure of @rulecad/cad', checked: '2026-11-17' },
|
|
35
|
+
};
|
|
36
|
+
|
|
37
|
+
/**
|
|
38
|
+
* An assembly's panels worked out before its items are built: each panel item placed on its bay's plane, with its
|
|
39
|
+
* size and holes; its clips (or a door's hinges, handle and catch) added as items with their fastens; a door's joint
|
|
40
|
+
* and its two poses. Refused by name: a bay that is not four beams round a rectangle, faces out of one plane, a
|
|
41
|
+
* beam with no slotted face that looks along "out", and what @rulecad/frames refuses.
|
|
42
|
+
* @param {object} a the assembly as read @param {(x: any) => number} num @param {object} [context] framesContext()'s @param {string} [material]
|
|
43
|
+
* @returns {{ a: object, panels: object[] }}
|
|
44
|
+
*/
|
|
45
|
+
export function expandPanels(a, num, context = framesContext(), material = 'pla') {
|
|
46
|
+
const items = a.items || [], list = items.filter((it) => it.panel);
|
|
47
|
+
if (!list.length) return { a, panels: [] };
|
|
48
|
+
const beams = new Map(items.filter((it) => it.beam).map((it) => [it.id, it])), ids = new Set(items.map((it) => it.id)), models = new Map();
|
|
49
|
+
const modelOf = (id) => { if (!models.has(id)) models.set(id, beamOf(beams.get(id), num, context).model); return models.get(id); };
|
|
50
|
+
const free = (base) => { let n = base, k = 2; while (ids.has(n)) n = `${base}-${k++}`; ids.add(n); return n; };
|
|
51
|
+
const added = [], fasten = [], joints = [], poses = {}, panels = [], replaced = new Map();
|
|
52
|
+
for (const it of list) {
|
|
53
|
+
const what = `item ${it.id}`, P = it.panel;
|
|
54
|
+
if (!P || typeof P !== 'object' || Array.isArray(P)) throw new Error(`${what}: panel is { "sheet": "acrylic", "thickness": 3, "bay": ["x1", "z1", "x2", "z2"], "out": [0, -1, 0] } (got ${shown(P)})`);
|
|
55
|
+
for (const k of Object.keys(P)) if (!KEYS.includes(k)) throw new Error(`${what}: a panel has no "${k}": it takes ${KEYS.join(', ')}`);
|
|
56
|
+
if (it.at != null || it.rotate != null || it.repeat != null) throw new Error(`${what}: a panel is placed by its bay: leave out at, rotate and repeat`);
|
|
57
|
+
const T = typeof P.thickness === 'number' ? P.thickness : num(P.thickness ?? NaN);
|
|
58
|
+
if (!(Array.isArray(P.bay) && P.bay.length === 4)) throw new Error(`${what}: bay is the four beams round it, in order, as ["x1", "z1", "x2", "z2"] (got ${shown(P.bay)})`);
|
|
59
|
+
for (const b of P.bay) if (!beams.has(b)) throw new Error(`${what}: bay names beam items of this assembly, and ${b} is ${items.some((x) => x.id === b) ? 'not a beam' : 'not an item'} (beams: ${[...beams.keys()].join(', ') || 'none'})`);
|
|
60
|
+
if (new Set(P.bay).size !== 4) throw new Error(`${what}: bay is four different beams (got ${shown(P.bay)})`);
|
|
61
|
+
if (!(Array.isArray(P.out) && P.out.length === 3 && Math.hypot(...P.out.map(num)) > 0)) throw new Error(`${what}: out is the way the panel's face looks, [x, y, z], square to the bay (got ${shown(P.out)})`);
|
|
62
|
+
const out = unit(P.out.map(num));
|
|
63
|
+
// each beam: its frame, its slotted face looking along out, that face's plane and its slot's line
|
|
64
|
+
const edges = P.bay.map((id) => {
|
|
65
|
+
const it2 = beams.get(id), f = beamPlace(it2, num), B = modelOf(id);
|
|
66
|
+
if (!f) throw new Error(`${what}: a panel's bay is worked out from where its beams are: place ${id} by its ends (from, to)`);
|
|
67
|
+
const d = col(f, 2);
|
|
68
|
+
if (Math.abs(dot(d, out)) > 1e-6) throw new Error(`${what}: ${id} runs across the bay's plane, not in it: its beams lie square to out`);
|
|
69
|
+
const place = B.places.find((q) => q.slot && dot(turn(f, [...q.normal, 0]), out) > 1 - 1e-6);
|
|
70
|
+
if (!place) throw new Error(`${what}: ${id} has no slotted face that looks along out: turn it with roll so one does`);
|
|
71
|
+
const S = world(f, [place.at[0], place.at[1], 0]);
|
|
72
|
+
return { id, f, B, d, place, S, h: dot(S, out), half: Math.max(B.profile.width, B.profile.height) / 2, profile: B.profile.name, length: B.length };
|
|
73
|
+
});
|
|
74
|
+
const h = edges[0].h, off = edges.find((e) => Math.abs(e.h - h) > PANEL_CHECK.plane.value);
|
|
75
|
+
if (off) throw new Error(`${what}: the bay's faces are not in one plane: ${off.id}'s stands ${mm(Math.abs(off.h - h))} mm ${off.h > h ? 'proud of' : 'below'} ${edges[0].id}'s`);
|
|
76
|
+
const u = edges[0].d, v = cross(out, u), along = (e) => (Math.abs(dot(e.d, u)) > 1 - 1e-6 ? 'u' : Math.abs(dot(e.d, v)) > 1 - 1e-6 ? 'v' : null);
|
|
77
|
+
const us = edges.filter((e) => along(e) === 'u'), vs = edges.filter((e) => along(e) === 'v');
|
|
78
|
+
if (us.length !== 2 || vs.length !== 2) throw new Error(`${what}: a bay is four beams round a rectangle, two each way: ${P.bay.join(', ')} run ${us.length} along ${edges[0].id} and ${vs.length} across it`);
|
|
79
|
+
// each edge: the axis across it (u or v), its slot line's coordinate on that axis, and the way into the bay
|
|
80
|
+
for (const [pair, ax] of [[us, v], [vs, u]]) {
|
|
81
|
+
const c = pair.map((e) => dot(e.S, ax)), lo = c[0] < c[1] ? 0 : 1;
|
|
82
|
+
if (Math.abs(c[0] - c[1]) < 1) throw new Error(`${what}: ${pair[0].id} and ${pair[1].id} lie on one line: a bay has two beams each way, apart`);
|
|
83
|
+
pair.forEach((e, k) => Object.assign(e, { ax, c: c[k], in: k === lo ? 1 : -1 }));
|
|
84
|
+
}
|
|
85
|
+
const span = (e) => { const other = e.ax === v ? vs : us, q = e.ax === v ? u : v, cs = other.map((o) => dot(o.S, q)).sort((x, y) => x - y); return { q, lo: cs[0], hi: cs[1], half: Math.max(...other.map((o) => o.half)) }; };
|
|
86
|
+
const sheet = P.sheet, given = (e) => givenFor(context, e.profile);
|
|
87
|
+
const door = P.door != null ? doorSpec(what, P.door, P.bay, num) : null;
|
|
88
|
+
// where each edge's panel edge goes, from its slot line into the bay
|
|
89
|
+
let clipOf = null, hm = null, edgeIn = {};
|
|
90
|
+
const clipFor = (e) => { try { return panelClipModel(e.profile, { sheet: T, given: given(e), material, ...(P.nut ? { nut: P.nut } : {}), ...(P.load != null ? { load: num(P.load) } : {}) }); } catch (x) { throw new Error(`${what}: ${String(x.message).replace(/^\w+: /, '')}`); } };
|
|
91
|
+
try { panelModel(sheet, T, { size: [1, 1], corner: 0 }); } catch (x) { throw new Error(`${what}: ${String(x.message).replace(/^panelModel: /, '')}`); }
|
|
92
|
+
if (door) {
|
|
93
|
+
const H = edges.find((e) => e.id === door.hinge);
|
|
94
|
+
try { hm = hingeModel(H.profile, { sheet: T, given: given(H), material, ...(door.load != null ? { load: door.load } : {}) }); } catch (x) { throw new Error(`${what}: ${String(x.message).replace(/^\w+: /, '')}`); }
|
|
95
|
+
const probe = latchModel(H.profile, { sheet: T, standoff: hm.standoff, given: given(H), material }), clip = clipFor(H);
|
|
96
|
+
for (const e of edges) edgeIn[e.id] = e.id === door.hinge ? hm.edge : r3(Math.max(clip.edge, probe.edge));
|
|
97
|
+
} else { clipOf = new Map(edges.map((e) => [e.id, clipFor(e)])); for (const e of edges) edgeIn[e.id] = clipOf.get(e.id).edge; }
|
|
98
|
+
// the panel's rectangle in (u, v): between its edges, each set in from its slot line
|
|
99
|
+
const lim = (pair) => { const [p, q] = pair[0].in > 0 ? pair : [pair[1], pair[0]]; return [p.c + edgeIn[p.id], q.c - edgeIn[q.id]]; };
|
|
100
|
+
const [u0, u1] = lim(vs), [v0, v1] = lim(us);
|
|
101
|
+
if (!(u1 - u0 > 1 && v1 - v0 > 1)) throw new Error(`${what}: the bay is too small for a panel held at its edges: ${mm(u1 - u0)} x ${mm(v1 - v0)} mm between them`);
|
|
102
|
+
const lift = door ? hm.standoff : 0, O = add(add(add([0, 0, 0], u, u0), v, v0), out, h + lift), F = { u, v, w: out, O };
|
|
103
|
+
const toPanel = (p) => [r3(dot(sub(p, O), u)), r3(dot(sub(p, O), v)), r3(dot(sub(p, O), out))], dirPanel = (q) => [r3(dot(q, u)), r3(dot(q, v)), r3(dot(q, out))];
|
|
104
|
+
const holes = [], anchors = {}, mine = [];
|
|
105
|
+
// a part on an edge's beam at a distance along it: its address, turned so its y looks into the bay
|
|
106
|
+
const onBeam = (e, at, part) => {
|
|
107
|
+
const dist = r3(dot(sub(at, org(e.f)), e.d)), yIn = e.ax.map((c) => c * e.in), ylocal = cross(out, e.d);
|
|
108
|
+
return { at: `${e.id}.${e.place.name}@${dist}`, ...(dot(ylocal, yIn) > 0 ? {} : { rotate: [0, 0, 180] }), dist, x: dot(ylocal, yIn) > 0 ? e.d : e.d.map((c) => -c), part };
|
|
109
|
+
};
|
|
110
|
+
const pointOn = (e, s) => add(add(add([0, 0, 0], e.ax, e.c), span(e).q, s), out, h); // the slot line at s along the edge
|
|
111
|
+
const record = { id: it.id, sheet, thickness: T, door: !!door, items: [], fasten: [] };
|
|
112
|
+
if (!door) {
|
|
113
|
+
const pitch = P.pitch != null ? num(P.pitch) : PANEL_DEFAULTS.pitch.value;
|
|
114
|
+
if (!(pitch > 0)) throw new Error(`${what}: pitch is the most between clips along an edge, in mm, above 0 (got ${shown(P.pitch)})`);
|
|
115
|
+
for (const e of edges) {
|
|
116
|
+
const cm = clipOf.get(e.id), sp = span(e), clear = Math.max(sp.half, ...edges.filter((o) => o.ax !== e.ax).map((o) => clipOf.get(o.id).reach)) + cm.width / 2 + PANEL_CHECK.inset.value, lo = sp.lo + clear, hi = sp.hi - clear; // (clear of the beams across its ends and of their clips)
|
|
117
|
+
if (hi < lo) throw new Error(`${what}: ${e.id} is too short for a clip between the beams across its ends`);
|
|
118
|
+
const n = Math.max(2, Math.ceil((hi - lo) / pitch) + 1);
|
|
119
|
+
for (let k = 0; k < n; k++) {
|
|
120
|
+
const s = n === 1 ? (lo + hi) / 2 : lo + ((hi - lo) * k) / (n - 1), place = onBeam(e, pointOn(e, s)), id = free(`${it.id}-clip`);
|
|
121
|
+
const spec = { kind: 'panel-clip', profile: e.profile, sheet: T, ...(P.nut ? { nut: P.nut } : {}), ...(P.load != null ? { load: num(P.load) } : {}) };
|
|
122
|
+
added.push({ id, fitting: spec, at: place.at, ...(place.rotate ? { rotate: place.rotate } : {}), panelOf: it.id });
|
|
123
|
+
fasten.push({ screw: `${cm.thread} ${cm.head}`, through: [id], into: `${e.id}.${e.place.name}`, at: [`${id}.b1`], note: `${it.id}: a clip into ${e.id}`, nut: cm.screws[0].nutKind, panelOf: it.id });
|
|
124
|
+
record.items.push(id);
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
} else {
|
|
128
|
+
const H = edges.find((e) => e.id === door.hinge), L = edges.find((e) => e.ax === H.ax && e !== H), sp = span(H);
|
|
129
|
+
const axis = cross(H.ax.map((c) => c * H.in), out), lo = sp.lo + sp.half + hm.length / 2 + PANEL_CHECK.inset.value, hi = sp.hi - sp.half - hm.length / 2 - PANEL_CHECK.inset.value;
|
|
130
|
+
if (hi < lo + hm.length) throw new Error(`${what}: ${H.id} is too short for two ${mm(hm.length)} mm hinges between the beams across its ends`);
|
|
131
|
+
const jid = `${it.id}-hinge`, mid = (lo + hi) / 2;
|
|
132
|
+
[lo, hi].forEach((s, k) => {
|
|
133
|
+
const P0 = pointOn(H, s), place = onBeam(H, P0), fid = free(`${it.id}-hinge-${k + 1}`), did = free(`${it.id}-leaf-${k + 1}`);
|
|
134
|
+
added.push({ id: fid, fitting: { kind: 'hinge', profile: H.profile, sheet: T, part: 'frame', ...(door.load != null ? { load: door.load } : {}) }, at: place.at, ...(place.rotate ? { rotate: place.rotate } : {}), panelOf: it.id });
|
|
135
|
+
fasten.push({ screw: `${hm.thread} button`, through: [fid], into: `${H.id}.${H.place.name}`, at: [`${fid}.b1`, `${fid}.b2`], note: `${it.id}: hinge ${k + 1} into ${H.id}`, nut: hm.screws[0].nutKind, panelOf: it.id });
|
|
136
|
+
// the door's leaf on the door, at an anchor of the door where the hinge's frame is: x along the axis, z out
|
|
137
|
+
anchors[`h${k + 1}`] = { at: toPanel(P0), axis: [0, 0, 1], ref: dirPanel(axis) };
|
|
138
|
+
added.push({ id: did, fitting: { kind: 'hinge', profile: H.profile, sheet: T, part: 'door', ...(door.load != null ? { load: door.load } : {}) }, at: `${it.id}.h${k + 1}`, panelOf: it.id });
|
|
139
|
+
const yIn = H.ax.map((c) => c * H.in);
|
|
140
|
+
hm.door.forEach((q, j) => {
|
|
141
|
+
const W = add(add(add(P0, axis, q.at[0]), yIn, q.at[1]), out, q.at[2]), p = toPanel(W);
|
|
142
|
+
holes.push({ thread: hm.screw, at: [p[0], p[1]] });
|
|
143
|
+
anchors[`d${k + 1}${j + 1}`] = { at: p, axis: [0, 0, -1] };
|
|
144
|
+
});
|
|
145
|
+
fasten.push({ screw: `${hm.screw} button`, through: [did], into: it.id, at: hm.door.map((_, j) => `${did}.d${j + 1}`), nut: true, note: `${it.id}: hinge ${k + 1}'s leaf through the door`, panelOf: it.id });
|
|
146
|
+
record.items.push(fid, did);
|
|
147
|
+
});
|
|
148
|
+
// the joint: about the hinges' axis, its parent the hinge beam, the door's anchor "pivot" on it
|
|
149
|
+
const Pax = add(add(add(pointOn(H, mid), H.ax.map((c) => c * H.in), hm.axis[0]), out, hm.axis[1]), [0, 0, 0]);
|
|
150
|
+
anchors.pivot = { at: toPanel(Pax), axis: dirPanel(axis), ref: [0, 0, 1] };
|
|
151
|
+
joints.push({ id: jid, type: 'revolute', parent: { item: H.id, at: local(H.f, Pax), axis: localDir(H.f, axis), ref: localDir(H.f, out) }, child: `${it.id}.pivot`, min: 0, max: door.open, label: `${it.id} opens` });
|
|
152
|
+
poses[`${it.id}-shut`] = { [jid]: 0 }; poses[`${it.id}-open`] = { [jid]: door.open };
|
|
153
|
+
// the handle on the door's outer face, in from the latch side; screwed from inside into its feet
|
|
154
|
+
if (door.handle) {
|
|
155
|
+
const hd = handleModel({ sheet: T, material }), hid = free(`${it.id}-handle`), inward = L.ax.map((c) => c * L.in), at = add(add(pointOn(L, mid), inward, edgeIn[L.id] + 20), out, lift + T), p = toPanel(at);
|
|
156
|
+
const ref = cross(axis, out); // (the handle's x across it, so its y runs along the latch side)
|
|
157
|
+
anchors.handle = { at: p, axis: [0, 0, 1], ref: dirPanel(ref) };
|
|
158
|
+
added.push({ id: hid, fitting: { kind: 'handle', sheet: T }, at: `${it.id}.handle`, panelOf: it.id });
|
|
159
|
+
[-1, 1].forEach((sgn, j) => { const q = add(at, axis, (sgn * hd.span) / 2), pp = toPanel(q); holes.push({ thread: hd.thread, at: [pp[0], pp[1]] }); anchors[`k${j + 1}`] = { at: [pp[0], pp[1], 0], axis: [0, 0, 1] }; });
|
|
160
|
+
fasten.push({ screw: `${hd.thread} button`, through: [it.id], into: hid, at: [`${it.id}.k1`, `${it.id}.k2`], note: `${it.id}: the handle`, panelOf: it.id });
|
|
161
|
+
record.items.push(hid);
|
|
162
|
+
}
|
|
163
|
+
// a magnet catch under the door's edge on the latch beam, and a turn-button latch where asked
|
|
164
|
+
for (const [want, kind] of [[door.catch, 'magnet-catch'], [door.latch, 'latch']]) {
|
|
165
|
+
if (!want) continue;
|
|
166
|
+
const cid = free(`${it.id}-${kind === 'latch' ? 'latch' : 'catch'}`), place = onBeam(L, pointOn(L, kind === 'latch' ? mid + 40 : mid));
|
|
167
|
+
const spec = { kind, profile: L.profile, standoff: hm.standoff, edge: edgeIn[L.id], ...(kind === 'latch' ? { sheet: T } : {}) };
|
|
168
|
+
const cm = kind === 'latch' ? latchModel(L.profile, { sheet: T, standoff: hm.standoff, edge: edgeIn[L.id], given: given(L), material }) : magnetCatchModel(L.profile, { standoff: hm.standoff, edge: edgeIn[L.id], given: given(L), material });
|
|
169
|
+
added.push({ id: cid, fitting: spec, at: place.at, ...(place.rotate ? { rotate: place.rotate } : {}), panelOf: it.id });
|
|
170
|
+
fasten.push({ screw: `${cm.thread} button`, through: [cid], into: `${L.id}.${L.place.name}`, at: [`${cid}.b1`], note: `${it.id}: the ${kind.replace('-', ' ')} into ${L.id}`, nut: cm.screws[0].nutKind, panelOf: it.id });
|
|
171
|
+
record.items.push(cid);
|
|
172
|
+
if (kind === 'latch') Object.assign(record, { joint: jid, latch: cid });
|
|
173
|
+
}
|
|
174
|
+
}
|
|
175
|
+
const pm = panelModel(sheet, T, { size: [r3(u1 - u0), r3(v1 - v0)], holes });
|
|
176
|
+
record.model = pm; record.size = pm.size; panels.push(record);
|
|
177
|
+
const placed = { ...it, panel: { ...P }, _panel: { model: pm, anchors, frame: F } };
|
|
178
|
+
if (!door) joints.push({ id: `${it.id}-bay`, type: 'fixed', parent: { at: O.map(r3), axis: out, ref: u }, child: { item: it.id, at: [0, 0, 0], axis: [0, 0, 1], ref: [1, 0, 0] } });
|
|
179
|
+
replaced.set(it.id, placed);
|
|
180
|
+
}
|
|
181
|
+
const first = (a.fasten || []).length;
|
|
182
|
+
const out = { ...a, items: [...items.map((it) => replaced.get(it.id) ?? it), ...added], ...(fasten.length ? { fasten: [...(a.fasten || []), ...fasten] } : {}), joints: [...(a.joints || []), ...joints], poses: { ...(a.poses || {}), ...poses } };
|
|
183
|
+
for (const r of panels) r.fasten = fasten.map((x, k) => (x.panelOf === r.id ? first + k : -1)).filter((k) => k >= 0);
|
|
184
|
+
return { a: out, panels };
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
function doorSpec(what, d, bay, num) {
|
|
188
|
+
if (!d || typeof d !== 'object' || Array.isArray(d)) throw new Error(`${what}: door is { "hinge": "${bay[0]}", "open": 120 } (got ${shown(d)})`);
|
|
189
|
+
for (const k of Object.keys(d)) if (!DOOR_KEYS.includes(k)) throw new Error(`${what}: a door has no "${k}": it takes ${DOOR_KEYS.join(', ')}`);
|
|
190
|
+
if (!bay.includes(d.hinge)) throw new Error(`${what}: door.hinge is the beam of the bay its hinges go on, one of ${bay.join(', ')} (got ${shown(d.hinge)})`);
|
|
191
|
+
const open = d.open != null ? num(d.open) : DOOR_DEFAULTS.open.value;
|
|
192
|
+
if (!(open > 0 && open <= 180)) throw new Error(`${what}: door.open is how far it opens, in degrees, above 0 and up to 180 (got ${shown(d.open)})`);
|
|
193
|
+
for (const k of ['handle', 'catch', 'latch']) if (d[k] != null && typeof d[k] !== 'boolean') throw new Error(`${what}: door.${k} is true or false (got ${shown(d[k])})`);
|
|
194
|
+
return { hinge: d.hinge, open, handle: d.handle ?? true, catch: d.catch ?? true, latch: d.latch ?? false, ...(d.load != null ? { load: num(d.load) } : {}) };
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
/**
|
|
198
|
+
* An item with "panel", built once expandPanels has worked it out: the sheet as a bought reference (the list counts
|
|
199
|
+
* it by its sheet, thickness and size), its anchors (a door's pivot, hinge, screw and handle places), and its
|
|
200
|
+
* figures as values (door.width, door.height, door.grams). @param {object} it @param {string} id
|
|
201
|
+
*/
|
|
202
|
+
export async function panelBuilt(it, id) {
|
|
203
|
+
if (!it._panel) throw new Error(`item ${id}: a panel is worked out from its bay before it is built`);
|
|
204
|
+
let ops = null; try { ops = await booleans('manifold'); } catch {} // (cut by Manifold where installed, so the overlap check reads it exactly)
|
|
205
|
+
const { model: m, anchors } = it._panel, parts = named({ body: (() => { try { return panel(m, ops ? { ops } : {}); } catch { return panel(m); } })() }, { body: { label: m.title } });
|
|
206
|
+
const values = { width: m.size[0], height: m.size[1], thickness: m.thickness, grams: m.grams };
|
|
207
|
+
return referenceBuilt({ id, key: 'panel', objName: `panel:${m.name}`, name: m.name, parts, anchors, entries: [], values,
|
|
208
|
+
extra: { panel: m, bought: { set: `${m.sheet} sheet, ${mm(m.thickness)} mm`, variant: null, part: 'panel', mass: m.grams / 1000, size: m.size } } });
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
/**
|
|
212
|
+
* A built assembly's panel findings: panel.size for each (its sheet, size and mass, and the clips or door parts that
|
|
213
|
+
* hold it), and panel.thickness where the sheet is not commonly stocked. @param {object} s @param {Function} f
|
|
214
|
+
*/
|
|
215
|
+
export function panelFindings(s, f) {
|
|
216
|
+
for (const r of s.panels ?? []) {
|
|
217
|
+
const held = r.items.length;
|
|
218
|
+
for (const x of r.model.findings) f(x.level, `${r.id}: ${x.text}${x.code === 'panel.size' ? `; ${r.door ? `a door on ${r.items.filter((k) => /-hinge-\d+$/.test(k)).length} hinges` : `held by ${held} clips`}` : ''}`, x.level === 'warn' || x.level === 'fail' ? `${r.id}: ${x.code}` : null, { code: x.code, values: { ...(x.values ?? {}), ...(x.code === 'panel.size' ? { items: r.items } : {}) }, refs: { item: r.id } });
|
|
219
|
+
}
|
|
220
|
+
}
|
package/lib/plates.mjs
CHANGED
|
@@ -10,6 +10,8 @@ import { peekRuleSet } from './rules.mjs';
|
|
|
10
10
|
import { CadError } from './errors.mjs';
|
|
11
11
|
import { assemblyPath, buildAssembly, checkAssembly } from './assembly.mjs';
|
|
12
12
|
import { printedParts } from './list.mjs';
|
|
13
|
+
import { fittingBuilt, plasticOf } from './fittings.mjs';
|
|
14
|
+
import { framesContext } from './beams.mjs';
|
|
13
15
|
|
|
14
16
|
const n3 = (x) => +x.toFixed(3);
|
|
15
17
|
|
|
@@ -21,13 +23,18 @@ function rulesOf(project, gap) {
|
|
|
21
23
|
}
|
|
22
24
|
|
|
23
25
|
// Every printed thing to go on a plate: built as printed, its filaments, how big
|
|
26
|
+
// (a printed fitting, a join's, a guide's or an item's own, goes on as its item's fitting laid as it prints: "pose": "print")
|
|
24
27
|
async function plateParts(s) {
|
|
25
|
-
const out = [];
|
|
28
|
+
const out = [], items = new Map((s.items ?? []).map((it) => [it.id, it]));
|
|
26
29
|
for (const o of s.objects) {
|
|
27
30
|
if (o.unplaced || o.role !== 'part' || !o.objName) continue;
|
|
28
|
-
const
|
|
31
|
+
const it = o.fitting ? items.get(o.id) : null;
|
|
32
|
+
if (o.fitting && !it?.fitting) continue;
|
|
33
|
+
const fitting = it ? { ...it.fitting, pose: 'print' } : null;
|
|
34
|
+
const b = fitting ? (await fittingBuilt({ ...it, fitting }, o.id, framesContext(), plasticOf(s.project))).b : await build({ ...locate(`${s.project}/${o.objName}`), ...(o.variant ? { variant: o.variant } : {}) }, o.set || {});
|
|
35
|
+
const tris = b.parts.flatMap((p) => p.triangles), { lo, hi } = bounds(tris);
|
|
29
36
|
const fil = [...new Set(b.parts.filter((p) => p.role !== 'support').map((p) => p.filament || 'base'))].sort().join('+') || 'base';
|
|
30
|
-
out.push({ id: o.id.replace(/\./g, '_'), source: o.id, object: o.objName, variant: o.variant, set: o.set || {}, filament: fil, hash: b.hash, lo, size: [hi[0] - lo[0], hi[1] - lo[1]], height: hi[2] - lo[2] });
|
|
37
|
+
out.push({ id: o.id.replace(/\./g, '_'), source: o.id, object: o.objName, ...(fitting ? { fitting } : {}), variant: o.variant, set: o.set || {}, filament: fil, hash: b.hash, lo, size: [hi[0] - lo[0], hi[1] - lo[1]], height: hi[2] - lo[2] });
|
|
31
38
|
}
|
|
32
39
|
return out;
|
|
33
40
|
}
|
|
@@ -61,7 +68,7 @@ function plateJson(s, plate, { bed, gap }) {
|
|
|
61
68
|
const origin = (bed - 2 * gap) / 2;
|
|
62
69
|
return { title: `${s.a.title || s.name}: ${plate.filament}, plate ${plate.n}`, kind: 'plate', note: `Generated by cad plates from ${s.name}. Hand edits are replaced when a part on it changes.`,
|
|
63
70
|
packed: { of: s.name, filament: plate.filament, gap, parts: Object.fromEntries(plate.items.map(({ p }) => [p.id, p.hash])) },
|
|
64
|
-
items: plate.items.map(({ p, x, y }) => ({ id: p.id, object: p.object, ...(p.variant ? { variant: p.variant } : {}), ...(Object.keys(p.set).length ? { set: p.set } : {}), at: [n3(x - origin - p.lo[0]), n3(y - origin - p.lo[1]), n3(-p.lo[2])] })) };
|
|
71
|
+
items: plate.items.map(({ p, x, y }) => ({ id: p.id, ...(p.fitting ? { fitting: p.fitting } : { object: p.object }), ...(p.variant ? { variant: p.variant } : {}), ...(Object.keys(p.set).length ? { set: p.set } : {}), at: [n3(x - origin - p.lo[0]), n3(y - origin - p.lo[1]), n3(-p.lo[2])] })) };
|
|
65
72
|
}
|
|
66
73
|
|
|
67
74
|
/**
|