@rulecad/cad 0.7.42 → 0.7.43
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/AGENTS.md +21 -0
- package/EXAMPLES.md +4249 -1
- package/README.md +13 -0
- package/bin/cad.mjs +69 -9
- package/lib/animate.mjs +41 -0
- package/lib/assembly.mjs +23 -7
- package/lib/bought.mjs +7 -0
- package/lib/buildpage.mjs +81 -0
- package/lib/gait.mjs +66 -0
- package/lib/grip.mjs +23 -0
- package/lib/links.mjs +11 -2
- package/lib/loads.mjs +224 -0
- package/lib/machine.mjs +92 -0
- package/lib/motors.mjs +27 -9
- package/lib/order.mjs +242 -0
- package/lib/plates.mjs +108 -0
- package/lib/power.mjs +31 -0
- package/lib/seats.mjs +2 -2
- package/lib/sheet.mjs +68 -0
- package/lib/task.mjs +203 -0
- package/lib/wires.mjs +36 -0
- package/package.json +7 -6
- package/schemas/assembly.schema.json +11 -1
package/lib/order.mjs
ADDED
|
@@ -0,0 +1,242 @@
|
|
|
1
|
+
// The order a machine goes together in, worked out from the assembly: a part fastened into another comes after it, a
|
|
2
|
+
// bearing goes in before its shaft, a part goes where nothing placed yet stands in its way (a nut trapped by a wall goes
|
|
3
|
+
// in before its neighbour). Found by taking it apart: a part is free to leave when a straight line takes it clear of
|
|
4
|
+
// everything still there, and no part left depends on it. Taking parts away only ever frees others, so if nothing can leave
|
|
5
|
+
// no order exists, and that is a finding, assembly.order. A fit with "access": "<item>.<anchor>" names where a screw's
|
|
6
|
+
// tool comes from (its anchor's z points out along the screw): whatever stands on that line must go on after it.
|
|
7
|
+
// Works on the assembly's top-level items; a component (an assembly used as an item) is one step.
|
|
8
|
+
import crypto from 'node:crypto';
|
|
9
|
+
import path from 'node:path';
|
|
10
|
+
import fs from 'node:fs';
|
|
11
|
+
import { placeItems, jointValues, mul } from '@rulecad/model-link';
|
|
12
|
+
import { host } from './host.mjs';
|
|
13
|
+
import { paths } from './workspace.mjs';
|
|
14
|
+
|
|
15
|
+
const top = (n) => String(n).split(/[.@]/)[0];
|
|
16
|
+
const round = (v) => v.map((x) => (Math.abs(x) < 1e-9 ? 0 : +x.toFixed(6)));
|
|
17
|
+
const SIDES = [[0, 0, 1], [0, 0, -1], [1, 0, 0], [-1, 0, 0], [0, 1, 0], [0, -1, 0]];
|
|
18
|
+
const dot = (a, b) => a[0] * b[0] + a[1] * b[1] + a[2] * b[2];
|
|
19
|
+
const fan = (poly) => poly.slice(1, -1).map((_, i) => [poly[0], poly[i + 1], poly[i + 2]]);
|
|
20
|
+
function basis(d) {
|
|
21
|
+
const a = Math.abs(d[0]) < 0.9 ? [1, 0, 0] : [0, 1, 0], u = [d[1] * a[2] - d[2] * a[1], d[2] * a[0] - d[0] * a[2], d[0] * a[1] - d[1] * a[0]], l = Math.hypot(...u), n = u.map((x) => x / l);
|
|
22
|
+
return [n, [d[1] * n[2] - d[2] * n[1], d[2] * n[0] - d[0] * n[2], d[0] * n[1] - d[1] * n[0]]];
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
// One thing that gets placed: its triangles, its box, what a part is known as
|
|
26
|
+
function groups(s) {
|
|
27
|
+
const by = new Map();
|
|
28
|
+
s.parts.forEach((p, order) => {
|
|
29
|
+
if (!by.has(p.item)) by.set(p.item, { id: p.item, order, parts: [], tris: [] });
|
|
30
|
+
const g = by.get(p.item); g.parts.push(p);
|
|
31
|
+
for (const t of p.triangles) g.tris.push(...fan(t));
|
|
32
|
+
});
|
|
33
|
+
const objs = new Map(s.objects.map((o) => [o.id, o]));
|
|
34
|
+
for (const g of by.values()) { const o = objs.get(g.id); g.object = o?.objName ?? null; g.bought = o?.bought ?? null; g.motor = !!o?.motor; }
|
|
35
|
+
return [...by.values()];
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
// A part seen along a direction: for each cell of a grid across it, the nearest and furthest of it along the direction
|
|
39
|
+
function raster(g, d, h) {
|
|
40
|
+
const [u, v] = basis(d), cells = new Map();
|
|
41
|
+
let uLo = Infinity, uHi = -Infinity, vLo = Infinity, vHi = -Infinity, sLo = Infinity, sHi = -Infinity;
|
|
42
|
+
const k = (i, j) => (i + 1048576) * 2097152 + (j + 1048576);
|
|
43
|
+
for (const t of g.tris) {
|
|
44
|
+
const P = t.map((p) => [dot(p, u), dot(p, v), dot(p, d)]);
|
|
45
|
+
const lo = [Math.min(P[0][0], P[1][0], P[2][0]), Math.min(P[0][1], P[1][1], P[2][1])], hi = [Math.max(P[0][0], P[1][0], P[2][0]), Math.max(P[0][1], P[1][1], P[2][1])];
|
|
46
|
+
uLo = Math.min(uLo, lo[0]); uHi = Math.max(uHi, hi[0]); vLo = Math.min(vLo, lo[1]); vHi = Math.max(vHi, hi[1]); sLo = Math.min(sLo, P[0][2], P[1][2], P[2][2]); sHi = Math.max(sHi, P[0][2], P[1][2], P[2][2]);
|
|
47
|
+
const det = (P[1][1] - P[2][1]) * (P[0][0] - P[2][0]) + (P[2][0] - P[1][0]) * (P[0][1] - P[2][1]);
|
|
48
|
+
if (Math.abs(det) < 1e-9) continue; // a face seen edge-on covers no cell: the faces either side of it do
|
|
49
|
+
for (let i = Math.floor(lo[0] / h); i <= Math.floor(hi[0] / h); i++) for (let j = Math.floor(lo[1] / h); j <= Math.floor(hi[1] / h); j++) {
|
|
50
|
+
const x = (i + 0.5) * h, y = (j + 0.5) * h, a = ((P[1][1] - P[2][1]) * (x - P[2][0]) + (P[2][0] - P[1][0]) * (y - P[2][1])) / det, b = ((P[2][1] - P[0][1]) * (x - P[2][0]) + (P[0][0] - P[2][0]) * (y - P[2][1])) / det, c = 1 - a - b;
|
|
51
|
+
if (a < -1e-9 || b < -1e-9 || c < -1e-9) continue; // (exact: a slack in these fractions grows with the triangle)
|
|
52
|
+
const z = a * P[0][2] + b * P[1][2] + c * P[2][2];
|
|
53
|
+
const key = k(i, j), now = cells.get(key);
|
|
54
|
+
if (now) { if (z < now[0]) now[0] = z; if (z > now[1]) now[1] = z; } else cells.set(key, [z, z]);
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
return { cells, uLo, uHi, vLo, vHi, sLo, sHi, key: k };
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
// Blocked when, in a cell they share, the other has something further along than this part's rearmost: this part, moved
|
|
61
|
+
// on, runs into it. Parts meet at their edges, so this part is thinned by a cell; a thing narrower than that keeps its cells.
|
|
62
|
+
function blockers(p, q, d, h, rasterOf) {
|
|
63
|
+
const A = rasterOf(p, d), B = rasterOf(q, d);
|
|
64
|
+
if (A.uHi < B.uLo || B.uHi < A.uLo || A.vHi < B.vLo || B.vHi < A.vLo || B.sHi <= A.sLo + 0.2) return false;
|
|
65
|
+
const inner = [...A.cells].filter(([key]) => {
|
|
66
|
+
const j = key % 2097152, i = (key - j) / 2097152;
|
|
67
|
+
return [[1, 0], [-1, 0], [0, 1], [0, -1]].every(([a, b]) => A.cells.has((i + a) * 2097152 + (j + b)));
|
|
68
|
+
});
|
|
69
|
+
for (const [key, a] of inner.length ? inner : [...A.cells]) { const b = B.cells.get(key); if (b && b[1] > a[0] + 0.2) return true; }
|
|
70
|
+
return false;
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
// A pair meant to overlap (a press fit) tells nothing about what stands in whose way
|
|
74
|
+
const names = (x) => [x].flat().map(top);
|
|
75
|
+
const allowedPair = (s, a, b) => s.fits.some((x) => x.min != null && x.num(x.min) < 0 && ((names(x.a).includes(a.id) && names(x.b).includes(b.id)) || (names(x.a).includes(b.id) && names(x.b).includes(a.id))));
|
|
76
|
+
|
|
77
|
+
function hitsAlong(origin, dir, tris) {
|
|
78
|
+
for (const t of tris) {
|
|
79
|
+
const e1 = [t[1][0] - t[0][0], t[1][1] - t[0][1], t[1][2] - t[0][2]], e2 = [t[2][0] - t[0][0], t[2][1] - t[0][1], t[2][2] - t[0][2]];
|
|
80
|
+
const p = [dir[1] * e2[2] - dir[2] * e2[1], dir[2] * e2[0] - dir[0] * e2[2], dir[0] * e2[1] - dir[1] * e2[0]], det = dot(e1, p);
|
|
81
|
+
if (Math.abs(det) < 1e-12) continue;
|
|
82
|
+
const s = [origin[0] - t[0][0], origin[1] - t[0][1], origin[2] - t[0][2]], u = dot(s, p) / det;
|
|
83
|
+
if (u < 0 || u > 1) continue;
|
|
84
|
+
const q = [s[1] * e1[2] - s[2] * e1[1], s[2] * e1[0] - s[0] * e1[2], s[0] * e1[1] - s[1] * e1[0]], v = dot(dir, q) / det;
|
|
85
|
+
if (v < 0 || u + v > 1) continue;
|
|
86
|
+
if (dot(e2, q) / det > 0.05) return true;
|
|
87
|
+
}
|
|
88
|
+
return false;
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
/**
|
|
92
|
+
* The order to put an assembly together, as data.
|
|
93
|
+
* @param {object} s a built assembly
|
|
94
|
+
* @returns {{ steps: { n: number, items: string[], object: string|null, dir: number[], fasteners: {fit: string, fastener?: string, count?: number}[], text: string }[], stuck: object|null }}
|
|
95
|
+
*/
|
|
96
|
+
export function assemblyOrder(s) {
|
|
97
|
+
const all = groups(s).filter((g) => g.bought || g.motor || g.parts.some((p) => p.role === 'part' || p.role == null) || s.fits.some((x) => [x.a, x.b].flat().some((n) => top(n) === g.id)));
|
|
98
|
+
if (!all.length) return { steps: [], stuck: null };
|
|
99
|
+
const by = new Map(all.map((g) => [g.id, g])), ids = all.map((g) => g.id), joints = s.motion.joints, items = s.motion.items.map((x) => x[0]);
|
|
100
|
+
const bearing = (id) => by.get(id)?.bought?.part === 'bearing';
|
|
101
|
+
// How far each part is from the base along joints and fastenings: nearer goes first
|
|
102
|
+
const links = new Map(ids.map((id) => [id, new Set()])), tie = (a, b) => { if (links.has(a) && links.has(b) && a !== b) { links.get(a).add(b); links.get(b).add(a); } };
|
|
103
|
+
const fastening = s.fits.filter((x) => x.fastens || x.seat != null || x.shaft != null || x.engage != null);
|
|
104
|
+
for (const x of fastening) for (const a of [x.a].flat()) for (const b of [x.b].flat()) tie(top(a), top(b));
|
|
105
|
+
for (const j of joints) if (j.parent >= 0) tie(items[j.parent], items[j.child]);
|
|
106
|
+
const base = items.find((id) => by.has(id)) ?? ids[0], level = new Map([[base, 0]]);
|
|
107
|
+
for (let queue = [base]; queue.length;) { const id = queue.shift(); for (const o of links.get(id)) if (!level.has(o)) { level.set(o, level.get(id) + 1); queue.push(o); } }
|
|
108
|
+
const lv = (id) => level.get(id) ?? 1e6;
|
|
109
|
+
const rank = (id) => [lv(id), by.get(id).order], earlier = (a, b) => { const [x, y] = [rank(a), rank(b)]; return x[0] - y[0] || x[1] - y[1]; };
|
|
110
|
+
// Constraints: [u, v, why]: u before v
|
|
111
|
+
const before = new Map(ids.map((id) => [id, new Map()])), add = (u, v, why) => { if (by.has(u) && by.has(v) && u !== v) before.get(u).set(v, why); };
|
|
112
|
+
for (const j of joints) if (j.parent >= 0) add(items[j.parent], items[j.child], `${items[j.child]} turns on ${items[j.parent]}`);
|
|
113
|
+
for (const x of fastening) for (const A of [x.a].flat()) for (const B of [x.b].flat()) {
|
|
114
|
+
const a = top(A), b = top(B), [u, v] = earlier(a, b) <= 0 ? [a, b] : [b, a];
|
|
115
|
+
if (x.seat != null && (bearing(a) || bearing(b))) { const [h, r] = bearing(a) ? [b, a] : [a, b]; add(h, r, `${r} is pressed into ${h}`); continue; }
|
|
116
|
+
if ((x.shaft != null || x.engage != null) && (bearing(a) || bearing(b))) { const [r, shaft] = bearing(a) ? [a, b] : [b, a]; add(r, shaft, `${r} goes in before ${shaft}`); continue; }
|
|
117
|
+
if (x.fastens) add(u, v, x.note || `${v} fastens to ${u}`);
|
|
118
|
+
}
|
|
119
|
+
// Screws: what stands on the tool's line goes on after the screw, and if it must already be there, nothing can
|
|
120
|
+
const worlds = placeItems(s.motion, s.jointValues), marks = s.motion.marks, reaches = (u, v, seen = new Set()) => { if (u === v) return true; if (seen.has(u)) return false; seen.add(u); return [...before.get(u).keys()].some((w) => reaches(w, v, seen)); };
|
|
121
|
+
const R = 1.5, bad = [];
|
|
122
|
+
for (const x of s.fits.filter((f) => f.access)) {
|
|
123
|
+
const [id, name] = String(x.access).split('.'), m = marks.find((k) => k.id === id && k.name === name);
|
|
124
|
+
if (!m) throw new Error(`fit ${x.note || `${x.a} / ${x.b}`}: access: no anchor "${x.access}" (give <item>.<anchor>${items.includes(id) ? `; ${id} has ${marks.filter((k) => k.id === id).map((k) => k.name).join(', ') || 'none'}` : ''})`);
|
|
125
|
+
const W = mul(worlds[m.item], m.frame), O = [W[3], W[7], W[11]], D = [W[2], W[6], W[10]], [u, v] = basis(D), starts = [[0, 0], [R, 0], [-R, 0], [0, R], [0, -R]].map(([a, b]) => O.map((c, k) => c + a * u[k] + b * v[k]));
|
|
126
|
+
const screwed = [top(x.a), top(x.b)].filter((t) => by.has(t)), later = [...screwed].sort(earlier).at(-1);
|
|
127
|
+
for (const q of all) {
|
|
128
|
+
if (screwed.includes(q.id) || !starts.some((p) => hitsAlong(p, D, q.tris))) continue;
|
|
129
|
+
if (later && reaches(q.id, later)) bad.push({ fit: x, wall: q.id, at: O, later });
|
|
130
|
+
else if (later) add(later, q.id, `${q.id} covers the screw of ${x.note || later}`);
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
const box = (g) => { const p = g.tris.flat(); return [0, 1, 2].map((k) => { const v = p.map((x) => x[k]); return (Math.min(...v) + Math.max(...v)) / 2; }); };
|
|
134
|
+
if (bad.length) {
|
|
135
|
+
const b = bad[0], label = b.fit.note || `${b.fit.a} to ${b.fit.b}`;
|
|
136
|
+
return { steps: [], stuck: { item: b.later, screw: label, wall: b.wall, at: b.at, text: `the screw of "${label}" can't be reached in any order: ${b.wall} stands over it and goes on first (${[...before.get(b.wall)].slice(0, 1).map(([, why]) => why)})` } };
|
|
137
|
+
}
|
|
138
|
+
let span = 1;
|
|
139
|
+
for (const g of all) for (const t of g.tris) for (const p of t) for (const c of p) span = Math.max(span, Math.abs(c) * 2);
|
|
140
|
+
const h = Math.max(0.4, Math.min(1.5, span / 300)), memo = new Map(), rasterOf = (g, d) => { const key = `${g.id}|${d.join(',')}`; if (!memo.has(key)) memo.set(key, raster(g, d, h)); return memo.get(key); };
|
|
141
|
+
const free = (p, rest, d) => { for (const q of rest) if (q !== p && !allowedPair(s, p, q) && blockers(p, q, d, h, rasterOf)) return false; return true; };
|
|
142
|
+
const dirsFor = (p) => { // along its own axes first: a part on a joint goes on along that joint, then from above, then round the sides
|
|
143
|
+
const own = [];
|
|
144
|
+
for (const j of joints) if (items[j.child] === p.id) { const P = j.parent < 0 ? j.a : mul(worlds[j.parent], j.a); own.push([P[2], P[6], P[10]]); }
|
|
145
|
+
for (const m of marks) if (m.id === p.id) { const W = mul(worlds[m.item], m.frame); own.push([W[2], W[6], W[10]]); }
|
|
146
|
+
const list = [...own.flatMap((a) => [round(a), round(a.map((x) => -x))]), ...SIDES];
|
|
147
|
+
return [...new Map(list.map((d) => [d.map((x) => x.toFixed(3)).join(','), d])).values()];
|
|
148
|
+
};
|
|
149
|
+
// What stays together if a part can't leave alone: its joint parent and all that hangs from it (planets on their carrier)
|
|
150
|
+
const below = (a) => { const out = new Set([a]); for (let grew = true; grew;) { grew = false; for (const j of joints) if (j.parent >= 0 && out.has(items[j.parent]) && by.has(items[j.child]) && !out.has(items[j.child])) { out.add(items[j.child]); grew = true; } } return out; };
|
|
151
|
+
const parentOf = (id) => { const j = joints.find((x) => items[x.child] === id); return j && j.parent >= 0 ? items[j.parent] : null; };
|
|
152
|
+
// Take a set of parts apart, the last-attached first: [{ p, d }] or [{ group, d, sub }] (a set that leaves as one, then apart)
|
|
153
|
+
function takeApart(start) {
|
|
154
|
+
let rest = [...start].sort((a, b) => earlier(b.id, a.id));
|
|
155
|
+
const off = [], waits = (p, set) => [...before.get(p.id).keys()].some((v) => set.some((q) => q.id === v));
|
|
156
|
+
while (rest.length) {
|
|
157
|
+
let pick = null;
|
|
158
|
+
for (const p of rest) {
|
|
159
|
+
if (waits(p, rest)) continue;
|
|
160
|
+
if (rest.length === 1) { pick = { p, d: [0, 0, 1] }; break; }
|
|
161
|
+
const d = dirsFor(p).find((x) => free(p, rest, x));
|
|
162
|
+
if (d) { pick = { p, d }; break; }
|
|
163
|
+
}
|
|
164
|
+
if (!pick) for (const p of rest) { // nothing leaves alone: try what's joined to it, as one
|
|
165
|
+
for (let a = parentOf(p.id); a && a !== base && rest.some((q) => q.id === a) && !pick; a = parentOf(a)) {
|
|
166
|
+
const names = below(a), group = rest.filter((q) => names.has(q.id)), others = rest.filter((q) => !names.has(q.id));
|
|
167
|
+
if (group.length < 2 || !others.length || group.length === rest.length || group.some((q) => waits(q, others))) continue;
|
|
168
|
+
const d = dirsFor(by.get(a)).find((x) => group.every((q) => others.every((o) => allowedPair(s, q, o) || !blockers(q, o, x, h, rasterOf))));
|
|
169
|
+
if (d) { const sub = takeApart(group); if (sub.stuck) return sub; pick = { group, d, sub }; }
|
|
170
|
+
}
|
|
171
|
+
if (pick) break;
|
|
172
|
+
}
|
|
173
|
+
if (!pick) {
|
|
174
|
+
const stuckBy = rest.filter((p) => !waits(p, rest))[0] ?? rest[0];
|
|
175
|
+
const holders = [...new Set(SIDES.flatMap((d) => rest.filter((q) => q !== stuckBy && !allowedPair(s, stuckBy, q) && blockers(stuckBy, q, d, h, rasterOf)).map((q) => q.id)))];
|
|
176
|
+
const ringed = rest.filter((p) => waits(p, rest)).map((p) => p.id);
|
|
177
|
+
return { stuck: { item: stuckBy.id, wall: holders[0] ?? null, holders, at: box(stuckBy), text: holders.length ? `${stuckBy.id} can't be reached in any order: ${holders.join(' and ')} ${holders.length > 1 ? 'hold' : 'holds'} it in from every side` : `${ringed.join(', ')} each have to go on before the next, in a ring` } };
|
|
178
|
+
}
|
|
179
|
+
off.push(pick); const gone = pick.group ?? [pick.p]; rest = rest.filter((g) => !gone.includes(g));
|
|
180
|
+
}
|
|
181
|
+
return { off };
|
|
182
|
+
}
|
|
183
|
+
const apart = takeApart(all);
|
|
184
|
+
if (apart.stuck) return { steps: [], stuck: apart.stuck };
|
|
185
|
+
// Put together: last off is first on, a set built up on its own and then fitted as one
|
|
186
|
+
const seq = [], lay = (off) => { for (const x of [...off].reverse()) { if (x.group) { lay(x.sub.off); seq.push({ group: x.group, d: x.d }); } else seq.push(x); } };
|
|
187
|
+
lay(apart.off);
|
|
188
|
+
const at = new Map(), steps = [];
|
|
189
|
+
seq.forEach((x, i) => { for (const g of x.group ?? [x.p]) at.set(g.id, i); });
|
|
190
|
+
for (const [i, x] of seq.entries()) {
|
|
191
|
+
if (x.group) { steps.push({ items: x.group.map((g) => g.id), object: null, dir: round(x.d), fasteners: [], together: true }); continue; }
|
|
192
|
+
const { p, d } = x, list = [...new Set(s.fits.filter((f) => [...names(f.a), ...names(f.b)].includes(p.id) && (f.fastens || f.seat != null || f.fastener) && [...names(f.a), ...names(f.b)].every((n) => (at.get(n) ?? 0) <= i)))];
|
|
193
|
+
steps.push({ items: [p.id], object: p.object, dir: round(d), fasteners: list.map((f) => ({ fit: f.note || f.label || `${f.a} to ${f.b}`, ...(f.fastener ? { fastener: f.fastener } : {}), ...(f.count != null ? { count: f.num(f.count) } : {}) })) });
|
|
194
|
+
}
|
|
195
|
+
// Copies of one thing fitted the same way, one after another, are one step
|
|
196
|
+
const merged = [];
|
|
197
|
+
for (const st of steps) {
|
|
198
|
+
const last = merged.at(-1);
|
|
199
|
+
if (last && st.object && !st.together && last.object === st.object && last.dir.join() === st.dir.join() && JSON.stringify(last.fasteners.map((f) => f.fit)) === JSON.stringify(st.fasteners.map((f) => f.fit))) last.items.push(...st.items);
|
|
200
|
+
else merged.push({ items: [...st.items], object: st.object, dir: st.dir, fasteners: st.fasteners, ...(st.together ? { together: true } : {}) });
|
|
201
|
+
}
|
|
202
|
+
merged.forEach((st, i) => { st.n = i + 1; st.text = `${st.items.join(', ')}${st.object && !st.items.includes(st.object) ? ` (${st.object})` : ''}${st.together ? ' go on as one' : i ? ` goes on${st.items.length > 1 ? ', one by one' : ''}` : ' first'}${st.fasteners.length ? `: ${st.fasteners.map((f) => `${f.fit}${f.fastener ? ` (${f.count != null ? `${f.count} × ` : ''}${f.fastener})` : ''}`).join('; ')}` : ''}`; });
|
|
203
|
+
return { steps: merged, stuck: null };
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
// Cached by what the parts are and where they are, with everything else that changes the answer
|
|
207
|
+
function orderFile(s) {
|
|
208
|
+
const key = crypto.createHash('sha256').update(JSON.stringify([4, s.parts.map((p) => [p.item, p.hash ?? p.shape, Array.from(p.m ?? []).map((x) => +x.toFixed(4))]), s.fits.map(({ num, ...x }) => x), s.motion.joints.map((j) => [j.id, j.child, j.parent])])).digest('hex');
|
|
209
|
+
return paths.cache('order', `${key}.json`);
|
|
210
|
+
}
|
|
211
|
+
export function orderOf(s) {
|
|
212
|
+
if (s.orderSteps) return s.orderSteps;
|
|
213
|
+
const file = orderFile(s);
|
|
214
|
+
if (!process.env.CAD_NO_CACHE && host.exists(file)) return (s.orderSteps = JSON.parse(host.readText(file)));
|
|
215
|
+
const r = assemblyOrder(s);
|
|
216
|
+
try { fs.mkdirSync(path.dirname(file), { recursive: true }); host.writeText(file, JSON.stringify(r)); } catch {} // (only slower without it)
|
|
217
|
+
return (s.orderSteps = r);
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
// Whether an assembly is something that goes together with fastenings: anything else has no steps to find
|
|
221
|
+
export const isBuilt = (s) => s.a.kind !== 'plate' && s.fits.some((x) => x.fastens || x.seat != null || x.shaft != null || x.access);
|
|
222
|
+
|
|
223
|
+
/** assembly.order, in the assembly's findings shape. */
|
|
224
|
+
export function orderChecks(s, f) {
|
|
225
|
+
if (!isBuilt(s) || (s.pose != null && s.pose !== s.motion.pose)) return;
|
|
226
|
+
const r = orderOf(s);
|
|
227
|
+
if (r.stuck) f('fail', r.stuck.text, `${r.stuck.item}: can't be reached`, { code: 'assembly.order', at: r.stuck.at, refs: { item: r.stuck.item, ...(r.stuck.wall ? { wall: r.stuck.wall } : {}), ...(r.stuck.screw ? { screw: r.stuck.screw } : {}), ...(r.stuck.holders ? { holders: r.stuck.holders } : {}) } });
|
|
228
|
+
else f('pass', `goes together in ${r.steps.length} step${r.steps.length === 1 ? '' : 's'}, ${r.steps[0]?.items[0]} first, nothing trapped`, null, { code: 'assembly.order', values: { steps: r.steps.length }, refs: { first: r.steps[0]?.items[0] } });
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
/** Each step's picture: what's there, and the new part held off along the way it goes on. @returns {object[][]} parts lists, for preview() */
|
|
232
|
+
export function stepPictures(s, r) {
|
|
233
|
+
let off = 40;
|
|
234
|
+
for (const p of s.parts) for (const t of p.triangles) for (const v of t) off = Math.max(off, Math.abs(v[0]), Math.abs(v[1]), Math.abs(v[2]));
|
|
235
|
+
off *= 0.5;
|
|
236
|
+
return r.steps.map((st, i) => {
|
|
237
|
+
const shown = new Set(r.steps.slice(0, i + 1).flatMap((x) => x.items)), now = new Set(st.items);
|
|
238
|
+
return s.parts.filter((p) => shown.has(p.item)).map((p) => (now.has(p.item) ? { ...p, role: 'part', triangles: p.triangles.map((t) => t.map((v) => v.map((c, k) => c + st.dir[k] * off))) } : { ...p, role: 'reference' }));
|
|
239
|
+
});
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
export const orderText = (ref, r) => (r.stuck ? `${ref}: ${r.stuck.text}` : [`${ref}: how it goes together`, ...r.steps.map((st) => ` ${String(st.n).padStart(2)}. ${st.text}`)].join('\n'));
|
package/lib/plates.mjs
ADDED
|
@@ -0,0 +1,108 @@
|
|
|
1
|
+
// A machine's printed parts on beds: each object in its print orientation (as it's drawn, Z up, on the bed), grouped by
|
|
2
|
+
// filament, spaced by the first-layer rule, and written as plate assemblies, so check and export treat them as prints.
|
|
3
|
+
// Each plate remembers what's on it by the build's hash ("packed"): a changed part re-packs only its plate.
|
|
4
|
+
import fs from 'node:fs';
|
|
5
|
+
import path from 'node:path';
|
|
6
|
+
import { bounds, check as printCheck } from '@rulecad/printcheck';
|
|
7
|
+
import { locate, build } from './design.mjs';
|
|
8
|
+
import { paths, printerOf } from './workspace.mjs';
|
|
9
|
+
import { peekRuleSet } from './rules.mjs';
|
|
10
|
+
import { CadError } from './errors.mjs';
|
|
11
|
+
import { assemblyPath, buildAssembly, checkAssembly } from './assembly.mjs';
|
|
12
|
+
import { printedParts } from './list.mjs';
|
|
13
|
+
|
|
14
|
+
const n3 = (x) => +x.toFixed(3);
|
|
15
|
+
|
|
16
|
+
// The gap between parts on a plate: what two parts need to print apart at the first layer (print_gap, plus the first
|
|
17
|
+
// layer's spread each side), up to whole lines of the nozzle
|
|
18
|
+
function rulesOf(project, gap) {
|
|
19
|
+
const r = peekRuleSet(printerOf(project)).rules, num = (k, f) => { const v = r[k]?.value; return typeof v === 'number' ? v : f; }, bed = num('bed', 256), line = num('line', 0.42), need = num('print_gap', 0.3) + 2 * num('foot', 0.15);
|
|
20
|
+
return { bed, gap: gap ?? n3(Math.ceil((need - 1e-6) / line) * line), need };
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
// Every printed thing to go on a plate: built as printed, its filaments, how big
|
|
24
|
+
async function plateParts(s) {
|
|
25
|
+
const out = [];
|
|
26
|
+
for (const o of s.objects) {
|
|
27
|
+
if (o.unplaced || o.role !== 'part' || !o.objName) continue;
|
|
28
|
+
const d = locate(`${s.project}/${o.objName}`), b = await build({ ...d, ...(o.variant ? { variant: o.variant } : {}) }, o.set || {}), tris = b.parts.flatMap((p) => p.triangles), { lo, hi } = bounds(tris);
|
|
29
|
+
const fil = [...new Set(b.parts.filter((p) => p.role !== 'support').map((p) => p.filament || 'base'))].sort().join('+') || 'base';
|
|
30
|
+
out.push({ id: o.id.replace(/\./g, '_'), source: o.id, object: o.objName, variant: o.variant, set: o.set || {}, filament: fil, hash: b.hash, lo, size: [hi[0] - lo[0], hi[1] - lo[1]], height: hi[2] - lo[2] });
|
|
31
|
+
}
|
|
32
|
+
return out;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
// Shelves on a bed, largest first: as many plates as it takes
|
|
36
|
+
function pack(parts, { bed, gap }) {
|
|
37
|
+
const sorted = [...parts].sort((a, b) => b.size[1] - a.size[1] || b.size[0] - a.size[0] || a.id.localeCompare(b.id)), beds = [];
|
|
38
|
+
const room = bed - 2 * gap;
|
|
39
|
+
for (const p of sorted) {
|
|
40
|
+
let done = false;
|
|
41
|
+
for (const b of beds) {
|
|
42
|
+
const shelf = b.shelves.at(-1);
|
|
43
|
+
if (shelf.x + p.size[0] <= room && p.size[1] <= shelf.h) { b.items.push({ p, x: shelf.x, y: shelf.y }); shelf.x += p.size[0] + gap; done = true; break; }
|
|
44
|
+
const y = shelf.y + shelf.h + gap;
|
|
45
|
+
if (y + p.size[1] <= room && p.size[0] <= room) { b.shelves.push({ y, h: p.size[1], x: p.size[0] + gap }); b.items.push({ p, x: 0, y }); done = true; break; }
|
|
46
|
+
}
|
|
47
|
+
if (!done) beds.push({ shelves: [{ y: 0, h: p.size[1], x: p.size[0] + gap }], items: [{ p, x: 0, y: 0 }] });
|
|
48
|
+
}
|
|
49
|
+
return beds;
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
const plateFile = (project, name) => assemblyPath(`${project}/${name}`);
|
|
53
|
+
function existing(s) {
|
|
54
|
+
const dir = path.join(paths.project(s.project), 'assemblies'), out = [];
|
|
55
|
+
for (const f of fs.existsSync(dir) ? fs.readdirSync(dir) : []) { if (!f.endsWith('.json')) continue; let a; try { a = JSON.parse(fs.readFileSync(path.join(dir, f), 'utf8')); } catch { continue; } if (a.packed?.of === s.name) out.push({ name: f.slice(0, -5), a }); }
|
|
56
|
+
return out.sort((a, b) => a.name.localeCompare(b.name, undefined, { numeric: true }));
|
|
57
|
+
}
|
|
58
|
+
const nameOf = (s, filament, k) => `${s.name}-${filament.replace(/\+/g, '-')}-${k}`;
|
|
59
|
+
|
|
60
|
+
function plateJson(s, plate, { bed, gap }) {
|
|
61
|
+
const origin = (bed - 2 * gap) / 2;
|
|
62
|
+
return { title: `${s.a.title || s.name}: ${plate.filament}, plate ${plate.n}`, kind: 'plate', note: `Generated by cad plates from ${s.name}. Hand edits are replaced when a part on it changes.`,
|
|
63
|
+
packed: { of: s.name, filament: plate.filament, gap, parts: Object.fromEntries(plate.items.map(({ p }) => [p.id, p.hash])) },
|
|
64
|
+
items: plate.items.map(({ p, x, y }) => ({ id: p.id, object: p.object, ...(p.variant ? { variant: p.variant } : {}), ...(Object.keys(p.set).length ? { set: p.set } : {}), at: [n3(x - origin - p.lo[0]), n3(y - origin - p.lo[1]), n3(-p.lo[2])] })) };
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/**
|
|
68
|
+
* The plates of an assembly: a stale plate (a part on it changed or gone) and any new part packed again, every other plate left alone.
|
|
69
|
+
* @param {object} s a built assembly @param {{ write?: boolean, gap?: number }} [options]
|
|
70
|
+
* @returns {Promise<{ plates: object[], touched: string[], removed: string[], gap: number, bed: number, findings: object[] }>}
|
|
71
|
+
*/
|
|
72
|
+
export async function platesOf(s, { write = false, gap: asked } = {}) {
|
|
73
|
+
const parts = await plateParts(s), { bed, gap } = rulesOf(s.project, asked), findings = [], plates = [], touched = [], removed = [];
|
|
74
|
+
if (!parts.length) throw new CadError('plates.empty', `${s.project}/${s.name} has nothing printed to put on a plate`);
|
|
75
|
+
const big = parts.filter((p) => p.size[0] > bed - 2 * gap || p.size[1] > bed - 2 * gap);
|
|
76
|
+
for (const p of big) findings.push({ level: 'fail', text: `${p.id} (${p.object}) is ${Number(p.size[0].toFixed(1))} × ${Number(p.size[1].toFixed(1))} mm: bigger than the ${bed} mm bed, so it has no plate: split it or turn it`, code: 'plate.bed', refs: { item: p.id }, values: { size: p.size, bed } });
|
|
77
|
+
const by = new Map(parts.filter((p) => !big.includes(p)).map((p) => [p.id, p])), had = existing(s), kept = new Set(), used = new Set();
|
|
78
|
+
// A plate stands if everything on it is still there and unchanged
|
|
79
|
+
for (const e of had) {
|
|
80
|
+
const on = Object.entries(e.a.packed.parts || {}), ok = on.length && on.every(([id, h]) => by.get(id)?.hash === h) && e.a.packed.gap === gap;
|
|
81
|
+
if (!ok) continue;
|
|
82
|
+
kept.add(e.name); on.forEach(([id]) => used.add(id)); plates.push({ name: e.name, filament: e.a.packed.filament, a: e.a, items: e.a.items.map((it) => { const p = by.get(it.id), origin = (bed - 2 * gap) / 2; return { p, x: it.at[0] + p.lo[0] + origin, y: it.at[1] + p.lo[1] + origin }; }), stood: true });
|
|
83
|
+
}
|
|
84
|
+
// Everything else, packed by filament; names reused from the plates that are going, so a changed part keeps its name
|
|
85
|
+
const free = [...by.values()].filter((p) => !used.has(p.id)), byFilament = new Map();
|
|
86
|
+
for (const p of free) { if (!byFilament.has(p.filament)) byFilament.set(p.filament, []); byFilament.get(p.filament).push(p); }
|
|
87
|
+
const goingNames = had.filter((e) => !kept.has(e.name)).map((e) => e.name);
|
|
88
|
+
for (const [filament, list] of byFilament) {
|
|
89
|
+
const beds = pack(list, { bed, gap }); let k = 0;
|
|
90
|
+
const next = () => { const reuse = goingNames.find((n) => had.find((e) => e.name === n)?.a.packed.filament === filament); if (reuse) { goingNames.splice(goingNames.indexOf(reuse), 1); return reuse; } let name; do name = nameOf(s, filament, ++k); while (kept.has(name) || plates.some((x) => x.name === name)); return name; };
|
|
91
|
+
for (const b of beds) { const name = next(), n = Number(name.match(/-(\d+)$/)?.[1]) || 1, plate = { name, filament, n, items: b.items }; plate.a = plateJson(s, plate, { bed, gap }); plates.push(plate); touched.push(name); }
|
|
92
|
+
}
|
|
93
|
+
for (const n of goingNames) removed.push(n);
|
|
94
|
+
plates.sort((a, b) => a.name.localeCompare(b.name, undefined, { numeric: true }));
|
|
95
|
+
if (write) {
|
|
96
|
+
const dir = path.join(paths.project(s.project), 'assemblies'); fs.mkdirSync(dir, { recursive: true });
|
|
97
|
+
for (const p of plates) if (!p.stood) fs.writeFileSync(plateFile(s.project, p.name), `${JSON.stringify(p.a, null, 2)}\n`);
|
|
98
|
+
for (const n of removed) fs.rmSync(plateFile(s.project, n), { force: true });
|
|
99
|
+
}
|
|
100
|
+
const grams = new Map(printedParts(s).map((x) => [x.id.replace(/\./g, '_'), x]));
|
|
101
|
+
return { bed, gap, touched, removed, findings, plates: plates.map((p) => ({ name: p.name, filament: p.filament, parts: p.items.map(({ p: q, x, y }) => ({ id: q.id, object: q.object, x: n3(x + gap), y: n3(y + gap), w: n3(q.size[0]), d: n3(q.size[1]) })), grams: n3(p.items.reduce((t, { p: q }) => t + (grams.get(q.id)?.grams ?? 0), 0)), minutes: p.items.reduce((t, { p: q }) => t + (grams.get(q.id)?.minutes ?? 0), 0), stood: !!p.stood })) };
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
/** Each plate's checks: what check says of a plate, the print check over the whole bed included. */
|
|
105
|
+
export async function checkPlate(ref) {
|
|
106
|
+
const s = await buildAssembly(ref), printer = printerOf(s.project), rules = Object.fromEntries(Object.keys(peekRuleSet(printer).rules).map((k) => [k, s.num(`${printer}.${k}`)])), printed = s.parts.filter((p) => p.role !== 'reference');
|
|
107
|
+
return [...checkAssembly(s), ...printCheck(printed.flatMap((p) => p.triangles), rules, { parts: printed })];
|
|
108
|
+
}
|
package/lib/power.mjs
ADDED
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
// Drivers and supplies in an assembly: each stepper's driver is named by the bought item it plugs into, the current it is
|
|
2
|
+
// set to is checked and the trimmer's voltage said, and the supply is held against the whole machine's draw.
|
|
3
|
+
import { driver as driverModel, setting, powerBudget } from '@rulecad/motors';
|
|
4
|
+
|
|
5
|
+
const n3 = (x, d = 2) => String(Number(x.toFixed(d)));
|
|
6
|
+
|
|
7
|
+
function itemById(s, id) { return s.objects.find((o) => o.id === id); }
|
|
8
|
+
|
|
9
|
+
export function powerChecks(s, f) {
|
|
10
|
+
const drives = s.motion?.drives ?? [], supplies = s.objects.filter((o) => o.bought?.part === 'supply');
|
|
11
|
+
const psu = supplies[0]?.built.values, voltage = psu?.output_voltage, draws = [];
|
|
12
|
+
for (const d of drives) {
|
|
13
|
+
const m = d.model, refs = { item: d.id, ...(d.joint ? { joint: d.joint } : {}) };
|
|
14
|
+
if (m.type === 'stepper') {
|
|
15
|
+
const rated = m.figures.rated_current?.value, current = d.spec.current ?? rated, R = m.figures.resistance?.value;
|
|
16
|
+
draws.push({ name: d.id, current, resistance: R, ...(d.spec.duty != null ? { duty: d.spec.duty } : {}) });
|
|
17
|
+
if (!d.spec.driver) { if (s.task) f('warn', `${d.id} has no "driver": nothing checks the current it's set to (name a bought driver item)`, `${d.id}: no driver`, { code: 'motor.driver', refs }); continue; }
|
|
18
|
+
const o = itemById(s, d.spec.driver);
|
|
19
|
+
if (!o || o.bought?.part !== 'driver') { f('fail', `${d.id}: driver "${d.spec.driver}" isn't a bought driver item`, `${d.id}: no such driver`, { code: 'motor.driver', refs }); continue; }
|
|
20
|
+
const model = driverModel(o.bought.set, { variant: o.bought.variant ?? undefined }), { vref, findings } = setting(model, current, { cooled: !!d.spec.cooled, supply: voltage, microsteps: d.spec.microsteps });
|
|
21
|
+
for (const x of findings) f(x.level, `${d.id}: ${x.text}`, `${d.id}: driver`, { code: x.code, values: x.values, refs });
|
|
22
|
+
if (!findings.some((x) => x.level === 'fail')) f('pass', `${d.id} on ${model.name}: set the trimmer to ${n3(vref, 3)} V for ${n3(current, 2)} A per coil (${model.formula}${model.uart ? `, or set it over UART` : ''}), ${model.sense} ohm sense resistors: read yours before trusting this`, null, { code: 'motor.driver', refs, values: { vref, current, sense: model.sense } });
|
|
23
|
+
} else if (m.type === 'servo') {
|
|
24
|
+
draws.push({ name: d.id, current: 0.7, voltage: m.figures.rated_voltage?.value ?? 5, duty: d.spec.duty ?? 0.2 });
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
if (!draws.length || !supplies.length) { if (draws.length && s.task) f('warn', 'there is no "supply" among the bought items: nothing checks the power', 'no supply', { code: 'power.supply' }); return; }
|
|
28
|
+
const o = supplies[0], I = psu.output_current, extra = s.objects.filter((x) => x.bought?.part === 'board').map((x) => ({ name: x.id, current: 0.1, voltage: 5, duty: 1 }));
|
|
29
|
+
const r = powerBudget([...draws, ...extra], { voltage, current: I, margin: s.a.power?.margin ?? 1.25 });
|
|
30
|
+
for (const x of r.findings) f(x.level, `${o.id} (${o.bought.variant ?? o.bought.set}): ${x.text}`, x.level === 'pass' ? null : `${o.id}: too small`, { code: x.code, values: x.values, refs: { item: o.id } });
|
|
31
|
+
}
|
package/lib/seats.mjs
CHANGED
|
@@ -74,7 +74,7 @@ export function printerRules(s) {
|
|
|
74
74
|
// hole_comp smaller across, so half of that comes off the gap each side; what's left is held against the printer's fit
|
|
75
75
|
export function runningChecks(s, f, { axisOf, placeItems, jointValues, mul }) {
|
|
76
76
|
const motion = s.motion; if (!motion?.joints?.length) return;
|
|
77
|
-
const worlds = placeItems(motion, jointValues(motion, motion.pose ?? undefined)), ids = motion.items.map((x) => x[0]);
|
|
77
|
+
const worlds = placeItems(motion, s.jointValues ?? jointValues(motion, motion.pose ?? undefined)), ids = motion.items.map((x) => x[0]);
|
|
78
78
|
const P = printerRules(s), fit = P.fit ?? 0.2, comp = P.hole_comp ?? 0.1;
|
|
79
79
|
const refs = new Set(s.objects.filter((o) => o.role === 'reference').map((o) => String(o.id).split('.')[0]));
|
|
80
80
|
const partsOf = (id) => s.parts.filter((p) => p.item === id || p.leaf === id);
|
|
@@ -101,7 +101,7 @@ export function seatFit(x, s, f, { placeItems, jointValues, mul, seatSize }) {
|
|
|
101
101
|
if (!o) return f('fail', `${label}: a seat holds a bought bearing, and neither ${x.a} nor ${x.b} is one`, `${label}: no bearing`, { code });
|
|
102
102
|
const other = top(x.a) === o.id ? top(x.b) : top(x.a), parts = s.parts.filter((p) => p.item === other || p.leaf === other);
|
|
103
103
|
if (!parts.length) return f('fail', `${label}: no part "${other}"`, null, { code });
|
|
104
|
-
const motion = s.motion, ids = motion.items.map((y) => y[0]), W = placeItems(motion, jointValues(motion, motion.pose ?? undefined))[ids.indexOf(o.id)];
|
|
104
|
+
const motion = s.motion, ids = motion.items.map((y) => y[0]), W = placeItems(motion, s.jointValues ?? jointValues(motion, motion.pose ?? undefined))[ids.indexOf(o.id)];
|
|
105
105
|
const inv = (p) => { const q = [p[0] - W[3], p[1] - W[7], p[2] - W[11]]; return [W[0] * q[0] + W[4] * q[1] + W[8] * q[2], W[1] * q[0] + W[5] * q[1] + W[9] * q[2], W[2] * q[0] + W[6] * q[1] + W[10] * q[2]]; };
|
|
106
106
|
const tris = parts.flatMap((p) => p.triangles).map((t) => t.map(inv)), v = o.built.values, w = v.width, R = v.outer_diameter / 2, r = v.bore / 2;
|
|
107
107
|
const printer = printerRules(s), want = seatSize(v, { fit: x.seat === true ? 'press' : x.seat, printer }), refs = { item: o.id, part: other };
|
package/lib/sheet.mjs
CHANGED
|
@@ -112,9 +112,77 @@ function driverDrawing(set) {
|
|
|
112
112
|
return sheet(set, pens, W, H);
|
|
113
113
|
}
|
|
114
114
|
|
|
115
|
+
// A round part from its end and along its axis: linear bearings, nuts, couplers, pulleys, idlers, rods. Each says what it has: flange, hole circle, a dashed pitch circle, the bores of a coupler
|
|
116
|
+
function roundDrawing(set, { D, d = 0, L, bores, flange, circle: holeCircle, pitchD, notes = [] }) {
|
|
117
|
+
const R = Math.max(D, flange?.D ?? 0) / 2, S = Math.max(3, Math.min(14, 90 / R)), W = 2 * R * S + L * S + 340, H = 2 * R * S + 190;
|
|
118
|
+
const cx = R * S + 70, cy = H / 2 + 22, sx = cx + R * S + 120, top = cy - R * S, bottom = cy + R * S;
|
|
119
|
+
const pens = pen(), { line, circle, rect, text, span } = pens;
|
|
120
|
+
// ---- from the end ----
|
|
121
|
+
if (flange) circle(cx, cy, (flange.D / 2) * S, '#f6f4ee');
|
|
122
|
+
circle(cx, cy, (D / 2) * S, FILL);
|
|
123
|
+
if (pitchD) circle(cx, cy, (pitchD / 2) * S, 'none', THIN);
|
|
124
|
+
if (d) circle(cx, cy, (d / 2) * S, '#fff');
|
|
125
|
+
if (holeCircle) for (let i = 0; i < holeCircle.count; i++) { const a = (2 * Math.PI * i) / holeCircle.count; circle(cx + (holeCircle.D / 2) * Math.cos(a) * S, cy + (holeCircle.D / 2) * Math.sin(a) * S, (holeCircle.hole / 2) * S, '#fff'); }
|
|
126
|
+
line(cx - R * S - 8, cy, cx + R * S + 8, cy, THIN, 0.5, '8 3 2 3'); line(cx, cy - R * S - 8, cx, cy + R * S + 8, THIN, 0.5, '8 3 2 3');
|
|
127
|
+
span(cx - R * S, bottom + 6, cx + R * S, bottom + 6, `Ø${fig(flange?.D ?? D)}`, 18);
|
|
128
|
+
if (d) span(cx - (d / 2) * S, top - 6, cx + (d / 2) * S, top - 6, `bore Ø${fig(d)}`, -14);
|
|
129
|
+
// ---- along the axis ----
|
|
130
|
+
const ring = (x, len, a, b, fill = FILL) => { for (const side of [-1, 1]) rect(x, side < 0 ? cy - (b / 2) * S : cy + (a / 2) * S, len * S, ((b - a) / 2) * S, fill); };
|
|
131
|
+
if (bores) { ring(sx, L / 2, bores[0], D); ring(sx + (L / 2) * S, L / 2, bores[1], D); }
|
|
132
|
+
else if (d) ring(sx, L, d, D);
|
|
133
|
+
else rect(sx, cy - (D / 2) * S, L * S, D * S, METAL);
|
|
134
|
+
if (flange) ring(sx + flange.at * S, flange.w, d, flange.D, '#ddd9cf');
|
|
135
|
+
line(sx - 12, cy, sx + L * S + 12, cy, THIN, 0.5, '8 3 2 3');
|
|
136
|
+
span(sx, bottom + 6, sx + L * S, bottom + 6, `${fig(L)}`, 18);
|
|
137
|
+
span(sx + L * S + 6, cy - (D / 2) * S, sx + L * S + 6, cy + (D / 2) * S, `Ø${fig(D)}`, 30);
|
|
138
|
+
notes.forEach((t, i) => text(cx, bottom + 66 + i * 18, t, 'middle', 11));
|
|
139
|
+
return sheet(set, pens, W, H);
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
// A lead screw from the side: the crest and root, the starts' flanks, and pitch against lead
|
|
143
|
+
function leadScrewDrawing(set) {
|
|
144
|
+
const n = (k) => set.rules[k]?.value ?? 0, D = n('diameter'), root = n('root_diameter'), P = n('pitch'), lead = n('lead'), starts = n('starts') || 1;
|
|
145
|
+
const L = Math.max(3 * lead, 20), S = Math.min(14, 420 / L), W = L * S + 240, H = D * S + 200, x0 = 110, cy = H / 2 + 12;
|
|
146
|
+
const pens = pen(), { line, rect, text, span } = pens;
|
|
147
|
+
rect(x0, cy - (D / 2) * S, L * S, D * S, METAL);
|
|
148
|
+
for (const side of [-1, 1]) line(x0, cy + side * (root / 2) * S, x0 + L * S, cy + side * (root / 2) * S, THIN, 0.6, '4 3');
|
|
149
|
+
const lean = (D * S * Math.tan((n('helix_angle') * Math.PI) / 180)) / 2;
|
|
150
|
+
for (let i = 0; i * P <= L + 1e-9; i++) { const x = x0 + i * P * S; if (x - lean >= x0 && x + lean <= x0 + L * S) line(x - lean, cy + (D / 2) * S, x + lean, cy - (D / 2) * S, i % starts === 0 ? INK : THIN, i % starts === 0 ? 1.6 : 0.7); }
|
|
151
|
+
line(x0 - 12, cy, x0 + L * S + 12, cy, THIN, 0.5, '8 3 2 3');
|
|
152
|
+
const below = cy + (D / 2) * S + 6, above = cy - (D / 2) * S - 6;
|
|
153
|
+
span(x0, below, x0 + P * S, below, `pitch ${fig(P)}`, 18);
|
|
154
|
+
span(x0, below, x0 + lead * S, below, `lead ${fig(lead)}`, 44);
|
|
155
|
+
span(x0 + L * S + 6, cy - (D / 2) * S, x0 + L * S + 6, cy + (D / 2) * S, `Ø${fig(D)}`, 30);
|
|
156
|
+
span(x0 - 6, cy - (root / 2) * S, x0 - 6, cy + (root / 2) * S, `root Ø${fig(root)}`, -18);
|
|
157
|
+
text(x0 + (L * S) / 2, above - 8, `${set.rules.thread?.value ?? ''}, ${fig(starts)} start${starts > 1 ? 's' : ''}, helix ${fig(n('helix_angle'))}°`, 'middle', 12);
|
|
158
|
+
text(x0 + (L * S) / 2, below + 72, 'each dark line one start, repeating at the lead', 'middle', 11);
|
|
159
|
+
return sheet(set, pens, W, H);
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
// A short length of belt, teeth along it
|
|
163
|
+
function beltDrawing(set) {
|
|
164
|
+
const n = (k) => set.rules[k]?.value ?? 0, P = n('pitch'), w = n('width'), L = P * 8, S = 12, W = L * S + 220, H = w * S + 190, x0 = 90, cy = H / 2 + 10;
|
|
165
|
+
const pens = pen(), { line, rect, text, span } = pens;
|
|
166
|
+
rect(x0, cy - (w / 2) * S, L * S, w * S);
|
|
167
|
+
for (let i = 0; i <= 8; i++) line(x0 + i * P * S, cy - (w / 2) * S, x0 + i * P * S, cy + (w / 2) * S, THIN, 0.7);
|
|
168
|
+
span(x0, cy + (w / 2) * S + 6, x0 + P * S, cy + (w / 2) * S + 6, `pitch ${fig(P)}`, 18);
|
|
169
|
+
span(x0 + L * S + 6, cy - (w / 2) * S, x0 + L * S + 6, cy + (w / 2) * S, `${fig(w)}`, 18);
|
|
170
|
+
text(x0 + (L * S) / 2, cy + (w / 2) * S + 66, `${fig(n('stiffness'))} N per unit strain, pitch line ${n('pitch_line_offset')} beyond the teeth`, 'middle', 11);
|
|
171
|
+
text(x0 + (L * S) / 2, cy + (w / 2) * S + 84, `rated ${fig(n('rated_tension'))} N, breaks at ${fig(n('breaking_strength'))} N`, 'middle', 11);
|
|
172
|
+
return sheet(set, pens, W, H);
|
|
173
|
+
}
|
|
174
|
+
|
|
115
175
|
export function drawing(set, vocab) {
|
|
116
176
|
if (set.part === 'bearing') return bearingDrawing(set);
|
|
117
177
|
if (set.part === 'driver') return driverDrawing(set);
|
|
178
|
+
const v = (k) => set.rules[k]?.value ?? 0;
|
|
179
|
+
if (set.part === 'leadscrew') return leadScrewDrawing(set);
|
|
180
|
+
if (set.part === 'belt') return beltDrawing(set);
|
|
181
|
+
if (set.part === 'linear_bearing') return roundDrawing(set, { D: v('outer_diameter'), d: v('bore'), L: v('length'), notes: [`linear bearing: ${fig(v('dynamic_rating'))} N dynamic, ${fig(v('static_rating'))} N static`] });
|
|
182
|
+
if (set.part === 'nut') { return roundDrawing(set, { D: v('body_diameter'), d: v('diameter'), L: v('length'), flange: { D: v('flange_diameter'), w: v('flange_width'), at: v('flange_offset') }, circle: { D: v('hole_circle'), count: v('hole_count'), hole: v('mount_hole_diameter') || 3.5 }, notes: [`${set.rules.thread?.value ?? ''}, ${set.rules.material?.value ?? ''}, lead ${fig(v('lead'))}`, `${fig(v('hole_count'))} × Ø${fig(v('mount_hole_diameter'))} on Ø${fig(v('hole_circle'))}`] }); }
|
|
183
|
+
if (set.part === 'coupler') return roundDrawing(set, { D: v('outer_diameter'), L: v('length'), bores: [v('bore_a'), v('bore_b')], d: 0, notes: [`bores Ø${fig(v('bore_a'))} and Ø${fig(v('bore_b'))}`, String(set.rules.style?.value ?? '')] });
|
|
184
|
+
if (set.part === 'pulley' || set.part === 'idler') return roundDrawing(set, { D: v('outer_diameter'), d: v('bore'), L: v('body_width'), pitchD: v('pitch_diameter'), notes: [set.part === 'pulley' ? `${fig(v('teeth'))} teeth, pitch circle Ø${fig(v('pitch_diameter'))} (thin), across the teeth Ø${fig(v('tooth_diameter'))}` : `${set.rules.toothed?.value === 'yes' ? `${fig(v('teeth'))} teeth` : 'smooth'}, for ${fig(v('belt_width'))} mm belt`, set.part === 'pulley' ? `for ${fig(v('belt_width'))} mm belt` : ''] });
|
|
185
|
+
if (set.part === 'rod') return roundDrawing(set, { D: v('diameter'), L: 40, notes: [`${String(set.rules.tolerance?.value ?? '')}; ${String(set.rules.hardness?.value ?? '')}`] });
|
|
118
186
|
const get = (k) => { const r = set.rules[set.interface?.[k] ?? k]; return r?.value; }, n = (k, d = 0) => { const x = get(k); return typeof x === 'number' ? x : d; };
|
|
119
187
|
if (!set.part && !Object.keys(set.interface || {}).some((k) => k.startsWith('body_'))) throw new Error(`rule set "${set.name}" doesn't say what shape it is (no body_ names in it, or "part", or "interface"): there's nothing to draw`);
|
|
120
188
|
const shape = get('body_shape') ?? 'box', round = shape === 'round', w = round ? n('body_diameter') : n('body_width'), d = round ? w : shape === 'square' ? w : n('body_depth', n('body_width'));
|