@rulecad/cad 0.7.36 → 0.7.38

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
@@ -520,6 +520,7 @@ gap, and says whether the axle is where the gears need it.
520
520
  { "id": "slide", "type": "prismatic", "parent": "rail.track", "child": "rack.slide", "min": -100, "max": 100,
521
521
  "mesh": { "with": "knob", "module": "pinion.module", "teeth": ["pinion.teeth", "rack.teeth"], "shift": ["pinion.shift", 0] } }
522
522
  ],
523
+ "fits": [{ "a": "pinion", "b": "rail", "engage": "pinion.width", "note": "The pinion down its axle" }],
523
524
  "poses": { "home": { "knob": 0 }, "out": { "knob": 150 } }
524
525
  }
525
526
  ```
@@ -803,7 +804,8 @@ are built with Manifold's booleans (`"engine": "manifold"`): closed solids, so t
803
804
  "module": "ring.module", "teeth": ["sun.teeth", "p0.teeth", "ring.teeth"] }
804
805
  ],
805
806
  "fits": [{ "a": "handle", "b": "carrier", "min": "0 - carrier.fit * 2", "note": "The handle's peg pressed into the arm" },
806
- { "a": "ring", "b": "case", "fastens": true, "note": "The ring held still on the case by its two push pins" }],
807
+ { "a": "ring", "b": "case", "fastens": true, "note": "The ring held still on the case by its two push pins" },
808
+ { "a": "handle", "b": "carrier", "engage": "carrier.t", "note": "The handle's peg through the arm" }],
807
809
  "poses": { "rest": { "crank": 0 }, "quarter": { "crank": 90 } }
808
810
  }
809
811
  ```
package/README.md CHANGED
@@ -385,6 +385,10 @@ then y, then z, as `rotate` does.
385
385
  fastened to the first through fits with `"fastens": true` (the pins, screws or press that do it, named in the fit's
386
386
  note): `{ "a": "ring", "b": "case", "fastens": true, "note": "Two push pins" }`. A part only placed somewhere is
387
387
  said (`assembly.loose`): a ring gear resting on its case would turn with its planets.
388
+ - **Onto a shaft:** `{ "a": "arm", "b": "crank", "engage": "arm.thick" }` checks that a part slid onto a shaft, a pin or a
389
+ peg goes that far onto it along the joint between them (`fit.engage`), not just against its end: an arm resting on
390
+ a shaft's end touches it face to face, as a seated one does, and nothing overlaps either way, so only this tells
391
+ them apart. It looks within `radius` (10 mm) of the joint's axis.
388
392
  - **Loops:** each item has one joint to its parent. Where parts join in a ring (two links between the same two
389
393
  parts), let joints place every part, then name the meeting that closes the ring in `loops`. The check measures it
390
394
  in every pose: `"loops": [{ "a": "link_l.top", "b": "mount_l.axis", "label": "Left pivot lines up" }]`. Its anchors
package/bin/cad.mjs CHANGED
@@ -24,6 +24,7 @@ import { setVariables, addToAssembly, parseValue } from '../lib/edit.mjs';
24
24
  import { setAt } from '../lib/jsonedit.mjs';
25
25
  import { threemf, slotOf } from '../lib/threemf.mjs';
26
26
  import { liveView } from '../lib/live.mjs';
27
+ import { checkSets, drawSet, draftSet } from '../lib/sheet.mjs';
27
28
  import { filaments, slots, linkTo, objectModel, assemblyModel, VIEW } from '../lib/links.mjs';
28
29
 
29
30
  // What the print file asks of the AMS: which filament each kind of part prints in
@@ -46,6 +47,9 @@ const HELP = `cad: JSCAD designs you can trace, check, share and print (rulecad)
46
47
  cad agents AGENTS.md: how an AI agent should design in this workspace
47
48
  cad trust allow what this workspace's cad.config.json asks (no sandbox, its own targets)
48
49
  cad rules <project>/<object> every variable: value, the rule behind it, its source
50
+ cad rules check [set …] rule sets held to what makes them traceable (exit 1 on a failure) [--json]
51
+ cad rules draw <set> a dimension drawing of what a set says a part mounts by, <set>.svg, to compare with its datasheet [--out file]
52
+ cad rules draft <name> --from <file.pdf> the figures in a datasheet's text, into rules/<name>.json for you to name and check (all kind estimate)
49
53
  cad values <project>/<object> [names…] the object's variables, resolved [--json]
50
54
  cad set <project>/<object> name=value … change variables, keeping the file's layout [--unit, --rule, --label, --new to add one]
51
55
  cad add fit|joint|item|loop|pose <project>/<assembly> --a … --b … --min … add to an assembly, keeping its layout
@@ -104,7 +108,7 @@ const COMMANDS = ['new', 'import-kle', 'clone', 'agents', 'trust', 'rules', 'val
104
108
  const OPTIONS = ['all', 'along', 'at', 'bump', 'depth', 'dry-run', 'explode', 'force', 'fresh', 'json', 'licence', 'license', 'long', 'm', 'material', 'md', 'name', 'new',
105
109
  'no-models', 'no-pictures', 'no-rules', 'note', 'open', 'part', 'place', 'pose', 'progress', 'push', 'result', 'rules', 'samples', 'set', 'short', 'source', 'steps',
106
110
  'sweep', 'tol', 'trailer', 'ttl', 'version', 'watch', 'line',
107
- 'unit', 'rule', 'label', // cad set
111
+ 'unit', 'rule', 'label', 'from', 'out', // cad set, cad rules
108
112
  'a', 'b', 'min', 'max', 'poses', 'id', 'type', 'parent', 'child', 'follow', 'value', 'ratio', 'object', 'assembly', 'variant', 'rotate']; // cad add
109
113
  // What a command takes, where that isn't <project>/<object>
110
114
  const USAGE = { add: 'fit|joint|item|loop|pose <project>/<assembly> --key value …', why: '<project>/<object>.<variable>', set: '<project>/<object> name=value …',
@@ -311,6 +315,30 @@ async function analyses(b, d, tag) {
311
315
  return all;
312
316
  }
313
317
 
318
+ // cad rules check / draw / draft: rule sets themselves, not a design's use of them
319
+ function ruleSheets(what, names) {
320
+ if (what === 'check') {
321
+ const results = checkSets(names), bad = results.filter((r) => r.findings.length);
322
+ if (opt('json')) console.log(JSON.stringify(results.map((r) => ({ name: r.name, findings: r.findings })), null, 2));
323
+ else {
324
+ for (const r of bad) { console.log(`${r.name}: ${r.findings.length} to fix`); for (const x of r.findings) console.log(` FAIL ${x.text} (${x.code})`); }
325
+ console.log(`${results.length - bad.length} of ${results.length} rule sets pass`);
326
+ }
327
+ process.exitCode = bad.length ? 1 : 0;
328
+ return;
329
+ }
330
+ const name = names[0];
331
+ if (!name) throw new Error(`usage: cad rules ${what} <set>${what === 'draft' ? ' --from <file.pdf>' : ''}`);
332
+ if (what === 'draw') { const to = opt('out') || `${name}.svg`; fs.writeFileSync(to, drawSet(name)); return console.log(`drew ${to}: compare it with the datasheet`); }
333
+ if (!opt('from')) throw new Error('usage: cad rules draft <name> --from <file.pdf>');
334
+ const { set, found } = draftSet(name, opt('from'));
335
+ if (!found) return console.log(`no figures in ${opt('from')}'s text: it's probably a picture of a drawing, so read it by eye and write rules/${name}.json by hand`);
336
+ const to = path.join(paths.rules ? paths.rules() : path.join(WS, 'rules'), `${name}.json`);
337
+ if (fs.existsSync(to) && !opt('force')) throw new Error(`${path.relative(WS, to)} already exists (--force replaces it)`);
338
+ fs.mkdirSync(path.dirname(to), { recursive: true }); fs.writeFileSync(to, JSON.stringify(set, null, 2) + '\n');
339
+ return console.log(`${found} figures in ${path.relative(WS, to)}, every one an estimate: name them from the vocabulary, check them against the datasheet, then cad rules check ${name}`);
340
+ }
341
+
314
342
  async function main() {
315
343
  const first = args[0], pos = positional(), [cmd = first, ref] = pos; // names first or options first: cad check --json keyboard/case
316
344
  if (!first || ['help', '--help', '-h'].includes(first)) return console.log(HELP);
@@ -337,6 +365,8 @@ async function main() {
337
365
  return console.log(`made projects/${project}/objects/${name}.{js,json}`);
338
366
  }
339
367
 
368
+ if (cmd === 'rules' && ['check', 'draw', 'draft'].includes(ref)) return ruleSheets(ref, pos.slice(2));
369
+
340
370
  if (cmd === 'trust') { // this workspace may do what its cad.config.json asks (designs outside the sandbox, its own targets)
341
371
  const what = asks();
342
372
  if (!what.length) return console.log('this workspace asks for nothing outside the sandbox: nothing to trust');
package/lib/assembly.mjs CHANGED
@@ -696,6 +696,7 @@ export function checkAssembly(s) {
696
696
  for (const x of s.fits) {
697
697
  if (x.poses && !x.poses.includes(s.pose)) continue; // a fit for some poses only: the folded screen over the keys
698
698
  if (x.holes) { holesFit(x); continue; }
699
+ if (x.engage != null) { engageFit(x); continue; }
699
700
  const A = pickIn(x.a, x), key = x.note || `${x.a} / ${x.b}`;
700
701
  const lo = x.min != null ? x.num(x.min) : -Infinity, hi = x.max != null ? x.num(x.max) : Infinity;
701
702
  const reach = Math.max(2, ...[lo, hi].filter(Number.isFinite)) + 1; // look past the range, so a gap near it is measured
@@ -729,6 +730,29 @@ export function checkAssembly(s) {
729
730
  { code: 'fit', values: { ...(worst.gap < 0 ? { overlap: -worst.gap } : { gap: worst.gap }), min: lo, max: hi, inRange: results.filter((r) => r.ok).length, copies: results.length },
730
731
  refs: { a: x.a, b: x.b, label: x.label, ...(s.pose ? { pose: s.pose } : {}), outOfRange: results.filter((r) => !r.ok).map((r) => r.id), ...where }, ...(worst.at ? { at: { lo: worst.at, hi: worst.at } } : {}) });
731
732
  }
733
+ // Engage fits: a part slid onto a shaft, a pin or a peg goes onto it, not just against its end. Along the axis of the
734
+ // joint between them, each part's material near the axis (within radius, 10 mm) spans a stretch; how far the two
735
+ // stretches overlap is how far one is on the other. An arm resting on a shaft's end touches it face to face, as a
736
+ // seated one does, and nothing overlaps either way: only this tells them apart.
737
+ function engageFit(x) {
738
+ const top = (n) => String(n).split(/[.@]/)[0], ids = s.motion?.items.map((i) => i[0]) || [], a = top(x.a), b = top(x.b), label = x.note || `${x.a} onto ${x.b}`;
739
+ const j = (s.motion?.joints || []).find((jt) => { const pair = [ids[jt.child], jt.parent < 0 ? null : ids[jt.parent]]; return pair.includes(a) && pair.includes(b); });
740
+ if (!j) return f('fail', `${label}: no joint between ${a} and ${b} to measure along (engage measures along the joint that holds one on the other)`, null, { code: 'fit.engage', refs: { a: x.a, b: x.b } });
741
+ const worlds = placeItems(s.motion, s.jointValues), P = mul(j.parent < 0 ? [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0] : worlds[j.parent], j.a);
742
+ const O = [P[3], P[7], P[11]], Z = [P[2], P[6], P[10]], r = x.radius != null ? x.num(x.radius) : 10, need = x.num(x.engage);
743
+ const span = (parts) => {
744
+ let lo = Infinity, hi = -Infinity;
745
+ for (const p of parts) for (const t of p.triangles) for (const v of t) {
746
+ const d = [v[0] - O[0], v[1] - O[1], v[2] - O[2]], along = d[0] * Z[0] + d[1] * Z[1] + d[2] * Z[2];
747
+ if (Math.hypot(d[0] - along * Z[0], d[1] - along * Z[1], d[2] - along * Z[2]) <= r) { lo = Math.min(lo, along); hi = Math.max(hi, along); }
748
+ }
749
+ return [lo, hi];
750
+ };
751
+ const [la, ha] = span(pickIn(x.a, x)), [lb, hb] = span(pickIn(x.b, x)), on = Math.max(0, Math.min(ha, hb) - Math.max(la, lb));
752
+ const ok = on >= need - 1e-3; // (flush is on: a hair under, in the floating point, is not short)
753
+ f(ok ? 'pass' : 'fail', `${label}: ${on > 1e-3 ? `${mm(on)} mm on` : `not on at all (${Math.max(la, lb) - Math.min(ha, hb) < 1e-3 ? 'end to end' : 'apart'})`} along their joint${ok ? '' : `, where it should go ${mm(need)} mm on: its anchor is on the wrong face, or the shaft too short`}`, ok ? null : `${a}: not on ${b}`, { code: 'fit.engage', values: { engaged: on, need }, refs: { a: x.a, b: x.b, joint: j.id } });
754
+ }
755
+
732
756
  // Holes fits: each mounting hole's screw path, clear into a hole, with material round it
733
757
  function holesFit(x) {
734
758
  const A = pick(x.a), B = pick(x.b), label = x.label || `${x.a} into ${x.b}`;
package/lib/sheet.mjs ADDED
@@ -0,0 +1,136 @@
1
+ // Rule sets looked at: cad rules check holds every set to what makes it traceable, cad rules draw makes a dimension
2
+ // drawing from what a set says a part mounts by (so whoever read a datasheet can compare the two by eye), and cad
3
+ // rules draft pulls the figures out of a datasheet's text for a person to choose from. Nothing here writes a value
4
+ // the kit trusts: a draft is all "estimate" until someone has checked it.
5
+ import fs from 'node:fs';
6
+ import path from 'node:path';
7
+ import zlib from 'node:zlib';
8
+ import { fileURLToPath } from 'node:url';
9
+ import { checkRuleSet } from '@rulecad/variables';
10
+ import { RULE_DIRS } from './workspace.mjs';
11
+
12
+ const vocabularyFile = fileURLToPath(import.meta.resolve('@rulecad/rules/vocabulary.json'));
13
+ const readSet = (f) => JSON.parse(fs.readFileSync(f, 'utf8'));
14
+ export const vocabulary = () => readSet(vocabularyFile);
15
+
16
+ // Every set by name, a workspace's own copy before the published one
17
+ function allSets() {
18
+ const found = new Map();
19
+ for (const d of RULE_DIRS) if (fs.existsSync(d)) for (const f of fs.readdirSync(d).sort()) if (f.endsWith('.json') && !['package.json', 'vocabulary.json'].includes(f)) { const n = f.slice(0, -5); if (!found.has(n)) found.set(n, path.join(d, f)); }
20
+ return found;
21
+ }
22
+ function fileOf(name) {
23
+ const all = allSets(), file = all.get(name);
24
+ if (!file) throw new Error(`no rule set "${name}" (there are: ${[...all.keys()].join(', ')})`);
25
+ return file;
26
+ }
27
+
28
+ /** Every named set checked (or all of them): [{ name, file, findings }] */
29
+ export function checkSets(names = []) {
30
+ const v = vocabulary(), all = allSets();
31
+ return (names.length ? names.map((n) => [n, fileOf(n)]) : [...all]).map(([name, file]) => ({ name, file, findings: checkRuleSet(readSet(file), v) }));
32
+ }
33
+
34
+ // ---------- a dimension drawing ----------
35
+ const fig = (x) => String(+Number(x).toFixed(2));
36
+ const INK = '#1a1a1a', THIN = '#666', FILL = '#eceae4', METAL = '#c4c8cc';
37
+
38
+ /** @param {string} name the rule set's name @returns {string} an SVG drawing of what it says the part mounts by */
39
+ export function drawSet(name) { return drawing(readSet(fileOf(name)), vocabulary()); }
40
+
41
+ export function drawing(set, vocab) {
42
+ 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
+ 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
+ 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'));
45
+ const tabs = n('mount_tab_length'), off = n('boss_offset'), cx = tabs ? -off : 0, cy = tabs ? 0 : -off; // the body's centre, from the shaft
46
+ const spacing = n('mount_hole_spacing'), pattern = get('mount_pattern'), hole = n('mount_hole_diameter') || (parseFloat(String(get('mount_hole_thread') ?? '').slice(1)) || 2);
47
+ const holes = !spacing ? [] : pattern === 'square' ? [[-1, -1], [1, -1], [1, 1], [-1, 1]].map(([a, b]) => [cx + (a * spacing) / 2, cy + (b * spacing) / 2]) : [[cx - spacing / 2, cy], [cx + spacing / 2, cy]];
48
+ const earR = n('mount_ear_radius'), reach = Math.max(w / 2, d / 2, spacing / 2 + (earR || hole), tabs / 2) + 2, shaftD = n('shaft_diameter'), bossD = n('boss_diameter');
49
+ const L = n('body_length'), top = n('body_top'), bossH = n('boss_height'), shaftL = n('shaft_length'), flat = n('shaft_flat_length'), flats = n('shaft_flats'), across = n('shaft_flat_across');
50
+ // scaled so a small part fills the sheet as a large one does
51
+ const scale = 300 / (2 * reach + Math.max(L + top, shaftL + L, 10)) / 1.4, S = Math.max(3, Math.min(12, scale));
52
+ const W = 2 * reach * S + (L + Math.max(shaftL, top + bossH) + 8) * S + 200, H = Math.max(2 * reach * S + 150, 280);
53
+ 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
+ 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
+ };
66
+ // ---- the face, from the shaft's end ----
67
+ if (tabs) rect(X(cx - tabs / 2), Y(cy + d / 2), tabs * S, d * S, '#f6f4ee');
68
+ for (const [hx, hy] of earR ? holes : []) circle(X(hx), Y(hy), earR * S, '#f6f4ee');
69
+ if (shape === 'square') { const c = n('body_corner'), h = w / 2; const p = [[-h + c, -h], [h - c, -h], [h, -h + c], [h, h - c], [h - c, h], [-h + c, h], [-h, h - c], [-h, -h + c]].map(([a, b]) => `${fig(X(cx + a))},${fig(Y(cy + b))}`).join(' '); out.push(`<polygon points="${p}" fill="${FILL}" stroke="${INK}" stroke-width="1.2"/>`); }
70
+ else if (round) circle(X(cx), Y(cy), (w / 2) * S, FILL); else rect(X(cx - w / 2), Y(cy + d / 2), w * S, d * S);
71
+ if (bossD) circle(X(0), Y(0), (bossD / 2) * S, '#ddd9cf');
72
+ if (shaftD) circle(X(0), Y(0), (shaftD / 2) * S, METAL);
73
+ if (flats && across) { const a = flats === 2 ? across / 2 : across - shaftD / 2, c = Math.sqrt(Math.max(0, (shaftD / 2) ** 2 - a ** 2)); line(X(-c), Y(a), X(c), Y(a), INK, 1.4); if (flats === 2) line(X(-c), Y(-a), X(c), Y(-a), INK, 1.4); }
74
+ for (const [hx, hy] of holes) circle(X(hx), Y(hy), (hole / 2) * S, '#fff');
75
+ line(X(-reach), Y(0), X(reach), Y(0), THIN, 0.5, '8 3 2 3'); line(X(0), Y(-reach), X(0), Y(reach), THIN, 0.5, '8 3 2 3');
76
+ const bottom = Y(Math.min(cy - d / 2, -reach + 2)), topY = Y(Math.max(cy + d / 2, 0));
77
+ if (!round && !tabs) span(X(cx - w / 2), bottom, X(cx + w / 2), bottom, `${fig(w)}`, 18);
78
+ if (round) span(X(cx - w / 2), bottom, X(cx + w / 2), bottom, `Ø${fig(w)}`, 18);
79
+ if (tabs) span(X(cx - tabs / 2), bottom, X(cx + tabs / 2), bottom, `tabs ${fig(tabs)}`, 18);
80
+ if (spacing) span(X(holes[0][0]), bottom, X(holes[1][0]), bottom, `holes ${fig(spacing)}`, 40);
81
+ if (bossD) span(X(-bossD / 2), topY, X(bossD / 2), topY, `boss Ø${fig(bossD)}`, -14);
82
+ if (off) { text(X(reach), Y(reach) + 2, `shaft ${fig(off)} from centre`, 'end'); }
83
+ const thread = get('mount_hole_thread'), holeNote = thread ? `${holes.length} × ${thread}${n('mount_hole_depth') ? `, ${fig(n('mount_hole_depth'))} deep` : ''}` : hole ? `${holes.length} × Ø${fig(hole)}` : '';
84
+ if (holeNote) text(fx, bottom + 78, holeNote);
85
+ // ---- the side, shaft to the right ----
86
+ const halfH = (d / 2) * S;
87
+ if (L) rect(SX(-L), SY(cy + d / 2), L * S, d * S);
88
+ if (top) rect(SX(0), SY(cy + d / 2), top * S, d * S);
89
+ const bossAt = top; if (bossH) rect(SX(bossAt), SY(bossD / 2), bossH * S, bossD * S, '#ddd9cf');
90
+ if (shaftL) rect(SX(bossAt), SY(shaftD / 2), (shaftL + (top ? bossH : 0)) * S, shaftD * S, METAL);
91
+ if (flat) { const tip = bossAt + (top ? bossH : 0) + shaftL; const a = flats === 2 ? across / 2 : across - shaftD / 2; line(SX(tip - flat), SY(a), SX(tip), SY(a), INK, 1.2); if (flats === 2) line(SX(tip - flat), SY(-a), SX(tip), SY(-a), INK, 1.2); }
92
+ line(SX(0), SY(reach), SX(0), SY(-reach), THIN, 0.6, '4 3');
93
+ text(SX(0), SY(reach) - 6, 'mounting face', 'middle', 10);
94
+ const under = SY(cy - d / 2) + halfH * 0 + 6;
95
+ if (L) span(SX(-L), under, SX(0), under, `${fig(L)}`, 14);
96
+ if (shaftL) span(SX(top + (top ? bossH : 0)), under, SX(top + (top ? bossH : 0) + shaftL), under, `shaft ${fig(shaftL)}`, 36);
97
+ 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
+ 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`;
104
+ }
105
+
106
+ // ---------- a draft from a datasheet's text ----------
107
+ const UNITS = /(-?\d+(?:\.\d+)?)\s*(mm|N\s?m|N\.m|Ncm|N\.cm|kg\s?cm|kgf?\.?cm|V|A|mH|Ω|ohm|rpm|RPM|Hz|g|kg|°)(?![a-zA-Z])/g;
108
+ // Text drawn in a PDF: its streams unpacked, then the strings shown with Tj and TJ. A datasheet that is a picture has none.
109
+ export function pdfText(file) {
110
+ const raw = fs.readFileSync(file), latin = raw.toString('latin1'), lines = [];
111
+ for (const m of latin.matchAll(/stream\r?\n/g)) {
112
+ const start = m.index + m[0].length, end = latin.indexOf('endstream', start);
113
+ if (end < 0) continue;
114
+ const body = raw.subarray(start, end);
115
+ let s; try { s = zlib.inflateSync(body).toString('latin1'); } catch { s = body.toString('latin1'); }
116
+ if (!/\b(Tj|TJ)\b/.test(s)) continue;
117
+ for (const block of s.matchAll(/BT([\s\S]*?)ET/g)) {
118
+ const words = [...block[1].matchAll(/\[((?:[^\]\\]|\\.)*)\]\s*TJ|\(((?:[^()\\]|\\.)*)\)\s*Tj/g)].map((x) => (x[1] != null ? [...x[1].matchAll(/\(((?:[^()\\]|\\.)*)\)/g)].map((y) => y[1]).join('') : x[2]));
119
+ const t = words.join(' ').replace(/\\([()\\])/g, '$1').trim();
120
+ if (t) lines.push(t);
121
+ }
122
+ }
123
+ return lines;
124
+ }
125
+
126
+ /** Every figure a datasheet's text gives, as a rule set of estimates for a person to name and check. @returns {{ set: object, found: number }} */
127
+ export function draftSet(name, file) {
128
+ if (!fs.existsSync(file)) throw new Error(`no file ${file}`);
129
+ const lines = pdfText(file), rules = {}, stamp = new Date().toISOString().slice(0, 10), source = path.basename(file);
130
+ let i = 0;
131
+ for (const line of lines) for (const m of line.matchAll(UNITS)) {
132
+ i += 1;
133
+ rules[`figure_${String(i).padStart(3, '0')}`] = { value: Number(m[1]), unit: m[2], rule: `DRAFT: name and check me. From: "${line.slice(0, 120)}"`, kind: 'estimate', source, checked: stamp };
134
+ }
135
+ return { set: { _doc: `A draft from ${source}: rename each figure from vocabulary.json, delete the ones you don't want, and only then change its kind to spec.`, name, rules }, found: i };
136
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@rulecad/cad",
3
- "version": "0.7.36",
3
+ "version": "0.7.38",
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": {
@@ -57,14 +57,14 @@
57
57
  "url": "https://github.com/JoniBach/rulecad/issues"
58
58
  },
59
59
  "dependencies": {
60
- "@rulecad/variables": "^0.3.0",
60
+ "@rulecad/variables": "^0.3.2",
61
61
  "@rulecad/keyboard-layout": "^0.1.2",
62
62
  "@rulecad/printcheck": "^0.3.0",
63
63
  "@rulecad/fit": "^0.4.0",
64
64
  "@rulecad/model-link": "^0.3.0",
65
65
  "@rulecad/versions": "^0.1.0",
66
66
  "@rulecad/shapes": "^0.4.1",
67
- "@rulecad/rules": "^0.3.0",
67
+ "@rulecad/rules": "^0.3.6",
68
68
  "@jscad/modeling": "^2.12.0",
69
69
  "three": "^0.186.1",
70
70
  "@rulecad/fea": "^0.2.1",
@@ -64,6 +64,8 @@
64
64
  "properties": {
65
65
  "a": { "$ref": "#/$defs/names" },
66
66
  "b": { "$ref": "#/$defs/names" },
67
+ "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" },
68
+ "radius": { "$ref": "#/$defs/expr", "description": "With engage: how near the joint's axis to look (mm, default 10)" },
67
69
  "fastens": { "type": "boolean", "description": "a and b are fastened together (pins, screws, a press): what holds a part that has no joint" },
68
70
  "min": { "$ref": "#/$defs/expr" },
69
71
  "max": { "$ref": "#/$defs/expr" },
@@ -13,6 +13,9 @@
13
13
  "description": { "type": "string" },
14
14
  "licence": { "type": "string" },
15
15
  "private": { "type": "boolean" },
16
+ "part": { "type": "string", "description": "What sort of part it describes (motor): its names come from vocabulary.json, and cad rules check holds it to them" },
17
+ "interface": { "type": "object", "additionalProperties": { "type": "string" }, "description": "Which rule is which shared name in vocabulary.json, for a set that keeps its own names" },
18
+ "variants": { "type": "object", "description": "A maker's part numbers for this part, each the rules that differ: { \"17HS4401\": { \"kind\", \"source\", \"values\": { \"body_length\": 40 } } }" },
16
19
  "footprints": { "type": "object" },
17
20
  "circuit": { "type": "object", "description": "A published board's circuit (parts, pads, nets, planes, outline), read by cad clone, for @rulecad/pcb's clone()" },
18
21
  "rules": {