@rulecad/cad 0.7.57 → 0.7.59
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/AGENTS.md +48 -3
- package/CHANGELOG.md +213 -0
- package/EXAMPLES.md +421 -3
- package/README.md +391 -11
- package/bin/cad.mjs +105 -22
- package/lib/assembly.mjs +15 -2
- package/lib/beams.mjs +44 -11
- package/lib/buildpage.mjs +1 -1
- package/lib/design.mjs +3 -0
- package/lib/fasten.mjs +31 -9
- package/lib/fittings.mjs +50 -8
- package/lib/framebuild.mjs +62 -6
- package/lib/framecheck.mjs +831 -0
- package/lib/framegen.mjs +111 -0
- package/lib/frameheat.mjs +94 -0
- package/lib/frameprint.mjs +277 -0
- package/lib/frames.mjs +2 -1
- package/lib/framesize.mjs +261 -0
- package/lib/jigs.mjs +18 -15
- package/lib/joins.mjs +7 -3
- package/lib/kit.mjs +190 -0
- package/lib/links.mjs +12 -3
- package/lib/list.mjs +6 -2
- package/lib/loads.mjs +3 -2
- package/lib/measured.mjs +24 -2
- package/lib/optimise.mjs +18 -3
- package/lib/order.mjs +10 -4
- package/lib/panels.mjs +1 -1
- package/lib/plates.mjs +31 -17
- package/lib/preview.mjs +4 -3
- package/lib/sheet.mjs +15 -1
- package/lib/task.mjs +39 -1
- package/package.json +5 -5
- package/schemas/assembly.schema.json +9 -5
package/bin/cad.mjs
CHANGED
|
@@ -96,8 +96,13 @@ const HELP = `cad: JSCAD designs you can trace, check, share and print (rulecad)
|
|
|
96
96
|
cad plot <project>/<assembly> <drawing.svg> plans a drawing on the machine: a step file in exports/, an animation in
|
|
97
97
|
.preview/, and any stroke refused [--calibrate: the calibration drawing] [--tol 0.1] [--json]
|
|
98
98
|
cad order <project>/<assembly> the order it goes together in, each step with its fasteners; a frame from bars to square: cut, drill, sides built flat, nuts to load, joins with their torque, diagonals [--preview: an exploded picture of each step in .preview/]
|
|
99
|
-
cad plates <project>/<assembly> every printed part on beds, by filament, spaced by the first-layer rule: written as plate assemblies and checked; a changed part re-packs only its plate [--gap mm] [--json]
|
|
99
|
+
cad plates <project>/<assembly> every printed part on beds, by material and filament, spaced by the first-layer rule: written as plate assemblies and checked; a changed part re-packs only its plate; a frame's jigs on plates of their own [--gap mm] [--no-jigs] [--json]
|
|
100
|
+
cad kit <project>/<assembly> the folder to build it from without the model, in exports/: README.md (checks, what to buy and print, cut list, drilling, the build step by step), buy.csv, the plates' 3MFs, the jigs, each beam's sheet [--pictures] [--json]
|
|
100
101
|
cad list <project>/<assembly> what it takes to build: bought parts by set, the beams' cut list and bars to buy, every screw, nut and insert in packs, wire, printed parts in grams
|
|
102
|
+
cad frame <project>/<assembly> a generated frame ("frame": { "kind": "box", "inside": [..] }): its size, its beams by length, its joins and ends
|
|
103
|
+
--expand: written into the assembly as its beams, joins and end fittings, to edit by hand [--json]
|
|
104
|
+
--size: any frame's beams, by group, each given the lightest profile from frame.size.profiles that meets
|
|
105
|
+
its limits, as a table naming the limit that set each; --write writes the profiles in [--json]
|
|
101
106
|
cad beams <project>/<assembly> a cut-and-drill sheet for each mark of beam (beams that are the same share one), to scale, written to exports/ [--json]
|
|
102
107
|
--jigs: the jigs its beams take, as a plate in exports/ (a drill guide per distinct hole across a beam, a tap
|
|
103
108
|
guide per tapped end, a cut-length stop per length, a squaring corner per square join), each marked with its beam [--preview]
|
|
@@ -139,11 +144,11 @@ const HELP = `cad: JSCAD designs you can trace, check, share and print (rulecad)
|
|
|
139
144
|
|
|
140
145
|
// Every command and option there is: a misspelt one is refused by name, not passed over
|
|
141
146
|
const COMMANDS = ['new', 'import-kle', 'clone', 'agents', 'trust', 'rules', 'values', 'set', 'add', 'why', 'check', 'preview', 'animate', 'optimise', 'optimize', 'export',
|
|
142
|
-
'show', 'link', 'status', 'release', 'history', 'diff', 'printed', 'measure', 'measured', 'list', 'beams', 'wires', 'machine', 'plot', 'plates', 'order', 'match', 'variants', 'compare', 'help'];
|
|
147
|
+
'show', 'link', 'status', 'release', 'history', 'diff', 'printed', 'measure', 'measured', 'list', 'beams', 'frame', 'wires', 'machine', 'plot', 'plates', 'order', 'kit', 'match', 'variants', 'compare', 'help'];
|
|
143
148
|
const OPTIONS = ['table', 'calibrate', 'check', 'turns', 'preview', 'gap', 'no-steps', 'all', 'along', 'at', 'bump', 'depth', 'dry-run', 'explode', 'force', 'fresh', 'json', 'licence', 'license', 'long', 'm', 'material', 'md', 'name', 'new',
|
|
144
149
|
'no-models', 'no-pictures', 'no-rules', 'note', 'open', 'part', 'place', 'pose', 'profile', 'progress', 'push', 'result', 'rules', 'samples', 'set', 'short', 'source', 'steps',
|
|
145
150
|
'sweep', 'tol', 'trailer', 'ttl', 'version', 'watch', 'line',
|
|
146
|
-
'unit', 'rule', 'label', 'from', 'out', 'jigs', // cad set, cad rules, cad beams
|
|
151
|
+
'unit', 'rule', 'label', 'from', 'out', 'jigs', 'no-jigs', 'expand', 'size', 'write', 'pictures', // cad set, cad rules, cad beams, cad frame, cad plates, cad kit
|
|
147
152
|
'a', 'b', 'min', 'max', 'poses', 'id', 'type', 'parent', 'child', 'follow', 'value', 'ratio', 'object', 'assembly', 'variant', 'rotate', 'to', 'roll', // cad add
|
|
148
153
|
'screw', 'through', 'into', 'holes', 'nut', 'washer', 'length', 'torque', 'from-fits', // cad add fasten
|
|
149
154
|
'kind', 'fitting']; // cad add join
|
|
@@ -155,7 +160,7 @@ const USAGE = { add: 'fit|joint|item|beam|loop|pose|fasten|join <project>/<assem
|
|
|
155
160
|
const args = process.argv.slice(2);
|
|
156
161
|
// Options that stand alone. Every other takes the value after it: --name value, or -m for one-letter names
|
|
157
162
|
// (--sweep, --watch and --nut take one or not).
|
|
158
|
-
const FLAGS = ['table', 'calibrate', 'check', 'preview', 'no-steps', 'all', 'dry-run', 'explode', 'force', 'fresh', 'json', 'long', 'md', 'new', 'no-models', 'no-pictures', 'no-rules', 'open', 'progress', 'push', 'short', 'washer', 'from-fits', 'jigs'];
|
|
163
|
+
const FLAGS = ['table', 'calibrate', 'check', 'preview', 'no-steps', 'all', 'dry-run', 'explode', 'force', 'fresh', 'json', 'long', 'md', 'new', 'no-models', 'no-pictures', 'no-rules', 'open', 'progress', 'push', 'short', 'washer', 'from-fits', 'jigs', 'no-jigs', 'pictures', 'expand', 'size', 'write'];
|
|
159
164
|
const opt = (k) => {
|
|
160
165
|
const i = args.findIndex((a) => a === `--${k}` || (k.length === 1 && a === `-${k}`));
|
|
161
166
|
if (i < 0) return undefined;
|
|
@@ -472,8 +477,10 @@ async function main() {
|
|
|
472
477
|
if (cmd === 'compare') return compareVariants(locate(ref), pos[2], pos[3]);
|
|
473
478
|
if (cmd === 'measured') return measuredCommand(ref);
|
|
474
479
|
if (cmd === 'list' || cmd === 'wires' || cmd === 'beams') return listCommand(cmd, ref);
|
|
480
|
+
if (cmd === 'frame') return frameCommand(ref);
|
|
475
481
|
if (cmd === 'machine' || cmd === 'plot') return machineCommand(cmd, ref);
|
|
476
482
|
if (cmd === 'plates' || cmd === 'order') return platesCommand(cmd, ref);
|
|
483
|
+
if (cmd === 'kit') return kitCommand(ref);
|
|
477
484
|
if (cmd === 'history') return history(ref);
|
|
478
485
|
if (cmd === 'diff') return diff(locate(ref), pos[2], pos[3] || null);
|
|
479
486
|
if (cmd === 'printed') return printed(locate(ref));
|
|
@@ -715,17 +722,7 @@ async function assembly(cmd, ref) {
|
|
|
715
722
|
if (cmd === 'check') {
|
|
716
723
|
say(`${title} (${a.kind || 'fit'}: ${versions})`);
|
|
717
724
|
// Each pose (or the one asked for): what's the same in every pose is said once, the rest under the pose's name
|
|
718
|
-
const
|
|
719
|
-
const file = path.join(paths.project(s.project), 'assemblies', `${s.name}.json`), layouts = new Set((a.items || []).map((i) => i.repeat?.layout).filter((l) => l && !l.includes('/')));
|
|
720
|
-
const schemaProblems = [...(fs.existsSync(file) ? schemaFindings(JSON.parse(fs.readFileSync(file, 'utf8')), 'assembly', path.relative(WS, file)) : []),
|
|
721
|
-
...[...layouts].map((l) => path.join(paths.project(s.project), 'layouts', `${l}.json`)).filter((f) => fs.existsSync(f)).flatMap((f) => schemaFindings(JSON.parse(fs.readFileSync(f, 'utf8')), 'layout', path.relative(WS, f)))];
|
|
722
|
-
let findings = checkAssembly(s);
|
|
723
|
-
if (poses.length > 1) {
|
|
724
|
-
const each = poses.map((p) => [p, checkAssembly(s.at(p))]), same = (x) => each.every(([, list]) => list.some((y) => y.text === x.text && y.level === x.level));
|
|
725
|
-
findings = [{ level: 'pass', text: `${poses.length} poses checked: ${poses.join(', ')}`, code: 'poses', refs: { poses } }, ...each[0][1].filter(same),
|
|
726
|
-
...each.flatMap(([p, list]) => list.filter((x) => !same(x)).map((x) => ({ ...x, text: `${p}: ${x.text}`, ...(x.card ? { card: `${p}: ${x.card}` } : {}), refs: { ...x.refs, pose: p } })))];
|
|
727
|
-
}
|
|
728
|
-
findings.unshift(...(schemaProblems.length ? schemaProblems : [{ level: 'pass', text: 'files match their schemas', code: 'schema' }]));
|
|
725
|
+
const findings = assemblyFindings(s, a, pose);
|
|
729
726
|
if (opt('sweep')) findings.push(...sweep(s, { joint: typeof opt('sweep') === 'string' ? opt('sweep') : undefined, steps: Number(opt('steps')) || 24, progress: showProgress }));
|
|
730
727
|
if (a.kind === 'plate') findings.push(...check(printed.flatMap((p) => p.triangles), rules(printerOf(s.project)), { parts: printed }));
|
|
731
728
|
process.exitCode = report(findings, { assembly: ref, title, kind: a.kind || 'fit', ...(pose ? { pose } : {}) }) ? 1 : 0;
|
|
@@ -754,8 +751,9 @@ async function assembly(cmd, ref) {
|
|
|
754
751
|
marks = (await import('../lib/motorsvg.mjs')).workMarks(s);
|
|
755
752
|
}
|
|
756
753
|
const size = (await import('@rulecad/printcheck')).bounds(s.triangles).size.map((n) => fmt(n)).join(' × ');
|
|
757
|
-
const
|
|
758
|
-
|
|
754
|
+
const built = s.a.show === 'built' // (show: built: references drawn solid, as the thing built)
|
|
755
|
+
const faint = [...new Set(s.parts.filter((p) => p.role !== 'part' && !(built && p.role === 'reference')).map((p) => `${p.object || p.item}${p.role === 'support' ? ' supports' : ''}`))]; // each kind once
|
|
756
|
+
await preview([...s.parts, ...wireTubesOf(s)], { title: check ? `${title}: the motor at work` : title, meta: `${size} mm · ${versions}${faint.length ? ` · faint: ${faint.join(', ')}` : ''}`, out, explode: !!opt('explode'), marks, built });
|
|
759
757
|
// each motor at work beside it: its curve with the working point, and the torque through its train (said before
|
|
760
758
|
// the picture, which stays the last line, for whatever reads it)
|
|
761
759
|
if (s.motion?.drives?.length && !pose && !opt('explode') && !check) {
|
|
@@ -1040,18 +1038,100 @@ async function platesCommand(what, ref) {
|
|
|
1040
1038
|
}
|
|
1041
1039
|
const { platesOf, checkPlate } = await import('../lib/plates.mjs'), gap = opt('gap') != null ? Number(opt('gap')) : undefined;
|
|
1042
1040
|
if (gap != null && !(gap > 0)) throw new Error(`--gap is a distance in mm, above 0 (got ${opt('gap')})`);
|
|
1043
|
-
|
|
1041
|
+
// a frame's jigs (its beams' drill and tap guides, length stops and squaring corners) on beds of their own, in the
|
|
1042
|
+
// project's plastic: exports/<project>/<assembly>.jigs.3mf, as cad beams --jigs writes them (--no-jigs leaves them)
|
|
1043
|
+
const { cutListOf } = await import('../lib/beams.mjs'), jigs = !opt('no-jigs') && cutListOf(s) ? await (await import('../lib/jigs.mjs')).writeJigs(s) : null;
|
|
1044
|
+
let r;
|
|
1045
|
+
try { r = await platesOf(s, { write: true, gap }); } catch (e) { if (e.code !== 'plates.empty' || !jigs?.jigs.length) throw e; r = { bed: null, gap: null, plates: [], touched: [], removed: [], findings: [] }; } // (bought fittings only: the jigs are what it prints)
|
|
1046
|
+
const results = [];
|
|
1044
1047
|
for (const p of r.plates.filter((x) => !x.stood)) results.push({ name: p.name, findings: await checkPlate(`${s.project}/${p.name}`) });
|
|
1045
|
-
const
|
|
1046
|
-
|
|
1048
|
+
const jigRows = jigs ? { plates: jigs.plates.map((p) => ({ ...p, file: path.relative(WS, p.file) })), count: jigs.jigs.length, grams: +jigs.jigs.reduce((t, x) => t + x.grams, 0).toFixed(1), findings: jigs.findings } : null;
|
|
1049
|
+
const fails = [...r.findings, ...results.flatMap((x) => x.findings), ...(jigs?.findings ?? [])].some((x) => x.level === 'fail');
|
|
1050
|
+
if (opt('json')) { console.log(JSON.stringify({ assembly: ref, bed: r.bed, gap: r.gap, plates: r.plates, repacked: r.touched, removed: r.removed, findings: r.findings, checks: results, ...(jigRows ? { jigs: jigRows } : {}) }, null, 2)); process.exitCode = fails ? 1 : 0; return; }
|
|
1047
1051
|
report(r.findings);
|
|
1048
|
-
say(`${ref}: ${r.plates.length} plate${r.plates.length === 1 ? '' : 's'}, parts ${r.gap} mm apart (the first layer's rule)`);
|
|
1049
|
-
for (const p of r.plates) say(` ${p.name}${p.stood ? ' (unchanged)' : ''}: ${p.filament}, ${p.parts.length} part${p.parts.length === 1 ? '' : 's'}, ${p.grams} g, about ${p.minutes} min: ${p.parts.map((x) => x.id).join(', ')}`);
|
|
1052
|
+
if (r.plates.length) say(`${ref}: ${r.plates.length} plate${r.plates.length === 1 ? '' : 's'}, parts ${r.gap} mm apart (the first layer's rule)`);
|
|
1053
|
+
for (const p of r.plates) say(` ${p.name}${p.stood ? ' (unchanged)' : ''}: ${p.material}, ${p.filament}, ${p.parts.length} part${p.parts.length === 1 ? '' : 's'}, ${p.grams} g, about ${p.minutes} min: ${p.parts.map((x) => x.id).join(', ')}`);
|
|
1050
1054
|
if (r.removed.length) say(` removed ${r.removed.join(', ')} (nothing is on them now)`);
|
|
1051
1055
|
for (const x of results) { const bad = x.findings.filter((y) => (y.level === 'fail' || y.level === 'warn') && y.code !== 'rules.estimate'); say(` ${x.name}: ${bad.length ? `${bad.length} to look at` : 'prints clean'}`); for (const y of bad) say(` [${y.level}] ${y.text}`); }
|
|
1056
|
+
if (jigRows?.count) {
|
|
1057
|
+
say(`${ref}: ${jigRows.count} jig${jigRows.count === 1 ? '' : 's'} for its beams, ${jigRows.grams} g, on ${jigRows.plates.length} plate${jigRows.plates.length === 1 ? '' : 's'} of their own (cad beams ${ref} --jigs says what each is for)`);
|
|
1058
|
+
for (const p of jigRows.plates) say(` ${p.file}: ${p.material}, ${p.parts.length} part${p.parts.length === 1 ? '' : 's'}`);
|
|
1059
|
+
for (const f of jigRows.findings) say(` [${f.level}] ${f.text}`);
|
|
1060
|
+
}
|
|
1052
1061
|
process.exitCode = fails ? 1 : 0;
|
|
1053
1062
|
}
|
|
1054
1063
|
|
|
1064
|
+
// An assembly's findings as cad check gives them: each pose (or the one asked for), what is the same in every pose
|
|
1065
|
+
// said once and the rest under the pose's name, after its files' schema check. cad kit counts the same list
|
|
1066
|
+
function assemblyFindings(s, a, pose) {
|
|
1067
|
+
const poses = pose ? [pose] : Object.keys(s.motion.poses);
|
|
1068
|
+
const file = path.join(paths.project(s.project), 'assemblies', `${s.name}.json`), layouts = new Set((a.items || []).map((i) => i.repeat?.layout).filter((l) => l && !l.includes('/')));
|
|
1069
|
+
const schemaProblems = [...(fs.existsSync(file) ? schemaFindings(JSON.parse(fs.readFileSync(file, 'utf8')), 'assembly', path.relative(WS, file)) : []),
|
|
1070
|
+
...[...layouts].map((l) => path.join(paths.project(s.project), 'layouts', `${l}.json`)).filter((f) => fs.existsSync(f)).flatMap((f) => schemaFindings(JSON.parse(fs.readFileSync(f, 'utf8')), 'layout', path.relative(WS, f)))];
|
|
1071
|
+
let findings = checkAssembly(s);
|
|
1072
|
+
if (poses.length > 1) {
|
|
1073
|
+
const each = poses.map((p) => [p, checkAssembly(s.at(p))]), same = (x) => each.every(([, list]) => list.some((y) => y.text === x.text && y.level === x.level));
|
|
1074
|
+
findings = [{ level: 'pass', text: `${poses.length} poses checked: ${poses.join(', ')}`, code: 'poses', refs: { poses } }, ...each[0][1].filter(same),
|
|
1075
|
+
...each.flatMap(([p, list]) => list.filter((x) => !same(x)).map((x) => ({ ...x, text: `${p}: ${x.text}`, ...(x.card ? { card: `${p}: ${x.card}` } : {}), refs: { ...x.refs, pose: p } })))];
|
|
1076
|
+
}
|
|
1077
|
+
findings.unshift(...(schemaProblems.length ? schemaProblems : [{ level: 'pass', text: 'files match their schemas', code: 'schema' }]));
|
|
1078
|
+
return findings;
|
|
1079
|
+
}
|
|
1080
|
+
|
|
1081
|
+
// cad kit: the folder to build an assembly from, without the model (lib/kit.mjs)
|
|
1082
|
+
async function kitCommand(ref) {
|
|
1083
|
+
if (!isAssembly(ref)) throw new Error(`cad kit works on an assembly (<project>/<assembly>), and there is no "${ref}"`);
|
|
1084
|
+
// (laying out its plates reads the printer's rule set: a fresh workspace gets its own copy in rules/, as cad plates
|
|
1085
|
+
// gives it, and the kit says which it copied)
|
|
1086
|
+
const rulesDir = path.join(WS, 'rules'), had = new Set(fs.existsSync(rulesDir) ? fs.readdirSync(rulesDir) : []);
|
|
1087
|
+
const s = await buildAssembly(ref), { writeKit } = await import('../lib/kit.mjs');
|
|
1088
|
+
const r = await writeKit(s, assemblyFindings(s, s.a, undefined), { pictures: !!opt('pictures'), preview });
|
|
1089
|
+
const copied = (fs.existsSync(rulesDir) ? fs.readdirSync(rulesDir) : []).filter((f) => f.endsWith('.json') && !had.has(f)).map((f) => `rules/${f}`);
|
|
1090
|
+
const shown = { assembly: ref, dir: path.relative(WS, r.dir), files: r.files, copied, plates: r.plates.map(({ name, material, filament, parts, grams, minutes, file, issues }) => ({ name, material, filament, parts: parts.length, grams, minutes, file, issues })), jigs: r.jigs, sheets: r.sheets, steps: r.steps, warnings: r.findings.map((f) => f.text) };
|
|
1091
|
+
if (opt('json')) return console.log(JSON.stringify(shown, null, 2));
|
|
1092
|
+
say(`${ref}: the kit to build it from, in ${shown.dir}${path.sep}`);
|
|
1093
|
+
say(` README.md: what the checks say, what to buy, what to print${r.sheets.length ? ', the cut list, the drilling and tapping' : ''}${r.steps ? `, and the build in ${r.steps} steps` : ''}`);
|
|
1094
|
+
say(' buy.csv: the shopping list');
|
|
1095
|
+
for (const p of shown.plates) say(` ${p.file}: ${p.material}, ${p.parts} part${p.parts === 1 ? '' : 's'}, ${p.grams} g, about ${p.minutes} min${p.issues.length ? ` (${p.issues.length} to look at)` : ''}`);
|
|
1096
|
+
for (const p of r.jigs?.plates ?? []) say(` ${p.file}: ${r.jigs.count} jigs for the beams, ${p.parts} parts`);
|
|
1097
|
+
for (const x of r.sheets) say(` ${x.file}: mark ${x.mark} (${x.items.join(', ')})`);
|
|
1098
|
+
const pics = r.files.filter((f) => f.startsWith('pictures/'));
|
|
1099
|
+
if (pics.length) say(` pictures/: ${pics.length} pictures (the whole, and the steps of the build)`);
|
|
1100
|
+
for (const w of shown.warnings) say(` warning: ${w}`);
|
|
1101
|
+
for (const f of copied) say(`and copied ${f} into this workspace: the rule set its plates were laid out by, yours to keep and edit (the next kit reads your copy)`);
|
|
1102
|
+
}
|
|
1103
|
+
|
|
1104
|
+
// cad frame: a generated frame as it expands, and --expand writes the expansion into the assembly, to edit by hand
|
|
1105
|
+
async function frameCommand(ref) {
|
|
1106
|
+
if (!isAssembly(ref)) throw new Error(`cad frame works on an assembly (<project>/<assembly>), and there is no "${ref}"`);
|
|
1107
|
+
const { expandFrame, frameText } = await import('../lib/framegen.mjs'), { assemblyPath } = await import('../lib/assembly.mjs');
|
|
1108
|
+
const file = assemblyPath(ref), raw = readJson(file);
|
|
1109
|
+
if (opt('size')) {
|
|
1110
|
+
const { frameSizing, sizingText, writeSizing, sizeOption } = await import('../lib/framesize.mjs'), { placeItems, jointValues, mul } = await import('@rulecad/model-link');
|
|
1111
|
+
const s = await buildAssembly(ref), r = frameSizing(s, { placeItems, jointValues, mul }, sizeOption(s) ?? undefined);
|
|
1112
|
+
if (!r) throw new Error(`${ref} has no frame to size: its beams need joins between them, or "frame": { "supports" }`);
|
|
1113
|
+
const rows = r.rows, out = { assembly: ref, ok: r.ok, total: r.total, drawn: r.drawn, tried: r.tried, search: r.search, groups: rows, limits: r.limits };
|
|
1114
|
+
if (opt('write')) {
|
|
1115
|
+
if (!r.ok) throw new Error(`${ref}: no profile in the list meets every limit, so nothing is written (cad frame ${ref} --size says how near it comes)`);
|
|
1116
|
+
fs.writeFileSync(file, `${JSON.stringify(writeSizing(raw, raw.frame?.kind != null ? expandFrame(raw, s.num).a : raw, r), null, 2)}\n`);
|
|
1117
|
+
if (opt('json')) return console.log(JSON.stringify({ ...out, file: path.relative(WS, file) }, null, 2));
|
|
1118
|
+
console.log(sizingText(r).join('\n'));
|
|
1119
|
+
return console.log(`wrote ${path.relative(WS, file)}: ${rows.reduce((t, x) => t + x.beams.length, 0)} beams given their profiles${raw.frame?.kind != null ? ' (the generated frame written out expanded, as --expand does, as a generator takes one profile)' : ''}; their lines are kept (a deeper beam that would stand past the end of the one it meets moves along it), so check the joins and ends of any beam that changed size`);
|
|
1120
|
+
}
|
|
1121
|
+
if (opt('json')) return console.log(JSON.stringify(out, null, 2));
|
|
1122
|
+
return console.log(`${ref}: ${sizingText(r).join('\n')}\n(cad frame ${ref} --size --write writes these profiles into the assembly)`);
|
|
1123
|
+
}
|
|
1124
|
+
if (raw.frame?.kind == null) throw new Error(`${ref} asks for no generated frame: give it "frame": { "kind": "box", "inside": [300, 300, 350], "profile": "2020-misumi-hfs5", "join": "blind" }`);
|
|
1125
|
+
const s = await buildAssembly(ref), m = s.generated, out = expandFrame(raw, s.num).a;
|
|
1126
|
+
if (opt('expand')) {
|
|
1127
|
+
fs.writeFileSync(file, `${JSON.stringify(out, null, 2)}\n`);
|
|
1128
|
+
if (opt('json')) return console.log(JSON.stringify({ assembly: ref, file: path.relative(WS, file), frame: m }, null, 2));
|
|
1129
|
+
return console.log(`wrote ${path.relative(WS, file)}: the ${m.kind} as ${m.beams.length + (m.moving ? 1 : 0)} beams, ${m.joins.length} joins and ${m.ends.length + m.panels.length} fittings, to edit by hand (its "frame" keeps only how it is solved)`);
|
|
1130
|
+
}
|
|
1131
|
+
if (opt('json')) return console.log(JSON.stringify({ assembly: ref, frame: m, expanded: out }, null, 2));
|
|
1132
|
+
console.log(`${ref}: ${frameText(m).join('\n')}\n(cad frame ${ref} --expand writes these into the assembly, to edit by hand)`);
|
|
1133
|
+
}
|
|
1134
|
+
|
|
1055
1135
|
async function listCommand(what, ref) {
|
|
1056
1136
|
if (!isAssembly(ref)) throw new Error(`cad ${what} works on an assembly (<project>/<assembly>), and there is no "${ref}"`);
|
|
1057
1137
|
const s = await buildAssembly(ref);
|
|
@@ -1079,6 +1159,9 @@ async function listCommand(what, ref) {
|
|
|
1079
1159
|
if (opt('json')) return console.log(JSON.stringify(sheets.map((x) => ({ ...x, file: path.relative(WS, x.file) })), null, 2));
|
|
1080
1160
|
if (!sheets.length) return console.log(`${ref} has no beams`);
|
|
1081
1161
|
for (const x of sheets) say(` mark ${x.mark} (${x.items.join(', ')}), 1:${x.scale}: ${path.relative(WS, x.file)}`);
|
|
1162
|
+
const { writeFrameShape, writeFrameMode } = await import('../lib/framecheck.mjs'), sag = writeFrameShape(s), mode = writeFrameMode(s);
|
|
1163
|
+
if (sag) say(` the frame's sag, drawn ${+sag.scale.toPrecision(3)} times its size (a check view): ${path.relative(WS, sag.file)}`);
|
|
1164
|
+
if (mode) say(` the frame's lowest mode, ${+mode.Hz.toPrecision(3)} Hz, animated (a check view): ${path.relative(WS, mode.file)}`);
|
|
1082
1165
|
return;
|
|
1083
1166
|
}
|
|
1084
1167
|
const { wiresFor } = await import('../lib/assembly.mjs'), { wiringSheet } = await import('../lib/wires.mjs'), rows = wiresFor(s);
|
package/lib/assembly.mjs
CHANGED
|
@@ -51,6 +51,10 @@ import { orderChecks } from './order.mjs';
|
|
|
51
51
|
import { beamBuilt, beamPlace, beamAddress, beamFindings, marksOf, framesContext } from './beams.mjs';
|
|
52
52
|
import { fittingBuilt, fittingFindings, plasticOf } from './fittings.mjs';
|
|
53
53
|
import { expandJoins, joinChecks } from './joins.mjs';
|
|
54
|
+
import { expandFrame, frameText } from './framegen.mjs';
|
|
55
|
+
import { frameChecks } from './framecheck.mjs';
|
|
56
|
+
import { sizeChecks } from './framesize.mjs';
|
|
57
|
+
import { frameHeatChecks } from './frameheat.mjs';
|
|
54
58
|
import { expandPanels, panelBuilt, panelFindings, PANEL_CHECK } from './panels.mjs';
|
|
55
59
|
import { expandServices, serviceFindings } from './services.mjs';
|
|
56
60
|
import { expandGuides, guideBuilt, guideFindings } from './guides.mjs';
|
|
@@ -113,6 +117,9 @@ export async function buildAssembly(ref, stack = [], overrides = {}, opts = {})
|
|
|
113
117
|
return v;
|
|
114
118
|
};
|
|
115
119
|
const num = (x) => evaluate(x, lookup);
|
|
120
|
+
// A generated frame (lib/framegen.mjs): "frame": { "kind": "box", "inside": [..] } into beams, joins and their ends, first
|
|
121
|
+
let generated = null;
|
|
122
|
+
if (a.frame && typeof a.frame === 'object' && !Array.isArray(a.frame)) ({ a, frame: generated } = expandFrame(a, num, framesContext()));
|
|
116
123
|
// Joins between beams (lib/joins.mjs): their operations go on the beams and their screws into fasten before anything is built
|
|
117
124
|
let joins = [];
|
|
118
125
|
if (a.joins != null) ({ a, joins } = expandJoins(a, num, undefined, plasticOf(project)));
|
|
@@ -268,7 +275,7 @@ export async function buildAssembly(ref, stack = [], overrides = {}, opts = {})
|
|
|
268
275
|
for (const p of src.b.parts) {
|
|
269
276
|
if (p.role === 'support' && a.kind !== 'plate') continue; // supports are snipped off before parts go together
|
|
270
277
|
out.push({ name: `${id}.${p.name}`, item: id, leaf: id, object: src.objName, role: src.role === 'reference' ? 'reference' : p.role, label: `${id}: ${marks.has(id) ? `mark ${marks.get(id)}, ` : ''}${p.label}`,
|
|
271
|
-
...(p.filament ? { filament: p.filament } : {}), ...(p.mirror === false ? { mirror: false } : {}), part: p.name,
|
|
278
|
+
...(p.filament ? { filament: p.filament } : {}), ...(p.mirror === false ? { mirror: false } : {}), ...(p.fill != null ? { fill: p.fill } : {}), part: p.name,
|
|
272
279
|
geometry: transform(m, p.geometry), ...(p.collide ? { collide: transform(m, p.collide) } : {}), polygons: move(p.polygons), triangles: move(p.triangles),
|
|
273
280
|
shape: `${key}:${p.name}`, hash: `${src.b.hash}:${p.name}`, local: p.polygons, localTriangles: p.triangles, m });
|
|
274
281
|
}
|
|
@@ -327,7 +334,7 @@ export async function buildAssembly(ref, stack = [], overrides = {}, opts = {})
|
|
|
327
334
|
const v = jointValues(motion, p), moved = partsAt(placeItems(motion, v));
|
|
328
335
|
return { ...s, parts: moved, fastened: null, pose: typeof p === 'string' ? p : null, jointValues: v, polygons: moved.flatMap((x) => x.polygons), triangles: moved.flatMap((x) => x.triangles) };
|
|
329
336
|
};
|
|
330
|
-
const s = { a, project, name, items, parts, objects, fits, requires, values, num, seen, motion, wires, task, gait, fastened, hardware, joins, panels, mounts, runs, guides, pose: typeof pose === 'string' ? pose : null, jointValues: jv, at,
|
|
337
|
+
const s = { a, project, name, items, parts, objects, fits, requires, values, num, seen, motion, wires, task, gait, fastened, hardware, joins, generated, panels, mounts, runs, guides, pose: typeof pose === 'string' ? pose : null, jointValues: jv, at,
|
|
331
338
|
polygons: parts.flatMap((p) => p.polygons), triangles: parts.flatMap((p) => p.triangles) };
|
|
332
339
|
return s;
|
|
333
340
|
}
|
|
@@ -937,6 +944,8 @@ export function checkAssembly(s) {
|
|
|
937
944
|
const ids = s.motion.items.map((x) => x[0]), top = (n) => String(n).split(/[.@]/)[0];
|
|
938
945
|
// (a beam placed by its ends is the frame, held where it is drawn: what is screwed to it is held by it)
|
|
939
946
|
const held = new Set([ids[0], ...s.motion.joints.filter((j) => !j.at).map((j) => ids[j.child]), ...s.items.filter((it) => it.beam && it.from != null).map((it) => it.id)]), links = s.fits.filter((x) => x.fastens).map((x) => [top(x.a), top(x.b)]);
|
|
947
|
+
// (a fitting at a beam's end, an end cap pressed into it or a foot screwed into its bore, is held by that beam)
|
|
948
|
+
for (const it of s.a.items || []) { const m = typeof it.at === 'string' && (it.fitting || it.bought) ? /^([\w-]+)\.[ab]$/.exec(it.at.trim()) : null; if (m && s.items.some((x) => x.id === m[1] && x.beam)) links.push([it.id, m[1]]); }
|
|
940
949
|
for (let grew = true; grew;) { grew = false; for (const [a, b] of links) { if (held.has(a) && !held.has(b)) { held.add(b); grew = true; } if (held.has(b) && !held.has(a)) { held.add(a); grew = true; } } }
|
|
941
950
|
const placed = new Set(s.objects.filter((o) => !o.unplaced && o.role !== 'reference').map((o) => top(o.id)));
|
|
942
951
|
const loose = ids.filter((id) => !held.has(id) && placed.has(id));
|
|
@@ -979,15 +988,19 @@ export function checkAssembly(s) {
|
|
|
979
988
|
panelFindings(s, f);
|
|
980
989
|
serviceFindings(s, f);
|
|
981
990
|
guideFindings(s, f);
|
|
991
|
+
if (s.generated) { const m = s.generated, [what, ...more] = frameText(m); f('info', `generated: ${what}; ${more.map((x) => x.trim()).join('; ')}`, null, { code: 'frame.generated', values: { inside: m.inside, outside: m.outside, lengths: m.lengths.map(({ length, count }) => ({ length, count })) }, refs: { kind: m.kind, profile: m.profile, join: m.join.kind, arrangement: m.arrangement, by: m.by } }); }
|
|
982
992
|
joinChecks(s, f);
|
|
983
993
|
slotNutChecks(s, f);
|
|
984
994
|
frameSquareChecks(s, f);
|
|
995
|
+
frameHeatChecks(s, f);
|
|
985
996
|
massFinding(s, f);
|
|
986
997
|
runningChecks(s, f, { axisOf, placeItems, jointValues, mul });
|
|
987
998
|
if (s.wires?.length) wireChecks(s, f, { placeItems, jointValues, mul });
|
|
988
999
|
motorChecks(s, f, { placeItems, jointValues, mul }, materialOf(s.project));
|
|
989
1000
|
powerChecks(s, f);
|
|
990
1001
|
loadChecks(s, f, { placeItems, jointValues, mul });
|
|
1002
|
+
frameChecks(s, f, { placeItems, jointValues, mul });
|
|
1003
|
+
sizeChecks(s, f, { placeItems, jointValues, mul });
|
|
991
1004
|
gripChecks(s, f);
|
|
992
1005
|
gaitChecks(s, f, { jointValues, placeItems, sweepOne: (v) => clashesOf(s.at(v), named) });
|
|
993
1006
|
taskChecks(s, f);
|
package/lib/beams.mjs
CHANGED
|
@@ -8,19 +8,23 @@
|
|
|
8
8
|
// about its own axis, a toward b, right-handed.
|
|
9
9
|
// Its addresses are anchors (lib/assembly.mjs reads them through beamAnchor): x1.a, x1.b, x1.a.1, x1.top, x1.top@120,
|
|
10
10
|
// x1.top@-20, x1.top@50%, x1.top.2@120.
|
|
11
|
+
// "printed": true (or { pose, walls, infill, end, pull }) makes it a printed part (@rulecad/frames printed beams): drawn
|
|
12
|
+
// solid, weighed by the plastic its walls and infill lay, on a plate laid as it prints ("laid": true, which cad plates
|
|
13
|
+
// writes), off the cut list; its findings say how it prints and what stops it.
|
|
11
14
|
// Its operations ("ops": cut, mitre, tap, access, drill, counterbore, pocket, notch, deburr) are @rulecad/frames': each
|
|
12
15
|
// is cut into its preview, a mitre into its envelope too, and their findings (beam.op) are the beam's.
|
|
13
16
|
import * as frames from '@rulecad/frames';
|
|
14
17
|
import fs from 'node:fs';
|
|
18
|
+
import crypto from 'node:crypto';
|
|
15
19
|
import path from 'node:path';
|
|
16
|
-
import { beamModel, beam, beamAnchor, cutList, beamMarks, beamSheet } from '@rulecad/frames';
|
|
20
|
+
import { beamModel, beam, beamAnchor, cutList, beamMarks, beamSheet, printedBeam, printedInPlace } from '@rulecad/frames';
|
|
17
21
|
import { frame } from '@rulecad/model-link';
|
|
18
22
|
import { RULE_DIRS, paths } from './workspace.mjs';
|
|
19
23
|
import { named } from './parts.mjs';
|
|
20
24
|
import { referenceBuilt } from './bought.mjs';
|
|
21
25
|
import { framesContext as contextIn, givenFor } from './frames.mjs';
|
|
22
26
|
|
|
23
|
-
const KEYS = ['profile', 'length', 'printed', 'material', 'ops'];
|
|
27
|
+
const KEYS = ['profile', 'length', 'printed', 'material', 'ops', 'laid'];
|
|
24
28
|
const OP_NUMBERS = ['angle', 'depth', 'diameter', 'length', 'radius'];
|
|
25
29
|
const shown = (v) => (v === undefined ? 'nothing' : JSON.stringify(v));
|
|
26
30
|
const mm = (x) => String(+Number(x).toFixed(2));
|
|
@@ -30,8 +34,8 @@ export const framesContext = () => contextIn(RULE_DIRS[0]);
|
|
|
30
34
|
|
|
31
35
|
/**
|
|
32
36
|
* The beam an item names, its length worked out: { model, length }. A length may be an expression; left out, it is the
|
|
33
|
-
* distance from from to to. Refused by name: an unknown key, no profile,
|
|
34
|
-
* that disagrees with its ends, ends and at both given.
|
|
37
|
+
* distance from from to to. Refused by name: an unknown key, no profile, printed neither true, false nor its options, a
|
|
38
|
+
* length that disagrees with its ends, ends and at both given.
|
|
35
39
|
* @param {object} it the item @param {(x: any) => number} num the assembly's expressions @param {object} [context] framesContext()'s
|
|
36
40
|
*/
|
|
37
41
|
export function beamOf(it, num, context = framesContext()) {
|
|
@@ -39,8 +43,8 @@ export function beamOf(it, num, context = framesContext()) {
|
|
|
39
43
|
if (!b || typeof b !== 'object' || Array.isArray(b)) throw new Error(`${what}: beam is { "profile", "length", "material" } (got ${shown(b)})`);
|
|
40
44
|
for (const k of Object.keys(b)) if (!KEYS.includes(k)) throw new Error(`${what}: a beam has no "${k}": it takes ${KEYS.join(', ')}`);
|
|
41
45
|
if (typeof b.profile !== 'string' || !b.profile) throw new Error(`${what}: beam.profile names a profile, such as 2020-misumi-hfs5 (got ${shown(b.profile)})`);
|
|
42
|
-
if (b.printed != null && typeof b.printed !== 'boolean') throw new Error(`${what}: beam.printed is true or
|
|
43
|
-
if (b.printed) throw new Error(`${what}: a printed beam
|
|
46
|
+
if (b.printed != null && typeof b.printed !== 'boolean' && (typeof b.printed !== 'object' || Array.isArray(b.printed))) throw new Error(`${what}: beam.printed is true, false, or how it prints: { "pose": "lying", "walls": 3, "infill": 0.4, "end": "insert" } (got ${shown(b.printed)})`);
|
|
47
|
+
if (b.laid != null && (typeof b.laid !== 'boolean' || (b.laid && !b.printed))) throw new Error(`${what}: beam.laid draws a printed beam as it prints: true or false, with printed (got ${shown(b.laid)}${b.printed ? '' : ' on a bought beam'})`);
|
|
44
48
|
if (b.ops != null && !Array.isArray(b.ops)) throw new Error(`${what}: beam.ops is a list of operations, [{ "op": "tap", "at": "a" }] (got ${shown(b.ops)})`);
|
|
45
49
|
// an operation's numbers may be expressions, as a length is
|
|
46
50
|
const ops = (b.ops ?? []).map((o) => (o && typeof o === 'object' && !Array.isArray(o) ? Object.fromEntries(Object.entries(o).map(([k, v]) => [k, OP_NUMBERS.includes(k) && v != null ? num(v) : k === 'size' && Array.isArray(v) ? v.map(num) : v])) : o));
|
|
@@ -59,7 +63,7 @@ export function beamOf(it, num, context = framesContext()) {
|
|
|
59
63
|
const given = givenFor(context, b.profile);
|
|
60
64
|
let model;
|
|
61
65
|
try {
|
|
62
|
-
model = beamModel(frames.profileModel(b.profile, {}, given), { length, ...(b.material ? { material: b.material } : {}), ...(ops.length ? { ops } : {}), given });
|
|
66
|
+
model = beamModel(frames.profileModel(b.profile, {}, given), { length, ...(b.material ? { material: b.material } : {}), ...(ops.length ? { ops } : {}), ...(b.printed ? { printed: b.printed } : {}), given });
|
|
63
67
|
} catch (e) { throw new Error(`${what}: ${strip(e)}`); }
|
|
64
68
|
return { model, length };
|
|
65
69
|
}
|
|
@@ -86,6 +90,7 @@ export function beamPlace(it, num) {
|
|
|
86
90
|
*/
|
|
87
91
|
export function beamBuilt(it, num, id, context = framesContext()) {
|
|
88
92
|
const { model: m, length } = beamOf(it, num, context);
|
|
93
|
+
if (m.printed) return printedBuilt(it, m, id);
|
|
89
94
|
const meta = { body: { label: `${m.profile.name} x ${mm(length)} mm` } };
|
|
90
95
|
const parts = named({ body: beam(m) }, meta), link = named({ body: beam(m, { display: 'link', tracks: true }) }, meta)[0];
|
|
91
96
|
parts[0].collide = link.geometry; // (the overlap check measures the envelope, light, less any V tracks: a V-wheel's rim runs in them, and a rim out of them hits the beam)
|
|
@@ -97,6 +102,31 @@ export function beamBuilt(it, num, id, context = framesContext()) {
|
|
|
97
102
|
extra: { beam: m, bought: { set: m.profile.name, variant: null, part: 'beam', mass: grams != null ? grams / 1000 : null, length } } });
|
|
98
103
|
}
|
|
99
104
|
|
|
105
|
+
// A printed beam, built: a printed part, solid, in its place (or laid as it prints, for a plate), its part's fill the share
|
|
106
|
+
// of its section the walls and infill lay (cad list weighs it by that), its anchors and figures as a bought beam's
|
|
107
|
+
function printedBuilt(it, m, id) {
|
|
108
|
+
const sec = m.printed.section, laid = !!it.beam.laid, label = `${m.profile.name} x ${mm(m.length)} mm, printed ${m.printed.pose === 'lying' ? 'lying down' : 'standing up'}`;
|
|
109
|
+
const parts = named({ body: laid ? printedBeam(m) : printedInPlace(m) }, { body: { label } }); // (in its place, its ends' inserts or nuts cut in, as a screw into them is checked)
|
|
110
|
+
parts[0].fill = +(sec.plastic / sec.solid.area).toFixed(4);
|
|
111
|
+
if (!laid) parts[0].collide = named({ body: printedInPlace(m, { display: 'link' }) }, { body: { label } })[0].geometry;
|
|
112
|
+
const anchors = laid ? {} : Object.fromEntries(Object.entries(m.anchors).map(([k, a]) => [k, { at: a.origin, axis: a.axis, ref: a.ref }]));
|
|
113
|
+
const values = { length: m.length, width: m.profile.width, height: m.profile.height, grams: m.mass, design: m.printed.design };
|
|
114
|
+
const entries = Object.entries(m.figures).filter(([, f]) => typeof f?.value === 'number').map(([k, f]) => ({ name: `${m.profile.name}.printed.${k}`, value: f.value, unit: f.unit, rule: `The printed beam's ${k}, from its walls and infill`, kind: f.kind, source: f.source, checked: '2026-11-17', set: m.profile.name }));
|
|
115
|
+
const hash = crypto.createHash('sha256').update(JSON.stringify([it.beam, m.name, m.mass, laid])).digest('hex').slice(0, 16);
|
|
116
|
+
const b = { object: { name: m.name, title: label, role: 'part', version: '0.0.0', anchors }, values, entries, deps: [], units: {}, parts, polygons: parts.flatMap((p) => p.polygons), triangles: parts.flatMap((p) => p.triangles), hash };
|
|
117
|
+
return { key: `beam:${id}:${hash}`, objName: `beam:${m.profile.name}:printed`, b, version: '0.0.0', role: 'part', beam: m };
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
/**
|
|
121
|
+
* A printed beam's item as a plate takes it: its numbers worked out (the plate has none of the assembly's values), its
|
|
122
|
+
* length given (the plate places it by at), and laid as it prints.
|
|
123
|
+
* @param {object} it the assembly's item @param {(x: any) => number} num @param {number} length @returns {object} the plate item's beam
|
|
124
|
+
*/
|
|
125
|
+
export function laidSpec(it, num, length) {
|
|
126
|
+
const { profile, printed, material, ops } = it.beam;
|
|
127
|
+
return { profile, length, printed, ...(material ? { material } : {}), ...(ops?.length ? { ops: ops.map((o) => Object.fromEntries(Object.entries(o).map(([k, v]) => [k, OP_NUMBERS.includes(k) && v != null ? num(v) : k === 'size' && Array.isArray(v) ? v.map(num) : v]))) } : {}), laid: true };
|
|
128
|
+
}
|
|
129
|
+
|
|
100
130
|
/**
|
|
101
131
|
* An anchor on a beam by its address (a, b, a.1, top, top@120, top@-20, top@50%, top.2@120), as a frame of 12 numbers in
|
|
102
132
|
* the beam's own frame. Past the beam's end, or a name it does not have: refused by name, with its length.
|
|
@@ -108,18 +138,21 @@ export function beamAddress(m, address, what) {
|
|
|
108
138
|
return frame(a.origin, a.axis, a.ref);
|
|
109
139
|
}
|
|
110
140
|
|
|
111
|
-
/** The assembly's beams, nested ones too, as { id, beam } for @rulecad/frames' cut list. @param {object} s a built assembly */
|
|
112
|
-
export const beamsIn = (s) => s.objects.filter((o) => o.beam && !o.unplaced).map((o) => ({ id: o.id, beam: o.beam }));
|
|
141
|
+
/** The assembly's bought beams, nested ones too, as { id, beam } for @rulecad/frames' cut list. @param {object} s a built assembly */
|
|
142
|
+
export const beamsIn = (s) => s.objects.filter((o) => o.beam && !o.beam.printed && !o.unplaced).map((o) => ({ id: o.id, beam: o.beam })); // (a printed beam is printed, not cut)
|
|
113
143
|
|
|
114
144
|
/** Each beam's mark: beams that are the same share one (A, B, ...), as the cut list and the sheets name them. @returns {Map<string, string>} item to mark */
|
|
115
145
|
export function marksOf(objects) {
|
|
116
|
-
const list = objects.filter((o) => o.beam && !o.unplaced), out = new Map();
|
|
146
|
+
const list = objects.filter((o) => o.beam && !o.beam.printed && !o.unplaced), out = new Map();
|
|
117
147
|
if (list.length) for (const m of beamMarks(list.map((o) => ({ id: o.id, beam: o.beam })))) for (const id of m.items) out.set(id, m.mark);
|
|
118
148
|
return out;
|
|
119
149
|
}
|
|
120
150
|
|
|
121
151
|
/** The cut list of an assembly's beams (frames' cutList), or null where it has none. @param {object} s a built assembly */
|
|
122
|
-
export function cutListOf(s) {
|
|
152
|
+
export function cutListOf(s) {
|
|
153
|
+
const b = beamsIn(s), t = s.a?.frame?.cut?.tolerance;
|
|
154
|
+
return b.length ? cutList(b, t != null && Number.isFinite(s.num(t)) && s.num(t) >= 0 ? { tolerance: s.num(t) } : {}) : null; // (the workshop's own tolerance, frame.cut; refused by name in frame.square)
|
|
155
|
+
}
|
|
123
156
|
|
|
124
157
|
/** The cut list as the list and the build page keep it: no beam models, the numbers and words only. */
|
|
125
158
|
export const cutListData = (c) => c && { marks: c.marks.map(({ beam, ...m }) => m), stock: c.stock, totals: c.totals, rules: Object.fromEntries(Object.entries(c.rules).map(([k, r]) => [k, { value: r.value, unit: r.unit, kind: r.kind }])) };
|
package/lib/buildpage.mjs
CHANGED
|
@@ -67,7 +67,7 @@ export async function buildData(s) {
|
|
|
67
67
|
const machine = s.task ? await guard(() => machineOf(s)) : null;
|
|
68
68
|
// each mark's cut-and-drill sheet, by its file in the exports (cad beams writes them), and whether it is there yet
|
|
69
69
|
const beams = await guard(() => { const c = cutListOf(s); return c ? { sheets: c.marks.map((m) => ({ mark: m.mark, items: m.items, file: ['exports', s.project, path.basename(sheetFile(s, m.mark))].join('/'), written: fs.existsSync(sheetFile(s, m.mark)) })) } : null; });
|
|
70
|
-
const frame = s.joins?.length ? await guard(() => { const { steps, sides, notFlat, bays, torques, stuck } = frameBuild(s); return { steps, sides: sides.map((x) => ({ beams: x.beams, name: x.name })), notFlat, bays: bays.map((b) => ({ beams: b.beams, name: b.name, width: b.width, height: b.height, diagonal: b.square.diagonal, accept: b.square.accept, lean: b.square.lean })), torques, stuck }; }) : null; // (from bars to a square frame)
|
|
70
|
+
const frame = s.joins?.length ? await guard(() => { const { steps, sides, notFlat, bays, torques, stuck } = frameBuild(s); return { steps, sides: sides.map((x) => ({ beams: x.beams, name: x.name })), notFlat, bays: bays.map((b) => ({ beams: b.beams, name: b.name, width: b.width, height: b.height, diagonal: b.square.diagonal, accept: b.square.accept, rss: b.square.rss, lean: b.square.lean, terms: b.square.terms })), torques, stuck }; }) : null; // (from bars to a square frame)
|
|
71
71
|
// a frame's build is its one sequence, from bars to square with the rest mounted: the assembly order is not shown beside it
|
|
72
72
|
return { build: { list, wires, plates, order: frame && !frame.error ? null : order, machine, beams, ...(frame ? { frame } : {}) } };
|
|
73
73
|
}
|
package/lib/design.mjs
CHANGED
|
@@ -126,6 +126,9 @@ export function variantSet(d, object, set = {}) {
|
|
|
126
126
|
}
|
|
127
127
|
|
|
128
128
|
const CACHE = paths.cache('builds'), CACHE_VERSION = 3;
|
|
129
|
+
// The autorouter's results too, by its exact input (@rulecad/pcb reads RULECAD_ROUTE_CACHE): a board rebuilt for anything
|
|
130
|
+
// but its routing (a change to the library, its finish, its checks) reuses its route instead of searching again
|
|
131
|
+
if (!process.env.CAD_NO_CACHE) process.env.RULECAD_ROUTE_CACHE ||= paths.cache('routes');
|
|
129
132
|
const source = (f) => fs.readFileSync(new URL(f, import.meta.url), 'utf8');
|
|
130
133
|
// What every build is made with: this code, the shape helpers and JSCAD's version (an upgrade rebuilds everything);
|
|
131
134
|
// boards also with the board engine (engineId: its code and tscircuit's version), loaded only for boards
|
package/lib/fasten.mjs
CHANGED
|
@@ -165,12 +165,13 @@ const same = (a, b) => {
|
|
|
165
165
|
* near: the faces within R, in the axis's own coordinates, for further slices; x, y: the directions across the axis
|
|
166
166
|
*/
|
|
167
167
|
export function profile(tris, O, D, R) {
|
|
168
|
-
const f = frameOf(O, D), near = [], hits = [], cuts = new Set();
|
|
168
|
+
const f = frameOf(O, D), near = [], hits = [], cuts = new Set(), flats = new Set();
|
|
169
169
|
for (const poly of tris) for (const t of fan(poly)) {
|
|
170
170
|
const q = t.map(f.to);
|
|
171
171
|
if (Math.min(q[0][0], q[1][0], q[2][0]) > R || Math.max(q[0][0], q[1][0], q[2][0]) < -R || Math.min(q[0][1], q[1][1], q[2][1]) > R || Math.max(q[0][1], q[1][1], q[2][1]) < -R) continue;
|
|
172
172
|
near.push(q);
|
|
173
173
|
for (const p of q) cuts.add(Math.round(p[2] * 1e6) / 1e6);
|
|
174
|
+
if (Math.abs(q[0][2] - q[1][2]) < 1e-6 && Math.abs(q[0][2] - q[2][2]) < 1e-6) flats.add(Math.round(q[0][2] * 1e6) / 1e6); // (a face square to the axis: a seat, a floor)
|
|
174
175
|
// where the axis itself goes through this face, and which way the face looks
|
|
175
176
|
const [a, b, c] = q, det = (b[0] - a[0]) * (c[1] - a[1]) - (c[0] - a[0]) * (b[1] - a[1]);
|
|
176
177
|
if (Math.abs(det) < 1e-12) continue;
|
|
@@ -184,7 +185,8 @@ export function profile(tris, O, D, R) {
|
|
|
184
185
|
for (let i = 0; i < hits.length;) { let j = i, net = 0; while (j < hits.length && hits[j][0] - hits[i][0] < 1e-6) net += hits[j++][1]; if (net) walls.push([hits[i][0], net > 0 ? -1 : 1]); i = j; }
|
|
185
186
|
const solidAt = (z) => { let depth = 0; for (const [w, s] of walls) { if (w > z) break; depth += s; } return depth > 0; };
|
|
186
187
|
let zs = [...cuts].sort((a, b) => a - b);
|
|
187
|
-
|
|
188
|
+
// (a drawn thread: sampled evenly, and at every face square to the axis, so a counterbore's floor is a step, not a cone)
|
|
189
|
+
if (zs.length > 600) { const lo = zs[0], hi = zs.at(-1); zs = [...new Set([...Array.from({ length: 401 }, (_, i) => lo + ((hi - lo) * i) / 400), ...flats])].sort((a, b) => a - b); }
|
|
188
190
|
const segs = [];
|
|
189
191
|
for (let i = 0; i + 1 < zs.length; i++) {
|
|
190
192
|
const z0 = zs[i], z1 = zs[i + 1], len = z1 - z0; if (len < 1e-5) continue;
|
|
@@ -371,6 +373,8 @@ function slotInto(s, n, what) {
|
|
|
371
373
|
if (m[3] != null) { try { distance = beamAnchor(b, `${open[0].name}@${m[3]}`).distance; } catch (e) { throw new Error(`${what}: ${String(e.message).replace(/^beamAnchor: /, '')}`); } }
|
|
372
374
|
return { item: id, beam: b, face: m[1], places: open.map((p) => ({ ...p, slotModel: b.profile.slots[p.slot] })), distance, address: rest };
|
|
373
375
|
}
|
|
376
|
+
// what is under a screw's head in a slot past the part: the lip, or down to where the nut seats under sloped lips
|
|
377
|
+
const lipSays = (sl) => (sl.seat > sl.lip + 1e-6 ? `the ${mm2(sl.seat)} mm down to its nut's seat under the slot's sloped ${mm2(sl.lip)} mm lips` : `the slot's ${mm2(sl.lip)} mm lip`);
|
|
374
378
|
// A screw into a slot (into is slotInto's): where its axis meets the face, read in the beam's own frame, held to a slot's
|
|
375
379
|
// centre line within the play its hole gives it (fasten.slot); then the slot nut under the lips, as the far end: its
|
|
376
380
|
// thread from its tongue down, the slot's floor under it. null where the screw is not over a slot, said as fasten.slot
|
|
@@ -394,10 +398,12 @@ function slotEnd(s, at, n, { B, O, D, x, fx, cl, clr, say, sc }) {
|
|
|
394
398
|
if (off > play + 1e-3) return bad(`${part}'s hole is ${mm(off)} mm off the centre line of ${slot}, where its ${mm(d)} mm hole lets ${an(fx.thread)} ${fx.thread} screw move ${mm(play)} mm: the screw meets ${at.face === 'top' || at.face === 'bottom' ? 'the face' : 'the side'} beside the slot, not its nut${pitch ? `. ${item}'s ${at.face} slots are ${mm(pitch)} mm apart` : ''}. Move the hole ${mm(off)} mm, or ${part} is drawn for another profile`);
|
|
395
399
|
if (h.along < -1e-3 || h.along > L + 1e-3) return bad(`the screw meets ${face} ${mm(h.along)} mm from its end a, past the beam: it is ${mm(L)} mm long`);
|
|
396
400
|
say('fasten.slot', 'pass', `over the centre line of ${slot} (${h.p.slot})${off > 1e-3 ? `, ${mm(off)} mm off it, within the ${mm(play)} mm its ${mm(d)} mm hole gives` : ''}, ${mm(h.along)} mm from ${item}'s end a`, values);
|
|
397
|
-
|
|
401
|
+
// the nut's top seats under the lips, lower where their undersides slope and it is wider than the opening (nutFit's
|
|
402
|
+
// slot_nut.seat): its thread, its tongue's with it, starts there
|
|
403
|
+
const sm = h.p.slotModel, seat = n.fits?.find((q) => q.code === 'slot_nut.seat')?.values?.seat ?? sm.lip, zFace = h.t, zLip = zFace + seat, alongW = unit([pm[8], pm[9], pm[10]]);
|
|
398
404
|
sc.slot = { item, place: h.p.name, named, face: at.face, slot: h.p.slot, distance: r3(h.along), nut: n.name, kind: n.nutKind, entry: n.entry, thread: fx.thread, part };
|
|
399
405
|
sc.slotPlay = play; sc.slotSays = slot; // (for the place "into" gives, held over the group: slotPlaced)
|
|
400
|
-
return { slot: { item, place: named, face: at.face, slot: h.p.slot, opening: sm.opening, lip: sm.lip, along: alongW, distance: r3(h.along), part }, kind: 'nut', mouth: zFace, depth: sm.cavityDepth, floor: zFace + sm.cavityDepth,
|
|
406
|
+
return { slot: { item, place: named, face: at.face, slot: h.p.slot, opening: sm.opening, lip: sm.lip, seat: r3(seat), along: alongW, distance: r3(h.along), part }, kind: 'nut', mouth: zFace, depth: sm.cavityDepth, floor: zFace + sm.cavityDepth,
|
|
401
407
|
blind: true, far: zFace + sm.cavityDepth, d: fx.major, free: fx.major, nut: { kind: n.nutKind, model: n, z: zLip, seated: true }, zThr: zLip - n.tongueHeight, thread: n.height + n.tongueHeight };
|
|
402
408
|
}
|
|
403
409
|
/**
|
|
@@ -452,6 +458,21 @@ function beamTap(s, B, O, D) {
|
|
|
452
458
|
return out;
|
|
453
459
|
}
|
|
454
460
|
|
|
461
|
+
// A printed beam's end the screw goes into, where its line runs up that end's fixing: the thread its insert or
|
|
462
|
+
// captive nut takes (the beam's printed ends), so a screw of another thread is refused by name
|
|
463
|
+
function printedEnd(s, B, O, D) {
|
|
464
|
+
for (const p of B.parts) {
|
|
465
|
+
const b = s.objects.find((o) => o.id === p.leaf)?.beam;
|
|
466
|
+
if (!b?.printed?.ends || !p.m) continue;
|
|
467
|
+
for (const [e, fix] of Object.entries(b.printed.ends)) {
|
|
468
|
+
const z = e === 'a' ? 0 : b.length, P = vec3.transform([0, 0, 0], [fix.at[0], fix.at[1], z], p.m), q = vec3.transform([0, 0, 0], [fix.at[0], fix.at[1], e === 'a' ? 1 : b.length - 1], p.m);
|
|
469
|
+
const Z = unit([q[0] - P[0], q[1] - P[1], q[2] - P[2]]), off = Math.hypot(...cross(add(P, O, -1), D));
|
|
470
|
+
if (Math.abs(Math.abs(dot(Z, D)) - 1) < 1e-6 && off <= FASTEN.align.value) return { end: e, thread: fix.thread, kind: fix.kind };
|
|
471
|
+
}
|
|
472
|
+
}
|
|
473
|
+
return null;
|
|
474
|
+
}
|
|
475
|
+
|
|
455
476
|
/**
|
|
456
477
|
* An assembly's fasten relations, worked out from its parts as they stand: each screw followed along its axis, what
|
|
457
478
|
* was measured, what was found, and the hardware to place.
|
|
@@ -704,10 +725,10 @@ export function fastenOf(s, worlds, opts = {}) {
|
|
|
704
725
|
for (const kind of sh === 'square' ? ['square'] : ['hex', 'lock']) { try { const n = nutModel(kind); if (across >= n.flats - 0.05 && across <= n.flats + 1 && (!seatNut || wantNut === kind)) seatNut = { kind, model: n, across }; } catch {} }
|
|
705
726
|
}
|
|
706
727
|
if (end.slot) {
|
|
707
|
-
const n = end.nut.model, warns = n.fits.filter((q) => q.level
|
|
728
|
+
const n = end.nut.model, warns = n.fits.filter((q) => q.level === 'warn' || q.level === 'fail'), notes = n.fits.filter((q) => q.level === 'info'), where = `${end.slot.item}'s ${end.slot.place} slot`;
|
|
708
729
|
if (end.slot.opening < fx.major) say('fasten.clearance', 'fail', `${where} opens ${mm(end.slot.opening)} mm, narrower than ${an(fx.thread)} ${fx.thread} screw (${mm(fx.major)} mm): it does not pass between the lips`, { opening: end.slot.opening, major: fx.major });
|
|
709
730
|
else say('fasten.clearance', 'pass', `${an(fx.thread)} ${fx.thread} screw passes between the lips of ${where}, ${mm(end.slot.opening)} mm apart`, { opening: end.slot.opening, major: fx.major });
|
|
710
|
-
say('fasten.end', warns.length ? 'warn' : 'pass', `ends in ${an(n.nutKind)} ${n.nutKind} nut under the lips of ${where}: ${n.name}, ${mm(end.thread)} mm of ${n.thread} thread from ${mm(end.zThr - end.mouth)} to ${mm(end.zThr - end.mouth + end.thread)} mm under the face, the slot's floor at ${mm(end.depth)} mm${n.entry === 'end' ? '. It goes in from an open end of the slot (frame.nut)' : '. It goes in through the opening, anywhere along the slot'}${warns.length ? `. ${warns.map((q) => q.text).join('; ')}` : ''}`, { thread: end.thread, floor: end.depth, height: n.height, tongue: n.tongueHeight });
|
|
731
|
+
say('fasten.end', warns.length ? 'warn' : 'pass', `ends in ${an(n.nutKind)} ${n.nutKind} nut under the lips of ${where}: ${n.name}, ${mm(end.thread)} mm of ${n.thread} thread from ${mm(end.zThr - end.mouth)} to ${mm(end.zThr - end.mouth + end.thread)} mm under the face, the slot's floor at ${mm(end.depth)} mm${n.entry === 'end' ? '. It goes in from an open end of the slot (frame.nut)' : '. It goes in through the opening, anywhere along the slot'}${warns.length || notes.length ? `. ${[...warns, ...notes].map((q) => q.text).join('; ')}` : ''}`, { thread: end.thread, floor: end.depth, height: n.height, tongue: n.tongueHeight });
|
|
711
732
|
} else if (end.motor) { end.kind = 'tap'; say('fasten.end', 'pass', end.motor.reach ? `ends in ${x.into}'s own ${fx.thread} thread, which its maker allows a screw ${mm(end.depth)} mm into (${end.motor.model}.mount_hole_reach)` : `ends in ${x.into}'s own ${fx.thread} thread, ${mm(end.depth)} mm deep (${end.motor.model}.mount_hole_depth)`, endValues); }
|
|
712
733
|
else if (wantNut || seatNut) {
|
|
713
734
|
const kind = wantNut ?? seatNut.kind, nm = nutModel(kind);
|
|
@@ -719,7 +740,8 @@ export function fastenOf(s, worlds, opts = {}) {
|
|
|
719
740
|
say('fasten.end', 'pass', `ends in ${an(nm.name)} ${nm.name} ${end.nut.seated ? `in its seat in ${x.into}, ${mm(seatNut.across)} mm across the flats for the nut's ${mm(nm.flats)} mm` : `on the far face of ${x.into}`}, past a ${mm(end.d)} mm clearance hole`, { ...endValues, flats: nm.flats });
|
|
720
741
|
}
|
|
721
742
|
} else {
|
|
722
|
-
const bt = beamTap(s, B, O, D);
|
|
743
|
+
const bt = beamTap(s, B, O, D), pe = bt ? null : printedEnd(s, B, O, D);
|
|
744
|
+
if (pe && pe.thread !== fx.thread) { say('fasten.end', 'fail', `${x.into}'s end ${pe.end} is printed with ${an(pe.thread)} ${pe.thread} ${pe.kind === 'nut' ? 'captive nut' : 'heat-set insert'} in place of a tap, and the screw is ${fx.thread}: use ${an(pe.thread)} ${pe.thread} screw (a printed foot takes it as "thread": "${pe.thread}")`, { thread: pe.thread }); bad = true; return; }
|
|
723
745
|
if (bt && bt.thread !== fx.thread) { say('fasten.end', 'fail', `${x.into}'s bore ${bt.bore} is tapped ${bt.thread}, and the screw is ${fx.thread}: use ${an(bt.thread)} ${bt.thread} screw, or tap it ${fx.thread}`); bad = true; return; }
|
|
724
746
|
if (bt) { end.kind = 'tap'; end.blind = bt.depth < bt.length - 1e-6; end.depth = Math.min(bt.depth, bt.length); end.beamTap = bt; }
|
|
725
747
|
const hit = bt ? null : kinds.filter((c) => Math.abs(end.d - c.hole.diameter) <= sizeTol).sort((p, q) => Math.abs(end.d - p.hole.diameter) - Math.abs(end.d - q.hole.diameter))[0];
|
|
@@ -746,7 +768,7 @@ export function fastenOf(s, worlds, opts = {}) {
|
|
|
746
768
|
const lo = end.zThr + need - zHead, hi = end.floor - FASTEN.floor.value - zHead, L0 = sold.find((l) => l >= lo - EPS && l <= hi + EPS);
|
|
747
769
|
end.need = need; end.window = [r3(lo), r3(hi)];
|
|
748
770
|
if (L0) pick = { name: F.screwModel(fx, { length: L0, head: form }).name, length: L0, engaged: r3(Math.min(end.thread, zHead + L0 - end.zThr)), spare: r3(end.floor - zHead - L0) };
|
|
749
|
-
else none = `no ${fx.thread} ${form} screw is sold from ${mm2(lo)} to ${mm2(hi)} mm long, what ${mm2(grip)} mm under its head (${end.slot.part}${washer ? ', the washer' : ''} and
|
|
771
|
+
else none = `no ${fx.thread} ${form} screw is sold from ${mm2(lo)} to ${mm2(hi)} mm long, what ${mm2(grip)} mm under its head (${end.slot.part}${washer ? ', the washer' : ''} and ${lipSays(end.slot)}) leaves: ${mm2(need)} mm in the nut and ${mm2(FASTEN.floor.value)} mm kept off the slot's floor (${(sold.filter((l) => l < lo - EPS).at(-1) ?? null) != null ? `${fx.thread}x${sold.filter((l) => l < lo - EPS).at(-1)} engages too little, ` : ''}${sold.find((l) => l > hi + EPS) != null ? `${fx.thread}x${sold.find((l) => l > hi + EPS)} reaches the floor` : 'none is that long'}). A part of another thickness, or a washer under the head`;
|
|
750
772
|
} else if (end.motor && form !== 'set') { // the longest sold length that stops short of the motor's thread's end, as motor.mount chooses
|
|
751
773
|
const sold = fx.figures.lengths?.value || [], room = end.depth - (end.motor.reach ? 0 : tipRoom), L0 = [...sold].reverse().find((l) => l > grip + EPS && l - grip <= room + (end.motor.reach ? READ : EPS)); // (a maker's reach is the limit itself: no room kept past it, the mesh's grid allowed)
|
|
752
774
|
if (L0) pick = { name: F.screwModel(fx, { length: L0, head: form }).name, length: L0, engaged: r3(L0 - grip), spare: r3(room - (L0 - grip)) };
|
|
@@ -775,7 +797,7 @@ export function fastenOf(s, worlds, opts = {}) {
|
|
|
775
797
|
const lenValues = { length: L, grip: r3(grip), into: r3(inEnd) }, under = `${mm2(grip)} mm under its head${washer ? ' (its washer with it)' : ''}`;
|
|
776
798
|
const wouldDo = pick && pick.length !== L ? `${pick.name} would do` : null;
|
|
777
799
|
if (given == null) {
|
|
778
|
-
if (pick && end.slot) say('fasten.length', 'pass', `${pick.name} chosen, the shortest sold that fits: ${under} (${end.slot.part}${washer ? ', the washer' : ''} and
|
|
800
|
+
if (pick && end.slot) say('fasten.length', 'pass', `${pick.name} chosen, the shortest sold that fits: ${under} (${end.slot.part}${washer ? ', the washer' : ''} and ${lipSays(end.slot)}), ${mm2(pick.engaged)} mm into its nut, its tip ${mm2(zTip - end.mouth)} mm into the slot and ${mm2(pick.spare)} mm short of its floor`, { ...lenValues, floor: r3(pick.spare) });
|
|
779
801
|
else if (pick) say('fasten.length', 'pass', `${pick.name} chosen, the ${end.motor ? (end.motor.reach ? 'longest sold that goes no further than its maker allows' : 'longest sold that stops short of the end of the thread') : 'shortest sold that fits'}: ${under} and ${mm2(pick.engaged)} mm into ${x.into}${end.kind === 'nut' ? '\'s nut' : ''}${pick.spare != null ? `, ${mm2(pick.spare)} mm short of bottoming out` : ''}`, lenValues);
|
|
780
802
|
else if (none) say('fasten.length', 'fail', `no length chosen: ${none}`, lenValues);
|
|
781
803
|
else if (form !== 'set') say('fasten.length', 'info', `no length chosen until the far end is one a screw holds in: ${model.name} is drawn`, lenValues);
|