@rulecad/cad 0.7.56 → 0.7.58

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.
@@ -0,0 +1,132 @@
1
+ // A machine's services on its frame (@rulecad/frames' services.mjs): a bought board or supply with "mount" sits on a
2
+ // printed mount at an address on a beam's slotted face, its holes read from its own rule set,
3
+ // { "id": "psu", "bought": "supply-24v", "variant": "LRS-50-24", "mount": { "on": "rail.top@200" } }
4
+ // and a wire may run along a beam's slot, held by printed cable clips at a pitch,
5
+ // "via": [{ "along": "rail.top", "from": 20, "to": 380, "pitch": 100 }]
6
+ // Before the items are built, each mount is added as a fitting item with its fastens (into the slot, and into or
7
+ // through the device) and the device placed on it; each run's clips are added at their places along the slot and the
8
+ // wire routed through them, so its length follows the beam. Units: mm.
9
+ import { beamAnchor, runClips, SERVICE_DEFAULTS } from '@rulecad/frames';
10
+ import { beamOf, framesContext } from './beams.mjs';
11
+ import { fittingModel } from './fittings.mjs';
12
+ import { boughtSets } from './bought.mjs';
13
+
14
+ const MOUNT_KEYS = ['on', 'turn', 'offset', 'standoff', 'load', 'nut', 'head', 'screw'];
15
+ const RUN_KEYS = ['along', 'from', 'to', 'pitch', 'cable'];
16
+ const shown = (v) => (v === undefined ? 'nothing' : JSON.stringify(v));
17
+ const mm = (x) => String(+Number(x).toFixed(2)), r3 = (x) => +x.toFixed(3);
18
+
19
+ // a slotted place on a beam by its face's name (top, top.2) and the beam's model, refused by name
20
+ function slotPlace(what, id, B, name) {
21
+ const q = B.places.find((x) => x.name === name || (x.face === name && x.index === 1));
22
+ if (!q) throw new Error(`${what}: ${id} has no face "${name}": it has ${[...new Set(B.places.map((x) => x.face))].join(', ')}`);
23
+ if (!q.slot) throw new Error(`${what}: ${id}'s ${name} face is closed: a mount or a clip goes into a slot`);
24
+ return q;
25
+ }
26
+ // the face a fitting is drawn for: top, or top.2 where the face has two slots
27
+ const faceOf = (B, q) => (B.places.filter((x) => x.face === q.face).length > 1 ? q.name : q.face);
28
+
29
+ /**
30
+ * An assembly's mounts and slot runs worked out before its items are built: each bought item with "mount" placed on a
31
+ * printed device mount at its address, the mount's screws into the slot and the device's screws as fastens; each wire's
32
+ * run along a slot as cable clips at a pitch, the wire routed through them. Refused by name: a mount on what is not a
33
+ * bought board or supply, an item with both at and mount, an address that is not on a slotted face of a beam, a run past
34
+ * a beam's end, and what @rulecad/frames refuses.
35
+ * @param {object} a the assembly as read @param {(x: any) => number} num @param {object} [context] framesContext()'s @param {string} [material]
36
+ * @returns {{ a: object, mounts: object[], runs: object[] }}
37
+ */
38
+ export function expandServices(a, num, context = framesContext(), material = 'pla') {
39
+ const items = a.items || [], mounted = items.filter((it) => it.mount != null), runs0 = (a.wires || []).some((w) => (w.via ?? []).some((v) => v && typeof v === 'object'));
40
+ if (!mounted.length && !runs0) return { a, mounts: [], runs: [] };
41
+ const beams = new Map(items.filter((it) => it.beam).map((it) => [it.id, it])), ids = new Set(items.map((it) => it.id)), models = new Map();
42
+ const modelOf = (id) => { if (!models.has(id)) models.set(id, beamOf(beams.get(id), num, context).model); return models.get(id); };
43
+ const free = (base) => { let n = base, k = 2; while (ids.has(n)) n = `${base}-${k++}`; ids.add(n); return n; };
44
+ const beamOfAddress = (what, ref, key) => {
45
+ const s = String(ref ?? ''), i = s.indexOf('.');
46
+ if (i < 0) throw new Error(`${what}: ${key} is a beam's slotted face${key === 'on' ? ' and a distance, as rail.top@200' : ', as rail.top'} (got ${shown(ref)})`);
47
+ const id = s.slice(0, i), rest = s.slice(i + 1);
48
+ if (!beams.has(id)) throw new Error(`${what}: ${key} names a beam item of this assembly, and ${id} is ${items.some((x) => x.id === id) ? 'not a beam' : 'not an item'} (beams: ${[...beams.keys()].join(', ') || 'none'})`);
49
+ return { id, rest, B: modelOf(id) };
50
+ };
51
+ const added = [], fasten = [], fits = [], mounts = [], runs = [], plates = [], replaced = new Map(), ahead = new Map();
52
+ for (const it of mounted) {
53
+ const what = `item ${it.id}`, M = it.mount;
54
+ if (!M || typeof M !== 'object' || Array.isArray(M)) throw new Error(`${what}: mount is { "on": "rail.top@200" }, an address on a beam's slotted face (got ${shown(M)})`);
55
+ for (const k of Object.keys(M)) if (!MOUNT_KEYS.includes(k)) throw new Error(`${what}: a mount has no "${k}": it takes ${MOUNT_KEYS.join(', ')}`);
56
+ if (!it.bought) throw new Error(`${what}: mount holds a bought board or supply by the holes its rule set gives: give "bought"`);
57
+ const part = boughtSets().get(it.bought);
58
+ if (!['board', 'supply', 'encoder'].includes(part)) throw new Error(`${what}: mount holds a bought board or supply, and ${it.bought} is ${part ? `a ${part}` : 'no bought part'}`);
59
+ if (it.at != null || it.rotate != null || it.repeat != null) throw new Error(`${what}: a mounted item is placed by its mount: leave out at, rotate and repeat`);
60
+ const { id: bid, rest, B } = beamOfAddress(what, M.on, 'on'), [face, dist] = rest.split('@');
61
+ if (dist == null) throw new Error(`${what}: on is a beam's face and a distance along it, as ${bid}.${face}@200 (got ${shown(M.on)})`);
62
+ try { beamAnchor(B, rest); } catch (e) { throw new Error(`${what}: on: ${String(e.message).replace(/^beamAnchor: /, '')}`); }
63
+ const q = slotPlace(what, bid, B, face), mid = free(`${it.id}-mount`);
64
+ const spec = { kind: 'device-mount', profile: B.profile.name, face: faceOf(B, q), device: it.bought, ...(it.variant != null ? { variant: it.variant } : {}),
65
+ ...(M.turn != null ? { turn: M.turn } : {}), ...(M.offset != null ? { offset: num(M.offset) } : {}), ...(M.standoff != null ? { standoff: num(M.standoff) } : {}), ...(M.load != null ? { load: num(M.load) } : {}),
66
+ ...(M.nut != null ? { nut: M.nut } : {}), ...(M.head != null ? { head: M.head } : {}), ...(M.screw != null ? { screw: M.screw } : {}) };
67
+ const m = fittingModel(spec, context, material, what), D = m.device;
68
+ ahead.set(it.id, { id: mid, fitting: spec, at: `${bid}.${rest}`, mountOf: it.id }); // (listed just before its device: of two parts as near the base, the earlier goes on first)
69
+ fasten.push({ screw: `${m.thread} ${m.head}`, through: [mid], into: `${bid}.${q.name}`, at: m.screws.map((_, k) => `${mid}.b${k + 1}`), nut: m.screws[0].nutKind, note: `${it.id}'s mount into ${bid}`, mountOf: it.id });
70
+ const at = D.holes.map((_, k) => `${mid}.d${k + 1}`);
71
+ fasten.push(m.fix === 'tapped'
72
+ ? { screw: `${D.thread} ${D.head}`, through: [mid], into: it.id, at, note: `${it.id} on its mount, from under it`, mountOf: it.id }
73
+ : { screw: `${D.thread} ${D.head}`, through: [it.id], into: mid, at, note: `${it.id} on its mount`, mountOf: it.id });
74
+ replaced.set(it.id, { ...it, at: `${mid}.device` });
75
+ // the stretch of the slot its plate covers (either way along, as its outline reaches): a run's clips keep off it
76
+ const reachX = Math.max(...m.outline.map((pt) => Math.abs(pt[0]))), d0 = num(dist), at0 = d0 < 0 ? B.length + d0 : d0;
77
+ plates.push({ mount: mid, item: it.id, beam: bid, slot: q.name, lo: r3(at0 - reachX), hi: r3(at0 + reachX) });
78
+ mounts.push({ id: it.id, mount: mid, beam: bid, on: M.on, set: it.bought, variant: it.variant ?? null, fix: m.fix, holes: D.holes.length, thread: D.thread, length: D.length, grams: m.grams, margin: m.margin });
79
+ }
80
+ // wires: each run along a slot becomes clips, and the wire goes through each clip's cable anchor in turn
81
+ const wires = (a.wires || []).map((w, wi) => {
82
+ if (!(w.via ?? []).some((v) => v && typeof v === 'object')) return w;
83
+ const via = [];
84
+ for (const v of w.via) {
85
+ if (!v || typeof v !== 'object') { via.push(v); continue; }
86
+ const what = `wire ${w.id || wi + 1}`;
87
+ if (Array.isArray(v)) throw new Error(`${what}: a run in via is { "along": "rail.top", "from": 20, "to": 380 } (got ${shown(v)})`);
88
+ for (const k of Object.keys(v)) if (!RUN_KEYS.includes(k)) throw new Error(`${what}: a run along a slot has no "${k}": it takes ${RUN_KEYS.join(', ')}`);
89
+ const { id: bid, rest, B } = beamOfAddress(what, v.along, 'along');
90
+ if (rest.includes('@')) throw new Error(`${what}: along names the face (${bid}.${rest.split('@')[0]}); the run's ends are from and to, in mm from end a`);
91
+ const q = slotPlace(what, bid, B, rest);
92
+ if (v.from == null || v.to == null) throw new Error(`${what}: a run along ${v.along} gives from and to, in mm from ${bid}'s end a`);
93
+ const from = num(v.from), to = num(v.to), L = B.length;
94
+ for (const [k, x] of [['from', from], ['to', to]]) if (!(Number.isFinite(x) && x >= 0 && x <= L)) throw new Error(`${what}: a run's ${k} is from 0 to ${mm(L)} mm along ${bid} (got ${shown(v[k])})`);
95
+ let clips;
96
+ try { clips = runClips(Math.abs(to - from), v.pitch != null ? { pitch: num(v.pitch) } : {}); } catch (e) { throw new Error(`${what}: ${String(e.message).replace(/^runClips: /, '')}`); }
97
+ const sgn = to >= from ? 1 : -1, cable = v.cable != null ? num(v.cable) : SERVICE_DEFAULTS.cable.value, list = [];
98
+ // a mount on the same slot: no clip under its plate; one each side of it instead, and the wire said to go round it
99
+ const cw = fittingModel({ kind: 'cable-clip', profile: B.profile.name, face: faceOf(B, q), cable }, context, material, what).width, keep = cw / 2 + SERVICE_DEFAULTS.gap.value;
100
+ const rlo = Math.min(from, to), rhi = Math.max(from, to), round = plates.filter((pl) => pl.beam === bid && pl.slot === q.name && pl.lo - keep < rhi && pl.hi + keep > rlo).map((pl) => ({ ...pl, lo: r3(pl.lo - keep), hi: r3(pl.hi + keep) }));
101
+ let ds = clips.at.map((s) => r3(from + sgn * s));
102
+ if (round.length) {
103
+ ds = ds.filter((d) => !round.some((pl) => d > pl.lo && d < pl.hi));
104
+ for (const pl of round) for (const e of [pl.lo, pl.hi]) if (e >= rlo - 1e-9 && e <= rhi + 1e-9 && !round.some((o) => e > o.lo + 1e-9 && e < o.hi - 1e-9) && !ds.some((d) => Math.abs(d - e) < cw)) ds.push(e);
105
+ ds.sort((x, y) => sgn * (x - y));
106
+ if (!ds.length) throw new Error(`${what}: a run along ${bid}.${q.name} from ${mm(from)} to ${mm(to)} mm lies under ${round.map((pl) => pl.mount).join(' and ')}: no clip has room there; run it along another face`);
107
+ }
108
+ for (const d of ds) {
109
+ const cid = free(`${w.id || `w${wi + 1}`}-clip`);
110
+ added.push({ id: cid, fitting: { kind: 'cable-clip', profile: B.profile.name, face: faceOf(B, q), cable }, at: `${bid}.${q.name}@${d}`, runOf: w.id || `w${wi + 1}` });
111
+ fits.push({ a: cid, b: bid, fastens: true, note: `${cid}: snapped into ${bid}'s ${q.name} slot, its barbs under the lips` }); // (no screw: its barbs hold it)
112
+ via.push(`${cid}.cable`); list.push(cid);
113
+ }
114
+ runs.push({ wire: w.id || `w${wi + 1}`, along: `${bid}.${q.name}`, from, to, length: r3(Math.abs(to - from)), clips: list, count: list.length, pitch: clips.pitch, round: round.map((pl) => ({ mount: pl.mount, item: pl.item, from: pl.lo, to: pl.hi })), most: v.pitch != null ? num(v.pitch) : SERVICE_DEFAULTS.pitch.value, cable });
115
+ }
116
+ return { ...w, via };
117
+ });
118
+ const out = { ...a, items: [...items.flatMap((it) => [...(ahead.has(it.id) ? [ahead.get(it.id)] : []), replaced.get(it.id) ?? it]), ...added], ...(fasten.length ? { fasten: [...(a.fasten || []), ...fasten] } : {}), ...(runs.length ? { wires } : {}), ...(fits.length ? { fits: [...(a.fits || []), ...fits] } : {}) };
119
+ return { a: out, mounts, runs };
120
+ }
121
+
122
+ /**
123
+ * A built assembly's service findings: service.mount for each mounted device (its set, its holes and screws, the
124
+ * mount's grams and margin) and wire.run for each run along a slot (its length and its clips at their pitch).
125
+ * @param {object} s a built assembly @param {Function} f the findings' sink
126
+ */
127
+ export function serviceFindings(s, f) {
128
+ for (const m of s.mounts ?? []) f('info', `${m.id}: on a printed mount (${m.mount}) at ${m.on}, held by its ${m.holes} ${m.fix === 'tapped' ? `tapped ${m.thread} holes from ${m.set}'s rule set, screwed up from under the mount` : `holes from ${m.set}'s rule set, ${m.thread} screws down into the mount`}; the mount ${mm(m.grams)} g, ${mm(m.margin)}× its load`, null, { code: 'service.mount', refs: { item: m.id, mount: m.mount, beam: m.beam, set: m.set }, values: { holes: m.holes, length: m.length, grams: m.grams, margin: m.margin } });
129
+ for (const r of s.runs ?? []) f('info', `${r.wire}: ${mm(r.length)} mm along ${r.along} from ${mm(r.from)} to ${mm(r.to)} mm, held by ${r.count} cable clip${r.count > 1 ? 's' : ''} ${r.count > 1 ? (r.round?.length ? `no more than ${mm(r.most)} mm apart but across ${r.round.map((x) => `${x.mount} (${mm(x.to - x.from)} mm, a clip each side)`).join(' and ')},` : `${mm(r.pitch)} mm apart (no more than ${mm(r.most)})`) : ''} for a ${mm(r.cable)} mm bundle`.trimEnd(), null, { code: 'wire.run', refs: { wire: r.wire, along: r.along, clips: r.clips }, values: { length: r.length, clips: r.count, pitch: r.pitch } });
130
+ // a run under a mount's plate: its clips are set either side, and the wire cannot lie in the slot under the plate
131
+ for (const r of s.runs ?? []) for (const x of r.round ?? []) f('warn', `${r.wire}: its run along ${r.along} passes ${x.mount} (${x.item}'s mount) from ${mm(x.from)} to ${mm(x.to)} mm: no clip goes under the plate, so one is set each side of it, and the wire must go round the mount there: run it along another face, or end the run before the mount`, `${r.wire}: round ${x.mount}`, { code: 'wire.run', refs: { wire: r.wire, along: r.along, mount: x.mount, item: x.item }, values: { from: x.from, to: x.to } });
132
+ }
package/lib/sheet.mjs CHANGED
@@ -73,6 +73,18 @@ function partFindings(set, name, file, all) {
73
73
  return out;
74
74
  }
75
75
 
76
+ // A draft's figures not yet read from a sheet: cad rules draft profile writes each with a source that starts "DRAFT"
77
+ // (its rule is the field's own sentence, which stays), and cad rules draft from a PDF writes each figure's rule
78
+ // "DRAFT: name and check me" while its kind is estimate. A set that still has one checks and draws as it stands, so it
79
+ // is said by name until each is filled (a source of its own, or a rule of its own and kind spec) or deleted
80
+ const isDraft = (r) => /^DRAFT\b/.test(String(r.source ?? '')) || (/^DRAFT\b/.test(String(r.rule ?? '')) && r.kind === 'estimate');
81
+ function draftLeft(set) {
82
+ const left = Object.entries(set.rules && typeof set.rules === 'object' ? set.rules : {}).filter(([, r]) => r && typeof r === 'object' && isDraft(r)).map(([k]) => k);
83
+ if (!left.length) return [];
84
+ const n = Object.keys(set.rules).length, named = left.length > 8 ? `${left.slice(0, 8).join(', ')} and ${left.length - 8} more` : left.join(', ');
85
+ return [{ level: 'warn', code: 'rules.draft', text: `${left.length} of its ${n} figures are still the draft's, not read from a sheet: ${named}. Fill each from the maker's sheet (its value, the sheet and page as its source, the date) or delete it`, values: { count: left.length, total: n }, refs: { rules: left } }];
86
+ }
87
+
76
88
  /** Every named set checked (or all of them): [{ name, file, findings, notes? }]. A finding's level is fail, warn or info;
77
89
  * notes: what is said and never fails */
78
90
  export function checkSets(names = []) {
@@ -80,6 +92,7 @@ export function checkSets(names = []) {
80
92
  return (names.length ? names.map((n) => [n, fileOf(n)]) : [...all]).map(([name, file]) => {
81
93
  const set = readSet(file), findings = checkRuleSet(set, v), notes = notesOf(set, file);
82
94
  if (!findings.length && ['profile', 'slot', 'slot_nut'].includes(set.part)) findings.push(...partFindings(set, name, file, all));
95
+ findings.push(...draftLeft(set));
83
96
  return { name, file, findings, ...(notes.length ? { notes } : {}) };
84
97
  });
85
98
  }
@@ -490,9 +503,10 @@ export function draftPart(part, name) {
490
503
  const v = vocabulary(), fields = v.drafts?.[part];
491
504
  if (!fields) return null;
492
505
  const stamp = new Date().toISOString().slice(0, 10), rules = {};
493
- for (const [k, value] of Object.entries(fields)) rules[k] = { value, ...(v.fields[k]?.unit != null ? { unit: v.fields[k].unit } : {}), rule: `DRAFT, not read from a sheet yet: ${v.fields[k]?.says ?? k}`, kind: 'estimate', source: 'DRAFT: give the sheet, its page and the date you read it', checked: stamp };
506
+ for (const [k, value] of Object.entries(fields)) rules[k] = { value, ...(v.fields[k]?.unit != null ? { unit: v.fields[k].unit } : {}), rule: sentence(v.fields[k]?.says ?? k), kind: 'estimate', source: 'DRAFT, not read from a sheet yet: give the sheet, its page and the date you read it', checked: stamp };
494
507
  return { _doc: `A draft ${part.replace('_', ' ')}: every field the vocabulary has for one, each with a starting value. Put in the figures from the maker's sheet, with the sheet and its page as the source and today's date, and change each kind to spec as you go. Delete what the sheet has no figure for (cad rules check says which a ${part.replace('_', ' ')} needs). Then cad rules check ${name}, and cad rules draw ${name} to hold against the sheet's drawing.`, name, part, rules };
495
508
  }
509
+ const sentence = (t) => { const x = String(t).trim(); return x ? x[0].toUpperCase() + x.slice(1) : x; };
496
510
  export const draftParts = () => Object.keys(vocabulary().drafts || {});
497
511
 
498
512
  /** 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 }} */
@@ -0,0 +1,159 @@
1
+ // Slot nuts in a frame: what a fasten into a beam's slot (lib/fasten.mjs) asks of the joins round it. A slide-in nut
2
+ // (and a plain square nut) goes into a slot only from an open end of it; a drop-in, roll-in, hammer-head nut or T-bolt
3
+ // goes in through the opening anywhere along it. A slot's end is closed by a join that butts on it (the beam's end
4
+ // meets another beam), or, for the stretch of slot a nut is in, by a blind join's head sitting in that slot between
5
+ // the nut and the end; an item placed at the end (a cap, a foot) closes it too, though it comes off again.
6
+ // frame.nut: the nuts whose stretch of slot joins close at both ends. Once those joins are made a slide-in nut has
7
+ // no way in, so the check fails and names the nut of that thread that goes in through the opening.
8
+ // frame.preload: the nuts with a way in that a join closes and none that stays open (the other end capped): they
9
+ // go into the slot before that join is made. cad order and the build page list them at the step that makes it.
10
+ import { nutFor } from '@rulecad/frames';
11
+ import { framesContext } from './beams.mjs';
12
+ import { givenFor } from './frames.mjs';
13
+
14
+ const mm = (x) => String(+Number(x).toFixed(2)), r3 = (x) => +x.toFixed(3);
15
+ const EPS = 1e-3; // mm: a closure this near a nut is where the nut is, not beside it
16
+ const THROUGH = ['drop-in', 'roll-in', 'hammer', 't-bolt']; // (the kinds that go in through the opening, in the order a stand-in is offered)
17
+ const list = (xs) => (xs.length < 2 ? xs.join('') : `${xs.slice(0, -1).join(', ')} and ${xs.at(-1)}`);
18
+ const an = (t) => (/^(?:[aeiou8]|M\d)/i.test(String(t)) ? 'an' : 'a');
19
+
20
+ /**
21
+ * Each fasten's nuts in one slot: the relation, the beam and its slot (place: top.1, as joins name it; named: top, as
22
+ * said where the face has one slot), the nut, its kind and entry, the part it holds, and where along the beam each is.
23
+ * @param {object} s a built assembly
24
+ * @returns {{ rel: object, item: string, place: string, named: string, nut: string, kind: string, entry: string, thread: string, part: string, at: number[], screws: object[] }[]}
25
+ */
26
+ export function nutGroupsOf(s) {
27
+ const out = new Map();
28
+ for (const rel of s.fastened?.relations ?? []) for (const sc of rel.screws) {
29
+ if (!sc.slot) continue;
30
+ const key = `${rel.index}|${sc.slot.item}|${sc.slot.place}`; // (place: top.1, as joins name it; named: top, as said where the face has one slot)
31
+ if (!out.has(key)) out.set(key, { rel, ...sc.slot, at: [], screws: [] });
32
+ out.get(key).at.push(sc.slot.distance); out.get(key).screws.push(sc);
33
+ }
34
+ return [...out.values()];
35
+ }
36
+
37
+ /**
38
+ * What closes a beam's slot, and where along it: joins at its ends, blind joins' heads in that slot, items at its ends.
39
+ * @param {object} s a built assembly @param {string} item the beam @param {string} place its slot (top.1)
40
+ * @returns {{ at: number, end: string|null, join?: object, head?: boolean, item?: string }[]}
41
+ */
42
+ export function closuresOf(s, item, place) {
43
+ const L = s.objects.find((o) => o.id === item)?.beam?.length ?? 0, out = [], endAt = (e) => (e === 'a' ? 0 : L);
44
+ for (const j of s.joins ?? []) {
45
+ if (j.items[0] === item) out.push({ at: endAt(j.end[0]), end: j.end[0], join: j });
46
+ if (j.items[1] === item && j.model.b.end) out.push({ at: endAt(j.model.b.end[0]), end: j.model.b.end[0], join: j });
47
+ if (j.items[1] === item && j.kind === 'blind' && j.model.b.place === place) out.push({ at: j.model.b.distance, end: null, join: j, head: true });
48
+ }
49
+ for (const it of s.a.items || []) {
50
+ const m = typeof it.at === 'string' ? /^([\w-]+)\.([ab])(\.|$)/.exec(it.at.trim()) : null;
51
+ if (m && m[1] === item) out.push({ at: endAt(m[2]), end: m[2], item: it.id });
52
+ }
53
+ return out;
54
+ }
55
+
56
+ // The two ways out of a stretch of slot from lo to hi along the beam: every closure toward each end, nearest first (a
57
+ // join before an item where both stand at one place). A way is closed by a join where any closure on it is a join, not
58
+ // only the nearest: a head between the nuts and an end closed further along closes it as much as that end
59
+ function waysOf(s, item, place, lo, hi) {
60
+ const cs = closuresOf(s, item, place), near = (far) => (p, q) => (far ? q.at - p.at : p.at - q.at) || (q.join ? 1 : 0) - (p.join ? 1 : 0);
61
+ const all = { a: cs.filter((c) => c.at < lo - EPS).sort(near(true)), b: cs.filter((c) => c.at > hi + EPS).sort(near(false)) };
62
+ return { a: all.a[0] ?? null, b: all.b[0] ?? null, all, join: { a: all.a.find((c) => c.join) ?? null, b: all.b.find((c) => c.join) ?? null } };
63
+ }
64
+ const closerSays = (g, w) => (w.head ? `the head of the ${w.join.label} at ${mm(w.at)} mm` : w.join ? `${g.item}'s end ${w.end} (the ${w.join.label})` : `${g.item}'s end ${w.end} (${w.item} placed there)`);
65
+ const nutsSay = (g) => `${g.at.length} ${g.kind} nut${g.at.length > 1 ? 's' : ''} (${g.nut})`;
66
+
67
+ // The nut of that thread made for the slot that goes in through its opening: a drop-in first, then the other kinds
68
+ function throughNut(s, g) {
69
+ const b = s.objects.find((o) => o.id === g.item)?.beam;
70
+ for (const kind of THROUGH) { try { return nutFor(b.profile, g.place, g.thread, { kind, given: givenFor(framesContext(), b.profile.name) }); } catch {} }
71
+ return null;
72
+ }
73
+
74
+ /**
75
+ * The nuts that must be in a slot before a join closes it: slide-in and square nuts whose stretch of slot has no way
76
+ * that stays open, and a way a join closes. @param {object} s a built assembly
77
+ * @returns {{ fasten: number, label: string, item: string, place: string, named: string, part: string, nut: string, count: number, end: string|null, way: string, at: number, join: object, closers: object[], other: object|null, text: string }[]}
78
+ * join: the nearest join on the way the nuts go in; closers: every join on that way, nearest the nuts first (any of them
79
+ * made shuts the way, so the nuts go in before the first of them is made)
80
+ */
81
+ export function preloadOf(s) {
82
+ const out = [];
83
+ for (const g of nutGroupsOf(s)) {
84
+ if (g.entry !== 'end') continue;
85
+ const w = waysOf(s, g.item, g.place, Math.min(...g.at), Math.max(...g.at));
86
+ if (!w.a || !w.b || (w.join.a && w.join.b) || (!w.join.a && !w.join.b)) continue; // (a way stays open; or joins close both: frame.nut's; or only items placed at the ends do, which go on after the nuts)
87
+ // every join on that way closes it (a head nearer the end as much as the nearest), so the nuts go in before the first
88
+ // made; an item at that end (a foot, a cap) is off until then too
89
+ const way = w.join.a ? 'a' : 'b', other = way === 'a' ? 'b' : 'a', by = w.join[way], ends = w.all[other].filter((c) => c.item), caps = w.all[way].filter((c) => c.item);
90
+ const closers = [...new Map(w.all[way].filter((c) => c.join).map((c) => [c.join.index, c])).values()];
91
+ const end = closers.find((c) => c.end)?.end ?? null, heads = closers.filter((c) => c.head);
92
+ const from = closers.length > 1 || !end ? `from end ${way}${heads.length ? `, past ${list(heads.map((c) => `${mm(c.at)}`).reverse())} mm` : ''}` : `through its end ${end}`;
93
+ const capped = caps.length ? ` (${list(caps.map((c) => c.item))} off until then)` : '';
94
+ const before = closers.length > 1 ? `before the first made of ${list(closers.map((c) => `the ${c.join.label}`).reverse())}, each of which closes that way` : `before the ${by.join.label} closes it`;
95
+ const or = ends.length ? ` (or through end ${other} before ${list(ends.map((c) => c.item))} go${ends.length > 1 ? '' : 'es'} on)` : '';
96
+ const how = `${from}${capped}, ${before}${or}`;
97
+ out.push({ fasten: g.rel.index, label: g.rel.label, item: g.item, place: g.place, named: g.named, part: g.part, nut: g.nut, count: g.at.length, end: by.end, way, at: by.at, join: by.join, closers: closers.map((c) => c.join), other: ends[0] ?? null, how,
98
+ text: `load ${g.at.length} × ${g.nut} into ${g.item}'s ${g.named} slot ${from}${capped}, for ${g.part}, ${before}${or}` });
99
+ }
100
+ return out;
101
+ }
102
+
103
+ /**
104
+ * The slide-in and square nuts that joins shut in: their stretch of slot closed at both ends by joins (frame.nut's
105
+ * failures), each with the two joins and the nut that goes in through the opening, where there is one.
106
+ * @param {object} s a built assembly
107
+ * @returns {{ fasten: number, label: string, item: string, place: string, named: string, nut: string, kind: string, count: number, part: string, at: number[], joins: object[], alternative: object|null }[]}
108
+ */
109
+ export function trappedOf(s) {
110
+ const out = [];
111
+ for (const g of nutGroupsOf(s)) {
112
+ if (g.entry !== 'end') continue;
113
+ const w = waysOf(s, g.item, g.place, Math.min(...g.at), Math.max(...g.at));
114
+ if (w.join.a && w.join.b) out.push({ fasten: g.rel.index, label: g.rel.label, item: g.item, place: g.place, named: g.named, nut: g.nut, kind: g.kind, count: g.at.length, part: g.part, at: g.at, joins: [w.join.a.join, w.join.b.join], alternative: throughNut(s, g) });
115
+ }
116
+ return out;
117
+ }
118
+
119
+ /**
120
+ * frame.nut and frame.preload, in the assembly's findings shape. @param {object} s a built assembly @param {Function} f the findings' sink
121
+ */
122
+ export function slotNutChecks(s, f) {
123
+ const groups = nutGroupsOf(s);
124
+ if (!groups.length) return;
125
+ const pre = preloadOf(s);
126
+ for (const g of groups) {
127
+ const lo = Math.min(...g.at), hi = Math.max(...g.at), where = `${g.item}'s ${g.named} slot`, first = g.screws[0];
128
+ const refs = { fasten: g.rel.index, item: g.item, place: g.place, nut: g.nut, kind: g.kind, along: g.at };
129
+ if (g.entry !== 'end') { f('pass', `${g.rel.label}: ${nutsSay(g)} go${g.at.length > 1 ? '' : 'es'} into ${where} through its opening, anywhere along it`, null, { code: 'frame.nut', at: first.at.map(r3), refs }); continue; }
130
+ const w = waysOf(s, g.item, g.place, lo, hi);
131
+ if (w.join.a && w.join.b) {
132
+ const alt = throughNut(s, g), joins = [w.join.a.join.index, w.join.b.join.index];
133
+ f('fail', `${g.rel.label}: ${nutsSay(g)} go${g.at.length > 1 ? '' : 'es'} into ${where} at ${g.at.map(mm).join(' and ')} mm, between ${closerSays(g, w.join.a)} and ${closerSays(g, w.join.b)}, which close it at both ends: a ${g.kind} nut goes in only from an open end. ${alt ? `${alt.name} (${an(alt.thread)} ${alt.thread} ${alt.nutKind} nut) goes in through the opening anywhere: give "nut": "${alt.nutKind}"` : `No ${g.thread} nut made for ${g.slot} goes in through its opening: load these before the later of the two joins, or move them to a slot with an open end`}`,
134
+ `${g.rel.label}: nut`, { code: 'frame.nut', at: first.at.map(r3), values: { nuts: g.at.length }, refs: { ...refs, joins, ...(alt ? { alternative: alt.name, kind_needed: alt.nutKind } : {}) } });
135
+ continue;
136
+ }
137
+ const open = !w.a ? 'a' : !w.b ? 'b' : null, pl = open ? null : pre.find((p) => p.fasten === g.rel.index && p.item === g.item && p.place === g.place);
138
+ f('pass', `${g.rel.label}: ${nutsSay(g)} go${g.at.length > 1 ? '' : 'es'} into ${where} ${open ? `from its end ${open}, which nothing closes` : pl ? `before a join closes its way, ${pl.how} (frame.preload)` : `from an end before ${list(['a', 'b'].map((e) => w.all[e].filter((c) => c.item).map((c) => c.item)).flat())} go on`}`, null, { code: 'frame.nut', at: first.at.map(r3), refs });
139
+ }
140
+ for (const p of pre) f('info', `${p.label}: ${p.text}`, null, { code: 'frame.preload', values: { nuts: p.count }, refs: { fasten: p.fasten, item: p.item, place: p.place, nut: p.nut, join: p.join.index, joins: p.closers.map((j) => j.index), end: p.end, way: p.way } });
141
+ if (!pre.length) f('pass', 'no slot nut has to be in its slot before a join closes it', null, { code: 'frame.preload' });
142
+ }
143
+
144
+ /**
145
+ * The order of assembly with the nuts to load first: each preload at the step that makes the join that closes its slot
146
+ * (the step its later item goes on in), as that step's load. @param {object} s a built assembly @param {object} r orderOf's
147
+ * @returns {object} r, its steps copied with load: string[] where there are nuts to load before them
148
+ */
149
+ export function withPreload(s, r) {
150
+ if (!r?.steps?.length) return r;
151
+ const pre = preloadOf(s);
152
+ if (!pre.length) return r;
153
+ const steps = r.steps.map((st) => ({ ...st })), stepOf = (id) => steps.findIndex((st) => st.items.includes(id));
154
+ for (const p of pre) {
155
+ const i = Math.min(...p.closers.map((j) => Math.max(0, ...j.items.map(stepOf)))); // (the step that makes the first of the joins on the way)
156
+ (steps[i].load ||= []).push(p.text);
157
+ }
158
+ return { ...r, steps };
159
+ }
package/lib/task.mjs CHANGED
@@ -7,6 +7,7 @@ import { chainFromMotion, reach, sheetFrame, sheetPoint, jacobian, fk } from '@r
7
7
  import { evaluate, peekRuleSet } from './rules.mjs';
8
8
  import { paths } from './workspace.mjs';
9
9
  import { trainFrom, workingSpeed } from './motors.mjs';
10
+ import { placeItems } from '@rulecad/model-link';
10
11
 
11
12
  const n3 = (x, d = 2) => String(Number(x.toFixed(d)));
12
13
  const dot = (a, b) => a[0] * b[0] + a[1] * b[1] + a[2] * b[2];
@@ -118,17 +119,55 @@ function speedCheck(s, f) {
118
119
  else f('pass', `${t.tool} moves ${say}`, null, { code, at, values });
119
120
  }
120
121
 
121
- // Each joint's error terms: step resolution from its motor, and what the assembly says of its play, its twist and so on
122
- function terms(s, c) {
122
+ // Each joint's error terms: step resolution from its motor, what the assembly says of its play, its twist and so on, and a
123
+ // guide's rail's (its parallelism, its carriage's play, the beam's straightness and sag)
124
+ export function terms(s, c) {
123
125
  const motion = s.motion, specs = new Map((s.a.joints || []).map((j) => [j.id, j]));
124
126
  return c.names.map((id) => {
125
127
  const out = [], t = trainFrom(motion, id), d = motion.drives.find((x) => x.joint === t.root), spec = specs.get(id);
126
128
  if (d?.model.stepAngle) { const micro = d.spec.microsteps ?? 16; out.push({ term: 'step', value: t.slide != null ? (d.model.stepAngle / micro) * t.slide : d.model.stepAngle / micro / t.ratio, kind: 'spec', note: `${n3(d.model.stepAngle, 3)}° at 1/${micro} step, ${n3(t.ratio, 1)}:1` }); }
127
129
  const belt = motion.joints.find((x) => x.id === id)?.slide?.stretch; if (belt) out.push({ term: 'belt stretch', value: (belt.load * belt.length) / (belt.k * belt.width), kind: 'estimate', note: `${belt.load} N over ${belt.length} mm` });
128
130
  for (const [term, expr] of Object.entries(spec?.errors ?? {})) out.push({ term, value: s.num(expr), kind: kindOf(expr), expr });
131
+ for (const x of spec?._guide?.terms ?? []) out.push({ term: x.term, value: x.value, kind: x.kind, note: x.note }); // (a guide's rail: mm along its travel, from its rule sets and the beam's)
132
+ if (spec?._guide?.id) { const fr = frameTerms(s, spec._guide); return { joint: id, terms: [...out.filter((x) => !fr.drop.includes(x.term)), ...fr.add], geared: t.stages.length > 0 }; }
129
133
  return { joint: id, terms: out, geared: t.stages.length > 0 };
130
134
  });
131
135
  }
136
+
137
+ /**
138
+ * The frame's share of a guide's error, in mm at the tool: the beam it runs on sags under the frame's loads (solved with
139
+ * the frame where the frame checks ran, in place of the guide's own pinned-ends estimate), and is only as straight and
140
+ * untwisted as its profile is made. Twist turns the carriage about the beam's axis, so it moves the tool by the angle
141
+ * times the tool's distance from that axis. Rods and screws span between holders at their ends, so the beam's own form
142
+ * does not reach them. @returns {{ add: object[], drop: string[] }} terms to add, and the guide's own to drop
143
+ */
144
+ export function frameTerms(s, g) {
145
+ const none = { add: [], drop: [] }, rec = (s.guides ?? []).find((x) => x.id === g.id);
146
+ if (!rec?.beam || ['rods', 'screw'].includes(rec.kind)) return none;
147
+ const o = s.objects.find((x) => x.id === rec.beam && x.beam), p = o?.beam?.profile, L = rec.length;
148
+ if (!p || !(L > 0)) return none;
149
+ const add = [], drop = [], have = new Set((g.terms ?? []).map((x) => x.term)), solved = s.frameGuideSag?.get(g.id);
150
+ if (solved) {
151
+ drop.push('beam sag');
152
+ add.push({ term: 'beam sag', value: solved.sag, kind: solved.restsOn === 'beams' ? 'derived' : solved.restsOn, note: `${rec.beam} under ${g.id}, solved with the frame${solved.pose ? `, ${solved.pose}` : ''}: ${n3(solved.rigid, 3)} mm with its joins rigid` });
153
+ }
154
+ const st = p.supply?.straightness;
155
+ if (st != null && !have.has('beam straightness')) add.push({ term: 'beam straightness', value: +((st * L) / 1000).toFixed(4), kind: p.figures?.straightness_per_metre?.kind ?? 'spec', note: `${p.name}, ${n3(st)} mm a metre over the guide's ${n3(L, 1)} mm` });
156
+ const tw = p.supply?.twist, W = s.task?.point && s.motion ? worldOf(s, rec.beam) : null, T = W ? worldOf(s, s.task.item) : null;
157
+ if (tw != null && W && T) {
158
+ const q = s.task.point, P = [0, 1, 2].map((r) => T[4 * r] * q[0] + T[4 * r + 1] * q[1] + T[4 * r + 2] * q[2] + T[4 * r + 3]); // (the tool, in the world, as drawn)
159
+ const O = [W[3], W[7], W[11]], d = [W[2], W[6], W[10]], v = P.map((x, k) => x - O[k]), along = dot(v, d), lever = Math.hypot(...v.map((x, k) => x - along * d[k]));
160
+ const deg = (tw * L) / 1000;
161
+ if (lever > 1e-6) add.push({ term: 'beam twist', value: +(((deg * Math.PI) / 180) * lever).toFixed(4), kind: p.figures?.twist_per_metre?.kind ?? 'spec', note: `${p.name}, ${n3(tw)}° a metre over the guide's ${n3(L, 1)} mm, ${n3(deg, 3)}°, at the tool ${n3(lever, 1)} mm from ${rec.beam}'s axis` });
162
+ }
163
+ return { add, drop };
164
+ }
165
+ // An item's world placement as drawn (row-major 4 × 4), or null
166
+ function worldOf(s, id) {
167
+ const i = s.motion.items.findIndex((x) => x[0] === id);
168
+ if (i < 0) return null;
169
+ try { return placeItems(s.motion, s.jointValues)[i]; } catch { return null; }
170
+ }
132
171
  function kindOf(expr) {
133
172
  const kinds = [...String(expr).matchAll(/([a-z][\w-]*)\.([a-z_]\w*)/gi)].map(([, set, rule]) => { try { return peekRuleSet(set).rules[rule]?.kind ?? 'estimate'; } catch { return 'estimate'; } });
134
173
  return kinds.length ? (kinds.includes('estimate') ? 'estimate' : kinds[0]) : 'estimate';
@@ -154,7 +193,8 @@ function accuracyCheck(s, f, picture) {
154
193
  const t = s.task, code = 'task.accuracy'; if (t.accuracy == null) return null;
155
194
  const { list, at, worst } = accuracyOf(s); if (!worst) return null;
156
195
  const big = [...worst.e.parts].sort((a, b) => b.mm - a.mm)[0], soft = worst.e.parts.filter((p) => p.kind === 'estimate');
157
- const name = (p) => `${p.joint ? `${p.joint}'s ` : ''}${p.term}${p.angle != null ? ` (${n3(p.angle, 3)}°)` : ''}`;
196
+ const slides = new Set(s.motion.joints.filter((j) => j.type === 'prismatic').map((j) => j.id)); // (a sliding joint's terms are mm already)
197
+ const name = (p) => `${p.joint ? `${p.joint}'s ` : ''}${p.term}${p.angle != null && !slides.has(p.joint) ? ` (${n3(p.angle, 3)}°)` : ''}`;
158
198
  const unmeasured = list.filter((j) => j.geared && !j.terms.some((x) => /play|backlash/.test(x.term))).map((j) => j.joint);
159
199
  const predict = { name: code, figure: `${t.tool} error at its worst point`, value: worst.e.worst, unit: 'mm' };
160
200
  const margin = worst.e.worst / t.accuracy, level = margin > 1 ? 'fail' : margin > 0.8 ? 'warn' : 'pass';
package/lib/wires.mjs CHANGED
@@ -80,7 +80,8 @@ export function wireRows(s, helpers) {
80
80
  export function wireChecks(s, f, helpers) {
81
81
  for (const w of wireRows(s, helpers)) {
82
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 });
83
+ const run = (s.runs ?? []).filter((r) => r.wire === w.id), clips = run.reduce((t, r) => t + r.count, 0);
84
+ 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)${run.length ? `; ${run.map((r) => `${n3(r.length, 0)} mm of it along ${r.along}`).join(', ')}, held by ${clips} cable clip${clips > 1 ? 's' : ''}` : ''}`, null, { code: 'wire.length', at, refs, values: { ...values, ...(run.length ? { along: run.reduce((t, r) => t + r.length, 0), clips } : {}) } });
84
85
  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
86
  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
87
  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 });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@rulecad/cad",
3
- "version": "0.7.56",
3
+ "version": "0.7.58",
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": {
@@ -58,24 +58,24 @@
58
58
  "url": "https://github.com/JoniBach/rulecad/issues"
59
59
  },
60
60
  "dependencies": {
61
- "@rulecad/variables": "^0.3.4",
61
+ "@rulecad/variables": "^0.3.5",
62
62
  "@rulecad/keyboard-layout": "^0.1.2",
63
63
  "@rulecad/printcheck": "^0.3.0",
64
64
  "@rulecad/fit": "^0.4.0",
65
65
  "@rulecad/model-link": "^0.3.2",
66
66
  "@rulecad/versions": "^0.1.6",
67
67
  "@rulecad/shapes": "^0.4.5",
68
- "@rulecad/rules": "^0.3.15",
68
+ "@rulecad/rules": "^0.3.17",
69
69
  "@jscad/modeling": "^2.12.0",
70
70
  "three": "^0.186.1",
71
- "@rulecad/fea": "^0.2.1",
71
+ "@rulecad/fea": "^0.2.11",
72
72
  "@rulecad/topopt": "^0.3.0",
73
73
  "@rulecad/flexures": "^0.5.0",
74
74
  "@rulecad/gears": "^0.3.2",
75
75
  "@rulecad/motors": "^0.1.6",
76
76
  "@rulecad/fixings": "^0.1.4",
77
- "@rulecad/robots": "^0.1.1",
78
- "@rulecad/frames": "^0.1.7"
77
+ "@rulecad/robots": "^0.1.2",
78
+ "@rulecad/frames": "^0.1.9"
79
79
  },
80
80
  "peerDependencies": {
81
81
  "@rulecad/pcb": "^0.1.0 || ^0.2.0 || ^0.3.0 || ^0.4.0 || ^0.5.0"