@rulecad/cad 0.7.41 → 0.7.42

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/EXAMPLES.md CHANGED
@@ -473,7 +473,7 @@ export function main (v) {
473
473
  "boss": { "value": 12, "unit": "mm", "rule": "Round the axle's foot" },
474
474
  "foot": { "value": 40, "unit": "mm", "rule": "A foot across the middle, so it stands without rocking" },
475
475
  "thick": { "value": "x1c.layer * 15", "unit": "mm", "rule": "Fifteen layers" },
476
- "pin": { "value": "3.2 - x1c.line / 2", "unit": "mm", "rule": "The axle: the pinion's 3.2 mm bore less half a line, so it turns" },
476
+ "pin": { "value": "3.2 - 2 * x1c.fit - x1c.hole_comp", "unit": "mm", "rule": "The axle: the pinion's 3.2 mm bore, less the printer's fit each side and what a printed bore loses, so it turns" },
477
477
  "pin_height": { "value": "x1c.layer * 60", "unit": "mm", "rule": "Up through the pinion and its knob" },
478
478
  "guide_y": { "value": "0 - 5.45 - x1c.line / 2", "unit": "mm", "rule": "Behind the rack's back (1.25 + 4.2 mm under its pitch line), half a line clear" },
479
479
  "guide": { "value": "x1c.line * 4", "unit": "mm", "rule": "The guide wall: four lines" },
@@ -646,7 +646,7 @@ export function main (v) {
646
646
  "module": { "value": 1, "unit": "mm", "rule": "As the ring" },
647
647
  "teeth": { "value": 18, "rule": "From planetary(): 18 for 4 : 1 with three planets" },
648
648
  "width": { "value": "x1c.layer * 30", "unit": "mm", "rule": "As the ring" },
649
- "bore": { "value": "3 + x1c.line / 2", "unit": "mm", "rule": "A 3 mm pin and half a line's clearance" }
649
+ "bore": { "value": "3 + 2 * x1c.fit + x1c.hole_comp", "unit": "mm", "rule": "A 3 mm pin, the printer's fit each side, and what a printed bore loses" }
650
650
  }
651
651
  }
652
652
  ```
@@ -672,7 +672,7 @@ The sun is a planet with the spool's shaft on top, bored through for its axle:
672
672
  "module": { "value": 1, "unit": "mm", "rule": "As the ring" },
673
673
  "teeth": { "value": 18, "rule": "From planetary()" },
674
674
  "width": { "value": "x1c.layer * 30", "unit": "mm", "rule": "As the ring" },
675
- "bore": { "value": "3 + x1c.line / 2", "unit": "mm", "rule": "On the case's 3 mm axle" },
675
+ "bore": { "value": "3 + 2 * x1c.fit + x1c.hole_comp", "unit": "mm", "rule": "On the case's 3 mm axle: the printer's fit each side, and what a printed bore loses" },
676
676
  "shaft": { "value": 8, "unit": "mm", "rule": "The spool's shaft, inside the sun's roots" },
677
677
  "shaft_height": { "value": 12, "unit": "mm", "rule": "Up through the carrier, and a spool's width over it" }
678
678
  }
package/bin/cad.mjs CHANGED
@@ -80,6 +80,12 @@ const HELP = `cad: JSCAD designs you can trace, check, share and print (rulecad)
80
80
  cad printed <project>/<object> --result ok|failed [--note "…"] [--material PETG] [--version 0.1.0]
81
81
  cad release <project> --all -m "…" release every object that changed (each with this message), then the project
82
82
 
83
+ cad list <project>/<assembly> what it takes to build: bought parts by set, fasteners, wire, printed parts in grams
84
+ cad wires <project>/<assembly> the wiring sheet: each wire's length, gauge and ends [--out wiring.md]
85
+ cad measured <project>/<assembly> <name>=<value> … a measurement, where the estimate was: a rule (x1c.press=0.08) or a
86
+ check's prediction (task.accuracy=0.8): says what moved, and keeps a ledger of predicted
87
+ against measured, shown by cad history [--unit mm] [--source "how"] [--rule "what it is"]
88
+ [--table: what the assembly still assumes, as Markdown; --out MEASURE.md: kept in that file]
83
89
  cad measure <model.stl|3mf> a model from elsewhere, measured: size, the stretches along its length with the same
84
90
  cross-section, and each section's shape, with a drawing in .preview/measure/
85
91
  [--along x|y|z] [--at 10,50: sections there too] [--line 0.6,2.5;4.6,2.5: where lines
@@ -104,8 +110,8 @@ const HELP = `cad: JSCAD designs you can trace, check, share and print (rulecad)
104
110
 
105
111
  // Every command and option there is: a misspelt one is refused by name, not passed over
106
112
  const COMMANDS = ['new', 'import-kle', 'clone', 'agents', 'trust', 'rules', 'values', 'set', 'add', 'why', 'check', 'preview', 'animate', 'optimise', 'optimize', 'export',
107
- 'show', 'link', 'status', 'release', 'history', 'diff', 'printed', 'measure', 'match', 'variants', 'compare', 'help'];
108
- const OPTIONS = ['all', 'along', 'at', 'bump', 'depth', 'dry-run', 'explode', 'force', 'fresh', 'json', 'licence', 'license', 'long', 'm', 'material', 'md', 'name', 'new',
113
+ 'show', 'link', 'status', 'release', 'history', 'diff', 'printed', 'measure', 'measured', 'list', 'wires', 'match', 'variants', 'compare', 'help'];
114
+ const OPTIONS = ['table', 'all', 'along', 'at', 'bump', 'depth', 'dry-run', 'explode', 'force', 'fresh', 'json', 'licence', 'license', 'long', 'm', 'material', 'md', 'name', 'new',
109
115
  'no-models', 'no-pictures', 'no-rules', 'note', 'open', 'part', 'place', 'pose', 'progress', 'push', 'result', 'rules', 'samples', 'set', 'short', 'source', 'steps',
110
116
  'sweep', 'tol', 'trailer', 'ttl', 'version', 'watch', 'line',
111
117
  'unit', 'rule', 'label', 'from', 'out', // cad set, cad rules
@@ -118,7 +124,7 @@ const USAGE = { add: 'fit|joint|item|loop|pose <project>/<assembly> --key value
118
124
  const args = process.argv.slice(2);
119
125
  // Options that stand alone. Every other takes the value after it: --name value, or -m for one-letter names
120
126
  // (--sweep and --watch take one or not).
121
- const FLAGS = ['all', 'dry-run', 'explode', 'force', 'fresh', 'json', 'long', 'md', 'new', 'no-models', 'no-pictures', 'no-rules', 'open', 'progress', 'push', 'short'];
127
+ const FLAGS = ['table', 'all', 'dry-run', 'explode', 'force', 'fresh', 'json', 'long', 'md', 'new', 'no-models', 'no-pictures', 'no-rules', 'open', 'progress', 'push', 'short'];
122
128
  const opt = (k) => {
123
129
  const i = args.findIndex((a) => a === `--${k}` || (k.length === 1 && a === `-${k}`));
124
130
  if (i < 0) return undefined;
@@ -410,6 +416,8 @@ async function main() {
410
416
  if (cmd === 'release') return ref.includes('/') ? releaseObject(locate(ref)) : opt('all') ? releaseAll(ref) : releaseProject(ref);
411
417
  if (cmd === 'variants') return variants(locate(ref));
412
418
  if (cmd === 'compare') return compareVariants(locate(ref), pos[2], pos[3]);
419
+ if (cmd === 'measured') return measuredCommand(ref);
420
+ if (cmd === 'list' || cmd === 'wires') return listCommand(cmd, ref);
413
421
  if (cmd === 'history') return history(ref);
414
422
  if (cmd === 'diff') return diff(locate(ref), pos[2], pos[3] || null);
415
423
  if (cmd === 'printed') return printed(locate(ref));
@@ -894,10 +902,54 @@ async function status(project) {
894
902
  }
895
903
  }
896
904
 
905
+ async function listCommand(what, ref) {
906
+ if (!isAssembly(ref)) throw new Error(`cad ${what} works on an assembly (<project>/<assembly>), and there is no "${ref}"`);
907
+ const s = await buildAssembly(ref);
908
+ if (what === 'list') {
909
+ const { shoppingList, listText } = await import('../lib/list.mjs'), l = shoppingList(s);
910
+ return console.log(opt('json') ? JSON.stringify(l, null, 2) : listText(ref, l));
911
+ }
912
+ const { wiresFor } = await import('../lib/assembly.mjs'), { wiringSheet } = await import('../lib/wires.mjs'), rows = wiresFor(s);
913
+ if (opt('json')) return console.log(JSON.stringify(rows.map(({ route, ...r }) => r), null, 2));
914
+ if (!rows.length) return console.log(`${ref} has no "wires"`);
915
+ if (opt('out')) { fs.writeFileSync(path.resolve(opt('out')), wiringSheet(rows) + '\n'); return console.log(`wrote ${opt('out')}`); }
916
+ console.log(wiringSheet(rows));
917
+ }
918
+
919
+ async function measuredCommand(ref) {
920
+ const { recordMeasured, assumptionsTable, writeTable, ledgerLines } = await import('../lib/measured.mjs');
921
+ if (opt('table')) {
922
+ const table = await assumptionsTable(ref);
923
+ if (opt('out')) { writeTable(path.resolve(opt('out')), table); return console.log(`wrote the table to ${opt('out')}`); }
924
+ return console.log(table);
925
+ }
926
+ const values = Object.fromEntries(positional().slice(2).map((x) => { const i = x.indexOf('='); if (i < 1) throw new Error(`usage: cad measured <project>/<assembly> <name>=<value> … (got "${x}")`); return [x.slice(0, i), Number(x.slice(i + 1))]; }));
927
+ const r = await recordMeasured(ref, values, { unit: opt('unit'), source: opt('source'), rule: opt('rule') });
928
+ if (opt('json')) return console.log(JSON.stringify({ entries: r.entries, moved: r.moved }, null, 2));
929
+ for (const l of ledgerLines(r.entries)) say(l);
930
+ for (const m of r.moved) say(m.figure ? ` ${m.figure}: ${Number(m.from.toFixed(4))} ${m.unit} to ${Number(m.to.toFixed(4))} ${m.unit}` : ` ${m.code}: ${m.text}`);
931
+ if (!r.moved.length) say(' nothing the checks say has moved');
932
+ }
933
+
934
+ async function ledger(project, name) {
935
+ const { readLedger, ledgerLines } = await import('../lib/measured.mjs');
936
+ const rows = readLedger(project).filter((e) => !name || e.assembly === name);
937
+ return { rows, lines: ledgerLines(rows) };
938
+ }
939
+
897
940
  async function history(ref) {
898
941
  const [project, name] = ref.split('/');
942
+ if (name && isAssembly(ref)) {
943
+ const { rows, lines } = await ledger(project, name);
944
+ if (opt('json')) return console.log(JSON.stringify({ assembly: ref, ledger: rows }, null, 2));
945
+ if (!lines.length) return say(`${ref}: nothing measured yet (cad measured ${ref} <name>=<value>)`);
946
+ say('predicted against measured:'); for (const l of lines) say(` ${l}`);
947
+ return;
948
+ }
899
949
  if (!name) {
900
- if (opt('json')) return console.log(JSON.stringify({ project, releases: tags(project).reverse() }, null, 2));
950
+ const { rows, lines } = await ledger(project);
951
+ if (lines.length && !opt('json')) { console.log('predicted against measured:'); for (const l of lines) console.log(` ${l}`); }
952
+ if (opt('json')) return console.log(JSON.stringify({ project, releases: tags(project).reverse(), ledger: rows }, null, 2));
901
953
  for (const t of tags(project).reverse()) console.log(`${t.tag} ${t.date} ${t.kind} ${t.message}`);
902
954
  return status(project);
903
955
  }
package/lib/assembly.mjs CHANGED
@@ -32,7 +32,12 @@ import { keys as keyCentres, readLayout, hasLayout } from './layout.mjs';
32
32
  import { DOFS, frame, turn, mul, pathLength, jointValues, placeItems, jointMatrix } from '@rulecad/model-link';
33
33
  import { gearModel, internalModel, rackModel, mesh as meshOf, phase, rackPhase, contact, wormModel, wormMesh, bevelModel, bevelMesh, compoundEfficiency } from '@rulecad/gears';
34
34
  import { ops as booleans } from '@rulecad/shapes';
35
- import { motorBuilt, motorDrives, shaftFits, loadsOf, motorChecks, shaftFit } from './motors.mjs';
35
+ import { motorBuilt, motorDrives, shaftFits, loadsOf, motorChecks, shaftFit, axisOf } from './motors.mjs';
36
+ import { runningChecks, seatFit } from './seats.mjs';
37
+ import { seatSize } from '@rulecad/shapes';
38
+ import { wiresOf, wireChecks, wireRows } from './wires.mjs';
39
+ import { printedParts } from './list.mjs';
40
+ import { boughtBuilt, boughtFindings, boughtSets } from './bought.mjs';
36
41
 
37
42
  export const assemblyPath = (ref) => { const [project, name] = String(ref).split('/'); return path.join(paths.project(project || ''), 'assemblies', `${name || ''}.json`); };
38
43
  export const isAssembly = (ref) => String(ref).includes('/') && host.exists(assemblyPath(ref.split('@')[0]));
@@ -96,6 +101,11 @@ export async function buildAssembly(ref, stack = [], overrides = {}, opts = {})
96
101
  const built = new Map(); // each object or component is built once per set of values, however many copies are placed
97
102
  const source = async (it, extra) => {
98
103
  if (it.motor) { const key = JSON.stringify(['motor', it.id, it.motor]); if (!built.has(key)) built.set(key, motorBuilt(it.motor, num, it.id)); return built.get(key); }
104
+ if (it.bought) {
105
+ const key = JSON.stringify(['bought', it.id, it.bought, it.variant]);
106
+ if (!built.has(key)) built.set(key, boughtSets().get(it.bought) === 'motor' ? motorBuilt({ model: it.bought }, num, it.id) : boughtBuilt(it.bought, it, num, it.id));
107
+ return built.get(key);
108
+ }
99
109
  // from: inputs worked out from items built before this one ({ "usb_y": "board.pcb.pico_y" }): numbers, in this
100
110
  // assembly's names, so a part can take a value only another part knows once it's built
101
111
  const from = Object.fromEntries(Object.entries(it.from || {}).map(([k, x]) => [k, num(x)]));
@@ -132,7 +142,7 @@ export async function buildAssembly(ref, stack = [], overrides = {}, opts = {})
132
142
  let builtCount = 0;
133
143
  for (const it of a.items || []) {
134
144
  if (!/^[a-z][\w-]*$/.test(it.id || '')) throw new Error(`each item needs an id (letters, digits, - or _): got ${JSON.stringify(it.id)}`);
135
- if ([it.object, it.assembly, it.motor].filter(Boolean).length !== 1) throw new Error(`item ${it.id}: give one of "object", "assembly" or "motor"`);
145
+ if ([it.object, it.assembly, it.motor, it.bought].filter(Boolean).length !== 1) throw new Error(`item ${it.id}: give one of "object", "assembly", "motor" or "bought"`);
136
146
  // Copies: one, a grid from repeat x/y, or a layout's keys. Each: { id, offset (from at), extra (values to set) }
137
147
  const rx = it.repeat?.x, ry = it.repeat?.y, rl = it.repeat?.layout, copies = [];
138
148
  if (rl) {
@@ -185,7 +195,7 @@ export async function buildAssembly(ref, stack = [], overrides = {}, opts = {})
185
195
  }
186
196
  for (const c of copies) { placed.push([it, c]); ids.push(c.id); }
187
197
  }
188
- const motion = motionOf(a, placed, num, ref);
198
+ const motion = motionOf(a, placed, num, ref), wires = wiresOf(a, placed, motion.joints);
189
199
  fits.push(...shaftFits(motion.drives, motion.joints, placed.map(([, c]) => c.id)).map((x) => ({ ...x, num })));
190
200
  for (const [it, c] of placed) {
191
201
  const src = c.src, id = c.id;
@@ -197,7 +207,7 @@ export async function buildAssembly(ref, stack = [], overrides = {}, opts = {})
197
207
  for (const n of sub.seen) seen.add(n);
198
208
  items.push({ ...it, id, sub, role: 'part' });
199
209
  } else {
200
- objects.push({ id, objName: src.objName, version: src.version, built: src.b, role: src.role });
210
+ objects.push({ id, objName: src.objName, version: src.version, built: src.b, role: src.role, ...(src.bought ? { bought: src.bought } : {}), ...(src.motor ? { motor: src.motor } : {}) });
201
211
  items.push({ ...it, id, objName: src.objName, built: src.b, version: src.version, role: src.role });
202
212
  }
203
213
  }
@@ -234,6 +244,7 @@ export async function buildAssembly(ref, stack = [], overrides = {}, opts = {})
234
244
  // A fit with * applies to every copy: "key-*.switch.bottom" becomes one fit for key-0-0, key-0-1, …
235
245
  // With * on both sides, each copy is checked against all the others: { "a": "key-*.cap", "b": "key-*.cap" }
236
246
  for (let x of a.fits || []) {
247
+ if (x.seat != null && x.min == null) x = { ...x, min: -1000 }; // a seat presses, so the pair may overlap
237
248
  if (x.holes) x = { ...x, a: x.holes, b: x.into }; // a holes fit: a board's holes (a) over what its screws go into (b)
238
249
  const star = [x.a, x.b].find((n) => n.includes('*'));
239
250
  if (!star) { fits.push({ ...x, num }); continue; }
@@ -256,7 +267,7 @@ export async function buildAssembly(ref, stack = [], overrides = {}, opts = {})
256
267
  const v = jointValues(motion, p), moved = partsAt(placeItems(motion, v));
257
268
  return { ...s, parts: moved, pose: typeof p === 'string' ? p : null, jointValues: v, polygons: moved.flatMap((x) => x.polygons), triangles: moved.flatMap((x) => x.triangles) };
258
269
  };
259
- const s = { a, project, name, items, parts, objects, fits, requires, values, num, seen, motion, pose: typeof pose === 'string' ? pose : null, jointValues: jv, at,
270
+ const s = { a, project, name, items, parts, objects, fits, requires, values, num, seen, motion, wires, pose: typeof pose === 'string' ? pose : null, jointValues: jv, at,
260
271
  polygons: parts.flatMap((p) => p.polygons), triangles: parts.flatMap((p) => p.triangles) };
261
272
  return s;
262
273
  }
@@ -633,6 +644,7 @@ export function anchorsAt(s, values = s.jointValues) {
633
644
 
634
645
  // keyCentres(layout): each key's centre, from lib/layout.mjs (kept under this name for older callers)
635
646
  export { keyCentres };
647
+ export const wiresFor = (s) => wireRows(s, { placeItems, jointValues, mul });
636
648
 
637
649
  // ---------- checks ----------
638
650
  export { closest };
@@ -678,6 +690,14 @@ function saveOverlaps() {
678
690
  // What a project prints in, for the motors' heat and press-fit checks
679
691
  const materialOf = (project) => { try { return readJson(path.join(paths.project(project), 'project.json')).material; } catch { return null; } };
680
692
 
693
+ // What's printed and how much it weighs, so "design small" is seen on every change
694
+ function massFinding(s, f) {
695
+ if (!s.parts.some((p) => p.role === 'reference') && !s.motion?.joints.length) return; // a machine, not a keyboard plate
696
+ const parts = printedParts(s); if (!parts.length) return;
697
+ const sorted = [...parts].sort((a, b) => b.grams - a.grams), total = sorted.reduce((t, p) => t + p.grams, 0);
698
+ f('info', `${Number(total.toFixed(1))} g printed in ${sorted.length} parts; heaviest ${sorted.slice(0, 3).map((p) => `${p.id} ${p.grams} g`).join(', ')}`, null, { code: 'mass.parts', values: { grams: total, parts: Object.fromEntries(sorted.map((p) => [p.id, p.grams])) } });
699
+ }
700
+
681
701
  export function checkAssembly(s) {
682
702
  const out = [], f = (level, text, card, extra) => out.push({ level, text, ...(card && { card }), ...extra }), mm = (n) => `${Number(n.toFixed(3))}`;
683
703
  // Versions: every pin, from this assembly and its components, against every copy of that object
@@ -724,6 +744,7 @@ export function checkAssembly(s) {
724
744
  if (x.holes) { holesFit(x); continue; }
725
745
  if (x.silent) continue; // lets a pair overlap, and has nothing to report
726
746
  if (x.engage != null) { engageFit(x); continue; }
747
+ if (x.seat != null) { seatFit(x, s, f, { placeItems, jointValues, mul, seatSize }); continue; }
727
748
  if (x.shaft != null) { shaftFit(x, s, f, { placeItems, jointValues, mul, materialName: materialOf(s.project) }); continue; }
728
749
  const A = pickIn(x.a, x), key = x.note || `${x.a} / ${x.b}`;
729
750
  const lo = x.min != null ? x.num(x.min) : -Infinity, hi = x.max != null ? x.num(x.max) : Infinity;
@@ -834,6 +855,10 @@ export function checkAssembly(s) {
834
855
  }
835
856
  }
836
857
  }
858
+ boughtFindings(s, f);
859
+ massFinding(s, f);
860
+ runningChecks(s, f, { axisOf, placeItems, jointValues, mul });
861
+ if (s.wires?.length) wireChecks(s, f, { placeItems, jointValues, mul });
837
862
  motorChecks(s, f, { placeItems, jointValues, mul }, materialOf(s.project));
838
863
  // Plates print everything: no references
839
864
  if (s.a.kind === 'plate') {
@@ -844,7 +869,7 @@ export function checkAssembly(s) {
844
869
  const est = new Set();
845
870
  for (const o of s.objects) for (const e of o.built.entries) if (e.kind === 'estimate' && (e.used || !e.name.includes('.'))) est.add(e.name);
846
871
  for (const n of s.seen) { const [u, k] = n.split('.'); if (loadRuleSet(u).rules[k]?.kind === 'estimate') est.add(n); }
847
- if (est.size) f('warn', `uses estimates, not measurements: ${[...est].join(', ')}. Measure them and record kind: measured`, `Estimate: ${[...est].join(', ')}`, { code: 'rules.estimate', refs: { rules: [...est] } });
872
+ if (est.size) f('warn', `uses estimates, not measurements: ${[...est].join(', ')}. Measure each and settle it with cad measured ${s.project}/${s.name} <name>=<value>`, `Estimate: ${[...est].join(', ')}`, { code: 'rules.estimate', refs: { rules: [...est] } });
848
873
  saveOverlaps();
849
874
  return out;
850
875
  }
package/lib/bought.mjs ADDED
@@ -0,0 +1,98 @@
1
+ // Bought parts in assemblies: a bearing, a switch, a driver, a board or a supply named by its rule set, drawn from the
2
+ // set's figures as a faint reference (never on a plate), with anchors from what it is. A motor is the same thing with a
3
+ // shaft that turns a joint, so its item is built here too (lib/motors.mjs).
4
+ import crypto from 'node:crypto';
5
+ import fs from 'node:fs';
6
+ import jscad from '@jscad/modeling';
7
+ import { peekRuleSet as loadRuleSet } from './rules.mjs';
8
+ import { RULE_DIRS } from './workspace.mjs';
9
+ import { named } from './parts.mjs';
10
+
11
+ const { cuboid, cylinder, polygon } = jscad.primitives, { translate } = jscad.transforms, { union, subtract } = jscad.booleans, { extrudeRotate } = jscad.extrusions;
12
+ const SEG = 48;
13
+
14
+ // Rule sets that are bought parts, for saying what there is
15
+ export function boughtSets() {
16
+ const out = new Map();
17
+ for (const d of RULE_DIRS) if (fs.existsSync(d)) for (const f of fs.readdirSync(d)) {
18
+ if (!f.endsWith('.json') || f === 'vocabulary.json' || f === 'package.json') continue;
19
+ try { const set = JSON.parse(fs.readFileSync(`${d}/${f}`, 'utf8')); if (set.part && !out.has(set.name)) out.set(set.name, set.part); } catch {}
20
+ }
21
+ return out;
22
+ }
23
+
24
+ // A reference item the assembly can place, from its parts, anchors and figures: what a motor and any bought part share
25
+ export function referenceBuilt({ id, key, objName, name, parts, anchors, entries, values, extra = {} }) {
26
+ const b = { object: { name, title: name, role: 'reference', version: '0.0.0', anchors }, values, entries, deps: [], units: {}, parts, polygons: parts.flatMap((p) => p.polygons), triangles: parts.flatMap((p) => p.triangles), hash: crypto.createHash('sha256').update(JSON.stringify([values, entries.map((e) => e.name)])).digest('hex').slice(0, 16) };
27
+ return { key: `${key}:${id}:${b.hash}`, objName, b, version: '0.0.0', role: 'reference', ...extra };
28
+ }
29
+
30
+ const z = (at, axis = [0, 0, 1]) => ({ at, axis });
31
+ const box = (w, d, h, x = 0, y = 0, z0 = 0) => translate([x, y, z0 + h / 2], cuboid({ size: [w, d, h] }));
32
+
33
+ // What each kind of part looks like, from its figures. Each returns { parts: { name: solid }, anchors }
34
+ const SHAPES = {
35
+ bearing(v, set) {
36
+ const r = v.bore / 2, R = v.outer_diameter / 2, w = v.width, c = Math.min(v.chamfer ?? 0.2, (R - r) / 4, w / 4);
37
+ const flange = v.flange_diameter ? v.flange_diameter / 2 : 0, f = v.flange_width ?? 0;
38
+ const pts = flange
39
+ ? [[r + c, 0], [R - c, 0], [R, c], [R, w - f], [flange, w - f], [flange, w], [r + c, w], [r, w - c], [r, c]]
40
+ : [[r + c, 0], [R - c, 0], [R, c], [R, w - c], [R - c, w], [r + c, w], [r, w - c], [r, c]];
41
+ return { parts: { body: extrudeRotate({ segments: SEG }, polygon({ points: pts })) }, anchors: { bore: z([0, 0, w / 2]), outer: z([0, 0, w / 2]), face: z([0, 0, 0]), top: z([0, 0, w]) } };
42
+ },
43
+ switch(v) {
44
+ const w = v.body_width, d = v.body_depth, h = v.body_length, holes = (v.mount_hole_spacing ?? 0) / 2, up = h / 2;
45
+ const pin = (x) => translate([x, 0, up], jscad.transforms.rotateX(Math.PI / 2, cylinder({ radius: (v.mount_hole_diameter ?? 2.4) / 2, height: d + 2, segments: 24 })));
46
+ const body = holes ? subtract(box(w, d, h), pin(-holes), pin(holes)) : box(w, d, h);
47
+ return { parts: { body, lever: box(w, Math.min(4, d), 0.4, w * 0.1, 0, h + 2) }, anchors: { lever: z([w * 0.6, 0, h + 2]), left: z([-holes, 0, up], [0, 1, 0]), right: z([holes, 0, up], [0, 1, 0]), base: z([0, 0, 0]) } };
48
+ },
49
+ board(v, set) {
50
+ const w = v.body_width, d = v.body_depth, t = 1.6;
51
+ const axes = [...new Set(Object.keys(set.rules).map((k) => /^step_pin_(\w+)$/.exec(k)?.[1]).filter(Boolean))].map((a) => a.toUpperCase());
52
+ // Where a board's axis connectors are along its edge is for routing a wire, no closer than that
53
+ const sockets = Object.fromEntries(axes.map((a, i) => [a, z([-w / 2 + ((i + 0.5) * w) / axes.length, d / 2, t], [0, 1, 0])]));
54
+ return { parts: { body: box(w, d, t) }, anchors: { centre: z([0, 0, t / 2]), top: z([0, 0, t]), bottom: z([0, 0, 0]), ...sockets } };
55
+ },
56
+ driver(v) {
57
+ const w = v.body_width, d = v.body_depth, t = 1.6, row = v.row_spacing / 2, pins = v.pin_count / 2, pitch = v.pin_pitch, run = pitch * (pins - 1), pin = 0.64, drop = 8;
58
+ const rows = [-row, row].flatMap((y) => Array.from({ length: pins }, (_, i) => box(pin, pin, drop + t, -run / 2 + i * pitch, y, -drop)));
59
+ return { parts: { body: union(box(w, d, t), box(5, 5, 1, 0, 0, t)), pins: union(rows) }, anchors: { header: z([0, 0, 0]), top: z([0, 0, t]) } };
60
+ },
61
+ encoder(v, set) { return SHAPES.board(v, set); },
62
+ supply(v) {
63
+ const w = v.body_width, d = v.body_depth, h = v.body_length;
64
+ return { parts: { body: box(w, d, h) }, anchors: { base: z([0, 0, 0]), top: z([0, 0, h]), terminals: z([0, -d / 2, h / 2], [0, -1, 0]) } };
65
+ },
66
+ };
67
+
68
+ export function boughtModel(name, variant) {
69
+ const sets = boughtSets();
70
+ if (!sets.has(name)) throw new Error(`no bought part "${name}" (${[...sets.keys()].sort().join(', ')})`);
71
+ const set = loadRuleSet(name);
72
+ let rules = set.rules;
73
+ if (variant != null) {
74
+ const vs = set.variants || {};
75
+ if (!vs[variant]) throw new Error(`${name} has no variant "${variant}" (${Object.keys(vs).join(', ') || 'none'})`);
76
+ rules = { ...set.rules, ...Object.fromEntries(Object.entries(vs[variant].values ?? {}).map(([k, value]) => [k, { ...set.rules[k], value, kind: vs[variant].kind ?? set.rules[k]?.kind, source: vs[variant].source ?? set.rules[k]?.source }])) };
77
+ }
78
+ return { name, part: set.part, variant: variant ?? null, rules };
79
+ }
80
+
81
+ // An item with "bought": built like any other, a reference, its figures in values and its rules in entries
82
+ export function boughtBuilt(spec, it, num, id) {
83
+ const m = boughtModel(spec, it.variant);
84
+ if (!SHAPES[m.part]) throw new Error(`item ${id}: ${spec} is a ${m.part}: bought parts are ${Object.keys(SHAPES).join(', ')}, and a motor goes in "motor"`);
85
+ const values = Object.fromEntries(Object.entries(m.rules).filter(([, r]) => typeof r.value === 'number').map(([k, r]) => [k, r.value]));
86
+ let shape;
87
+ try { shape = SHAPES[m.part](values, m); } catch (e) { throw new Error(`item ${id}: ${spec} doesn't say enough to draw it: ${e.message}`); }
88
+ const missing = Object.entries(shape.anchors).filter(([, a]) => a.at.some((c) => !Number.isFinite(c))).map(([k]) => k);
89
+ if (missing.length) throw new Error(`item ${id}: ${spec}: its rules don't place the anchors ${missing.join(', ')}`);
90
+ const parts = named(shape.parts, Object.fromEntries(Object.keys(shape.parts).map((k) => [k, { label: `${m.name} ${k}` }])));
91
+ const entries = Object.entries(m.rules).map(([k, r]) => ({ name: `${m.name}.${k}`, value: r.value, unit: r.unit, rule: r.rule, kind: r.kind, source: r.source, checked: r.checked, set: m.name }));
92
+ return referenceBuilt({ id, key: 'bought', objName: `bought:${m.name}`, name: m.name, parts, anchors: shape.anchors, entries, values, extra: { bought: { set: m.name, variant: m.variant, part: m.part, mass: values.mass ?? null } } });
93
+ }
94
+
95
+ // One line in the check for each bought item, so the shopping list and the wiring can read it
96
+ export function boughtFindings(s, f) {
97
+ for (const o of s.objects) if (o.bought) f('info', `${o.id}: ${o.bought.set}${o.bought.variant ? ` (${o.bought.variant})` : ''}, a ${o.bought.part}`, null, { code: 'bought.item', refs: { item: o.id, set: o.bought.set, variant: o.bought.variant, part: o.bought.part } });
98
+ }
package/lib/list.mjs ADDED
@@ -0,0 +1,58 @@
1
+ // What a machine takes to build, in numbers: the bought items by rule set with quantities, fasteners from the fits that
2
+ // name them, wires by gauge, and the printed parts with their grams and an estimate of the minutes.
3
+ import { peekRuleSet as loadRuleSet } from './rules.mjs';
4
+ import { paths } from './workspace.mjs';
5
+ import { readJson } from './host.mjs';
6
+ import path from 'node:path';
7
+ import { volume } from './mesh.mjs';
8
+ import { wiresFor } from './assembly.mjs';
9
+
10
+ const n = (x, d = 1) => Number(x.toFixed(d));
11
+
12
+ export function materialOf(project) {
13
+ let name = 'pla';
14
+ try { name = String(readJson(path.join(paths.project(project), 'project.json')).material || 'pla').toLowerCase().split(/\s/)[0]; } catch {}
15
+ try { return { name, density: loadRuleSet(name).rules.density.value }; } catch { return { name, density: 1.25, assumed: true }; }
16
+ }
17
+
18
+ // Every printed thing in the assembly, once for each copy: its volume, grams and minutes
19
+ export function printedParts(s) {
20
+ const mat = materialOf(s.project); let flow = 12;
21
+ try { flow = loadRuleSet('x1c').rules.print_flow?.value ?? flow; } catch {}
22
+ const by = new Map();
23
+ for (const p of s.parts) {
24
+ if (p.role !== 'part' && p.role != null) continue;
25
+ const key = p.leaf ?? p.item, mm3 = volume(p.triangles), o = by.get(key) ?? { id: key, object: p.object ?? null, volume: 0 };
26
+ o.volume += mm3; by.set(key, o);
27
+ }
28
+ return [...by.values()].map((o) => ({ ...o, volume: n(o.volume, 0), grams: n((o.volume / 1000) * mat.density), minutes: n(o.volume / flow / 60, 0) }));
29
+ }
30
+
31
+ /** The whole list. @returns {{ bought: object[], fasteners: object[], wires: object[], printed: object[], totals: object }} */
32
+ export function shoppingList(s) {
33
+ const mat = materialOf(s.project), printed = printedParts(s), bought = new Map(), fasteners = new Map();
34
+ for (const o of s.objects) if (o.bought && !o.unplaced) {
35
+ const key = `${o.bought.set}|${o.bought.variant ?? ''}`, line = bought.get(key) ?? { set: o.bought.set, variant: o.bought.variant, part: o.bought.part, qty: 0, grams: o.bought.mass != null ? o.bought.mass * 1000 : null, items: [] };
36
+ line.qty++; line.items.push(o.id); bought.set(key, line);
37
+ }
38
+ for (const x of s.fits) if (x.fastener) {
39
+ const count = x.count != null ? x.num(x.count) : 1, line = fasteners.get(x.fastener) ?? { fastener: x.fastener, qty: 0, from: [] };
40
+ line.qty += count; line.from.push(x.note || `${x.a} / ${x.b}`); fasteners.set(x.fastener, line);
41
+ }
42
+ const rows = s.wires?.length ? wiresFor(s) : [], wires = new Map();
43
+ for (const w of rows) { const key = w.gauge ?? 'gauge not given', l = wires.get(key) ?? { gauge: w.gauge, conductors: 0, length: 0, runs: [] }; l.length += w.length * w.conductors; l.conductors += w.conductors; l.runs.push(w.id); wires.set(key, l); }
44
+ const boughtList = [...bought.values()].map((b) => ({ ...b, grams: b.grams != null ? n(b.grams) : null })).sort((a, b) => a.part.localeCompare(b.part) || a.set.localeCompare(b.set));
45
+ const printedGrams = printed.reduce((t, p) => t + p.grams, 0), boughtGrams = boughtList.reduce((t, b) => t + (b.grams ?? 0) * b.qty, 0), unknown = boughtList.filter((b) => b.grams == null).map((b) => b.set);
46
+ return { bought: boughtList, fasteners: [...fasteners.values()], wires: [...wires.values()], printed, totals: { printedGrams: n(printedGrams), boughtGrams: n(boughtGrams), machineGrams: n(printedGrams + boughtGrams), minutes: n(printed.reduce((t, p) => t + p.minutes, 0), 0), material: mat.name, ...(mat.assumed ? { densityAssumed: true } : {}), ...(unknown.length ? { noMassFor: unknown } : {}) } };
47
+ }
48
+
49
+ export function listText(ref, l) {
50
+ const out = [`${ref}: what it takes to build`];
51
+ const row = (a) => out.push(a.join(' '));
52
+ if (l.bought.length) { out.push('', 'Bought'); for (const b of l.bought) row([` ${String(b.qty).padStart(3)} ×`, `${b.set}${b.variant ? ` (${b.variant})` : ''}`, `a ${b.part}`, b.grams != null ? `${b.grams} g each` : 'mass not given', b.items.join(', ')]); }
53
+ if (l.fasteners.length) { out.push('', 'Fasteners'); for (const f of l.fasteners) row([` ${String(f.qty).padStart(3)} ×`, f.fastener, f.from.join('; ')]); }
54
+ if (l.wires.length) { out.push('', 'Wire'); for (const w of l.wires) row([` ${w.length} mm of`, w.gauge ?? 'gauge not given', `in ${w.runs.join(', ')}`]); }
55
+ if (l.printed.length) { out.push('', `Printed (${l.totals.material})`); for (const p of l.printed) row([` ${String(p.grams).padStart(7)} g`, `about ${p.minutes} min`, `${p.id}${p.object && p.object !== p.id ? ` (${p.object})` : ''}`]); }
56
+ out.push('', `Total: ${l.totals.printedGrams} g printed, about ${l.totals.minutes} min of printing (an estimate from volume and the printer's flow), ${l.totals.machineGrams} g as a machine${l.totals.noMassFor ? ` (no mass given for ${l.totals.noMassFor.join(', ')})` : ''}`);
57
+ return out.join('\n');
58
+ }
@@ -0,0 +1,87 @@
1
+ // A bench exists so measurements replace estimates and the predictions move. cad measured writes a measured value where
2
+ // the estimate was (in the workspace's copy of the rule set), or a measurement of something a check predicts (a figure
3
+ // no rule holds, like the pen's error at the far corner), runs the assembly's checks either side, says what moved, and
4
+ // keeps a ledger of predicted against measured beside prints.jsonl.
5
+ import fs from 'node:fs';
6
+ import path from 'node:path';
7
+ import { setAt } from './jsonedit.mjs';
8
+ import { CadError } from './errors.mjs';
9
+ import { paths, WS } from './workspace.mjs';
10
+ import { loadRuleSet } from './rules.mjs';
11
+ import { buildAssembly, checkAssembly, assemblyPath } from './assembly.mjs';
12
+
13
+ const today = () => new Date().toISOString().slice(0, 10), n = (x) => String(Number(Number(x).toFixed(4)));
14
+ export const ledgerFile = (project) => path.join(paths.project(project), 'ledger.jsonl');
15
+ export const readLedger = (project) => { const f = ledgerFile(project); return fs.existsSync(f) ? fs.readFileSync(f, 'utf8').split('\n').filter(Boolean).map((l) => JSON.parse(l)) : []; };
16
+
17
+ const findingsOf = async (ref) => checkAssembly(await buildAssembly(ref));
18
+ const keyOf = (x) => `${x.code}|${JSON.stringify(x.refs ?? {})}`;
19
+ // A prediction's name, as cad measured takes it: the check's code, and the part or joint it's about if there are several
20
+ export const predictionsOf = (findings) => findings.filter((x) => x.predict);
21
+
22
+ function ruleFile(name) {
23
+ const dot = name.indexOf('.');
24
+ if (dot < 1) throw new CadError('measured.name', `"${name}": name a rule as <set>.<rule> (x1c.press), or a prediction by its check's code (task.accuracy)`);
25
+ const set = name.slice(0, dot), rule = name.slice(dot + 1);
26
+ const data = loadRuleSet(set); // (copies the tool's set into the workspace, the first time: the measurement goes in your copy)
27
+ return { set, rule, data, file: path.join(WS, 'rules', `${set}.json`) };
28
+ }
29
+
30
+ /**
31
+ * Write measurements back.
32
+ * @param {string} ref project/assembly
33
+ * @param {Record<string, number>} values name → measured value
34
+ * @param {{ unit?: string, source?: string, rule?: string, date?: string }} [options]
35
+ * @returns {Promise<{ entries: object[], moved: { from: string, to: string }[] }>}
36
+ */
37
+ export async function recordMeasured(ref, values, { unit, source, rule, date = today() } = {}) {
38
+ const [project, name] = String(ref).split('/');
39
+ if (!project || !name || !fs.existsSync(assemblyPath(ref))) throw new CadError('measured.assembly', `no assembly "${ref}": give <project>/<assembly>, the one whose predictions it moves`);
40
+ if (!Object.keys(values).length) throw new CadError('measured.usage', 'usage: cad measured <project>/<assembly> <name>=<value> … [--unit mm] [--source "how it was measured"]');
41
+ const before = await findingsOf(ref), entries = [], predictions = predictionsOf(before);
42
+ for (const [k, value] of Object.entries(values)) {
43
+ if (!Number.isFinite(value)) throw new CadError('measured.value', `${k}: a measurement is a number (got ${value})`);
44
+ const named = predictions.filter((x) => x.code === k || x.predict.name === k);
45
+ if (named.length) {
46
+ const p = named[0].predict;
47
+ entries.push({ date, assembly: name, name: k, code: named[0].code, figure: p.figure, unit: p.unit, predicted: p.value, measured: value, ratio: p.value ? value / p.value : null, ...(source ? { source } : {}) });
48
+ continue;
49
+ }
50
+ const { set, rule: key, data, file } = ruleFile(k);
51
+ const old = data.rules?.[key];
52
+ if (!old && !rule) throw new CadError('measured.rule', `${set} has no rule "${key}" (and no check here predicts "${k}"): --rule "what it is" to add it (checks: ${[...new Set(predictions.map((x) => x.code))].join(', ') || 'none'})`);
53
+ if (unit && old?.unit && unit !== old.unit) throw new CadError('measured.unit', `${k} is in ${old.unit}, and this is in ${unit}: give it in ${old.unit}`);
54
+ const entry = { value, unit: unit ?? old?.unit ?? '', rule: rule ?? old.rule, kind: 'measured', source: source || 'measured on the bench', checked: date };
55
+ fs.writeFileSync(file, setAt(fs.readFileSync(file, 'utf8'), ['rules', key], entry));
56
+ entries.push({ date, assembly: name, name: k, figure: entry.rule, unit: entry.unit, predicted: typeof old?.value === 'number' ? old.value : null, was: old?.kind ?? null, measured: value, ratio: typeof old?.value === 'number' && old.value ? value / old.value : null, ...(source ? { source } : {}) });
57
+ }
58
+ const after = await findingsOf(ref), was = new Map(before.map((x) => [keyOf(x), x])), moved = [];
59
+ for (const x of after) {
60
+ const y = was.get(keyOf(x));
61
+ if (x.predict && y?.predict && Math.abs(x.predict.value - y.predict.value) > 1e-9) moved.push({ code: x.code, figure: x.predict.figure, unit: x.predict.unit, from: y.predict.value, to: x.predict.value });
62
+ else if (y && y.text !== x.text && !x.predict) moved.push({ code: x.code, text: x.text, was: y.text });
63
+ }
64
+ fs.appendFileSync(ledgerFile(project), entries.map((e) => JSON.stringify({ ...e, moved: moved.filter((m) => m.figure) })).join('\n') + '\n');
65
+ return { entries, moved, findings: after };
66
+ }
67
+
68
+ // What the kit assumes, as a Markdown table: each rule used that is only an estimate, what measures it, and what it feeds
69
+ export async function assumptionsTable(ref) {
70
+ const findings = await findingsOf(ref), estimates = findings.find((x) => x.code === 'rules.estimate')?.refs?.rules ?? [], preds = predictionsOf(findings);
71
+ const rows = estimates.map((name) => {
72
+ let rule = ''; try { const [u, k] = name.split('.'); rule = loadRuleSet(u).rules[k]?.rule ?? ''; } catch {}
73
+ return `| \`${name}\` | ${rule} | estimate | \`cad measured ${ref} ${name}=<value>\` |`;
74
+ });
75
+ const out = ['| What the kit assumes | What it is | Trust | How to settle it |', '|---|---|---|---|', ...rows,
76
+ ...preds.map((x) => `| ${x.predict.figure} | ${n(x.predict.value)} ${x.predict.unit}, predicted by \`${x.code}\` | prediction | \`cad measured ${ref} ${x.predict.name ?? x.code}=<value>\` |`)];
77
+ return out.join('\n');
78
+ }
79
+ // A table kept in a file, between two markers: the rest of the file stays as written
80
+ export const MARK = ['<!-- cad measured: start -->', '<!-- cad measured: end -->'];
81
+ export function writeTable(file, table) {
82
+ const text = fs.existsSync(file) ? fs.readFileSync(file, 'utf8') : '', a = text.indexOf(MARK[0]), b = text.indexOf(MARK[1]);
83
+ const block = `${MARK[0]}\n${table}\n${MARK[1]}`;
84
+ fs.writeFileSync(file, a >= 0 && b > a ? text.slice(0, a) + block + text.slice(b + MARK[1].length) : `${text}${text && !text.endsWith('\n') ? '\n' : ''}\n${block}\n`);
85
+ }
86
+
87
+ export const ledgerLines = (entries) => entries.map((e) => `${e.date} ${e.assembly} ${e.name}: measured ${n(e.measured)} ${e.unit || ''}`.trimEnd() + (e.predicted != null ? `, predicted ${n(e.predicted)}${e.was ? ` (${e.was})` : ''}${e.ratio != null ? `, ratio ${n(e.ratio)}` : ''}` : '') + (e.source ? ` [${e.source}]` : ''));
package/lib/motors.mjs CHANGED
@@ -2,11 +2,11 @@
2
2
  // slider is the motor turning), and the assembly can say what it has to do: "loads" on joints or masses on links.
3
3
  // From those, what reaches each loaded joint through the meshes and planetaries, whether the joint holds with the
4
4
  // power on and off, and whether the shaft and its mount are fit for it.
5
- import crypto from 'node:crypto';
6
5
  import { createRequire } from 'node:module';
7
6
  import { motorModel, motorParts, mountModel, performance } from '@rulecad/motors';
8
7
  import { stageEfficiency } from '@rulecad/gears';
9
8
  import { named } from './parts.mjs';
9
+ import { referenceBuilt } from './bought.mjs';
10
10
 
11
11
  const require = createRequire(import.meta.url);
12
12
  const n3 = (x, d = 3) => String(Number(x.toFixed(d)));
@@ -22,9 +22,7 @@ export function motorBuilt(spec, num, id) {
22
22
  const anchors = Object.fromEntries(Object.entries(model.anchors).map(([k, a]) => [k, { at: a.origin, axis: a.axis }]));
23
23
  const values = Object.fromEntries(Object.entries(model.figures).filter(([, f]) => typeof f.value === 'number').map(([k, f]) => [k, f.value]));
24
24
  const entries = Object.entries(model.figures).map(([k, f]) => ({ name: `${model.name}.${k}`, value: f.value, unit: f.unit, rule: f.rule, kind: f.kind, source: f.source, checked: f.checked, set: model.name }));
25
- const hash = crypto.createHash('sha256').update(JSON.stringify(model.figures)).digest('hex').slice(0, 16);
26
- const b = { object: { name: model.name, title: model.name, role: 'reference', version: '0.0.0', anchors }, values, entries, deps: [], units: {}, parts, polygons: parts.flatMap((p) => p.polygons), triangles: parts.flatMap((p) => p.triangles), hash };
27
- return { key: `motor:${id}:${hash}`, objName: `motor:${model.name}`, b, version: '0.0.0', role: 'reference', motor: model, spec };
25
+ return referenceBuilt({ id, key: 'motor', objName: `motor:${model.name}`, name: model.name, parts, anchors, entries, values, extra: { motor: model, spec, bought: { set: model.name, variant: null, part: 'motor', mass: model.mass ?? null } } });
28
26
  }
29
27
 
30
28
  // Which joint each motor drives, checked by name; a servo's range and a stepper's step go on the joint. The shaft
@@ -89,7 +87,7 @@ function trainFrom(motion, id) {
89
87
 
90
88
  // World axis of a joint and the world position of a point on an item
91
89
  const rowsAt = (W, p) => [0, 1, 2].map((k) => W[4 * k] * p[0] + W[4 * k + 1] * p[1] + W[4 * k + 2] * p[2] + W[4 * k + 3]);
92
- const axisOf = (motion, worlds, j, mul) => { const P = j.parent < 0 ? j.a : mul(worlds[j.parent], j.a); return { O: [P[3], P[7], P[11]], Z: [P[2], P[6], P[10]] }; };
90
+ export const axisOf = (motion, worlds, j, mul) => { const P = j.parent < 0 ? j.a : mul(worlds[j.parent], j.a); return { O: [P[3], P[7], P[11]], Z: [P[2], P[6], P[10]] }; };
93
91
  const sub = (a, b) => a.map((x, i) => x - b[i]), dot = (a, b) => a[0] * b[0] + a[1] * b[1] + a[2] * b[2];
94
92
  const cross = (a, b) => [a[1] * b[2] - a[2] * b[1], a[2] * b[0] - a[0] * b[2], a[0] * b[1] - a[1] * b[0]];
95
93
 
package/lib/rules.mjs CHANGED
@@ -20,5 +20,11 @@ export function loadRuleSet(name, dir) {
20
20
  }
21
21
  return readJson(own);
22
22
  }
23
+ // A rule set read as it is, the workspace's if it has one: for figures a check only reads, leaving the workspace alone
24
+ export function peekRuleSet(name) {
25
+ const file = RULE_DIRS.map((d) => path.join(d, `${name}.json`)).find((f) => host.exists(f));
26
+ if (!file) throw new Error(`no rule set "${name}" (rules/${name}.json)`);
27
+ return readJson(file);
28
+ }
23
29
  // resolve() as @rulecad/variables describes it, loading the rule sets it isn't handed
24
30
  export const resolve = (object, opts = {}) => resolveWith(object, { load: loadRuleSet, ...opts });
package/lib/seats.mjs ADDED
@@ -0,0 +1,128 @@
1
+ // Seats and running fits, read from the parts as drawn: a slice across the axis, rays out from it. Whether a child turns
2
+ // freely on its pin (joint.running), and whether a printed pocket is right for the bought bearing in it (fit.seat).
3
+ import { createRequire } from 'node:module';
4
+
5
+ const require = createRequire(import.meta.url);
6
+ const n3 = (x, d = 3) => String(Number(x.toFixed(d)));
7
+ const sub = (a, b) => [a[0] - b[0], a[1] - b[1], a[2] - b[2]], dot = (a, b) => a[0] * b[0] + a[1] * b[1] + a[2] * b[2];
8
+ const cross = (a, b) => [a[1] * b[2] - a[2] * b[1], a[2] * b[0] - a[0] * b[2], a[0] * b[1] - a[1] * b[0]];
9
+ const unit = (v) => { const l = Math.hypot(...v); return v.map((c) => c / l); };
10
+
11
+ // Coordinates about an axis: z along it from O, x and y across it
12
+ export function axisFrame(O, Z) {
13
+ const z = unit(Z), seed = Math.abs(z[0]) < 0.9 ? [1, 0, 0] : [0, 1, 0], x = unit(cross(seed, z)), y = cross(z, x);
14
+ return (p) => { const q = sub(p, O); return [dot(q, x), dot(q, y), dot(q, z)]; };
15
+ }
16
+ // A slice across the axis at z, as 2D segments
17
+ export function sliceAt(tris, z) {
18
+ const segs = [];
19
+ for (const t of tris) {
20
+ const c = [];
21
+ for (let i = 0; i < 3; i++) { const a = t[i], b = t[(i + 1) % 3]; if ((a[2] - z) * (b[2] - z) < 0) { const u = (z - a[2]) / (b[2] - a[2]); c.push([a[0] + u * (b[0] - a[0]), a[1] + u * (b[1] - a[1])]); } }
22
+ if (c.length === 2) segs.push(c);
23
+ }
24
+ return segs;
25
+ }
26
+ // How far out from the axis a ray crosses the slice's walls
27
+ export function rayHits(segs, ang) {
28
+ const dx = Math.cos(ang), dy = Math.sin(ang), out = [];
29
+ for (const [p, q] of segs) {
30
+ const ex = q[0] - p[0], ey = q[1] - p[1], den = dx * ey - dy * ex;
31
+ if (Math.abs(den) < 1e-12) continue;
32
+ const t = (p[0] * ey - p[1] * ex) / den, u = (p[0] * dy - p[1] * dx) / den;
33
+ if (t > 1e-6 && u >= 0 && u < 1) out.push(t);
34
+ }
35
+ return out.sort((a, b) => a - b);
36
+ }
37
+ const RAYS = 48, FACETS = 0.02; // mm: what a round drawn in facets is short of its true size
38
+ // At one slice: is the axis in solid (a pin) or in a space (a bore), and the first wall out, each way round
39
+ function round(segs) {
40
+ if (segs.length < 3) return null;
41
+ let solid = 0, bore = 0; const first = [];
42
+ for (let k = 0; k < RAYS; k++) { const h = rayHits(segs, ((k + 0.37) * 2 * Math.PI) / RAYS); if (!h.length) return null; (h.length % 2 ? solid++ : bore++); first.push(h[0]); }
43
+ return { pin: solid > bore, first };
44
+ }
45
+ const span = (tris, r) => { let lo = Infinity, hi = -Infinity; for (const t of tris) for (const p of t) if (Math.hypot(p[0], p[1]) < r) { lo = Math.min(lo, p[2]); hi = Math.max(hi, p[2]); } return [lo, hi]; };
46
+
47
+ // The running gap of a revolute: where one side is a pin and the other a bore round it, the least gap each side as drawn
48
+ // (over a few slices along the length they share) and how far along it runs. null: nothing there turns on a pin
49
+ export function runningGap(aTris, bTris) {
50
+ const reach = 40, [la, ha] = span(aTris, reach), [lb, hb] = span(bTris, reach), lo = Math.max(la, lb), hi = Math.min(ha, hb);
51
+ if (!(hi - lo > 0.2)) return null;
52
+ let least = null, along = 0, step = (hi - lo) / 8;
53
+ for (let k = 0; k < 8; k++) {
54
+ const z = lo + step * (k + 0.5), A = round(sliceAt(aTris, z)), B = round(sliceAt(bTris, z));
55
+ if (!A || !B || A.pin === B.pin) continue;
56
+ const pin = A.pin ? A : B, bore = A.pin ? B : A;
57
+ // A real pin is round about the axis: the widest and narrowest of it agree
58
+ if (Math.max(...pin.first) - Math.min(...pin.first) > 0.5) continue;
59
+ const gap = Math.min(...bore.first.map((r, i) => r - pin.first[i]));
60
+ if (gap > 2) continue; // room, not a running fit
61
+ along += step;
62
+ if (least == null || gap < least.gap) least = { gap, z, pin: Math.max(...pin.first), bore: Math.min(...bore.first), pinOn: A.pin ? 'a' : 'b' };
63
+ }
64
+ return least && { ...least, length: along };
65
+ }
66
+
67
+ // What the project prints on, for the fits to hold a gap against: a rule set the assembly reads, or the kit's default
68
+ export function printerRules(s) {
69
+ const pick = (name) => { try { return Object.fromEntries(Object.entries(require(`@rulecad/rules/${name}.json`).rules).map(([k, r]) => [k, r.value])); } catch { return null; } };
70
+ return { ...pick('x1c'), ...(s.values?.x1c && typeof s.values.x1c === 'object' ? s.values.x1c : {}) };
71
+ }
72
+
73
+ // joint.running: for each revolute, the gap where its child turns on a pin or in a bore. A printed bore comes out
74
+ // hole_comp smaller across, so half of that comes off the gap each side; what's left is held against the printer's fit
75
+ export function runningChecks(s, f, { axisOf, placeItems, jointValues, mul }) {
76
+ const motion = s.motion; if (!motion?.joints?.length) return;
77
+ const worlds = placeItems(motion, jointValues(motion, motion.pose ?? undefined)), ids = motion.items.map((x) => x[0]);
78
+ const P = printerRules(s), fit = P.fit ?? 0.2, comp = P.hole_comp ?? 0.1;
79
+ const refs = new Set(s.objects.filter((o) => o.role === 'reference').map((o) => String(o.id).split('.')[0]));
80
+ const partsOf = (id) => s.parts.filter((p) => p.item === id || p.leaf === id);
81
+ for (const j of motion.joints) {
82
+ if (j.type !== 'revolute' || j.parent < 0) continue;
83
+ const a = ids[j.parent], b = ids[j.child];
84
+ if (refs.has(a) || refs.has(b)) continue; // a bought part's seat is fit.seat's business
85
+ const pa = partsOf(a), pb = partsOf(b);
86
+ if (!pa.length || !pb.length) continue;
87
+ const { O, Z } = axisOf(motion, worlds, j, mul), to = axisFrame(O, Z), g = runningGap(pa.flatMap((p) => p.triangles).map((t) => t.map(to)), pb.flatMap((p) => p.triangles).map((t) => t.map(to)));
88
+ if (!g) continue;
89
+ const printed = g.gap - comp / 2, at = O.map((c, i) => c + unit(Z)[i] * g.z), pin = g.pinOn === 'a' ? a : b, bore = g.pinOn === 'a' ? b : a, refsOut = { joint: j.id, pin, bore };
90
+ const values = { drawn: g.gap, printed, fit, length: g.length }, words = `${bore} on ${pin}'s ${n3(g.pin * 2, 2)} mm pin: ${n3(g.gap)} mm each side as drawn, about ${n3(printed)} mm printed`;
91
+ if (printed <= 0) f('fail', `${j.id}: ${words} (a printed bore comes out ${comp} mm small across): it won't turn. The bore wants ${n3(2 * (g.pin + fit) + comp, 2)} mm`, `${j.id}: no running gap`, { code: 'joint.running', at, refs: refsOut, values });
92
+ else if (printed < fit - FACETS) f('warn', `${j.id}: ${words}, under the printer's ${fit} mm fit: expect it to bind. The bore wants ${n3(2 * (g.pin + fit) + comp, 2)} mm`, `${j.id}: tight on its pin`, { code: 'joint.running', at, refs: refsOut, values });
93
+ else f('pass', `${j.id}: ${words}`, null, { code: 'joint.running', at, refs: refsOut, values });
94
+ }
95
+ }
96
+
97
+ // fit.seat: a printed pocket against the bought bearing in it, read from the part as drawn, so a pocket drawn by hand is
98
+ // caught as well as one from bearingSeat. { "a": "b1", "b": "housing", "seat": "press" | "slip" | clearance in mm }
99
+ export function seatFit(x, s, f, { placeItems, jointValues, mul, seatSize }) {
100
+ const top = (n) => String(n).split(/[.@]/)[0], o = s.objects.find((y) => y.bought?.part === 'bearing' && (y.id === top(x.a) || y.id === top(x.b))), label = x.note || `${x.a} in ${x.b}`, code = 'fit.seat';
101
+ if (!o) return f('fail', `${label}: a seat holds a bought bearing, and neither ${x.a} nor ${x.b} is one`, `${label}: no bearing`, { code });
102
+ const other = top(x.a) === o.id ? top(x.b) : top(x.a), parts = s.parts.filter((p) => p.item === other || p.leaf === other);
103
+ if (!parts.length) return f('fail', `${label}: no part "${other}"`, null, { code });
104
+ const motion = s.motion, ids = motion.items.map((y) => y[0]), W = placeItems(motion, jointValues(motion, motion.pose ?? undefined))[ids.indexOf(o.id)];
105
+ const inv = (p) => { const q = [p[0] - W[3], p[1] - W[7], p[2] - W[11]]; return [W[0] * q[0] + W[4] * q[1] + W[8] * q[2], W[1] * q[0] + W[5] * q[1] + W[9] * q[2], W[2] * q[0] + W[6] * q[1] + W[10] * q[2]]; };
106
+ const tris = parts.flatMap((p) => p.triangles).map((t) => t.map(inv)), v = o.built.values, w = v.width, R = v.outer_diameter / 2, r = v.bore / 2;
107
+ const printer = printerRules(s), want = seatSize(v, { fit: x.seat === true ? 'press' : x.seat, printer }), refs = { item: o.id, part: other };
108
+ const firstWall = (z) => { const segs = sliceAt(tris, z); if (segs.length < 3) return null; const h = []; for (let k = 0; k < RAYS; k++) { const a = rayHits(segs, ((k + 0.37) * 2 * Math.PI) / RAYS); if (!a.length) return null; h.push(a[0]); } return h; };
109
+ const mid = firstWall(w / 2);
110
+ if (!mid) return f('fail', `${label}: halfway along ${o.bought.set}, ${other} doesn't go round it`, `${label}: no seat`, { code, refs });
111
+ const drawn = 2 * Math.max(...mid), diff = drawn - want.pocket, values = { drawn, wanted: want.pocket, difference: diff, comp: want.comp, clearance: want.clearance };
112
+ const inMaterial = 2 * Math.min(...mid) < 2 * r + 0.1;
113
+ if (inMaterial) return f('fail', `${label}: ${other} is solid where the bearing goes (the wall is ${n3(Math.min(...mid), 2)} mm from its axis, inside the ${v.bore} mm bore)`, `${label}: no pocket`, { code, refs, values });
114
+ const say = `${o.bought.set} (${n3(2 * R, 2)} mm) in a pocket drawn ${n3(drawn, 3)} mm`;
115
+ if (Math.abs(diff) > 0.15) f('fail', `${label}: ${say}, and a ${typeof want.fit === 'string' ? want.fit : `${want.fit} mm`} fit on this printer wants ${n3(want.pocket, 3)} mm: ${n3(Math.abs(diff), 2)} mm too ${diff < 0 ? 'small: it will not press in' : 'big: it will rattle'}`, `${label}: seat ${diff < 0 ? 'small' : 'big'}`, { code, refs, values });
116
+ else if (Math.abs(diff) > 0.05) f('warn', `${label}: ${say}, ${n3(diff, 3)} mm from the ${n3(want.pocket, 3)} mm a ${typeof want.fit === 'string' ? want.fit : `${want.fit} mm`} fit wants`, `${label}: seat off`, { code, refs, values });
117
+ else f('pass', `${label}: ${say}, a ${typeof want.fit === 'string' ? want.fit : `${want.fit} mm`} fit (printed about ${n3(want.clearance, 3)} mm)`, null, { code, refs, values });
118
+ // How much of the race the wall holds, and what stops it
119
+ const levels = 9, held = Array.from({ length: levels }, (_, k) => firstWall(w * (k + 0.5) / levels)).filter((h) => h && Math.min(...h) < R + 0.5).length / levels;
120
+ if (held < 0.8) f('warn', `${label}: the pocket holds only ${n3(held * w, 1)} mm of the ${w} mm race: the bearing can tip`, `${label}: shallow`, { code: 'fit.seat', refs, values: { held: held * w, width: w } });
121
+ const ledges = [firstWall(-0.3), firstWall(w + 0.3)].map((h) => (h ? Math.min(...h) : null)).filter((h) => h != null && h < R - 0.1);
122
+ if (!ledges.length) f('warn', `${label}: nothing stops the bearing at either face: draw a lip`, `${label}: no lip`, { code: 'fit.seat', refs });
123
+ else {
124
+ const lip = Math.max(...ledges);
125
+ if (lip < r + (R - r) / 2) f('fail', `${label}: the lip comes in to ${n3(2 * lip, 2)} mm across, onto the inner race (which turns): it wants ${n3(2 * r + (R - r), 2)} mm or more`, `${label}: lip on inner race`, { code: 'fit.seat', refs, values: { lip: 2 * lip } });
126
+ else f('pass', `${label}: a ${n3(R - lip, 2)} mm lip stops the outer race and clears the inner`, null, { code: 'fit.seat', refs, values: { lip: 2 * lip } });
127
+ }
128
+ }
package/lib/sheet.mjs CHANGED
@@ -38,7 +38,83 @@ const INK = '#1a1a1a', THIN = '#666', FILL = '#eceae4', METAL = '#c4c8cc';
38
38
  /** @param {string} name the rule set's name @returns {string} an SVG drawing of what it says the part mounts by */
39
39
  export function drawSet(name) { return drawing(readSet(fileOf(name)), vocabulary()); }
40
40
 
41
+ // The drawing's marks, in sheet units: each adds to out, and span is a dimension with its extension lines, ticks and figure
42
+ function pen() {
43
+ const out = [];
44
+ const line = (a, b, c, e, s = INK, sw = 1.2, dash = '') => out.push(`<line x1="${fig(a)}" y1="${fig(b)}" x2="${fig(c)}" y2="${fig(e)}" stroke="${s}" stroke-width="${sw}"${dash ? ` stroke-dasharray="${dash}"` : ''}/>`);
45
+ const circle = (x, y, r, fill = 'none', s = INK) => out.push(`<circle cx="${fig(x)}" cy="${fig(y)}" r="${fig(r)}" fill="${fill}" stroke="${s}" stroke-width="1.2"/>`);
46
+ const rect = (x, y, a, b, fill = FILL) => out.push(`<rect x="${fig(x)}" y="${fig(y)}" width="${fig(a)}" height="${fig(b)}" fill="${fill}" stroke="${INK}" stroke-width="1.2"/>`);
47
+ const text = (x, y, t, a = 'middle', z = 12) => out.push(`<text x="${fig(x)}" y="${fig(y)}" text-anchor="${a}" font-size="${z}" font-family="system-ui, sans-serif" fill="${INK}">${t}</text>`);
48
+ const span = (x1, y1, x2, y2, t, across_ = 14) => { // a dimension: extension lines, a line with its ticks, the figure
49
+ const horizontal = Math.abs(y2 - y1) < 1e-6, ox = horizontal ? 0 : across_, oy = horizontal ? across_ : 0;
50
+ line(x1, y1, x1 + ox, y1 + oy, THIN, 0.6); line(x2, y2, x2 + ox, y2 + oy, THIN, 0.6); line(x1 + ox, y1 + oy, x2 + ox, y2 + oy, THIN, 0.8);
51
+ for (const [a, b] of [[x1 + ox, y1 + oy], [x2 + ox, y2 + oy]]) line(a - 3, b + 3, a + 3, b - 3, THIN, 0.8);
52
+ if (horizontal) text((x1 + x2) / 2, y1 + oy + (across_ > 0 ? 13 : -4), t); else text(x1 + ox + (across_ > 0 ? 4 : -4), (y1 + y2) / 2 + 4, t, across_ > 0 ? 'start' : 'end');
53
+ };
54
+ return { out, line, circle, rect, text, span };
55
+ }
56
+
57
+ // The sheet's heading (what's trustworthy) and its frame
58
+ function sheet(set, { out, text }, W, H) {
59
+ const kinds = Object.values(set.rules).reduce((m, r) => ({ ...m, [r.kind]: (m[r.kind] || 0) + 1 }), {});
60
+ text(20, 26, set.name, 'start', 16);
61
+ text(20, 44, `all in mm. ${Object.entries(kinds).map(([k, c]) => `${c} ${k}`).join(', ')}: compare it with the datasheet`, 'start', 11);
62
+ return `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 ${fig(W)} ${fig(H + 60)}" width="${fig(W)}" height="${fig(H + 60)}"><rect width="100%" height="100%" fill="#fff"/>${out.join('')}</svg>\n`;
63
+ }
64
+
65
+ // A bearing from its end and in section: bore, outer diameter, width, and the flange or the thrust washers where it has them
66
+ function bearingDrawing(set) {
67
+ const n = (k) => set.rules[k]?.value ?? 0, thrust = set.rules.type?.value === 'thrust';
68
+ const d = n('bore'), D = n('outer_diameter'), B = n('width'), F = n('flange_diameter'), Fw = n('flange_width'), d1 = n('shaft_washer_diameter'), D1 = n('housing_washer_bore');
69
+ const R = Math.max(D, F) / 2, S = Math.max(4, Math.min(20, 90 / R)), W = 2 * R * S + B * S + 330, H = 2 * R * S + 170;
70
+ const cx = R * S + 70, cy = H / 2 + 22, sx = cx + R * S + 120, top = cy - R * S, bottom = cy + R * S;
71
+ const pens = pen(), { line, circle, rect, text, span } = pens;
72
+ // ---- from the end ----
73
+ if (F) circle(cx, cy, (F / 2) * S, '#f6f4ee');
74
+ circle(cx, cy, (D / 2) * S, FILL);
75
+ if (D1) circle(cx, cy, (D1 / 2) * S, 'none', THIN);
76
+ circle(cx, cy, (d / 2) * S, '#fff');
77
+ line(cx - R * S - 8, cy, cx + R * S + 8, cy, THIN, 0.5, '8 3 2 3'); line(cx, cy - R * S - 8, cx, cy + R * S + 8, THIN, 0.5, '8 3 2 3');
78
+ span(cx - (D / 2) * S, bottom + 6, cx + (D / 2) * S, bottom + 6, `Ø${fig(D)}`, 18);
79
+ span(cx - (d / 2) * S, top - 6, cx + (d / 2) * S, top - 6, `bore Ø${fig(d)}`, -14);
80
+ if (F) text(cx, bottom + 66, `flange Ø${fig(F)}, ${fig(Fw)} thick`);
81
+ if (thrust) text(cx, bottom + 66, `shaft washer Ø${fig(d1)}, housing washer bore Ø${fig(D1)}`);
82
+ // ---- the section, axis along the sheet ----
83
+ for (const side of [-1, 1]) {
84
+ const y = (a, b) => (side < 0 ? [cy - b * S, (b - a) * S] : [cy + a * S, (b - a) * S]);
85
+ const [ry, rh] = y(d / 2, D / 2); rect(sx, ry, B * S, rh);
86
+ if (F) { const [fy, fh] = y(D / 2, F / 2); rect(sx, fy, Fw * S, fh, '#ddd9cf'); }
87
+ if (thrust) line(sx + (B * S) / 2, ry, sx + (B * S) / 2, ry + rh, THIN, 0.8, '4 3');
88
+ }
89
+ line(sx - 12, cy, sx + B * S + 12, cy, THIN, 0.5, '8 3 2 3');
90
+ span(sx, bottom + 6, sx + B * S, bottom + 6, `${fig(B)}`, 18);
91
+ span(sx + B * S + 6, cy - (D / 2) * S, sx + B * S + 6, cy + (D / 2) * S, `Ø${fig(D)}`, 30);
92
+ text(sx + (B * S) / 2, top - 22, `chamfer ${fig(n('chamfer'))}`, 'middle', 11);
93
+ text(cx, bottom + 86, `${set.rules.type?.value || 'bearing'}: ${fig(n('dynamic_rating'))} N dynamic, ${fig(n('static_rating'))} N static${set.rules.radial_play ? `, ${set.rules.radial_play.value}` : ''}`, 'middle', 11);
94
+ return sheet(set, pens, W, H);
95
+ }
96
+
97
+ // A driver module from above: the board and its two header rows, at their spacing
98
+ function driverDrawing(set) {
99
+ const n = (k) => set.rules[k]?.value ?? 0, w = n('body_width'), d = n('body_depth'), pitch = n('pin_pitch'), row = n('row_spacing'), count = n('pin_count') / 2;
100
+ const S = 16, W = w * S + 260, H = d * S + 170, cx = W / 2, cy = H / 2 + 22, X = (x) => cx + x * S, Y = (y) => cy - y * S;
101
+ const pens = pen(), { line, circle, rect, text, span } = pens;
102
+ rect(X(-w / 2), Y(d / 2), w * S, d * S);
103
+ const pins = Array.from({ length: count }, (_, i) => (i - (count - 1) / 2) * pitch);
104
+ for (const y of [-row / 2, row / 2]) for (const x of pins) circle(X(x), Y(y), (pitch / 3.2) * S, METAL);
105
+ line(X(-w / 2) - 10, Y(0), X(w / 2) + 10, Y(0), THIN, 0.5, '8 3 2 3');
106
+ span(X(-w / 2), Y(-d / 2) + 6, X(w / 2), Y(-d / 2) + 6, `${fig(w)}`, 18);
107
+ span(X(-w / 2) - 6, Y(d / 2), X(-w / 2) - 6, Y(-d / 2), `${fig(d)}`, -18);
108
+ span(X(w / 2) + 6, Y(row / 2), X(w / 2) + 6, Y(-row / 2), `rows ${fig(row)}`, 18);
109
+ span(X(pins[0]), Y(d / 2) - 6, X(pins[1]), Y(d / 2) - 6, `pitch ${fig(pitch)}`, -14);
110
+ text(cx, Y(-d / 2) + 66, `${n('pin_count')} pins: ${set.rules.vref_formula?.value ?? ''}`, 'middle', 11);
111
+ text(cx, Y(-d / 2) + 84, `Rs ${n('sense_resistor')} ohm, ${n('vref_gain')} A per volt of Vref`, 'middle', 11);
112
+ return sheet(set, pens, W, H);
113
+ }
114
+
41
115
  export function drawing(set, vocab) {
116
+ if (set.part === 'bearing') return bearingDrawing(set);
117
+ if (set.part === 'driver') return driverDrawing(set);
42
118
  const get = (k) => { const r = set.rules[set.interface?.[k] ?? k]; return r?.value; }, n = (k, d = 0) => { const x = get(k); return typeof x === 'number' ? x : d; };
43
119
  if (!set.part && !Object.keys(set.interface || {}).some((k) => k.startsWith('body_'))) throw new Error(`rule set "${set.name}" doesn't say what shape it is (no body_ names in it, or "part", or "interface"): there's nothing to draw`);
44
120
  const shape = get('body_shape') ?? 'box', round = shape === 'round', w = round ? n('body_diameter') : n('body_width'), d = round ? w : shape === 'square' ? w : n('body_depth', n('body_width'));
@@ -52,17 +128,7 @@ export function drawing(set, vocab) {
52
128
  const W = 2 * reach * S + (L + Math.max(shaftL, top + bossH) + 8) * S + 200, H = Math.max(2 * reach * S + 150, 280);
53
129
  const fx = reach * S + 70, fy = H / 2 + 8, X = (x) => fx + x * S, Y = (y) => fy - y * S; // the face view, shaft at the origin
54
130
  const sx = fx + reach * S + 90 + L * S, SX = (z) => sx + z * S, SY = (y) => fy - y * S; // the side view: z along the sheet, the mounting face at z = 0
55
- const out = [];
56
- const line = (a, b, c, e, s = INK, sw = 1.2, dash = '') => out.push(`<line x1="${fig(a)}" y1="${fig(b)}" x2="${fig(c)}" y2="${fig(e)}" stroke="${s}" stroke-width="${sw}"${dash ? ` stroke-dasharray="${dash}"` : ''}/>`);
57
- const circle = (x, y, r, fill = 'none', s = INK) => out.push(`<circle cx="${fig(x)}" cy="${fig(y)}" r="${fig(r)}" fill="${fill}" stroke="${s}" stroke-width="1.2"/>`);
58
- const rect = (x, y, a, b, fill = FILL) => out.push(`<rect x="${fig(x)}" y="${fig(y)}" width="${fig(a)}" height="${fig(b)}" fill="${fill}" stroke="${INK}" stroke-width="1.2"/>`);
59
- const text = (x, y, t, a = 'middle', z = 12) => out.push(`<text x="${fig(x)}" y="${fig(y)}" text-anchor="${a}" font-size="${z}" font-family="system-ui, sans-serif" fill="${INK}">${t}</text>`);
60
- const span = (x1, y1, x2, y2, t, across_ = 14) => { // a dimension: extension lines, a line with its ticks, the figure
61
- const horizontal = Math.abs(y2 - y1) < 1e-6, ox = horizontal ? 0 : across_, oy = horizontal ? across_ : 0;
62
- line(x1, y1, x1 + ox, y1 + oy, THIN, 0.6); line(x2, y2, x2 + ox, y2 + oy, THIN, 0.6); line(x1 + ox, y1 + oy, x2 + ox, y2 + oy, THIN, 0.8);
63
- for (const [a, b] of [[x1 + ox, y1 + oy], [x2 + ox, y2 + oy]]) line(a - 3, b + 3, a + 3, b - 3, THIN, 0.8);
64
- if (horizontal) text((x1 + x2) / 2, y1 + oy + (across_ > 0 ? 13 : -4), t); else text(x1 + ox + (across_ > 0 ? 4 : -4), (y1 + y2) / 2 + 4, t, across_ > 0 ? 'start' : 'end');
65
- };
131
+ const pens = pen(), { out, line, circle, rect, text, span } = pens;
66
132
  // ---- the face, from the shaft's end ----
67
133
  if (tabs) rect(X(cx - tabs / 2), Y(cy + d / 2), tabs * S, d * S, '#f6f4ee');
68
134
  for (const [hx, hy] of earR ? holes : []) circle(X(hx), Y(hy), earR * S, '#f6f4ee');
@@ -96,11 +162,7 @@ export function drawing(set, vocab) {
96
162
  if (shaftL) span(SX(top + (top ? bossH : 0)), under, SX(top + (top ? bossH : 0) + shaftL), under, `shaft ${fig(shaftL)}`, 36);
97
163
  if (flat) span(SX(top + (top ? bossH : 0) + shaftL - flat), SY(shaftD / 2) - 4, SX(top + (top ? bossH : 0) + shaftL), SY(shaftD / 2) - 4, `flat ${fig(flat)}`, -14);
98
164
  if (bossH) text(SX(bossAt + bossH / 2), under + 74, `boss ${fig(bossH)} high`, 'middle', 11);
99
- // ---- what's trustworthy ----
100
- const kinds = Object.values(set.rules).reduce((m, r) => ({ ...m, [r.kind]: (m[r.kind] || 0) + 1 }), {});
101
- text(20, 26, set.name, 'start', 16);
102
- text(20, 44, `all in mm. ${Object.entries(kinds).map(([k, c]) => `${c} ${k}`).join(', ')}: compare it with the datasheet`, 'start', 11);
103
- return `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 ${fig(W)} ${fig(H + 60)}" width="${fig(W)}" height="${fig(H + 60)}"><rect width="100%" height="100%" fill="#fff"/>${out.join('')}</svg>\n`;
165
+ return sheet(set, pens, W, H);
104
166
  }
105
167
 
106
168
  // ---------- a draft from a datasheet's text ----------
package/lib/wires.mjs ADDED
@@ -0,0 +1,95 @@
1
+ // Wires in the assembly: anchors at each end, a route between them, and the longest the route gets through the machine's
2
+ // poses. A wire that won't reach the elbow at full stretch, or is too thin for what it carries, is found here rather than
3
+ // on the bench. "wires": [{ "from": "elbow.connector", "to": "board.Y", "via": ["upper.cable"], "gauge": "awg22" }]
4
+ import { peekRuleSet as loadRuleSet } from './rules.mjs';
5
+
6
+ const n3 = (x, d = 1) => String(Number(x.toFixed(d)));
7
+ const GAUGE = /^awg(\d{1,2})$/i;
8
+ const areaOf = (gauge, base) => { const d = base * Math.pow(92, (36 - gauge) / 39); return (Math.PI * d * d) / 4; };
9
+
10
+ // Anchors to world points at given joint values
11
+ function pointer(s, { placeItems, jointValues, mul, marksOf }) {
12
+ const motion = s.motion, ids = motion.items.map((x) => x[0]);
13
+ const marks = (id, name) => motion.marks.find((m) => m.id === id && m.name === name);
14
+ return (ref, what) => {
15
+ const bits = String(ref).split('.'), name = bits.pop(), id = bits.join('.'), m = marks(id, name);
16
+ if (!m) throw new Error(`${what}: no anchor "${ref}" (give <item>.<anchor>${ids.includes(id) ? `; ${id} has ${motion.marks.filter((x) => x.id === id).map((x) => x.name).join(', ') || 'none'}` : ''})`);
17
+ const k = ids.indexOf(id), F = m.frame;
18
+ return (worlds) => { const W = mul(worlds[k], F); return [W[3], W[7], W[11]]; };
19
+ };
20
+ }
21
+ // Joint values to try: each named pose, each moving joint at its ends and middle, all together when few enough
22
+ function samples(motion, jointValues) {
23
+ const base = jointValues(motion, motion.pose ?? undefined), free = motion.joints.filter((j) => !j.follow && j.type !== 'fixed' && j.dofs.length === 1), out = [base];
24
+ for (const p of Object.keys(motion.poses || {})) out.push(jointValues(motion, p));
25
+ const levels = (j) => { const [lo, hi] = j.dofs[0]; return [lo, (lo + hi) / 2, hi]; }, leads = Object.fromEntries(Object.entries(base).filter(([id]) => !motion.joints.find((x) => x.id === id)?.follow));
26
+ if (free.length && free.length <= 5) {
27
+ const go = (i, set) => { if (i === free.length) { out.push(jointValues(motion, set)); return; } for (const v of levels(free[i])) go(i + 1, { ...set, [free[i].id]: [v] }); };
28
+ go(0, leads);
29
+ } else for (const j of free) for (const v of levels(j)) out.push(jointValues(motion, { ...leads, [j.id]: [v] }));
30
+ return out;
31
+ }
32
+
33
+ // Each wire as a route of point functions, checked by name when the assembly is built
34
+ export function wiresOf(a, placed, joints) {
35
+ return (a.wires || []).map((w, i) => {
36
+ const what = `wire ${w.id || i + 1}`;
37
+ if (!w.from || !w.to) throw new Error(`${what}: give "from" and "to", anchors as <item>.<anchor>`);
38
+ const g = GAUGE.exec(String(w.gauge ?? ''));
39
+ if (w.gauge != null && !g) throw new Error(`${what}: gauge is awg and a number (awg22), not ${JSON.stringify(w.gauge)}`);
40
+ for (const v of w.via ?? []) if (typeof v === 'string' && !v.includes('.') && !joints.some((j) => j.id === v && j.type === 'path')) throw new Error(`${what}: via "${v}" is neither an anchor (<item>.<anchor>) nor a path joint`);
41
+ return { ...w, id: w.id || `w${i + 1}` };
42
+ });
43
+ }
44
+
45
+ // What a wire carries: what it's given, or a motor's current at either end, or a signal's
46
+ function currentOf(w, s, top, signal) {
47
+ if (w.current != null) return { current: Number(w.current), why: 'as given' };
48
+ const motors = s.motion.drives.filter((d) => [top(w.from), top(w.to)].includes(d.id));
49
+ for (const d of motors) { const I = d.spec.current ?? d.model.figures.rated_current?.value; if (I != null) return { current: I, why: `${d.id}'s rated current` }; }
50
+ return { current: signal, why: 'a signal' };
51
+ }
52
+
53
+ // A wire ending on a board's axis connector: the board's pins for that axis, from its rule set
54
+ function pinsAt(w, s) {
55
+ for (const end of [w.from, w.to]) {
56
+ const [id, anchor] = String(end).split('.'), o = s.objects.find((x) => x.id === id && x.bought?.part === 'board'), e = o?.built.entries;
57
+ if (!e || !/^[A-Z]$/.test(anchor ?? '')) continue;
58
+ const pin = (k) => e.find((x) => x.name === `${o.bought.set}.${k}_pin_${anchor.toLowerCase()}`)?.value;
59
+ if (pin('step')) return `step ${pin('step')}, dir ${pin('dir')}${pin('limit') ? `, limit ${pin('limit')}` : ''}`;
60
+ }
61
+ return null;
62
+ }
63
+
64
+ export function wireRows(s, helpers) {
65
+ const motion = s.motion, wires = s.wires; if (!wires?.length) return [];
66
+ const rules = loadRuleSet('wire').rules, density = rules.current_density.value, loop = rules.service_loop.value, base = rules.awg_base.value, signal = rules.signal_current.value;
67
+ const point = pointer(s, helpers), { placeItems, jointValues } = helpers, top = (n) => String(n).split('.')[0], poses = samples(motion, jointValues).map((v) => placeItems(motion, v));
68
+ return wires.map((w) => {
69
+ const what = `wire ${w.id}`, chain = [w.from, ...(w.via ?? []), w.to];
70
+ const fns = chain.flatMap((v) => (typeof v === 'string' && !v.includes('.') ? [] : [point(v, what)]));
71
+ const pathLen = (w.via ?? []).reduce((t, v) => { const j = typeof v === 'string' && !v.includes('.') && motion.joints.find((x) => x.id === v); if (!j) return t; let l = 0; for (let k = 1; k < j.path.length; k++) l += Math.hypot(...j.path[k].map((c, m) => c - j.path[k - 1][m])); return t + l; }, 0);
72
+ let longest = 0, shortest = Infinity, atLongest = null;
73
+ for (const W of poses) { const P = fns.map((fn) => fn(W)); let l = pathLen; for (let k = 1; k < P.length; k++) l += Math.hypot(P[k][0] - P[k - 1][0], P[k][1] - P[k - 1][1], P[k][2] - P[k - 1][2]); if (l > longest) { longest = l; atLongest = P; } shortest = Math.min(shortest, l); }
74
+ const { current, why } = currentOf(w, s, top, signal), gauge = w.gauge ? Number(GAUGE.exec(w.gauge)[1]) : null, area = gauge != null ? areaOf(gauge, base) : null, capacity = area != null ? area * density : null;
75
+ return { id: w.id, from: w.from, to: w.to, via: w.via ?? [], pins: pinsAt(w, s), gauge: w.gauge ?? null, colour: w.colour ?? null, conductors: w.conductors ?? (s.motion.drives.some((d) => [top(w.from), top(w.to)].includes(d.id)) ? 4 : 1), connectors: w.connectors ?? null,
76
+ longest, shortest, length: Math.ceil(longest + loop), loop, current, why, area, capacity, route: atLongest };
77
+ });
78
+ }
79
+
80
+ export function wireChecks(s, f, helpers) {
81
+ for (const w of wireRows(s, helpers)) {
82
+ const refs = { wire: w.id, from: w.from, to: w.to }, at = w.route?.[0], values = { length: w.length, longest: w.longest, shortest: w.shortest, current: w.current, capacity: w.capacity };
83
+ f('info', `${w.id}: ${w.from} to ${w.to}, ${n3(w.length, 0)} mm with its ${w.loop} mm loop (${n3(w.shortest, 0)} to ${n3(w.longest, 0)} mm as the joints move)`, null, { code: 'wire.length', at, refs, values });
84
+ if (w.capacity == null) { f('warn', `${w.id}: no gauge given, so nothing checks it against ${n3(w.current, 2)} A (${w.why})`, `${w.id}: no gauge`, { code: 'wire.gauge', at, refs, values }); continue; }
85
+ if (w.current > w.capacity) f('fail', `${w.id}: ${w.gauge} carries ${n3(w.capacity, 2)} A at most, and this carries ${n3(w.current, 2)} A (${w.why}): a thicker wire`, `${w.id}: too thin`, { code: 'wire.gauge', at, refs, values });
86
+ else f('pass', `${w.id}: ${w.gauge} takes ${n3(w.current, 2)} A (${w.why}), up to ${n3(w.capacity, 2)} A`, null, { code: 'wire.gauge', at, refs, values });
87
+ }
88
+ }
89
+
90
+ // The sheet: each wire, its length, gauge, colour and connectors, in Markdown
91
+ export function wiringSheet(rows) {
92
+ const line = (a) => `| ${a.join(' | ')} |`;
93
+ return [line(['Wire', 'From', 'To', 'Length (mm)', 'Gauge', 'Conductors', 'Colour', 'Connectors', 'Board pins', 'Carries']), line(['---', '---', '---', '---:', '---', '---:', '---', '---', '---', '---']),
94
+ ...rows.map((w) => line([w.id, w.from, w.to, w.length, w.gauge ?? '', w.conductors, w.colour ?? '', Array.isArray(w.connectors) ? w.connectors.join(' to ') : w.connectors ?? '', w.pins ?? '', `${n3(w.current, 2)} A, ${w.why}`]))].join('\n');
95
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@rulecad/cad",
3
- "version": "0.7.41",
3
+ "version": "0.7.42",
4
4
  "description": "The cad command: JSCAD designs from traceable rules, checked for printing and fit, versioned by what fits, shared as links and exported as Bambu 3MF.",
5
5
  "type": "module",
6
6
  "bin": {
@@ -63,8 +63,8 @@
63
63
  "@rulecad/fit": "^0.4.0",
64
64
  "@rulecad/model-link": "^0.3.0",
65
65
  "@rulecad/versions": "^0.1.0",
66
- "@rulecad/shapes": "^0.4.1",
67
- "@rulecad/rules": "^0.3.6",
66
+ "@rulecad/shapes": "^0.4.3",
67
+ "@rulecad/rules": "^0.3.8",
68
68
  "@jscad/modeling": "^2.12.0",
69
69
  "three": "^0.186.1",
70
70
  "@rulecad/fea": "^0.2.1",
@@ -19,6 +19,7 @@
19
19
  "joints": { "type": "array", "items": { "$ref": "#/$defs/joint" } },
20
20
  "loops": { "type": "array", "items": { "$ref": "#/$defs/loop" } },
21
21
  "planetary": { "type": "array", "items": { "$ref": "#/$defs/planetary" } },
22
+ "wires": { "type": "array", "description": "Wires between anchors, their length measured through every pose", "items": { "type": "object", "required": ["from", "to"], "additionalProperties": false, "properties": { "id": { "type": "string" }, "from": { "type": "string" }, "to": { "type": "string" }, "via": { "type": "array", "items": { "type": "string" }, "description": "Anchors or path joints the wire is routed by" }, "gauge": { "type": "string", "description": "awg22" }, "colour": { "type": "string" }, "conductors": { "type": "number" }, "connectors": { "type": "array", "items": { "type": "string" } }, "current": { "type": "number", "description": "A: else a motor's rated current at either end, or a signal's" }, "note": { "type": "string" } } } },
22
23
  "gravity": { "$ref": "#/$defs/vec3", "description": "Which way down is, for masses in loads (default [0, 0, -1])" },
23
24
  "loads": { "type": "array", "description": "What the assembly has to do: a torque (N m) or force (N) on a joint, or a mass (kg) carried at an anchor", "items": { "type": "object", "additionalProperties": false, "properties": { "joint": { "type": "string" }, "torque": { "$ref": "#/$defs/expr" }, "force": { "$ref": "#/$defs/expr" }, "mass": { "$ref": "#/$defs/expr" }, "at": { "$ref": "#/$defs/anchorRef" }, "note": { "type": "string" } } } },
24
25
  "poses": { "type": "object", "description": "Named sets of joint values ({ \"hinge\": 90 }), and of items' variables (\"action.travel\": 25: a flexure drawn bent in that pose, printed as drawn)", "additionalProperties": { "type": "object", "additionalProperties": { "$ref": "#/$defs/values" } } },
@@ -38,6 +39,7 @@
38
39
  "object": { "type": "string" },
39
40
  "assembly": { "type": "string" },
40
41
  "motor": { "type": "object", "required": ["model"], "additionalProperties": false, "description": "A motor from @rulecad/motors: bought, not printed; its shaft turns the joint it drives", "properties": { "model": { "type": "string" }, "drives": { "type": "string" }, "set": { "type": "object", "description": "Figures that differ from the catalogue's, by name" }, "speed": { "$ref": "#/$defs/expr", "description": "The motor's speed, rpm (default: what it does comfortably)" }, "margin": { "$ref": "#/$defs/expr", "description": "How many times over the torque must be (default 2)" }, "duty": { "$ref": "#/$defs/expr", "description": "The share of the time it runs, 0 to 1 (default 1), for its heat" }, "screw": { "type": "string", "description": "The screws through a motor's plain holes, if not the size they take: M3" } } },
42
+ "bought": { "type": "string", "description": "A part from a rule set (\"608\", \"drv8825\"): bought, not printed; drawn faint from its figures, with anchors from what it is" },
41
43
  "variant": { "type": "string" },
42
44
  "set": { "type": "object" },
43
45
  "at": { "$ref": "#/$defs/vec3" },
@@ -70,6 +72,7 @@
70
72
  "engage": { "$ref": "#/$defs/expr", "description": "a goes at least this far (mm) onto b along the joint between them: a part slid onto a shaft or a pin, not resting on its end" },
71
73
  "radius": { "$ref": "#/$defs/expr", "description": "With engage: how near the joint's axis to look (mm, default 10)" },
72
74
  "shaft": { "anyOf": [{ "type": "boolean" }, { "enum": ["slide", "press"] }], "description": "a or b is a motor, and the other takes its shaft: reads the bore from the part as drawn" },
75
+ "seat": { "anyOf": [{ "type": "boolean" }, { "enum": ["press", "slip"] }, { "type": "number" }], "description": "a or b is a bought bearing, and the other its printed seat: reads the pocket as drawn against the bearing's rules and the printer's fit (fit.seat)" },
73
76
  "fastens": { "type": "boolean", "description": "a and b are fastened together (pins, screws, a press): what holds a part that has no joint" },
74
77
  "min": { "$ref": "#/$defs/expr" },
75
78
  "max": { "$ref": "#/$defs/expr" },