@rulecad/cad 0.7.56 → 0.7.58
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/AGENTS.md +103 -1
- package/CHANGELOG.md +241 -0
- package/EXAMPLES.md +782 -2
- package/README.md +719 -8
- package/TUTORIAL.md +2 -0
- package/bin/cad.mjs +135 -29
- package/lib/assembly.mjs +83 -17
- package/lib/beams.mjs +46 -13
- package/lib/bought.mjs +41 -5
- package/lib/buildpage.mjs +8 -3
- package/lib/edit.mjs +10 -4
- package/lib/fasten.mjs +279 -47
- package/lib/fittings.mjs +313 -0
- package/lib/framebuild.mjs +463 -0
- package/lib/framecheck.mjs +831 -0
- package/lib/framegen.mjs +111 -0
- package/lib/frameheat.mjs +94 -0
- package/lib/frameprint.mjs +277 -0
- package/lib/frames.mjs +5 -3
- package/lib/framesize.mjs +261 -0
- package/lib/guides.mjs +354 -0
- package/lib/jigs.mjs +240 -0
- package/lib/joins.mjs +263 -0
- package/lib/kit.mjs +190 -0
- package/lib/links.mjs +11 -3
- package/lib/list.mjs +28 -8
- package/lib/loads.mjs +12 -4
- package/lib/measured.mjs +86 -17
- package/lib/motors.mjs +7 -3
- package/lib/optimise.mjs +18 -3
- package/lib/order.mjs +28 -14
- package/lib/panels.mjs +220 -0
- package/lib/plates.mjs +37 -16
- package/lib/services.mjs +132 -0
- package/lib/sheet.mjs +15 -1
- package/lib/slotnuts.mjs +159 -0
- package/lib/task.mjs +43 -3
- package/lib/wires.mjs +2 -1
- package/package.json +6 -6
- package/schemas/assembly.schema.json +34 -9
package/lib/optimise.mjs
CHANGED
|
@@ -105,15 +105,30 @@ function holdEmpty(spec) {
|
|
|
105
105
|
for (let m = 0; m < g.nodes; m++) if (!on[m]) for (let a = 0; a < dim; a++) spec.fixed[dim * m + a] = 1;
|
|
106
106
|
return spec;
|
|
107
107
|
}
|
|
108
|
+
const digest = (x) => crypto.createHash('sha256').update(JSON.stringify(x)).digest('hex');
|
|
109
|
+
/**
|
|
110
|
+
* The code an optimisation's densities are made by, each piece by name: this file's VERSION, topopt's solver (its file
|
|
111
|
+
* up to its shapes from results), the FE's code and its threads backend (the solver's products), and cad's own code
|
|
112
|
+
* that readies the problem for the solver (holdEmpty). Drawing a shape from the densities is not in it.
|
|
113
|
+
* @returns {{ version: number, solver: string, fea: string, threads: string, cad: string }}
|
|
114
|
+
*/
|
|
115
|
+
export const densityCode = () => ({ version: VERSION, solver: source('@rulecad/topopt').split('// ---------- shapes from results ----------')[0], fea: source('@rulecad/fea'), threads: source('@rulecad/fea/threads'), cad: `${holdEmpty.toString()}\n${optimised.toString()}` });
|
|
116
|
+
/**
|
|
117
|
+
* The key an optimisation's densities are kept by (.cache/densities/<key>.json): the problem and every piece of
|
|
118
|
+
* densityCode (cad's own share is holdEmpty and optimised, which readies the problem and calls the solver with its
|
|
119
|
+
* settings), so a change to any of them optimises again, in this checkout or in another commit's copy that shares
|
|
120
|
+
* the folder (scripts/dimension-diff.mjs).
|
|
121
|
+
* @param {object} problem readProblem's problem @param {ReturnType<typeof densityCode>} [code] @returns {string}
|
|
122
|
+
*/
|
|
123
|
+
export const densitiesKey = (problem, code = densityCode()) => digest([code.version, problem, code.solver, code.fea, code.threads, code.cad]);
|
|
108
124
|
export async function optimised(project, ref, { onStep, onRun, fresh = false } = {}) {
|
|
109
|
-
const r = await readProblem(project, ref), topopt = source('@rulecad/topopt')
|
|
110
|
-
const digest = (x) => crypto.createHash('sha256').update(JSON.stringify(x)).digest('hex');
|
|
125
|
+
const r = await readProblem(project, ref), topopt = source('@rulecad/topopt');
|
|
111
126
|
// Two keeps: the densities, by the problem and the code that decides them (the slow part), and the shape drawn from
|
|
112
127
|
// them, by everything: a change to how shapes are drawn redraws them without optimising again
|
|
113
128
|
// The shape's key holds this file too, so a change to how cad draws a result (anchored below) redraws it
|
|
114
129
|
const hash = digest([VERSION, r.problem, r.outline, topopt, source('@rulecad/fea'), fs.readFileSync(new URL(import.meta.url), 'utf8')]), file = paths.cache('optimise', `${hash}.json`);
|
|
115
130
|
if (!fresh && !process.env.CAD_NO_CACHE && host.exists(file)) return { ...JSON.parse(host.readText(file)), cached: true };
|
|
116
|
-
const spec = holdEmpty(discretise(r.problem)), densities = paths.cache('densities', `${
|
|
131
|
+
const spec = holdEmpty(discretise(r.problem)), densities = paths.cache('densities', `${densitiesKey(r.problem)}.json`);
|
|
117
132
|
// A mark that this problem has been optimised before (by any solver), so a run can say whether it's the solver that changed
|
|
118
133
|
const seen = paths.cache('densities', `${digest([VERSION, r.problem])}.seen`);
|
|
119
134
|
if (!fresh && !process.env.CAD_NO_CACHE && !host.exists(densities)) onRun?.(host.exists(seen) ? 'the solver has changed since its last result' : 'no result yet');
|
package/lib/order.mjs
CHANGED
|
@@ -12,6 +12,8 @@ import { placeItems, jointValues, mul } from '@rulecad/model-link';
|
|
|
12
12
|
import { host } from './host.mjs';
|
|
13
13
|
import { paths } from './workspace.mjs';
|
|
14
14
|
import { motorScrews } from './motors.mjs';
|
|
15
|
+
import jscad from '@jscad/modeling';
|
|
16
|
+
const { geom3 } = jscad.geometries;
|
|
15
17
|
|
|
16
18
|
const top = (n) => String(n).split(/[.@]/)[0];
|
|
17
19
|
const round = (v) => v.map((x) => (Math.abs(x) < 1e-9 ? 0 : +x.toFixed(6)));
|
|
@@ -24,12 +26,14 @@ function basis(d) {
|
|
|
24
26
|
}
|
|
25
27
|
|
|
26
28
|
// One thing that gets placed: its triangles, its box, what a part is known as
|
|
29
|
+
// (a fitting whose tongue or pegs stand in a beam's slot, an end cap's in its end, is taken without them, as the overlap
|
|
30
|
+
// check takes it: they slide out along the slot or the beam, and would otherwise hold it to its beam from every side)
|
|
27
31
|
function groups(s) {
|
|
28
|
-
const by = new Map();
|
|
32
|
+
const by = new Map(), beams = new Set(s.objects.filter((o) => o.beam).map((o) => o.id));
|
|
29
33
|
s.parts.forEach((p, order) => {
|
|
30
34
|
if (!by.has(p.item)) by.set(p.item, { id: p.item, order, parts: [], tris: [] });
|
|
31
35
|
const g = by.get(p.item); g.parts.push(p);
|
|
32
|
-
for (const t of p.triangles) g.tris.push(...fan(t));
|
|
36
|
+
for (const t of p.collide && !beams.has(p.item) ? geom3.toPolygons(p.collide).map((q) => q.vertices) : p.triangles) g.tris.push(...fan(t));
|
|
33
37
|
});
|
|
34
38
|
const objs = new Map(s.objects.map((o) => [o.id, o]));
|
|
35
39
|
for (const g of by.values()) { const o = objs.get(g.id); g.object = o?.objName ?? null; g.bought = o?.bought ?? null; g.motor = !!o?.motor; }
|
|
@@ -92,7 +96,8 @@ function hitsAlong(origin, dir, tris) {
|
|
|
92
96
|
/**
|
|
93
97
|
* The order to put an assembly together, as data.
|
|
94
98
|
* @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 }}
|
|
99
|
+
* @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 }[] }}
|
|
100
|
+
* covers: each part that stands over a screw, which has to go on after the parts the screw joins
|
|
96
101
|
*/
|
|
97
102
|
export function assemblyOrder(s) {
|
|
98
103
|
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)));
|
|
@@ -115,11 +120,13 @@ export function assemblyOrder(s) {
|
|
|
115
120
|
const a = top(A), b = top(B), [u, v] = earlier(a, b) <= 0 ? [a, b] : [b, a];
|
|
116
121
|
if (x.seat != null && (bearing(a) || bearing(b))) { const [h, r] = bearing(a) ? [b, a] : [a, b]; add(h, r, `${r} is pressed into ${h}`); continue; }
|
|
117
122
|
if ((x.shaft != null || x.engage != null) && (bearing(a) || bearing(b))) { const [r, shaft] = bearing(a) ? [a, b] : [b, a]; add(r, shaft, `${r} goes in before ${shaft}`); continue; }
|
|
118
|
-
|
|
123
|
+
// (a part placed on another, as a fitting at a beam's address is, goes on after it: its joint says so, and a fastening
|
|
124
|
+
// between the two does not turn that round, however far each is from the base)
|
|
125
|
+
if (x.fastens && !before.get(v)?.has(u)) add(u, v, x.note || `${v} fastens to ${u}`);
|
|
119
126
|
}
|
|
120
127
|
// Screws: what stands on the tool's line goes on after the screw, and if it must already be there, nothing can
|
|
121
128
|
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 = [];
|
|
129
|
+
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
130
|
for (const x of s.fits.filter((f) => f.access)) {
|
|
124
131
|
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
132
|
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 +135,7 @@ export function assemblyOrder(s) {
|
|
|
128
135
|
for (const q of all) {
|
|
129
136
|
if (screwed.includes(q.id) || !starts.some((p) => hitsAlong(p, D, q.tris))) continue;
|
|
130
137
|
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}`);
|
|
138
|
+
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
139
|
}
|
|
133
140
|
}
|
|
134
141
|
// 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 +146,7 @@ export function assemblyOrder(s) {
|
|
|
139
146
|
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
147
|
const first = walls.filter((q) => !by.has(q) || screwed.includes(q) || (later && reaches(q, later)));
|
|
141
148
|
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}`);
|
|
149
|
+
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
150
|
}
|
|
144
151
|
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
152
|
if (bad.length) {
|
|
@@ -214,7 +221,7 @@ export function assemblyOrder(s) {
|
|
|
214
221
|
else merged.push({ items: [...st.items], object: st.object, dir: st.dir, fasteners: st.fasteners, ...(st.together ? { together: true } : {}) });
|
|
215
222
|
}
|
|
216
223
|
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 };
|
|
224
|
+
return { steps: merged, stuck: null, covers };
|
|
218
225
|
}
|
|
219
226
|
|
|
220
227
|
/** 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 +229,7 @@ export const fastenerText = (f) => `${f.fit}${f.fastener ? ` (${f.count != null
|
|
|
222
229
|
|
|
223
230
|
// Cached by what the parts are and where they are, with everything else that changes the answer
|
|
224
231
|
function orderFile(s) {
|
|
225
|
-
const key = crypto.createHash('sha256').update(JSON.stringify([
|
|
232
|
+
const key = crypto.createHash('sha256').update(JSON.stringify([8, 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
233
|
return paths.cache('order', `${key}.json`);
|
|
227
234
|
}
|
|
228
235
|
export function orderOf(s) {
|
|
@@ -237,12 +244,19 @@ export function orderOf(s) {
|
|
|
237
244
|
// Whether an assembly is something that goes together with fastenings: anything else has no steps to find
|
|
238
245
|
export const isBuilt = (s) => s.a.kind !== 'plate' && s.fits.some((x) => x.fastens || x.seat != null || x.shaft != null || x.access);
|
|
239
246
|
|
|
240
|
-
/**
|
|
241
|
-
|
|
247
|
+
/**
|
|
248
|
+
* assembly.order, in the assembly's findings shape. With a frame's build (frameBuild, for an assembly with joins) the
|
|
249
|
+
* steps counted are its, as cad order prints them: one count for the one sequence. @param {object} s @param {Function} f
|
|
250
|
+
* @param {{ frame?: (s: object) => object }} [o]
|
|
251
|
+
*/
|
|
252
|
+
export function orderChecks(s, f, { frame = null } = {}) {
|
|
242
253
|
if (!isBuilt(s) || (s.pose != null && s.pose !== s.motion.pose)) return;
|
|
243
254
|
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
|
-
|
|
255
|
+
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 } : {}) } });
|
|
256
|
+
const b = frame && s.joins?.length ? frame(s) : null;
|
|
257
|
+
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 } : {}) } });
|
|
258
|
+
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];
|
|
259
|
+
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
260
|
}
|
|
247
261
|
|
|
248
262
|
/** 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 +270,4 @@ export function stepPictures(s, r) {
|
|
|
256
270
|
});
|
|
257
271
|
}
|
|
258
272
|
|
|
259
|
-
export const orderText = (ref, r) => (r.stuck ? `${ref}: ${r.stuck.text}` : [`${ref}: how it goes together`, ...r.steps.
|
|
273
|
+
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, bay: [...P.bay], 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
|
@@ -9,7 +9,9 @@ import { paths, printerOf } from './workspace.mjs';
|
|
|
9
9
|
import { peekRuleSet } from './rules.mjs';
|
|
10
10
|
import { CadError } from './errors.mjs';
|
|
11
11
|
import { assemblyPath, buildAssembly, checkAssembly } from './assembly.mjs';
|
|
12
|
-
import { printedParts } from './list.mjs';
|
|
12
|
+
import { printedParts, materialOf } from './list.mjs';
|
|
13
|
+
import { fittingBuilt, plasticOf, companions } from './fittings.mjs';
|
|
14
|
+
import { framesContext, beamBuilt, laidSpec } from './beams.mjs';
|
|
13
15
|
|
|
14
16
|
const n3 = (x) => +x.toFixed(3);
|
|
15
17
|
|
|
@@ -21,13 +23,31 @@ 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")
|
|
27
|
+
// (each with its material: the project's, or a printed beam's own "material", so a plate is one plastic)
|
|
24
28
|
async function plateParts(s) {
|
|
25
|
-
const out = [];
|
|
29
|
+
const out = [], items = new Map((s.items ?? []).map((it) => [it.id, it])), own = materialOf(s.project).name;
|
|
26
30
|
for (const o of s.objects) {
|
|
27
31
|
if (o.unplaced || o.role !== 'part' || !o.objName) continue;
|
|
28
|
-
|
|
32
|
+
if (o.beam?.printed) { // a printed beam, laid as it prints (lib/beams.mjs)
|
|
33
|
+
const bi = (s.a.items || []).find((x) => x.id === o.id); // (the item as written: the built one holds the beam's model)
|
|
34
|
+
if (!bi?.beam?.profile) continue;
|
|
35
|
+
const beamSpec = laidSpec(bi, s.num, o.beam.length), b = beamBuilt({ id: o.id, beam: beamSpec }, s.num, o.id).b, tris = b.parts.flatMap((p) => p.triangles), { lo, hi } = bounds(tris);
|
|
36
|
+
out.push({ id: o.id.replace(/\./g, '_'), source: o.id, object: o.objName, beam: beamSpec, set: {}, filament: 'base', material: String(bi.beam.material ?? own).toLowerCase(), hash: b.hash, lo, size: [hi[0] - lo[0], hi[1] - lo[1]], height: hi[2] - lo[2] });
|
|
37
|
+
continue;
|
|
38
|
+
}
|
|
39
|
+
const it = o.fitting ? items.get(o.id) : null;
|
|
40
|
+
if (o.fitting && !it?.fitting) continue;
|
|
41
|
+
const fitting = it ? { ...it.fitting, pose: 'print' } : null;
|
|
42
|
+
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 || {});
|
|
43
|
+
const tris = b.parts.flatMap((p) => p.triangles), { lo, hi } = bounds(tris);
|
|
29
44
|
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] });
|
|
45
|
+
out.push({ id: o.id.replace(/\./g, '_'), source: o.id, object: o.objName, ...(fitting ? { fitting } : {}), variant: o.variant, set: o.set || {}, filament: fil, material: own, hash: b.hash, lo, size: [hi[0] - lo[0], hi[1] - lo[1]], height: hi[2] - lo[2] });
|
|
46
|
+
}
|
|
47
|
+
// what comes with a placed part and is printed beside it (a levelling foot's pad: lib/fittings.mjs companions)
|
|
48
|
+
for (const c of companions(s)) {
|
|
49
|
+
const fitting = { ...c.fitting, pose: 'print' }, b = (await fittingBuilt({ id: c.id, fitting }, c.id, framesContext(), plasticOf(s.project))).b, tris = b.parts.flatMap((p) => p.triangles), { lo, hi } = bounds(tris);
|
|
50
|
+
out.push({ id: c.id.replace(/\./g, '_'), source: c.of, object: b.object.name, fitting, set: {}, filament: 'base', material: own, hash: b.hash, lo, size: [hi[0] - lo[0], hi[1] - lo[1]], height: hi[2] - lo[2] });
|
|
31
51
|
}
|
|
32
52
|
return out;
|
|
33
53
|
}
|
|
@@ -55,13 +75,14 @@ function existing(s) {
|
|
|
55
75
|
for (const f of fs.existsSync(dir) ? fs.readdirSync(dir) : []) { if (!f.endsWith('.json')) continue; let a; try { a = JSON.parse(fs.readFileSync(path.join(dir, f), 'utf8')); } catch { continue; } if (a.packed?.of === s.name) out.push({ name: f.slice(0, -5), a }); }
|
|
56
76
|
return out.sort((a, b) => a.name.localeCompare(b.name, undefined, { numeric: true }));
|
|
57
77
|
}
|
|
58
|
-
|
|
78
|
+
// <assembly>-<filament>-<n>; a plate in another material than the project's has it in its name too
|
|
79
|
+
const nameOf = (s, filament, k, material, own) => `${s.name}-${material && material !== own ? `${material}-` : ''}${filament.replace(/\+/g, '-')}-${k}`;
|
|
59
80
|
|
|
60
81
|
function plateJson(s, plate, { bed, gap }) {
|
|
61
82
|
const origin = (bed - 2 * gap) / 2;
|
|
62
83
|
return { title: `${s.a.title || s.name}: ${plate.filament}, plate ${plate.n}`, kind: 'plate', note: `Generated by cad plates from ${s.name}. Hand edits are replaced when a part on it changes.`,
|
|
63
|
-
packed: { of: s.name, filament: plate.filament, gap, parts: Object.fromEntries(plate.items.map(({ p }) => [p.id, p.hash])) },
|
|
64
|
-
items: plate.items.map(({ p, x, y }) => ({ id: p.id, object: p.object, ...(p.variant ? { variant: p.variant } : {}), ...(Object.keys(p.set).length ? { set: p.set } : {}), at: [n3(x - origin - p.lo[0]), n3(y - origin - p.lo[1]), n3(-p.lo[2])] })) };
|
|
84
|
+
packed: { of: s.name, filament: plate.filament, material: plate.material, gap, parts: Object.fromEntries(plate.items.map(({ p }) => [p.id, p.hash])) },
|
|
85
|
+
items: plate.items.map(({ p, x, y }) => ({ id: p.id, ...(p.fitting ? { fitting: p.fitting } : p.beam ? { beam: p.beam } : { 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
86
|
}
|
|
66
87
|
|
|
67
88
|
/**
|
|
@@ -70,7 +91,7 @@ function plateJson(s, plate, { bed, gap }) {
|
|
|
70
91
|
* @returns {Promise<{ plates: object[], touched: string[], removed: string[], gap: number, bed: number, findings: object[] }>}
|
|
71
92
|
*/
|
|
72
93
|
export async function platesOf(s, { write = false, gap: asked } = {}) {
|
|
73
|
-
const parts = await plateParts(s), { bed, gap } = rulesOf(s.project, asked), findings = [], plates = [], touched = [], removed = [];
|
|
94
|
+
const parts = await plateParts(s), { bed, gap } = rulesOf(s.project, asked), findings = [], plates = [], touched = [], removed = [], own = materialOf(s.project).name;
|
|
74
95
|
if (!parts.length) throw new CadError('plates.empty', `${s.project}/${s.name} has nothing printed to put on a plate`);
|
|
75
96
|
const big = parts.filter((p) => p.size[0] > bed - 2 * gap || p.size[1] > bed - 2 * gap);
|
|
76
97
|
for (const p of big) findings.push({ level: 'fail', text: `${p.id} (${p.object}) is ${Number(p.size[0].toFixed(1))} × ${Number(p.size[1].toFixed(1))} mm: bigger than the ${bed} mm bed, so it has no plate: split it or turn it`, code: 'plate.bed', refs: { item: p.id }, values: { size: p.size, bed } });
|
|
@@ -79,16 +100,16 @@ export async function platesOf(s, { write = false, gap: asked } = {}) {
|
|
|
79
100
|
for (const e of had) {
|
|
80
101
|
const on = Object.entries(e.a.packed.parts || {}), ok = on.length && on.every(([id, h]) => by.get(id)?.hash === h) && e.a.packed.gap === gap;
|
|
81
102
|
if (!ok) continue;
|
|
82
|
-
kept.add(e.name); on.forEach(([id]) => used.add(id)); plates.push({ name: e.name, filament: e.a.packed.filament, a: e.a, items: e.a.items.map((it) => { const p = by.get(it.id), origin = (bed - 2 * gap) / 2; return { p, x: it.at[0] + p.lo[0] + origin, y: it.at[1] + p.lo[1] + origin }; }), stood: true });
|
|
103
|
+
kept.add(e.name); on.forEach(([id]) => used.add(id)); plates.push({ name: e.name, filament: e.a.packed.filament, material: e.a.packed.material ?? own, a: e.a, items: e.a.items.map((it) => { const p = by.get(it.id), origin = (bed - 2 * gap) / 2; return { p, x: it.at[0] + p.lo[0] + origin, y: it.at[1] + p.lo[1] + origin }; }), stood: true });
|
|
83
104
|
}
|
|
84
|
-
// Everything else, packed by filament; names reused from the plates that are going, so a changed part keeps its name
|
|
105
|
+
// Everything else, packed by material and filament; names reused from the plates that are going, so a changed part keeps its name
|
|
85
106
|
const free = [...by.values()].filter((p) => !used.has(p.id)), byFilament = new Map();
|
|
86
|
-
for (const p of free) { if (!byFilament.has(
|
|
107
|
+
for (const p of free) { const key = `${p.material}|${p.filament}`; if (!byFilament.has(key)) byFilament.set(key, []); byFilament.get(key).push(p); }
|
|
87
108
|
const goingNames = had.filter((e) => !kept.has(e.name)).map((e) => e.name);
|
|
88
|
-
for (const [
|
|
89
|
-
const beds = pack(list, { bed, gap }); let k = 0;
|
|
90
|
-
const next = () => { const reuse = goingNames.find((n) => had.find((
|
|
91
|
-
for (const b of beds) { const name = next(), n = Number(name.match(/-(\d+)$/)?.[1]) || 1, plate = { name, filament, n, items: b.items }; plate.a = plateJson(s, plate, { bed, gap }); plates.push(plate); touched.push(name); }
|
|
109
|
+
for (const [key, list] of byFilament) {
|
|
110
|
+
const [material, filament] = [key.slice(0, key.indexOf('|')), key.slice(key.indexOf('|') + 1)], beds = pack(list, { bed, gap }); let k = 0;
|
|
111
|
+
const next = () => { const reuse = goingNames.find((n) => { const e = had.find((x) => x.name === n); return e?.a.packed.filament === filament && (e.a.packed.material ?? own) === material; }); if (reuse) { goingNames.splice(goingNames.indexOf(reuse), 1); return reuse; } let name; do name = nameOf(s, filament, ++k, material, own); while (kept.has(name) || plates.some((x) => x.name === name)); return name; };
|
|
112
|
+
for (const b of beds) { const name = next(), n = Number(name.match(/-(\d+)$/)?.[1]) || 1, plate = { name, filament, material, n, items: b.items }; plate.a = plateJson(s, plate, { bed, gap }); plates.push(plate); touched.push(name); }
|
|
92
113
|
}
|
|
93
114
|
for (const n of goingNames) removed.push(n);
|
|
94
115
|
plates.sort((a, b) => a.name.localeCompare(b.name, undefined, { numeric: true }));
|
|
@@ -98,7 +119,7 @@ export async function platesOf(s, { write = false, gap: asked } = {}) {
|
|
|
98
119
|
for (const n of removed) fs.rmSync(plateFile(s.project, n), { force: true });
|
|
99
120
|
}
|
|
100
121
|
const grams = new Map(printedParts(s).map((x) => [x.id.replace(/\./g, '_'), x]));
|
|
101
|
-
return { bed, gap, touched, removed, findings, plates: plates.map((p) => ({ name: p.name, filament: p.filament, parts: p.items.map(({ p: q, x, y }) => ({ id: q.id, object: q.object, x: n3(x + gap), y: n3(y + gap), w: n3(q.size[0]), d: n3(q.size[1]) })), grams: n3(p.items.reduce((t, { p: q }) => t + (grams.get(q.id)?.grams ?? 0), 0)), minutes: p.items.reduce((t, { p: q }) => t + (grams.get(q.id)?.minutes ?? 0), 0), stood: !!p.stood })) };
|
|
122
|
+
return { bed, gap, touched, removed, findings, plates: plates.map((p) => ({ name: p.name, filament: p.filament, material: p.material, parts: p.items.map(({ p: q, x, y }) => ({ id: q.id, object: q.object, x: n3(x + gap), y: n3(y + gap), w: n3(q.size[0]), d: n3(q.size[1]) })), grams: n3(p.items.reduce((t, { p: q }) => t + (grams.get(q.id)?.grams ?? 0), 0)), minutes: p.items.reduce((t, { p: q }) => t + (grams.get(q.id)?.minutes ?? 0), 0), stood: !!p.stood })) };
|
|
102
123
|
}
|
|
103
124
|
|
|
104
125
|
/** Each plate's checks: what check says of a plate, the print check over the whole bed included. */
|