@rulecad/cad 0.8.0 → 0.9.0
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 +24 -10
- package/CHANGELOG.md +404 -0
- package/EXAMPLES.md +40 -38
- package/README.md +193 -67
- package/TUTORIAL.md +2 -2
- package/bin/cad.mjs +2250 -512
- package/lib/animate.mjs +173 -49
- package/lib/assembly.mjs +1847 -434
- package/lib/beams.mjs +256 -52
- package/lib/belts.mjs +66 -15
- package/lib/board-work.mjs +12 -0
- package/lib/bought.mjs +309 -53
- package/lib/buildpage.mjs +179 -29
- package/lib/carried.mjs +201 -0
- package/lib/clone.mjs +194 -42
- package/lib/design.mjs +649 -121
- package/lib/drive.mjs +187 -63
- package/lib/edit.mjs +899 -191
- package/lib/errors.mjs +16 -3
- package/lib/explain.mjs +62 -13
- package/lib/fasten.mjs +2702 -507
- package/lib/fittings.mjs +715 -121
- package/lib/fixings.mjs +21 -9
- package/lib/framebuild.mjs +790 -175
- package/lib/framecheck.mjs +1901 -368
- package/lib/framegen.mjs +100 -22
- package/lib/frameheat.mjs +225 -42
- package/lib/frameprint.mjs +513 -108
- package/lib/frames.mjs +81 -17
- package/lib/framesize.mjs +792 -120
- package/lib/frametip.mjs +235 -0
- package/lib/gait.mjs +135 -23
- package/lib/grip.mjs +62 -13
- package/lib/guides.mjs +1403 -230
- package/lib/host.mjs +123 -21
- package/lib/inplace.mjs +171 -36
- package/lib/jigs.mjs +360 -78
- package/lib/joins.mjs +697 -118
- package/lib/jsonedit.mjs +88 -26
- package/lib/kept.mjs +84 -0
- package/lib/kit.mjs +438 -68
- package/lib/layout.mjs +2 -1
- package/lib/links.mjs +149 -42
- package/lib/list.mjs +326 -64
- package/lib/live-guard.mjs +68 -0
- package/lib/live-shape.mjs +96 -24
- package/lib/live.mjs +189 -59
- package/lib/loads.mjs +579 -130
- package/lib/machine.mjs +372 -74
- package/lib/magnets.mjs +162 -44
- package/lib/measured.mjs +417 -94
- package/lib/mesh.mjs +526 -119
- package/lib/meshcmd.mjs +215 -60
- package/lib/motors.mjs +1021 -213
- package/lib/motorsvg.mjs +114 -32
- package/lib/names.mjs +3 -1
- package/lib/optimise.mjs +978 -283
- package/lib/order.mjs +519 -112
- package/lib/panels.mjs +482 -94
- package/lib/parts.mjs +78 -23
- package/lib/pins.mjs +163 -44
- package/lib/plates.mjs +223 -35
- package/lib/player.mjs +37 -9
- package/lib/power.mjs +64 -13
- package/lib/preview.mjs +83 -16
- package/lib/profilemeasure.mjs +572 -129
- package/lib/rules.mjs +15 -5
- package/lib/sandbox-hooks.mjs +77 -19
- package/lib/sandbox-run.mjs +117 -18
- package/lib/sandbox.mjs +509 -60
- package/lib/schema.mjs +42 -11
- package/lib/seats.mjs +227 -49
- package/lib/services.mjs +261 -52
- package/lib/sheet.mjs +851 -178
- package/lib/slotnuts.mjs +213 -34
- package/lib/targets/gist.mjs +4 -1
- package/lib/targets.mjs +22 -4
- package/lib/task.mjs +376 -79
- package/lib/versions.mjs +111 -28
- package/lib/wires.mjs +228 -45
- package/lib/workspace.mjs +197 -12
- package/package.json +19 -19
- package/schemas/assembly.schema.json +2 -2
package/lib/profilemeasure.mjs
CHANGED
|
@@ -9,14 +9,27 @@ import { fileURLToPath } from 'node:url';
|
|
|
9
9
|
import { signedArea, polygonSection, slotModel } from '@rulecad/frames';
|
|
10
10
|
import { fmt } from './rules.mjs';
|
|
11
11
|
import { WS, paths, RULE_DIRS } from './workspace.mjs';
|
|
12
|
+
import { readJson } from './host.mjs';
|
|
12
13
|
import { picture } from './preview.mjs';
|
|
13
14
|
import { AXES, axisOf, readMesh, bounds, section, profiles, loops as chain, limitingLicence } from './mesh.mjs';
|
|
14
15
|
|
|
15
|
-
const f2 = (n) => fmt(Math.round(n * 100) / 100),
|
|
16
|
+
const f2 = (n) => fmt(Math.round(n * 100) / 100),
|
|
17
|
+
r2 = (n) => Math.round(n * 100) / 100,
|
|
18
|
+
today = () => new Date().toISOString().slice(0, 10);
|
|
16
19
|
const RAD = Math.PI / 180;
|
|
17
20
|
|
|
18
21
|
// ---------- a DXF section ----------
|
|
19
|
-
const REFUSED = {
|
|
22
|
+
const REFUSED = {
|
|
23
|
+
SPLINE: 'a spline',
|
|
24
|
+
ELLIPSE: 'an ellipse',
|
|
25
|
+
POLYLINE: 'an old-style POLYLINE',
|
|
26
|
+
INSERT: 'a block (INSERT)',
|
|
27
|
+
HATCH: 'a hatch',
|
|
28
|
+
'3DFACE': 'a 3D face',
|
|
29
|
+
MLINE: 'a multiline',
|
|
30
|
+
REGION: 'a region',
|
|
31
|
+
LEADER: 'a leader',
|
|
32
|
+
};
|
|
20
33
|
const IGNORED = new Set(['TEXT', 'MTEXT', 'DIMENSION', 'POINT', 'ATTDEF', 'ATTRIB', 'VIEWPORT']);
|
|
21
34
|
const UNITS = { 0: 1, 4: 1, 1: 25.4, 5: 10, 6: 1000 }; // $INSUNITS: unitless and mm as they are, inches, cm, m
|
|
22
35
|
|
|
@@ -26,97 +39,269 @@ const UNITS = { 0: 1, 4: 1, 1: 25.4, 5: 10, 6: 1000 }; // $INSUNITS: unitless an
|
|
|
26
39
|
* one would put a wrong outline in a rule set. @param {string} text @returns {{ loops: number[][][], notes: string[] }}
|
|
27
40
|
*/
|
|
28
41
|
export function readDxf(text, { chord = 0.002 } = {}) {
|
|
29
|
-
const lines = String(text).split(/\r?\n/),
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
42
|
+
const lines = String(text).split(/\r?\n/),
|
|
43
|
+
pairs = [];
|
|
44
|
+
for (let i = 0; i + 1 < lines.length; i += 2) {
|
|
45
|
+
const code = Number(lines[i].trim());
|
|
46
|
+
if (!Number.isInteger(code))
|
|
47
|
+
throw new Error(
|
|
48
|
+
`not a DXF: line ${i + 1} should be a group code (a whole number), and is ${JSON.stringify(lines[i].slice(0, 30))}`,
|
|
49
|
+
);
|
|
50
|
+
pairs.push([code, lines[i + 1].trim()]);
|
|
51
|
+
}
|
|
52
|
+
if (!pairs.some(([c, v]) => c === 0 && v === 'SECTION'))
|
|
53
|
+
throw new Error('not a DXF: it has no SECTION (an ASCII DXF is wanted, not a binary one or a DWG)');
|
|
54
|
+
let scale = 1;
|
|
55
|
+
const notes = [];
|
|
33
56
|
const units = pairs.findIndex(([c, v]) => c === 9 && v === '$INSUNITS');
|
|
34
|
-
if (units >= 0) {
|
|
35
|
-
|
|
57
|
+
if (units >= 0) {
|
|
58
|
+
const u = Number(pairs[units + 1]?.[1]);
|
|
59
|
+
if (!(u in UNITS))
|
|
60
|
+
throw new Error(
|
|
61
|
+
`the DXF's units ($INSUNITS ${u}) are not ones this reads: millimetres (4), inches (1), centimetres (5), metres (6) or none (taken as mm)`,
|
|
62
|
+
);
|
|
63
|
+
scale = UNITS[u];
|
|
64
|
+
if (scale !== 1) notes.push(`its units are ${{ 1: 'inches', 5: 'centimetres', 6: 'metres' }[u]}: turned into mm`);
|
|
65
|
+
} else notes.push('it names no units ($INSUNITS): taken as mm');
|
|
36
66
|
const start = pairs.findIndex(([c, v], i) => c === 2 && v === 'ENTITIES' && pairs[i - 1]?.[1] === 'SECTION');
|
|
37
67
|
if (start < 0) throw new Error('the DXF has no ENTITIES section: nothing is drawn in it');
|
|
38
|
-
const entities = [];
|
|
39
|
-
|
|
40
|
-
|
|
68
|
+
const entities = [];
|
|
69
|
+
let cur = null;
|
|
70
|
+
for (let i = start + 1; i < pairs.length; i++) {
|
|
71
|
+
const [c, v] = pairs[i];
|
|
72
|
+
if (c === 0) {
|
|
73
|
+
if (v === 'ENDSEC') break;
|
|
74
|
+
cur = { type: v, codes: [] };
|
|
75
|
+
entities.push(cur);
|
|
76
|
+
} else if (cur) cur.codes.push([c, v]);
|
|
77
|
+
}
|
|
78
|
+
const segs = [],
|
|
79
|
+
closed = [],
|
|
80
|
+
passed = new Map();
|
|
41
81
|
// an arc as chords that stay within `chord` mm of it; a model's circle is likewise facets with their corners on it
|
|
42
|
-
const arc = (cx, cy, r, a0, sweep) => {
|
|
43
|
-
|
|
82
|
+
const arc = (cx, cy, r, a0, sweep) => {
|
|
83
|
+
const c = chord / scale,
|
|
84
|
+
n = Math.max(2, Math.ceil(Math.abs(sweep) / (2 * Math.acos(Math.max(0, 1 - c / Math.max(r, c))))));
|
|
85
|
+
return Array.from({ length: n + 1 }, (_, k) => [
|
|
86
|
+
cx + r * Math.cos(a0 + (sweep * k) / n),
|
|
87
|
+
cy + r * Math.sin(a0 + (sweep * k) / n),
|
|
88
|
+
]);
|
|
89
|
+
};
|
|
90
|
+
const bulged = (p, q, b) => {
|
|
91
|
+
// the arc from p to q that a polyline's bulge asks for: b is tan of a quarter of its angle
|
|
44
92
|
if (!b) return [p, q];
|
|
45
|
-
const dx = q[0] - p[0],
|
|
46
|
-
|
|
47
|
-
|
|
93
|
+
const dx = q[0] - p[0],
|
|
94
|
+
dy = q[1] - p[1],
|
|
95
|
+
c = Math.hypot(dx, dy);
|
|
96
|
+
if (!c) return [p];
|
|
97
|
+
const d = ((c / 2) * (1 - b * b)) / (2 * b),
|
|
98
|
+
cx = (p[0] + q[0]) / 2 - (dy / c) * d,
|
|
99
|
+
cy = (p[1] + q[1]) / 2 + (dx / c) * d;
|
|
100
|
+
const pts = arc(cx, cy, Math.hypot(p[0] - cx, p[1] - cy), Math.atan2(p[1] - cy, p[0] - cx), 4 * Math.atan(b));
|
|
101
|
+
pts[0] = p;
|
|
102
|
+
pts[pts.length - 1] = q;
|
|
103
|
+
return pts;
|
|
48
104
|
};
|
|
49
105
|
for (const e of entities) {
|
|
50
|
-
const g = (code) => {
|
|
51
|
-
|
|
52
|
-
|
|
106
|
+
const g = (code) => {
|
|
107
|
+
const x = e.codes.find(([c]) => c === code);
|
|
108
|
+
return x ? Number(x[1]) : undefined;
|
|
109
|
+
},
|
|
110
|
+
all = (code) => e.codes.filter(([c]) => c === code).map(([, v]) => Number(v));
|
|
111
|
+
if (REFUSED[e.type])
|
|
112
|
+
throw new Error(
|
|
113
|
+
`the DXF has ${REFUSED[e.type]} (${e.type}), which this does not read: export the section as lines, arcs and polylines (most CAD programs can "explode" or "convert to polyline"), and measure that`,
|
|
114
|
+
);
|
|
115
|
+
if (e.type === 'LINE')
|
|
116
|
+
segs.push([
|
|
117
|
+
[g(10), g(20)],
|
|
118
|
+
[g(11), g(21)],
|
|
119
|
+
]);
|
|
53
120
|
else if (e.type === 'CIRCLE') closed.push(arc(g(10), g(20), g(40), 0, 2 * Math.PI).slice(0, -1));
|
|
54
|
-
else if (e.type === 'ARC') {
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
121
|
+
else if (e.type === 'ARC') {
|
|
122
|
+
const a0 = g(50) * RAD;
|
|
123
|
+
let sweep = (g(51) - g(50)) * RAD;
|
|
124
|
+
while (sweep <= 0) sweep += 2 * Math.PI;
|
|
125
|
+
const pts = arc(g(10), g(20), g(40), a0, sweep);
|
|
126
|
+
for (let k = 0; k + 1 < pts.length; k++) segs.push([pts[k], pts[k + 1]]);
|
|
127
|
+
} else if (e.type === 'LWPOLYLINE') {
|
|
128
|
+
const pts = [],
|
|
129
|
+
isClosed = ((g(70) ?? 0) & 1) === 1;
|
|
130
|
+
let b = null;
|
|
131
|
+
for (const [c, v] of e.codes) {
|
|
132
|
+
if (c === 10) {
|
|
133
|
+
pts.push({ p: [Number(v), 0], b: 0 });
|
|
134
|
+
b = pts[pts.length - 1];
|
|
135
|
+
} else if (c === 20 && b) b.p[1] = Number(v);
|
|
136
|
+
else if (c === 42 && b) b.b = Number(v);
|
|
137
|
+
}
|
|
58
138
|
const out = [];
|
|
59
|
-
for (let k = 0; k < pts.length - (isClosed ? 0 : 1); k++) {
|
|
60
|
-
|
|
139
|
+
for (let k = 0; k < pts.length - (isClosed ? 0 : 1); k++) {
|
|
140
|
+
const run = bulged(pts[k].p, pts[(k + 1) % pts.length].p, pts[k].b);
|
|
141
|
+
out.push(...run.slice(0, -1));
|
|
142
|
+
if (!isClosed && k === pts.length - 2) out.push(run[run.length - 1]);
|
|
143
|
+
}
|
|
144
|
+
if (isClosed) closed.push(out);
|
|
145
|
+
else for (let k = 0; k + 1 < out.length; k++) segs.push([out[k], out[k + 1]]);
|
|
61
146
|
} else if (IGNORED.has(e.type)) passed.set(e.type, (passed.get(e.type) || 0) + 1);
|
|
62
|
-
else
|
|
63
|
-
|
|
147
|
+
else
|
|
148
|
+
throw new Error(
|
|
149
|
+
`the DXF has a ${e.type}, which this does not read: a section is LINE, LWPOLYLINE, ARC and CIRCLE entities`,
|
|
150
|
+
);
|
|
151
|
+
if ([...all(10), ...all(20)].some((x) => !Number.isFinite(x)))
|
|
152
|
+
throw new Error(`the DXF's ${e.type} has a coordinate that is not a number`);
|
|
64
153
|
}
|
|
65
154
|
if (passed.size) notes.push(`passed over: ${[...passed].map(([t, n]) => `${n} ${t}`).join(', ')}`);
|
|
66
155
|
// lines and arcs drawn one by one: joined end to end into loops, which must close
|
|
67
156
|
for (const line of chain(segs, 1e-3)) {
|
|
68
157
|
const gap = Math.hypot(line[0][0] - line[line.length - 1][0], line[0][1] - line[line.length - 1][1]);
|
|
69
|
-
if (gap > 0.01)
|
|
158
|
+
if (gap > 0.01)
|
|
159
|
+
throw new Error(
|
|
160
|
+
`the DXF's outline is not closed: a run of ${line.length - 1} lines and arcs ends ${f2(gap * scale)} mm from where it starts, at ${f2(line[line.length - 1][0] * scale)}, ${f2(line[line.length - 1][1] * scale)}. Close the gap (or delete the stray line) and measure again`,
|
|
161
|
+
);
|
|
70
162
|
closed.push(line.slice(0, -1));
|
|
71
163
|
}
|
|
72
|
-
if (!closed.length)
|
|
164
|
+
if (!closed.length)
|
|
165
|
+
throw new Error('the DXF has no outline: no LINE, LWPOLYLINE, ARC or CIRCLE in its ENTITIES section');
|
|
73
166
|
return { loops: closed.map((l) => l.map(([x, y]) => [x * scale, y * scale])), notes };
|
|
74
167
|
}
|
|
75
168
|
|
|
76
169
|
// ---------- the section of a model ----------
|
|
77
170
|
// The loops of the longest stretch of a mesh that keeps one cross-section
|
|
78
171
|
function meshSection(file, along) {
|
|
79
|
-
const tris = readMesh(file),
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
const
|
|
83
|
-
|
|
84
|
-
|
|
172
|
+
const tris = readMesh(file),
|
|
173
|
+
B = bounds(tris),
|
|
174
|
+
axis = along ? axisOf(along) : B.size.indexOf(Math.max(...B.size));
|
|
175
|
+
const runs = profiles(tris, axis)
|
|
176
|
+
.filter((r) => !r.varies && !r.empty)
|
|
177
|
+
.sort((a, b) => b.to - b.from - (a.to - a.from));
|
|
178
|
+
if (!runs.length)
|
|
179
|
+
throw new Error(
|
|
180
|
+
`${path.basename(file)} has no stretch along ${AXES[axis]} that keeps one cross-section: a beam's profile is measured where its section is constant (--along x|y|z picks another axis)`,
|
|
181
|
+
);
|
|
182
|
+
const run = runs[0],
|
|
183
|
+
lines = chain(section(tris, axis, run.at));
|
|
184
|
+
for (const l of lines)
|
|
185
|
+
if (Math.hypot(l[0][0] - l[l.length - 1][0], l[0][1] - l[l.length - 1][1]) > 1e-3)
|
|
186
|
+
throw new Error(
|
|
187
|
+
`${path.basename(file)}: its section at ${AXES[axis]} = ${f2(run.at)} is not closed outlines (the mesh has open edges there)`,
|
|
188
|
+
);
|
|
189
|
+
return {
|
|
190
|
+
loops: lines.map((l) => l.slice(0, -1)),
|
|
191
|
+
says: `the section across ${AXES[axis]} at ${f2(run.at)}, the middle of a stretch of ${f2(run.to - run.from)} mm that keeps it (of ${f2(B.size[axis])} mm)`,
|
|
192
|
+
length: run.to - run.from,
|
|
193
|
+
};
|
|
85
194
|
}
|
|
86
195
|
|
|
87
196
|
// Loops tidied: no point twice, no point in the middle of a straight run, nothing with no area; about the middle of
|
|
88
197
|
// the envelope, lying flat (wider than high), the outside counter-clockwise and holes clockwise
|
|
89
198
|
export function tidy(loops) {
|
|
90
|
-
let out = loops
|
|
199
|
+
let out = loops
|
|
200
|
+
.map((l) => {
|
|
201
|
+
const p = l.filter((q, i) => {
|
|
202
|
+
const n = l[(i + 1) % l.length];
|
|
203
|
+
return Math.hypot(q[0] - n[0], q[1] - n[1]) > 1e-6;
|
|
204
|
+
});
|
|
205
|
+
return p.filter((q, i) => {
|
|
206
|
+
const a = p[(i + p.length - 1) % p.length],
|
|
207
|
+
b = p[(i + 1) % p.length];
|
|
208
|
+
return (
|
|
209
|
+
Math.abs((q[0] - a[0]) * (b[1] - a[1]) - (q[1] - a[1]) * (b[0] - a[0])) >
|
|
210
|
+
1e-7 * (1 + Math.hypot(b[0] - a[0], b[1] - a[1]))
|
|
211
|
+
);
|
|
212
|
+
});
|
|
213
|
+
})
|
|
214
|
+
.filter((l) => l.length >= 3 && Math.abs(signedArea(l)) > 1e-6);
|
|
91
215
|
if (!out.length) throw new Error('the section has no outline with any area');
|
|
92
|
-
const xs = out.flat().map((p) => p[0]),
|
|
93
|
-
|
|
94
|
-
|
|
216
|
+
const xs = out.flat().map((p) => p[0]),
|
|
217
|
+
ys = out.flat().map((p) => p[1]),
|
|
218
|
+
cx = (Math.min(...xs) + Math.max(...xs)) / 2,
|
|
219
|
+
cy = (Math.min(...ys) + Math.max(...ys)) / 2;
|
|
220
|
+
let turned = false;
|
|
221
|
+
out = out.map((l) => l.map(([x, y]) => [x - cx, y - cy]));
|
|
222
|
+
if (Math.max(...ys) - Math.min(...ys) > Math.max(...xs) - Math.min(...xs) + 1e-6) {
|
|
223
|
+
out = out.map((l) => l.map(([x, y]) => [y, -x]));
|
|
224
|
+
turned = true;
|
|
225
|
+
}
|
|
95
226
|
out.sort((a, b) => Math.abs(signedArea(b)) - Math.abs(signedArea(a)));
|
|
96
|
-
const inside = ([x, y], loop) => {
|
|
97
|
-
|
|
227
|
+
const inside = ([x, y], loop) => {
|
|
228
|
+
let inn = false;
|
|
229
|
+
for (let i = 0, n = loop.length; i < n; i++) {
|
|
230
|
+
const [ax, ay] = loop[i],
|
|
231
|
+
[bx, by] = loop[(i + 1) % n];
|
|
232
|
+
if (ay > y !== by > y && x < ax + ((y - ay) * (bx - ax)) / (by - ay)) inn = !inn;
|
|
233
|
+
}
|
|
234
|
+
return inn;
|
|
235
|
+
};
|
|
236
|
+
out = out.map((l, i) => {
|
|
237
|
+
const depth = out.filter((o, j) => j !== i && inside(l[0], o)).length;
|
|
238
|
+
return (depth % 2 === 0) === signedArea(l) > 0 ? l : l.slice().reverse();
|
|
239
|
+
});
|
|
98
240
|
return { loops: out.map((l) => l.map(([x, y]) => [+x.toFixed(4), +y.toFixed(4)])), turned };
|
|
99
241
|
}
|
|
100
242
|
|
|
101
243
|
// ---------- what a section has ----------
|
|
102
|
-
const FACES = {
|
|
244
|
+
const FACES = {
|
|
245
|
+
top: { n: [0, 1], a: [1, 0] },
|
|
246
|
+
bottom: { n: [0, -1], a: [1, 0] },
|
|
247
|
+
front: { n: [-1, 0], a: [0, 1] },
|
|
248
|
+
back: { n: [1, 0], a: [0, 1] },
|
|
249
|
+
};
|
|
103
250
|
|
|
104
251
|
// One slot from its run of the outline in face coordinates [u along the face, v below it], mouth to mouth
|
|
105
252
|
function slotOf(run) {
|
|
106
|
-
const D = Math.max(...run.map((p) => p[1])),
|
|
107
|
-
|
|
108
|
-
|
|
253
|
+
const D = Math.max(...run.map((p) => p[1])),
|
|
254
|
+
n = 600,
|
|
255
|
+
step = D / n,
|
|
256
|
+
mouth = Math.abs(run[run.length - 1][0] - run[0][0]),
|
|
257
|
+
centre = (run[0][0] + run[run.length - 1][0]) / 2;
|
|
258
|
+
const width = (v) => {
|
|
259
|
+
let lo = Infinity,
|
|
260
|
+
hi = -Infinity;
|
|
261
|
+
for (let i = 0; i + 1 < run.length; i++) {
|
|
262
|
+
const [a, b] = [run[i], run[i + 1]];
|
|
263
|
+
if ((a[1] <= v && b[1] > v) || (b[1] <= v && a[1] > v)) {
|
|
264
|
+
const u = a[0] + ((v - a[1]) * (b[0] - a[0])) / (b[1] - a[1]);
|
|
265
|
+
lo = Math.min(lo, u);
|
|
266
|
+
hi = Math.max(hi, u);
|
|
267
|
+
}
|
|
268
|
+
}
|
|
269
|
+
return hi - lo;
|
|
270
|
+
};
|
|
271
|
+
const w = Array.from({ length: n }, (_, k) => width((k + 0.5) * step)),
|
|
272
|
+
widest = Math.max(...w);
|
|
109
273
|
// the neck: from the face down to where the width jumps toward the cavity's
|
|
110
|
-
let least = w[0],
|
|
111
|
-
|
|
274
|
+
let least = w[0],
|
|
275
|
+
neck = -1;
|
|
276
|
+
for (let k = 0; k < n; k++) {
|
|
277
|
+
least = Math.min(least, w[k]);
|
|
278
|
+
if (widest - least > 0.2 && w[k] > least + 0.5 * (widest - least)) {
|
|
279
|
+
neck = k;
|
|
280
|
+
break;
|
|
281
|
+
}
|
|
282
|
+
}
|
|
112
283
|
if (neck < 0) return { kind: 'groove', centre, mouth, depth: D }; // no wider below than at its mouth: a groove, not a slot for a nut
|
|
113
284
|
const opening = Math.min(...w.slice(0, neck));
|
|
114
|
-
let tip = 0;
|
|
285
|
+
let tip = 0;
|
|
286
|
+
for (let k = 0; k < neck; k++) if (w[k] <= opening + 0.05) tip = k; // the last depth still at the opening: the lip's tip
|
|
115
287
|
const lip = (tip + 1) * step;
|
|
116
|
-
let straight = neck;
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
288
|
+
let straight = neck;
|
|
289
|
+
for (let k = neck; k < n; k++) if (w[k] >= widest - 0.05) straight = k;
|
|
290
|
+
const floor = w[n - 1],
|
|
291
|
+
out = { kind: 'slot', centre, mouth, opening, lip, cavityWidth: widest, cavityDepth: D, floorWidth: floor };
|
|
292
|
+
if (floor < widest - 0.1) {
|
|
293
|
+
out.flankAngle = Math.atan2(D - (straight + 1) * step, (widest - floor) / 2) / RAD;
|
|
294
|
+
if (!(out.flankAngle > 1)) {
|
|
295
|
+
delete out.flankAngle;
|
|
296
|
+
out.floorWidth = widest;
|
|
297
|
+
}
|
|
298
|
+
} else out.floorWidth = widest;
|
|
299
|
+
if (mouth > opening + 0.2) {
|
|
300
|
+
let k = 0;
|
|
301
|
+
while (k < neck && w[k] > opening + 0.05) k++;
|
|
302
|
+
out.trackWidth = mouth;
|
|
303
|
+
out.trackAngle = (2 * Math.atan2((mouth - opening) / 2, Math.max(k * step, step))) / RAD;
|
|
304
|
+
}
|
|
120
305
|
return out;
|
|
121
306
|
}
|
|
122
307
|
|
|
@@ -126,66 +311,142 @@ function slotOf(run) {
|
|
|
126
311
|
* @param {number[][][]} loops the outside first (counter-clockwise), then holes
|
|
127
312
|
*/
|
|
128
313
|
export function findFeatures(loops) {
|
|
129
|
-
const outer = loops[0],
|
|
314
|
+
const outer = loops[0],
|
|
315
|
+
xs = outer.map((p) => p[0]),
|
|
316
|
+
ys = outer.map((p) => p[1]),
|
|
317
|
+
W = Math.max(...xs) - Math.min(...xs),
|
|
318
|
+
H = Math.max(...ys) - Math.min(...ys),
|
|
319
|
+
on = 0.25;
|
|
130
320
|
const faces = {};
|
|
131
321
|
for (const [face, { n, a }] of Object.entries(FACES)) {
|
|
132
|
-
const half = n[0] ? W / 2 : H / 2,
|
|
322
|
+
const half = n[0] ? W / 2 : H / 2,
|
|
323
|
+
across = n[0] ? H : W,
|
|
324
|
+
uv = outer.map(([x, y]) => [x * a[0] + y * a[1], half - (x * n[0] + y * n[1])]),
|
|
325
|
+
N = uv.length,
|
|
326
|
+
found = [];
|
|
133
327
|
const start = uv.findIndex((p, i) => p[1] <= on && uv[(i + 1) % N][1] > on);
|
|
134
|
-
if (start >= 0)
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
328
|
+
if (start >= 0)
|
|
329
|
+
for (let i = 0; i < N; i++) {
|
|
330
|
+
const k = (start + i) % N;
|
|
331
|
+
if (!(uv[k][1] <= on && uv[(k + 1) % N][1] > on)) continue;
|
|
332
|
+
const run = [uv[k]];
|
|
333
|
+
let j = (k + 1) % N;
|
|
334
|
+
while (uv[j][1] > on && run.length <= N) {
|
|
335
|
+
run.push(uv[j]);
|
|
336
|
+
j = (j + 1) % N;
|
|
337
|
+
}
|
|
338
|
+
run.push(uv[j]);
|
|
339
|
+
const deep = Math.max(...run.map((p) => p[1])),
|
|
340
|
+
wide = Math.max(...run.map((p) => p[0])) - Math.min(...run.map((p) => p[0]));
|
|
341
|
+
if (deep >= (n[0] ? W : H) - on || wide > across * 0.9 || deep < 0.5) continue; // round a corner to another face, or a scratch
|
|
342
|
+
const s = slotOf(run[0][0] <= run[run.length - 1][0] ? run : run.slice().reverse());
|
|
343
|
+
found.push({ ...s, face, at: [a[0] * s.centre + n[0] * half, a[1] * s.centre + n[1] * half] });
|
|
344
|
+
}
|
|
142
345
|
faces[face] = found.sort((p, q) => p.centre - q.centre);
|
|
143
346
|
}
|
|
144
|
-
const bores = [],
|
|
347
|
+
const bores = [],
|
|
348
|
+
hollows = [];
|
|
145
349
|
for (const l of loops.slice(1)) {
|
|
146
|
-
const p = polygonSection([l.slice().reverse()]),
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
350
|
+
const p = polygonSection([l.slice().reverse()]),
|
|
351
|
+
c = p.centroid,
|
|
352
|
+
rs = l.map(([x, y]) => Math.hypot(x - c[0], y - c[1])),
|
|
353
|
+
mean = rs.reduce((s, r) => s + r, 0) / rs.length;
|
|
354
|
+
const bx = l.map((q) => q[0]),
|
|
355
|
+
by = l.map((q) => q[1]);
|
|
356
|
+
if (Math.max(...rs) - Math.min(...rs) < 0.03 * mean + 0.03)
|
|
357
|
+
bores.push({ at: [r2(c[0]), r2(c[1])], diameter: 2 * mean });
|
|
358
|
+
else
|
|
359
|
+
hollows.push({
|
|
360
|
+
at: [r2(c[0]), r2(c[1])],
|
|
361
|
+
width: Math.max(...bx) - Math.min(...bx),
|
|
362
|
+
height: Math.max(...by) - Math.min(...by),
|
|
363
|
+
area: p.area,
|
|
364
|
+
});
|
|
150
365
|
}
|
|
151
366
|
return { width: W, height: H, faces, bores, hollows, area: polygonSection(loops).area };
|
|
152
367
|
}
|
|
153
368
|
|
|
154
369
|
// ---------- slots against the families there are ----------
|
|
155
|
-
const DIMS = [
|
|
156
|
-
|
|
370
|
+
const DIMS = [
|
|
371
|
+
['opening', 'opening'],
|
|
372
|
+
['lip_thickness', 'lip'],
|
|
373
|
+
['cavity_width', 'cavityWidth'],
|
|
374
|
+
['cavity_depth', 'cavityDepth'],
|
|
375
|
+
];
|
|
376
|
+
function allSets() {
|
|
377
|
+
// every rule set by name, the workspace's own first
|
|
157
378
|
const found = new Map();
|
|
158
|
-
for (const d of RULE_DIRS)
|
|
379
|
+
for (const d of RULE_DIRS)
|
|
380
|
+
if (fs.existsSync(d))
|
|
381
|
+
for (const f of fs.readdirSync(d).sort())
|
|
382
|
+
if (f.endsWith('.json') && !['package.json', 'vocabulary.json'].includes(f) && !found.has(f.slice(0, -5)))
|
|
383
|
+
found.set(f.slice(0, -5), path.join(d, f));
|
|
159
384
|
return found;
|
|
160
385
|
}
|
|
161
386
|
/** The slot family nearest a measured slot, and how far off its worst figure is: { name, off } or null where there is none */
|
|
162
387
|
export function nearestFamily(slot, families) {
|
|
163
388
|
let best = null;
|
|
164
|
-
for (const [name, set] of Object.entries(families)) {
|
|
389
|
+
for (const [name, set] of Object.entries(families)) {
|
|
390
|
+
const off = Math.max(...DIMS.map(([rule, k]) => Math.abs((set.rules[rule]?.value ?? Infinity) - slot[k])));
|
|
391
|
+
if (!best || off < best.off) best = { name, off };
|
|
392
|
+
}
|
|
165
393
|
return best;
|
|
166
394
|
}
|
|
167
395
|
|
|
168
396
|
// ---------- the drawing ----------
|
|
169
397
|
function drawingSvg({ name, file, loops, feat, groups, bores, source, licence }) {
|
|
170
|
-
const W = feat.width,
|
|
398
|
+
const W = feat.width,
|
|
399
|
+
H = feat.height,
|
|
400
|
+
S = Math.min(22, 560 / Math.max(W, H)),
|
|
401
|
+
pad = 150,
|
|
402
|
+
w = W * S + 2 * pad,
|
|
403
|
+
top = 110,
|
|
404
|
+
X = (x) => pad + (x + W / 2) * S,
|
|
405
|
+
Y = (y) => top + (H / 2 - y) * S;
|
|
171
406
|
const esc = (t) => String(t).replace(/[&<>]/g, (c) => ({ '&': '&', '<': '<', '>': '>' })[c]);
|
|
172
407
|
const d = loops.map((l) => `M ${l.map(([x, y]) => `${X(x).toFixed(2)} ${Y(y).toFixed(2)}`).join(' L ')} Z`).join(' ');
|
|
173
408
|
let body = `<path d="${d}" fill="#c4c8cc" fill-rule="evenodd" stroke="#1a1a1a" stroke-width="1.2" stroke-linejoin="round"/>`;
|
|
174
|
-
const text = (x, y, t, anchor = 'start', size = 13, weight = 400) => {
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
}
|
|
181
|
-
|
|
182
|
-
|
|
409
|
+
const text = (x, y, t, anchor = 'start', size = 13, weight = 400) => {
|
|
410
|
+
body += `<text x="${x.toFixed(1)}" y="${y.toFixed(1)}" text-anchor="${anchor}" font-size="${size}" font-weight="${weight}">${esc(t)}</text>`;
|
|
411
|
+
};
|
|
412
|
+
body += `<line x1="${X(-W / 2)}" y1="${Y(-H / 2) + 46}" x2="${X(W / 2)}" y2="${Y(-H / 2) + 46}" stroke="#666"/>`;
|
|
413
|
+
text(X(0), Y(-H / 2) + 64, `${f2(W)}`, 'middle');
|
|
414
|
+
body += `<line x1="${X(-W / 2) - 46}" y1="${Y(H / 2)}" x2="${X(-W / 2) - 46}" y2="${Y(-H / 2)}" stroke="#666"/>`;
|
|
415
|
+
text(X(-W / 2) - 52, Y(0) + 4, `${f2(H)}`, 'end');
|
|
416
|
+
for (const [face, list] of Object.entries(feat.faces))
|
|
417
|
+
for (const s of list) {
|
|
418
|
+
const n = FACES[face].n,
|
|
419
|
+
x = X(s.at[0]) + n[0] * 22,
|
|
420
|
+
y = Y(s.at[1]) - n[1] * 22 + 5;
|
|
421
|
+
body += `<circle cx="${x}" cy="${y - 5}" r="11" fill="#fff" stroke="#b0412e" stroke-width="1.4"/>`;
|
|
422
|
+
text(x, y, s.kind === 'slot' ? s.letter : '~', 'middle', 13, 600);
|
|
423
|
+
}
|
|
424
|
+
bores.forEach((b, i) => {
|
|
425
|
+
body += `<circle cx="${X(b.at[0])}" cy="${Y(b.at[1])}" r="${(b.diameter / 2) * S + 4}" fill="none" stroke="#2e6db0" stroke-width="1.4" stroke-dasharray="4 3"/>`;
|
|
426
|
+
text(X(b.at[0]) + (b.diameter / 2) * S + 8, Y(b.at[1]) - (b.diameter / 2) * S - 4, `${i + 1}`, 'start', 12, 600);
|
|
427
|
+
});
|
|
428
|
+
let y = Y(-H / 2) + 104;
|
|
429
|
+
const line = (t, weight) => {
|
|
430
|
+
text(40, y, t, 'start', 13, weight);
|
|
431
|
+
y += 19;
|
|
432
|
+
};
|
|
183
433
|
line('What was found (check each against the bar in hand):', 600);
|
|
184
|
-
for (const g of groups)
|
|
185
|
-
|
|
186
|
-
|
|
434
|
+
for (const g of groups)
|
|
435
|
+
line(
|
|
436
|
+
`${g.letter} × ${g.count} on ${g.faces.join(', ')}: opening ${f2(g.opening)}, lip ${f2(g.lip)}, ${f2(g.cavityWidth)} under the lips, ${f2(g.cavityDepth)} deep${g.trackWidth ? `, V mouth ${f2(g.trackWidth)} at ${f2(g.trackAngle)}°` : ''}: ${g.family ? `${g.drafted ? 'no family fits, drafted as' : 'matches'} ${g.family}${g.drafted ? '' : ` (within ${f2(g.off)} mm)`}` : ''}`,
|
|
437
|
+
);
|
|
438
|
+
const grooves = Object.values(feat.faces)
|
|
439
|
+
.flat()
|
|
440
|
+
.filter((s) => s.kind === 'groove');
|
|
441
|
+
for (const g of grooves)
|
|
442
|
+
line(
|
|
443
|
+
`~ ${g.face}: an opening ${f2(g.mouth)} wide and ${f2(g.depth)} deep with no room under lips: not a slot for a nut (what is inside it is in the outline only)`,
|
|
444
|
+
);
|
|
187
445
|
bores.forEach((b, i) => line(`${i + 1} bore Ø${f2(b.diameter)} at ${f2(b.at[0])}, ${f2(b.at[1])}`));
|
|
188
|
-
if (feat.hollows.length)
|
|
446
|
+
if (feat.hollows.length)
|
|
447
|
+
line(
|
|
448
|
+
`${feat.hollows.length} other hollow${feat.hollows.length === 1 ? '' : 's'} (${feat.hollows.map((h) => `${f2(h.width)} × ${f2(h.height)}`).join(', ')}): kept in the outline, not in the rules`,
|
|
449
|
+
);
|
|
189
450
|
line(`area of the section ${f2(feat.area)} mm²`);
|
|
190
451
|
const h = y + 20;
|
|
191
452
|
return `<svg xmlns="http://www.w3.org/2000/svg" width="${Math.max(w, 1080).toFixed(0)}" height="${h.toFixed(0)}" viewBox="0 0 ${Math.max(w, 1080).toFixed(0)} ${h.toFixed(0)}" font-family="-apple-system, Helvetica, Arial, sans-serif" fill="#1a1a1a"><rect width="100%" height="100%" fill="#fff"/>
|
|
@@ -199,80 +460,262 @@ function drawingSvg({ name, file, loops, feat, groups, bores, source, licence })
|
|
|
199
460
|
*/
|
|
200
461
|
export async function measureProfile(file, o = {}) {
|
|
201
462
|
const name = String(o.profile);
|
|
202
|
-
if (!/^[a-z][a-z0-9_-]*$/.test(name))
|
|
463
|
+
if (!/^[a-z][a-z0-9_-]*$/.test(name))
|
|
464
|
+
throw new Error('--profile <name>: lower case, digits, - and _ (a rule set name, like profile-2020-mine)');
|
|
203
465
|
if (!fs.existsSync(file)) throw new Error(`no file ${file}`);
|
|
204
|
-
const ext = path.extname(file).toLowerCase(),
|
|
466
|
+
const ext = path.extname(file).toLowerCase(),
|
|
467
|
+
tol = o.tol == null ? 0.1 : Number(o.tol);
|
|
205
468
|
if (!(tol > 0)) throw new Error(`--tol is how close a slot must be to a known family, in mm, above 0 (got ${o.tol})`);
|
|
206
|
-
if (!['.stl', '.3mf', '.dxf'].includes(ext))
|
|
207
|
-
|
|
469
|
+
if (!['.stl', '.3mf', '.dxf'].includes(ext))
|
|
470
|
+
throw new Error(
|
|
471
|
+
`${path.basename(file)}: a profile is measured from an STL or 3MF model of the beam, or a DXF of its section (not ${ext || 'a file with no extension'})`,
|
|
472
|
+
);
|
|
473
|
+
const rulesDir = path.join(WS, 'rules'),
|
|
474
|
+
to = path.join(rulesDir, `${name}.json`),
|
|
475
|
+
outlineTo = path.join(rulesDir, 'outlines', `${name}.json`);
|
|
208
476
|
// the kit holds no maker's outline: this writes to a workspace, never into the published rules
|
|
209
477
|
const kit = path.dirname(fileURLToPath(import.meta.resolve('@rulecad/rules/vocabulary.json')));
|
|
210
|
-
if (fs.realpathSync(fs.existsSync(rulesDir) ? rulesDir : WS).startsWith(fs.realpathSync(kit)))
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
478
|
+
if (fs.realpathSync(fs.existsSync(rulesDir) ? rulesDir : WS).startsWith(fs.realpathSync(kit)))
|
|
479
|
+
throw new Error(
|
|
480
|
+
"this is the kit's own rules folder: a measured outline goes into a workspace of your own, never into the kit",
|
|
481
|
+
);
|
|
482
|
+
if ((fs.existsSync(to) || fs.existsSync(outlineTo)) && !o.force)
|
|
483
|
+
throw new Error(`rules/${name}.json or its outline already exists (--force to replace them)`);
|
|
484
|
+
const read =
|
|
485
|
+
ext === '.dxf'
|
|
486
|
+
? { ...readDxf(fs.readFileSync(file, 'utf8')), says: "the DXF's outline" }
|
|
487
|
+
: meshSection(file, o.along);
|
|
488
|
+
const { loops, turned } = tidy(read.loops),
|
|
489
|
+
feat = findFeatures(loops),
|
|
490
|
+
source = o.source || path.basename(file),
|
|
491
|
+
stamp = today();
|
|
214
492
|
console.log(`${path.basename(file)}: ${read.says}${turned ? ', turned a quarter turn to lie flat' : ''}`);
|
|
215
493
|
for (const n of read.notes || []) console.log(` ${n}`);
|
|
216
|
-
if (o.licence && limitingLicence(o.licence))
|
|
217
|
-
|
|
494
|
+
if (o.licence && limitingLicence(o.licence))
|
|
495
|
+
console.log(
|
|
496
|
+
` ! licence "${o.licence}" limits reuse: measurements are facts, but the outline is the model's shape. Keep it in this workspace, and don't publish it or build it into a design under another licence`,
|
|
497
|
+
);
|
|
498
|
+
console.log(
|
|
499
|
+
` ${f2(feat.width)} × ${f2(feat.height)} mm, ${loops.length - 1} hole${loops.length === 2 ? '' : 's'}, area ${f2(feat.area)} mm²`,
|
|
500
|
+
);
|
|
218
501
|
// ---- slots: alike ones grouped, each group matched to a family or drafted as a new one ----
|
|
219
|
-
const sets = allSets(),
|
|
220
|
-
|
|
502
|
+
const sets = allSets(),
|
|
503
|
+
families = Object.fromEntries([...sets].map(([n, f]) => [n, readJson(f)]).filter(([, s]) => s.part === 'slot'));
|
|
504
|
+
const groups = [],
|
|
505
|
+
found = Object.values(feat.faces)
|
|
506
|
+
.flat()
|
|
507
|
+
.filter((s) => s.kind === 'slot');
|
|
221
508
|
for (const s of found) {
|
|
222
509
|
let g = groups.find((x) => DIMS.every(([, k]) => Math.abs(x[k] - s[k]) <= tol));
|
|
223
|
-
if (!g) {
|
|
224
|
-
|
|
510
|
+
if (!g) {
|
|
511
|
+
g = { ...s, count: 0, faces: [], letter: String.fromCharCode(65 + groups.length) };
|
|
512
|
+
groups.push(g);
|
|
513
|
+
}
|
|
514
|
+
g.count++;
|
|
515
|
+
if (!g.faces.includes(s.face)) g.faces.push(s.face);
|
|
516
|
+
s.letter = g.letter;
|
|
225
517
|
}
|
|
226
|
-
const extra = { kind: 'derived', source, ...(o.licence ? { licence: o.licence } : {}), checked: stamp },
|
|
227
|
-
|
|
518
|
+
const extra = { kind: 'derived', source, ...(o.licence ? { licence: o.licence } : {}), checked: stamp },
|
|
519
|
+
written = [];
|
|
520
|
+
const rule = (value, unit, says) => ({
|
|
521
|
+
value: typeof value === 'number' ? r2(value) : value,
|
|
522
|
+
...(unit != null ? { unit } : {}),
|
|
523
|
+
rule: says,
|
|
524
|
+
...extra,
|
|
525
|
+
});
|
|
228
526
|
const base = name.replace(/^profile-/, '');
|
|
229
527
|
for (const g of groups) {
|
|
230
528
|
const near = nearestFamily(g, families);
|
|
231
|
-
if (near && near.off <= tol) {
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
529
|
+
if (near && near.off <= tol) {
|
|
530
|
+
g.family = near.name;
|
|
531
|
+
g.off = near.off;
|
|
532
|
+
continue;
|
|
533
|
+
}
|
|
534
|
+
g.family = `slot-${Math.max(1, Math.round(g.opening))}-${base}${groups.filter((x) => x.drafted).length ? `-${String.fromCharCode(98 + groups.filter((x) => x.drafted).length - 1)}` : ''}`;
|
|
535
|
+
g.drafted = true;
|
|
536
|
+
g.near = near;
|
|
537
|
+
const rules = {
|
|
538
|
+
opening: rule(g.opening, 'mm', "Between the lips, at their narrowest: measured off the model's section"),
|
|
539
|
+
lip_thickness: rule(
|
|
540
|
+
g.lip,
|
|
541
|
+
'mm',
|
|
542
|
+
"From the face to the underside of the lip at its tip: measured off the model's section",
|
|
543
|
+
),
|
|
544
|
+
cavity_width: rule(g.cavityWidth, 'mm', "Width under the lips, at its widest: measured off the model's section"),
|
|
545
|
+
cavity_depth: rule(
|
|
546
|
+
g.cavityDepth,
|
|
547
|
+
'mm',
|
|
548
|
+
"From the face to the deepest point of the slot: measured off the model's section",
|
|
549
|
+
),
|
|
550
|
+
};
|
|
551
|
+
if (g.flankAngle) {
|
|
552
|
+
rules.floor_width = rule(g.floorWidth, 'mm', "Width of the slot at its floor: measured off the model's section");
|
|
553
|
+
rules.flank_angle = rule(
|
|
554
|
+
g.flankAngle,
|
|
555
|
+
'deg',
|
|
556
|
+
"How steeply the walls close in to the floor, from the face's plane: worked out from where they leave the full width",
|
|
557
|
+
);
|
|
558
|
+
}
|
|
559
|
+
if (g.trackWidth) {
|
|
560
|
+
rules.track_width = rule(
|
|
561
|
+
g.trackWidth,
|
|
562
|
+
'mm',
|
|
563
|
+
"Width of the V mouth at the face: measured off the model's section",
|
|
564
|
+
);
|
|
565
|
+
rules.track_angle = rule(
|
|
566
|
+
g.trackAngle,
|
|
567
|
+
'deg',
|
|
568
|
+
"The angle between the V mouth's two sides: worked out from its width and depth",
|
|
569
|
+
);
|
|
570
|
+
}
|
|
571
|
+
rules.nut_family = rule(
|
|
572
|
+
g.family,
|
|
573
|
+
null,
|
|
574
|
+
`No known slot family is within ${tol} mm of this one${near ? ` (the nearest, ${near.name}, is ${f2(near.off)} mm off in its worst figure)` : ''}: name the family whose nuts it takes once you know`,
|
|
575
|
+
);
|
|
576
|
+
const set = {
|
|
577
|
+
_doc: `A draft slot family, measured from ${path.basename(file)} by cad measure --profile ${name}. kind derived: read off someone else's model, so check it against the real thing.${o.licence ? ` The model's licence: ${o.licence}.` : ''}`,
|
|
578
|
+
name: g.family,
|
|
579
|
+
part: 'slot',
|
|
580
|
+
rules,
|
|
581
|
+
};
|
|
238
582
|
slotModel(set); // (held to sense before it is written)
|
|
239
583
|
written.push([path.join(rulesDir, `${g.family}.json`), set]);
|
|
240
584
|
}
|
|
241
585
|
// ---- the profile's own rules ----
|
|
242
|
-
const count = (f) => feat.faces[f].filter((s) => s.kind === 'slot').length,
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
586
|
+
const count = (f) => feat.faces[f].filter((s) => s.kind === 'slot').length,
|
|
587
|
+
across = Math.max(1, count('top'), count('bottom')),
|
|
588
|
+
up = Math.max(1, count('front'), count('back'));
|
|
589
|
+
const main = groups.slice().sort((a, b) => b.count - a.count)[0],
|
|
590
|
+
family = !groups.length ? 'custom' : groups.some((g) => g.trackWidth) ? 'v-slot' : 't-slot';
|
|
591
|
+
const rules = {
|
|
592
|
+
family: rule(
|
|
593
|
+
family,
|
|
594
|
+
null,
|
|
595
|
+
family === 'custom'
|
|
596
|
+
? 'No slot for a nut was found in the section: it is taken as an outline of its own'
|
|
597
|
+
: family === 'v-slot'
|
|
598
|
+
? 'Slots with a V mouth were found: a rail for wheels'
|
|
599
|
+
: 'Slots with room under their lips were found: a profile for T-nuts',
|
|
600
|
+
),
|
|
601
|
+
};
|
|
602
|
+
if (groups.length) {
|
|
603
|
+
const pitch = Math.min(feat.width / across, feat.height / up);
|
|
604
|
+
rules.series = rule(
|
|
605
|
+
pitch,
|
|
606
|
+
'mm',
|
|
607
|
+
`The size of one cell: ${across} slot${across === 1 ? '' : 's'} along the wide faces and ${up} up the sides`,
|
|
608
|
+
);
|
|
609
|
+
rules.cells_across = rule(across, '', 'Slots found side by side on a wide face');
|
|
610
|
+
rules.cells_up = rule(up, '', 'Slots found one above the other on a side');
|
|
611
|
+
}
|
|
612
|
+
rules.width = rule(feat.width, 'mm', "Across the section's envelope, measured off the model");
|
|
613
|
+
rules.height = rule(feat.height, 'mm', "Up the section's envelope, measured off the model");
|
|
247
614
|
if (main) {
|
|
248
|
-
rules.slot = rule(
|
|
249
|
-
|
|
615
|
+
rules.slot = rule(
|
|
616
|
+
main.family,
|
|
617
|
+
null,
|
|
618
|
+
`The slot found on ${main.faces.join(', ')} (${main.count} in all): ${main.drafted ? 'drafted as a family of its own' : `it matches ${main.family} within ${f2(main.off)} mm`}`,
|
|
619
|
+
);
|
|
620
|
+
for (const f of Object.keys(FACES)) {
|
|
621
|
+
const list = feat.faces[f].filter((s) => s.kind === 'slot'),
|
|
622
|
+
n = f === 'top' || f === 'bottom' ? across : up,
|
|
623
|
+
names = list.length === n ? list.map((s) => groups.find((g) => g.letter === s.letter).family) : null;
|
|
624
|
+
const written2 = !list.length
|
|
625
|
+
? 'closed'
|
|
626
|
+
: names && names.every((x) => x === main.family)
|
|
627
|
+
? null
|
|
628
|
+
: names
|
|
629
|
+
? names.join(', ')
|
|
630
|
+
: 'closed';
|
|
631
|
+
if (written2)
|
|
632
|
+
rules[`slot_${f}`] = rule(
|
|
633
|
+
written2,
|
|
634
|
+
null,
|
|
635
|
+
!list.length
|
|
636
|
+
? `No slot was found on the ${f} face`
|
|
637
|
+
: names
|
|
638
|
+
? `The ${f} face's slots, as found`
|
|
639
|
+
: `The ${f} face has ${list.length} slot${list.length === 1 ? '' : 's'} where its cells would give ${n}: left closed here, see the outline`,
|
|
640
|
+
);
|
|
641
|
+
}
|
|
250
642
|
}
|
|
251
643
|
// bores: the round holes at the middles of the cells are the profile's bores; others are told, and stay in the outline
|
|
252
|
-
const cells = Array.from({ length: across * up }, (_, k) => [
|
|
253
|
-
|
|
644
|
+
const cells = Array.from({ length: across * up }, (_, k) => [
|
|
645
|
+
((k % across) - (across - 1) / 2) * (feat.width / across),
|
|
646
|
+
(Math.floor(k / across) - (up - 1) / 2) * (feat.height / up),
|
|
647
|
+
]);
|
|
648
|
+
const central = feat.bores.filter((b) => cells.some((c) => Math.hypot(c[0] - b.at[0], c[1] - b.at[1]) < 0.15)),
|
|
649
|
+
others = feat.bores.filter((b) => !central.includes(b));
|
|
254
650
|
const bore = central.length ? central : groups.length ? [] : [];
|
|
255
|
-
if (bore.length) {
|
|
651
|
+
if (bore.length) {
|
|
652
|
+
rules.bore_diameter = rule(
|
|
653
|
+
bore.reduce((s, b) => s + b.diameter, 0) / bore.length,
|
|
654
|
+
'mm',
|
|
655
|
+
`The round hole at the middle of ${bore.length === 1 ? 'the section' : `each of ${bore.length} cells`}, measured off the model. Name the thread it taps to (bore_thread) once you know`,
|
|
656
|
+
);
|
|
657
|
+
if (bore.length !== cells.length)
|
|
658
|
+
rules.bore_at = rule(
|
|
659
|
+
bore.map((b) => `${b.at[0]},${b.at[1]}`).join('; '),
|
|
660
|
+
null,
|
|
661
|
+
'Where the bores are: not every cell has one',
|
|
662
|
+
);
|
|
663
|
+
}
|
|
256
664
|
const doc = `A draft profile, measured from ${path.basename(file)} by cad measure --profile (${read.says}). kind derived: read off someone else's model, so check each figure against the bar in hand, name its maker and series, and add what a model cannot say: the alloy, a material set (for its mass), the thread its bore taps to and the lengths it is sold in. Its outline is rules/outlines/${name}.json, which the check and the drawing use in place of a drawn one${others.length || feat.hollows.length ? `; it also holds ${[others.length ? `${others.length} round hole${others.length === 1 ? '' : 's'} off the cells' middles` : '', feat.hollows.length ? `${feat.hollows.length} hollow${feat.hollows.length === 1 ? '' : 's'}` : ''].filter(Boolean).join(' and ')} that the rules do not name` : ''}.${o.licence ? ` The model's licence: ${o.licence}.` : ''} The outline is the model's shape: it stays in this workspace.`;
|
|
257
665
|
written.push([to, { _doc: doc, name, part: 'profile', rules }]);
|
|
258
666
|
fs.mkdirSync(path.dirname(outlineTo), { recursive: true });
|
|
259
|
-
fs.writeFileSync(
|
|
667
|
+
fs.writeFileSync(
|
|
668
|
+
outlineTo,
|
|
669
|
+
`${JSON.stringify({ _doc: `The section of ${path.basename(file)}, measured by cad measure --profile. It is the model's shape: keep it in this workspace.`, name, unit: 'mm', source, licence: o.licence || "not given: find the model's terms before sharing this", checked: stamp, loops })}\n`,
|
|
670
|
+
);
|
|
260
671
|
for (const [f, set] of written) fs.writeFileSync(f, `${JSON.stringify(set, null, 2)}\n`);
|
|
261
672
|
// ---- the report ----
|
|
262
|
-
for (const g of groups)
|
|
263
|
-
|
|
264
|
-
|
|
673
|
+
for (const g of groups)
|
|
674
|
+
console.log(
|
|
675
|
+
` slot ${g.letter} × ${g.count} (${g.faces.join(', ')}): opening ${f2(g.opening)}, lip ${f2(g.lip)}, ${f2(g.cavityWidth)} under the lips, ${f2(g.cavityDepth)} deep${g.flankAngle ? `, floor ${f2(g.floorWidth)}` : ''}${g.trackWidth ? `, V mouth ${f2(g.trackWidth)} at ${f2(g.trackAngle)}°` : ''}\n ${g.drafted ? `no slot family within ${tol} mm${g.near ? ` (nearest ${g.near.name}, ${f2(g.near.off)} off)` : ''}: drafted as ${g.family}` : `matches ${g.family} within ${f2(g.off)} mm`}`,
|
|
676
|
+
);
|
|
677
|
+
const grooves = Object.values(feat.faces)
|
|
678
|
+
.flat()
|
|
679
|
+
.filter((s) => s.kind === 'groove');
|
|
680
|
+
for (const g of grooves)
|
|
681
|
+
console.log(
|
|
682
|
+
g.depth > 2 && g.mouth > 0.3 * Math.min(feat.width, feat.height)
|
|
683
|
+
? ` an open channel ${f2(g.mouth)} wide and ${f2(g.depth)} deep in the ${g.face} face (a C section): whatever slots are inside it are in the outline, not in the rules. Give the set cells_absent for them (see profile-4080-openbuilds-cbeam)`
|
|
684
|
+
: ` a groove ${f2(g.mouth)} wide and ${f2(g.depth)} deep in the ${g.face} face, with no room under lips: not a slot for a nut`,
|
|
685
|
+
);
|
|
265
686
|
if (!groups.length) console.log(' no slot for a nut found: written as a custom profile (its outline is all of it)');
|
|
266
|
-
if (bore.length)
|
|
267
|
-
|
|
268
|
-
|
|
687
|
+
if (bore.length)
|
|
688
|
+
console.log(
|
|
689
|
+
` ${bore.length} bore${bore.length === 1 ? '' : 's'} Ø${f2(rules.bore_diameter.value)} at the cells' middles`,
|
|
690
|
+
);
|
|
691
|
+
if (others.length)
|
|
692
|
+
console.log(
|
|
693
|
+
` ${others.length} other round hole${others.length === 1 ? '' : 's'}: ${others.map((b) => `Ø${f2(b.diameter)} at ${f2(b.at[0])}, ${f2(b.at[1])}`).join('; ')} (in the outline, not in the rules)`,
|
|
694
|
+
);
|
|
695
|
+
if (feat.hollows.length)
|
|
696
|
+
console.log(
|
|
697
|
+
` ${feat.hollows.length} hollow${feat.hollows.length === 1 ? '' : 's'}: ${feat.hollows.map((h) => `${f2(h.width)} × ${f2(h.height)}`).join(', ')} (in the outline, not in the rules)`,
|
|
698
|
+
);
|
|
269
699
|
const rel = (f) => path.relative(process.cwd(), f).split(path.sep).join('/');
|
|
270
|
-
console.log(
|
|
700
|
+
console.log(
|
|
701
|
+
`\n draft profile: ${rel(to)} (${Object.keys(rules).length} values, kind derived)\n outline: ${rel(outlineTo)} (${loops.length} loops${o.licence ? '' : '; no --licence given: say what terms the model came under'})`,
|
|
702
|
+
);
|
|
271
703
|
for (const [f] of written.slice(0, -1)) console.log(` draft slot: ${rel(f)}`);
|
|
272
|
-
const svg = drawingSvg({ name, file, loops, feat, groups, bores: feat.bores, source, licence: o.licence }),
|
|
273
|
-
|
|
704
|
+
const svg = drawingSvg({ name, file, loops, feat, groups, bores: feat.bores, source, licence: o.licence }),
|
|
705
|
+
svgTo = paths.preview('measure', `${name}-profile.svg`);
|
|
706
|
+
fs.mkdirSync(path.dirname(svgTo), { recursive: true });
|
|
707
|
+
fs.writeFileSync(svgTo, svg);
|
|
274
708
|
console.log(` drawing: ${rel(svgTo)}`);
|
|
275
|
-
if (o.pictures !== false) {
|
|
709
|
+
if (o.pictures !== false) {
|
|
710
|
+
const png = paths.preview('measure', `${name}-profile.png`);
|
|
711
|
+
const size = svg.match(/width="(\d+)" height="(\d+)"/);
|
|
712
|
+
await picture(
|
|
713
|
+
`<!doctype html><html><head><meta charset="utf-8"></head><body style="margin:0">${svg}</body></html>`,
|
|
714
|
+
png,
|
|
715
|
+
{ width: Number(size[1]), height: Number(size[2]) },
|
|
716
|
+
);
|
|
717
|
+
console.log(` ${rel(png)}`);
|
|
718
|
+
}
|
|
276
719
|
console.log(`\n next: look at the drawing, then npx cad rules check ${name}, and npx cad rules draw ${name}`);
|
|
277
720
|
return { name, loops, features: feat, groups, files: written.map(([f]) => f).concat(outlineTo, svgTo) };
|
|
278
721
|
}
|