@rulecad/cad 0.7.53 → 0.7.56

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/lib/fasten.mjs CHANGED
@@ -11,7 +11,7 @@
11
11
  // as reference parts (hardware, below): faint, checked for overlap, and carried into previews and links.
12
12
  import crypto from 'node:crypto';
13
13
  import path from 'node:path';
14
- import { fixingsFor, DEFAULTS, screwGroup } from '@rulecad/fixings';
14
+ import { fixingsFor, DEFAULTS, screwGroup, parseName, threads } from '@rulecad/fixings';
15
15
  import { placeItems, jointValues } from '@rulecad/model-link';
16
16
  import { massesOf } from './loads.mjs';
17
17
  import { mountTorque } from './motors.mjs';
@@ -293,10 +293,11 @@ function fixingsOf(project) {
293
293
  if (bound.get(project)?.hash !== hash) bound.set(project, { hash, F: fixingsFor({ ...(Object.keys(context.sets).length ? { sets: context.sets } : {}), ...(context.printer ? { printer: context.printer } : {}) }), material: context.material, printer: context.printer?.name ?? 'x1c' });
294
294
  return bound.get(project);
295
295
  }
296
- // A piece of hardware as a part's shape, made once for each name: the light solid of @rulecad/fixings, its faces, a hash
296
+ // A piece of hardware as a part's shape, made once for each name: the light solid of @rulecad/fixings, its faces, a hash.
297
+ // m is a model (a screw) or a thread's name (a nut, a washer, an insert), so a thread's name is the key as it is
297
298
  const shapes = new Map();
298
299
  function shapeOf(F, kind, m, o) {
299
- const key = `${kind}:${m.name}:${JSON.stringify(o)}`;
300
+ const key = `${kind}:${typeof m === 'string' ? m : m.name}:${JSON.stringify(o)}`;
300
301
  if (!shapes.has(key)) {
301
302
  const g = F[kind](m, o), [p] = named({ body: g }, { body: { label: g.model.name } });
302
303
  shapes.set(key, { geometry: p.geometry, polygons: p.polygons, triangles: p.triangles, model: g.model, hash: `fixing:${crypto.createHash('sha256').update(JSON.stringify([key, p.polygons])).digest('hex').slice(0, 16)}` });
@@ -344,6 +345,9 @@ export function fastenOf(s, worlds, opts = {}) {
344
345
  if (!Array.isArray(through)) throw new Error(`${what}: "through" lists the parts the screw passes, in order from under its head (["bracket"])`);
345
346
  if (typeof x.into !== 'string' || !x.into) throw new Error(`${what}: "into" names the part the screw ends in`);
346
347
  const members = [...through, x.into].map((n) => { const ps = pick(n); if (!ps.length) throw new Error(`${what}: no part "${n}" (items: ${ids.join(', ')})`); return { name: n, parts: ps }; });
348
+ // A yoke (a screw through one cheek, what lies between, into the other) or a split clamp (across its own slot)
349
+ const yoke = through.length > 0 && through[0] === x.into;
350
+ if (yoke && x.holes != null) throw new Error(`${what}: a screw that ends in ${x.into}, the part under its head, is placed with "at": an anchor on each screw's axis, pointing from the head into the part`);
347
351
  if ((x.at == null) === (x.holes == null)) throw new Error(`${what}: give "at" (an anchor for each screw: ["${top(through[0] ?? x.into)}.h1"]) or "holes" (a part whose holes are the screws' places), one of the two`);
348
352
  if (x.nut != null && x.nut !== false && x.nut !== true && !NUTS.includes(x.nut)) throw new Error(`${what}: "nut" is true (a hexagon nut) or ${NUTS.join(', ')} (got ${JSON.stringify(x.nut)}): a slot nut comes with a frame's beam`);
349
353
  const wantNut = x.nut === true ? 'hex' : x.nut || null;
@@ -404,19 +408,31 @@ export function fastenOf(s, worlds, opts = {}) {
404
408
  try { const e = F.engagement(fx, { depth: 1, material: name }); return { name, cls: e.class, known: true }; } catch { return { name, cls: p.role === 'reference' ? null : 'plastic', known: false }; }
405
409
  };
406
410
  const drawn = (kind) => { try { return F.holeModel(fx, { kind }); } catch { return null; } };
407
- const clr = { close: drawn('close'), normal: drawn('clearance'), loose: drawn('loose') }, sizeTol = FASTEN.size.value;
411
+ const clr = { close: drawn('close'), normal: drawn('clearance'), loose: drawn('loose') }, clrOf = clr, sizeTol = FASTEN.size.value;
412
+ // A circuit board's holes are drilled by its fab, not printed: held to the thread's clearance holes as they stand
413
+ const drilled = (n) => (typeof fx.figures[n]?.value === 'number' ? { diameter: fx.figures[n].value, nominal: fx.figures[n].value, comp: 0, basis: { rule: `${fx.set}.${n}` } } : null);
414
+ const clrDrilled = { close: drilled('clearance_close'), normal: drilled('clearance'), loose: drilled('clearance_loose') };
415
+ const isBoard = (m) => m.parts.some((p) => s.objects.find((o) => o.id === p.leaf)?.built?.circuit);
408
416
 
409
417
  axes.forEach((ax, i) => {
410
418
  const sc = { index: i, name: ax.name, found: {}, hardware: [] }, say = (code, level, text, values) => { (sc.found[code] ||= []).push({ level, text, ...(values ? { values } : {}) }); };
411
419
  rel.screws.push(sc);
412
- // Which way the screw goes: from the part under its head towards the part it ends in (a set screw: against its anchor)
413
- const raw = members.map((m) => reach(along(m.parts, ax.O, ax.D, R, false)));
420
+ // Which way the screw goes: from the part under its head towards the part it ends in (a set screw: against its anchor).
421
+ // A yoke or a split clamp ends the screw in the part under its head: its first stretch of material from the head is
422
+ // that side, the rest the far side, and the anchor's axis says the way (from the head into the part)
423
+ const side = (j, segs) => {
424
+ if (!yoke || (j !== 0 && j !== members.length - 1)) return segs;
425
+ const on = (seg) => seg.solid || seg.hole, i = segs.findIndex(on); let e = i;
426
+ while (e >= 0 && e < segs.length && on(segs[e])) e++;
427
+ return i < 0 ? segs : j === 0 ? segs.slice(0, e) : segs.slice(e);
428
+ };
429
+ const raw = members.map((m, j) => reach(side(j, along(m.parts, ax.O, ax.D, R, false))));
414
430
  const missing = members.filter((_, j) => !raw[j]);
415
431
  sc.at = ax.O; sc.between = [ax.O, ax.O];
416
- if (missing.length) return say('fasten.holes', 'fail', `${missing.map((m) => m.name).join(' and ')} ${missing.length > 1 ? 'are' : 'is'} nowhere on the screw's axis (nothing of ${missing.length > 1 ? 'them' : 'it'} within ${mm(R)} mm of it): the parts are not where the joint needs them`);
417
- const mid = (r) => (r[0] + r[1]) / 2, flip = members.length > 1 ? mid(raw.at(-1)) < mid(raw[0]) : true;
432
+ if (missing.length) return say('fasten.holes', 'fail', `${missing.map((m) => m.name).join(' and ')} ${missing.length > 1 ? 'are' : 'is'} nowhere on the screw's axis (nothing of ${missing.length > 1 ? 'them' : 'it'} within ${mm(R)} mm of it)${yoke ? `: a screw that ends in ${x.into}, the part under its head, goes through one side of it and into the other, along its anchor's axis` : ': the parts are not where the joint needs them'}`);
433
+ const mid = (r) => (r[0] + r[1]) / 2, flip = yoke ? false : members.length > 1 ? mid(raw.at(-1)) < mid(raw[0]) : true;
418
434
  const D = flip ? ax.D.map((c) => -c) : ax.D, O = ax.O, at = (z) => add(O, D, z);
419
- const runs = members.map((m) => ({ ...m, segs: along(m.parts, O, ax.D, R, flip) }));
435
+ const runs = members.map((m, j) => ({ ...m, segs: side(j, along(m.parts, O, ax.D, R, flip)) }));
420
436
  for (const r of runs) r.reach = reach(r.segs);
421
437
  const order = runs.slice(1).find((r, j) => mid(r.reach) < mid(runs[j].reach));
422
438
  if (order) return say('fasten.holes', 'fail', `${order.name} lies before ${runs[runs.indexOf(order) - 1].name} along the screw: "through" lists the parts in order from under the head, and "into" comes last`);
@@ -458,7 +474,7 @@ export function fastenOf(s, worlds, opts = {}) {
458
474
  if (!holes.length) { say('fasten.holes', 'fail', `${r.name} has no hole on the screw's axis`); bad = true; continue; }
459
475
  const narrow = holes.reduce((m, seg) => (size(seg) < size(m) ? seg : m), holes[0]), d = size(narrow);
460
476
  for (const seg of holes) { const o = offAxis(seg); if (o != null && o > worst) worst = o; if (o != null && o > FASTEN.align.value) { say('fasten.holes', 'fail', `${r.name}'s hole is ${mm(o)} mm off the screw's axis: the holes do not line up`, { distance: r3(o) }); bad = true; break; } }
461
- cl.push({ name: r.name, d, free: 2 * Math.min(narrow.a.free, narrow.b.free) });
477
+ cl.push({ name: r.name, d, free: 2 * Math.min(narrow.a.free, narrow.b.free), board: isBoard(r) });
462
478
  }
463
479
  // The far end: the hole in the last part, from its mouth
464
480
  const first = B.segs.find((seg) => seg.solid || seg.hole);
@@ -494,11 +510,12 @@ export function fastenOf(s, worlds, opts = {}) {
494
510
  if (cl.length) {
495
511
  if (!clr.normal) say('fasten.clearance', 'info', `${fx.thread} has no clearance hole in its rule set (${fx.set}): the holes it passes are not held to one`);
496
512
  else for (const c of cl) {
513
+ const clr = c.board && clrDrilled.normal ? clrDrilled : clrOf, as = c.board && clrDrilled.normal ? 'as drilled' : 'as drawn';
497
514
  const lo = (clr.close ?? clr.normal).diameter, hi = (clr.loose ?? clr.normal).diameter, want = clr.normal, basis = `${want.basis.rule} ${mm(want.nominal)} mm${want.comp ? ` and ${printer}.hole_comp ${mm(want.comp)} mm` : ''}`;
498
515
  const values = { diameter: r3(c.d), wanted: want.diameter, least: lo, most: hi };
499
- if (c.d < lo - sizeTol) say('fasten.clearance', 'fail', `${c.name}'s hole measures ${mm(c.d)} mm where ${an(fx.thread)} ${fx.thread} screw passes through: a clearance hole should be ${mm(want.diameter)} mm as drawn (${basis}), ${mm(lo)} mm at the closest`, values);
500
- else if (c.d > hi + sizeTol) say('fasten.clearance', 'warn', `${c.name}'s hole measures ${mm(c.d)} mm, wider than the loosest clearance hole for ${fx.thread}, ${mm(hi)} mm as drawn: the screw does not place the part, and the head has less to sit on (${mm(want.diameter)} mm is the normal hole)`, values);
501
- else say('fasten.clearance', 'pass', `${c.name}'s hole measures ${mm(c.d)} mm, ${an(fx.thread)} ${fx.thread} clearance hole as drawn (${Math.abs(c.d - want.diameter) <= sizeTol ? basis : `between the close ${mm(lo)} mm and the loose ${mm(hi)} mm; the normal hole is ${mm(want.diameter)} mm`})`, values);
516
+ if (c.d < lo - sizeTol) say('fasten.clearance', 'fail', `${c.name}'s hole measures ${mm(c.d)} mm where ${an(fx.thread)} ${fx.thread} screw passes through: a clearance hole should be ${mm(want.diameter)} mm ${as} (${basis}), ${mm(lo)} mm at the closest`, values);
517
+ else if (c.d > hi + sizeTol) say('fasten.clearance', 'warn', `${c.name}'s hole measures ${mm(c.d)} mm, wider than the loosest clearance hole for ${fx.thread}, ${mm(hi)} mm ${as}: the screw does not place the part, and the head has less to sit on (${mm(want.diameter)} mm is the normal hole)`, values);
518
+ else say('fasten.clearance', 'pass', `${c.name}'s hole measures ${mm(c.d)} mm, ${an(fx.thread)} ${fx.thread} clearance hole ${as} (${Math.abs(c.d - want.diameter) <= sizeTol ? basis : `between the close ${mm(lo)} mm and the loose ${mm(hi)} mm; the normal hole is ${mm(want.diameter)} mm`})`, values);
502
519
  }
503
520
  }
504
521
  if (!end) return;
@@ -581,9 +598,14 @@ export function fastenOf(s, worlds, opts = {}) {
581
598
  }
582
599
 
583
600
  // fasten.engagement: thread engaged at the far end, against the rule for what it is in
584
- if (end.motor && form !== 'set') { const e = Math.max(0, Math.min(inEnd, end.depth)); say('fasten.engagement', 'pass', `${mm(e)} mm of ${x.into}'s own thread, ${mm(+(e / fx.pitch).toFixed(1))} turns of its ${mm(end.depth)} mm: a bought part's thread, held to its depth and to no engagement rule`, { engaged: r3(e), depth: end.depth, turns: +(e / fx.pitch).toFixed(1) }); }
601
+ if (end.motor && form !== 'set') { // a bought part's thread: held to its depth, and to the least engagement any metal is given (engagement.steel), as motor.mount is
602
+ const e = Math.max(0, Math.min(inEnd, end.depth)), least = r3(F.engagement(fx, { depth: 1, material: 'steel' }).need), turns = +(e / fx.pitch).toFixed(1), values = { engaged: r3(e), depth: end.depth, turns, least };
603
+ if (e >= least - EPS) say('fasten.engagement', 'pass', `${mm(e)} mm of ${x.into}'s own thread, ${mm(turns)} turns of its ${mm(end.depth)} mm: a bought part's thread, held to its depth and to the ${mm(least)} mm engagement.steel gives any metal`, values);
604
+ else say('fasten.engagement', 'fail', `${mm(e)} mm of ${x.into}'s own thread, ${mm(turns)} turns of its ${mm(end.depth)} mm: less than the ${mm(least)} mm engagement.steel gives any metal, so the thread strips before the screw holds. A longer screw, or a counterbore to sink its head`, values);
605
+ }
585
606
  else if (end.kind && need != null && form !== 'set') {
586
- const engaged = Math.max(0, Math.min(inEnd, avail)), ok = engaged >= need - EPS, values = { engaged: r3(engaged), need: r3(need), turns: +(engaged / fx.pitch).toFixed(1) };
607
+ // (held to the micron it is said in: the length was chosen from the stack rounded to the micron)
608
+ const engaged = Math.max(0, Math.min(inEnd, avail)), ok = r3(engaged) >= need - EPS, values = { engaged: r3(engaged), need: r3(need), turns: +(engaged / fx.pitch).toFixed(1) };
587
609
  const what2 = end.kind === 'nut' ? `its ${end.nut.model.name}, ${mm(avail)} mm high` : end.kind === 'insert' ? `the insert, ${mm(avail)} mm long` : `${intoMat.name ? `${intoMat.name}${intoMat.cls && intoMat.known ? ` (a${intoMat.cls === 'aluminium' ? 'n' : ''} ${intoMat.cls})` : ''}` : end.kind === 'pilot' ? 'plastic' : x.into}`;
588
610
  const rule = end.kind === 'nut' ? 'a nut wants its whole height engaged' : end.kind === 'insert' ? `fixings.insert_engagement asks a diameter of thread or the whole insert, ${mm(need)} mm` : end.kind === 'pilot' && fx.figures.pilot_depth ? `${fx.set}.pilot_depth asks ${mm(need)} mm` : `engagement.${end.kind === 'pilot' ? 'plastic' : intoMat.cls ?? 'plastic'} asks ${mm(need / fx.major)} diameters, ${mm(need)} mm`;
589
611
  if (ok) say('fasten.engagement', 'pass', `${mm(engaged)} mm of thread in ${what2}, ${mm(values.turns)} turns: ${rule}`, values);
@@ -822,3 +844,38 @@ export function fastenChecks(s, f, { placeItems }) {
822
844
  loadSays(s, f, rel, lead);
823
845
  }
824
846
  }
847
+
848
+ // ---------- the older forms, said as one fasten ----------
849
+ // A holes fit and a fit that fastens the same two items say apart what a fasten says at once. The screw is read from the
850
+ // fit's fastener ("M2x6"), else a thread set the holes fit's depth names (m2.insert_length), else the board's mounting
851
+ // holes as drawn: the largest metric thread narrower than the narrowest of them.
852
+ const metric = (t) => { const m = /^M(\d+(?:\.\d+)?)$/.exec(t); return m ? Number(m[1]) : null; };
853
+ function screwFrom(h, fit, s) {
854
+ try { const n = fit.fastener && parseName(String(fit.fastener)); if (n && (n.item === 'screw' || n.item === 'thread')) return `${n.thread}${n.length != null ? `x${n.length}` : ''} ${n.head ?? 'cap'}`; } catch {} // (a fastener in words, "Two push pins", names no thread)
855
+ let sets = {}; try { sets = fixingsContext({ project: s.project, dir: paths.project(s.project) }).context.sets; } catch {}
856
+ const known = threads({ sets }), set = /\b[mM](\d+(?:_\d+)?)\.\w/.exec([h.depth, h.ring].filter((x) => typeof x === 'string').join(' '));
857
+ if (set) { const t = `M${set[1].replace('_', '.')}`; if (known.includes(t)) return `${t} cap`; }
858
+ const board = s.objects.find((o) => o.id === top(h.holes))?.built, ds = (board?.circuit || []).filter((e) => e.type === 'pcb_hole' && !e.pcb_component_id).map((e) => e.hole_diameter).filter((d) => d > 0);
859
+ if (!ds.length) return null;
860
+ const d = Math.min(...ds), fit1 = known.filter((t) => metric(t) != null && metric(t) < d).sort((a, b) => metric(b) - metric(a))[0];
861
+ return fit1 ? `${fit1} cap` : null;
862
+ }
863
+
864
+ /**
865
+ * The fasten that would stand for each holes fit whose two items a fit that fastens also joins, and that no fasten
866
+ * names yet: the entry to paste, and where the two fits are in "fits".
867
+ * @param {{ a: object, project: string, objects: object[] }} s a built assembly
868
+ * @returns {{ fasten: object, holes: number, fastens: number, pair: string[], label: string, screw: string | null }[]}
869
+ */
870
+ export function fastenFromFits(s) {
871
+ const fits = s.a.fits || [], out = [], named = new Set((s.a.fasten || []).flatMap((x) => [...(x.through || []), x.into].map(top)));
872
+ fits.forEach((h, i) => {
873
+ if (!h.holes || !h.into || h.direction === 'up') return; // (screws from below: through and into the other way round, said by hand)
874
+ const pair = [top(h.holes), top(h.into)], same = (x) => typeof x.a === 'string' && typeof x.b === 'string' && [top(x.a), top(x.b)].sort().join() === [...pair].sort().join();
875
+ const k = fits.findIndex((x) => x.fastens && !x.holes && same(x));
876
+ if (k < 0 || pair.every((n) => named.has(n))) return;
877
+ const screw = screwFrom(h, fits[k], s), note = h.label || h.note || fits[k].note;
878
+ out.push({ fasten: { screw: screw ?? 'M3 cap', through: [h.holes], into: h.into, holes: h.holes, ...(note ? { note } : {}) }, holes: i, fastens: k, pair, label: h.label || `${h.holes} into ${h.into}`, screw });
879
+ });
880
+ return out;
881
+ }
package/lib/frames.mjs ADDED
@@ -0,0 +1,63 @@
1
+ // v.frames: @rulecad/frames as a design gets it, reading the workspace's own profile, slot and material sets (a profile
2
+ // measured with cad measure --profile, with its outline beside it) before the kit's. No files are read by designFrames:
3
+ // framesContext reads them for the build, and the sandbox's runner is handed what it found.
4
+ import fs from 'node:fs';
5
+ import path from 'node:path';
6
+ import crypto from 'node:crypto';
7
+ import * as frames from '@rulecad/frames';
8
+
9
+ // The workspace's own profile, slot and material sets (cad measure --profile writes a draft profile there, with its
10
+ // outline in rules/outlines/), read once per change to the folder
11
+ let seen = null;
12
+ /**
13
+ * What @rulecad/frames is handed from a workspace: its own rule sets by name, and the measured outlines beside them.
14
+ * @param {string} dir the workspace's rules/ folder
15
+ * @returns {{ sets: Record<string, object>, outlines: Record<string, object>, hash: string }}
16
+ */
17
+ export function framesContext(dir) {
18
+ const out = path.join(dir, 'outlines');
19
+ const stamp = (d) => { try { return fs.readdirSync(d).filter((f) => f.endsWith('.json')).sort().map((f) => `${f}:${fs.statSync(path.join(d, f)).mtimeMs}`).join('|'); } catch { return ''; } };
20
+ const key = `${dir}|${stamp(dir)}|${stamp(out)}`;
21
+ if (seen?.key === key) return seen.context;
22
+ const sets = {}, outlines = {}, text = [];
23
+ for (const [d, into] of [[dir, sets], [out, outlines]]) {
24
+ let files = []; try { files = fs.readdirSync(d).filter((f) => f.endsWith('.json')).sort(); } catch {}
25
+ for (const f of files) {
26
+ try {
27
+ const raw = fs.readFileSync(path.join(d, f), 'utf8'), s = JSON.parse(raw);
28
+ if (into === sets ? s?.rules && typeof s.rules === 'object' && ['profile', 'slot', 'slot_nut', 'material', 'thread'].includes(s.part) : Array.isArray(s?.loops)) { into[s.name ?? f.slice(0, -5)] = s; text.push(raw); }
29
+ } catch {} // (a broken set is cad rules check's to name)
30
+ }
31
+ }
32
+ const context = { sets, outlines, hash: crypto.createHash('sha256').update(text.join('\n')).digest('hex').slice(0, 24) };
33
+ seen = { key, context };
34
+ return context;
35
+ }
36
+
37
+ // profileModel's third argument for a profile by name: the workspace's sets, and its measured outline if it has one
38
+ export const givenFor = (context, profile, given = {}) => {
39
+ const name = typeof profile === 'string' ? (context.sets?.[profile] ? profile : context.sets?.[`profile-${profile}`] ? `profile-${profile}` : null) : null;
40
+ const outline = name && context.outlines?.[name];
41
+ return { ...given, sets: { ...(context.sets || {}), ...(given.sets || {}) }, ...(outline && !given.outline ? { outline } : {}) };
42
+ };
43
+
44
+ /**
45
+ * @rulecad/frames as a design gets it (v.frames): every export, with profileModel, slotModel, beamModel, beam, carrierModel
46
+ * and carrier reading the workspace's own rule sets (a profile measured with cad measure --profile, with its outline, or
47
+ * a slot measured by caliper on the slot coupon) before the kit's.
48
+ * @param {{ sets?: Record<string, object>, outlines?: Record<string, object> }} [context] framesContext()'s
49
+ * @returns {Record<string, any>}
50
+ */
51
+ export function designFrames(context = {}) {
52
+ const bound = { ...frames };
53
+ // (a name is looked up in given.sets before the kit's, with or without its profile- prefix)
54
+ bound.profileModel = (which, change = {}, given = {}) => frames.profileModel(which, change, givenFor(context, which, given));
55
+ bound.slotModel = (which, change = {}, given = {}) => frames.slotModel(which, change, { ...given, sets: { ...(context.sets || {}), ...(given.sets || {}) } });
56
+ bound.beamModel = (profile, o = {}) => frames.beamModel(typeof profile === 'string' ? bound.profileModel(profile, {}, o.given) : profile, { ...o, given: givenFor(context, profile, o.given) });
57
+ bound.beam = (m, o = {}) => frames.beam(m?.kind === 'beam' || m?.kind === 'profile' ? m : typeof m === 'string' ? bound.profileModel(m, {}, o.given) : m, o);
58
+ // (a printed carrier drawn from the workspace's slot, as measured by caliper on the slot coupon)
59
+ bound.carrierModel = (where, o = {}) => frames.carrierModel(where, { ...o, given: givenFor(context, where, o?.given) });
60
+ bound.carrier = (m, o = {}) => frames.carrier(m, m?.kind === 'slot-carrier' ? o : { ...o, given: givenFor(context, m, o?.given) });
61
+ return bound;
62
+ }
63
+
package/lib/jsonedit.mjs CHANGED
@@ -88,3 +88,22 @@ function insert(text, s, key, value) {
88
88
  const after = last.end;
89
89
  return multi ? `${text.slice(0, after)},${eol}${indent}${piece}${text.slice(after)}` : `${text.slice(0, after)}, ${piece}${text.slice(after)}`;
90
90
  }
91
+
92
+ /**
93
+ * Remove the value at a path: a key from its object, or an entry from its array, with the comma and the line it was on.
94
+ * @param {string} text @param {(string | number)[]} path @returns {string}
95
+ */
96
+ export function removeAt(text, path) {
97
+ const s = find(text, path);
98
+ if (!s || !path.length) throw Object.assign(new Error(`no ${path.join('.') || 'value'} to remove`), { code: 'edit.path' });
99
+ const parent = find(text, path.slice(0, -1)), all = spans(text);
100
+ const members = all.filter((x) => x.path.length === path.length && same(x.path.slice(0, -1), parent.path)).sort((a, b) => a.start - b.start);
101
+ const keyed = text[parent.start] === '{';
102
+ // where a member starts: at its key in an object (the last "key" before its value), else at its value
103
+ const startOf = (m) => (keyed ? text.lastIndexOf(JSON.stringify(m.path.at(-1)), m.start) : m.start);
104
+ const k = members.findIndex((m) => same(m.path, path));
105
+ if (members.length === 1) return `${text.slice(0, parent.start + 1)}${text.slice(parent.end - 1)}`; // the only one: {} or []
106
+ // not the first: from the end of the one before (its comma, the line break) to this one's end; the first: to the next one's start
107
+ if (k > 0) return text.slice(0, members[k - 1].end) + text.slice(s.end);
108
+ return text.slice(0, startOf(s)) + text.slice(startOf(members[1]));
109
+ }
package/lib/list.mjs CHANGED
@@ -1,7 +1,8 @@
1
1
  // What a machine takes to build, in numbers: the bought items by rule set with quantities, every screw, nut, washer and
2
2
  // insert (fasten.count: from the fasten relations, a motor's mounting screws, and fits that name a fastener), each by
3
- // thread, length and head with its mass and the packs it is bought in, wires by gauge, and the printed parts with
4
- // their grams and an estimate of the minutes.
3
+ // thread, length and head with its mass and the packs it is bought in, wires by gauge, the printed parts with their
4
+ // grams and an estimate of the minutes, and the beams' cut list (each mark, the bars to buy and the cuts on each:
5
+ // @rulecad/frames' cutList).
5
6
  import { placeItems, jointValues } from '@rulecad/model-link';
6
7
  import { screwModel } from '@rulecad/fixings';
7
8
  import { peekRuleSet as loadRuleSet } from './rules.mjs';
@@ -11,6 +12,8 @@ import { readJson } from './host.mjs';
11
12
  import path from 'node:path';
12
13
  import { volume } from './mesh.mjs';
13
14
  import { wiresFor } from './assembly.mjs';
15
+ import { cutListOf, cutListData } from './beams.mjs';
16
+ import { cutListText } from '@rulecad/frames';
14
17
 
15
18
  const n = (x, d = 1) => Number(x.toFixed(d));
16
19
 
@@ -33,11 +36,13 @@ export function printedParts(s) {
33
36
  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) }));
34
37
  }
35
38
 
36
- /** The whole list. @returns {{ bought: object[], fasteners: object[], wires: object[], printed: object[], totals: object }} */
39
+ /** The whole list. @returns {{ bought: object[], fasteners: object[], wires: object[], printed: object[], cut: object | null, totals: object }} */
37
40
  export function shoppingList(s) {
38
41
  const mat = materialOf(s.project), printed = printedParts(s), bought = new Map(), fasteners = new Map();
39
42
  for (const o of s.objects) if (o.bought && !o.unplaced) {
40
- 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: [] };
43
+ // (a beam by its profile and length: one line for each length cut, lib/beams.mjs)
44
+ const len = o.bought.length != null ? Number(o.bought.length.toFixed(2)) : null, key = `${o.bought.set}|${o.bought.variant ?? ''}|${len ?? ''}`;
45
+ const line = bought.get(key) ?? { set: o.bought.set, variant: o.bought.variant, part: o.bought.part, ...(len != null ? { length: len } : {}), qty: 0, grams: o.bought.mass != null ? o.bought.mass * 1000 : null, items: [] };
41
46
  line.qty++; line.items.push(o.id); bought.set(key, line);
42
47
  }
43
48
  // fasten.count: the hardware a fasten placed (a component's too), one part a piece; a motor's mounting screws; and a fit
@@ -45,8 +50,8 @@ export function shoppingList(s) {
45
50
  const add = (name, n, from, more = {}) => { const line = fasteners.get(name) ?? { fastener: name, qty: 0, from: [], ...more }; line.qty += n; if (!line.from.includes(from)) line.from.push(from); fasteners.set(name, line); };
46
51
  for (const p of s.parts) if (p.hardware) { const h = p.hardware; add(h.name, 1, h.from ?? h.name, { kind: h.kind, thread: h.thread ?? null, length: h.length ?? null, head: h.head ?? null, grams: h.grams ?? null }); }
47
52
  for (const m of motorScrews(s, { placeItems, jointValues })) {
48
- let grams = null; try { grams = screwModel(m.thread, { length: m.length, head: 'cap', anyLength: true }).mass; } catch {}
49
- add(`${m.thread}x${m.length} cap`, m.count, `${m.item} on ${m.other} (its mount, a fit that fastens)`, { kind: 'screw', thread: m.thread, length: m.length, head: 'cap', grams });
53
+ let grams = null; try { grams = screwModel(m.thread, { length: m.length, head: m.head, anyLength: true }).mass; } catch {}
54
+ add(m.name, m.count, `${m.item} on ${m.other} (its mount, a fit that fastens)`, { kind: 'screw', thread: m.thread, length: m.length, head: m.head, grams });
50
55
  }
51
56
  for (const x of s.fits) if (x.fastener && x.fasten == null) add(x.fastener, x.count != null ? x.num(x.count) : 1, x.note || `${x.a} / ${x.b}`);
52
57
  // Rounded up to whole packs (packs.pack), the spares said
@@ -55,16 +60,18 @@ export function shoppingList(s) {
55
60
  .sort((a, b) => (a.kind ? 0 : 1) - (b.kind ? 0 : 1) || ['screw', 'nut', 'washer', 'insert'].indexOf(a.kind) - ['screw', 'nut', 'washer', 'insert'].indexOf(b.kind) || String(a.thread).localeCompare(String(b.thread)) || (a.length ?? 0) - (b.length ?? 0) || a.fastener.localeCompare(b.fastener));
56
61
  const rows = s.wires?.length ? wiresFor(s) : [], wires = new Map();
57
62
  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); }
58
- 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));
63
+ 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) || (b.length ?? 0) - (a.length ?? 0));
59
64
  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);
65
+ const cut = cutListData(cutListOf(s));
60
66
  const fixingsGrams = fixings.reduce((t, f) => t + (f.mass ?? 0), 0);
61
- return { bought: boughtList, fasteners: fixings, wires: [...wires.values()], printed, totals: { printedGrams: n(printedGrams), boughtGrams: n(boughtGrams), fixingsGrams: n(fixingsGrams), machineGrams: n(printedGrams + boughtGrams + fixingsGrams), ...(pack && fixings.some((f) => f.packs) ? { pack } : {}), minutes: n(printed.reduce((t, p) => t + p.minutes, 0), 0), material: mat.name, ...(mat.assumed ? { densityAssumed: true } : {}), ...(unknown.length ? { noMassFor: unknown } : {}) } };
67
+ return { bought: boughtList, fasteners: fixings, wires: [...wires.values()], printed, cut, totals: { printedGrams: n(printedGrams), boughtGrams: n(boughtGrams), fixingsGrams: n(fixingsGrams), machineGrams: n(printedGrams + boughtGrams + fixingsGrams), ...(pack && fixings.some((f) => f.packs) ? { pack } : {}), minutes: n(printed.reduce((t, p) => t + p.minutes, 0), 0), material: mat.name, ...(mat.assumed ? { densityAssumed: true } : {}), ...(unknown.length ? { noMassFor: unknown } : {}) } };
62
68
  }
63
69
 
64
70
  export function listText(ref, l) {
65
71
  const out = [`${ref}: what it takes to build`];
66
72
  const row = (a) => out.push(a.join(' '));
67
- 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(', ')]); }
73
+ 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})` : ''}${b.length != null ? ` x ${b.length} mm` : ''}`, `a ${b.part}`, b.grams != null ? `${b.grams} g each` : 'mass not given', b.items.join(', ')]); }
74
+ if (l.cut) { out.push('', `Cut list (kerf ${l.cut.rules.kerf.value} mm, trim ${l.cut.rules.trim.value} mm; a sheet for each mark: cad beams ${ref})`, ...cutListText(l.cut)); }
68
75
  if (l.fasteners.length) {
69
76
  out.push('', 'Fasteners');
70
77
  for (const f of l.fasteners) row([` ${String(f.qty).padStart(3)} ×`, f.fastener, ...(f.mass != null ? [`${f.grams} g each, ${f.mass} g`] : []), ...(f.packs ? [`${f.packs} pack${f.packs > 1 ? 's' : ''} of ${l.totals.pack.size}, ${f.spare} spare`] : []), f.from.join('; ')]);
package/lib/measured.mjs CHANGED
@@ -2,14 +2,16 @@
2
2
  // the estimate was (in the workspace's copy of the rule set), or a measurement of something a check predicts (a figure
3
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
4
  // keeps a ledger of predicted against measured beside prints.jsonl. The rules the fixings coupon measures (a pilot or an
5
- // insert hole per thread, the nut fits, the thread gap and flank form) need no --rule: what each is comes from here.
5
+ // insert hole per thread, the nut fits, the thread gap and flank form) and the slot coupon's fits need no --rule: what
6
+ // each is comes from here; a slot's figures go in the workspace's copy of its set, checked as a slot.
6
7
  import fs from 'node:fs';
7
8
  import path from 'node:path';
8
9
  import { setAt } from './jsonedit.mjs';
9
10
  import { CadError } from './errors.mjs';
10
- import { paths, WS, RULE_DIRS } from './workspace.mjs';
11
+ import { paths, WS, RULE_DIRS, printerOf } from './workspace.mjs';
11
12
  import { loadRuleSet } from './rules.mjs';
12
13
  import { buildAssembly, checkAssembly, assemblyPath } from './assembly.mjs';
14
+ import { slotModel } from '@rulecad/frames';
13
15
  import { fixingsContext } from './design.mjs';
14
16
  import { fixingsFor, threads } from '@rulecad/fixings';
15
17
 
@@ -30,6 +32,21 @@ function ruleFile(name) {
30
32
  return { set, rule, data, file: path.join(WS, 'rules', `${set}.json`) };
31
33
  }
32
34
 
35
+ // The slot coupon (examples/bench/projects/benchmarks/MEASURE.md, rows 29 to 33): the two fits it measures, which a
36
+ // printer's set may not hold yet, each with what it is and what the kit drew before (the printer's fit), so the ledger
37
+ // shows predicted against measured; and a slot's own figures, measured by caliper on the person's beam
38
+ const SLOT_COUPON = 'the slot coupon (examples/bench/projects/benchmarks/MEASURE.md)';
39
+ function slotRule(project, set, key, data) {
40
+ if (set === printerOf(project) && ['slot_fit', 'printed_slot_fit'].includes(key)) {
41
+ const fit = data.rules?.fit, was = typeof fit?.value === 'number' ? fit.value : null;
42
+ return { unit: 'mm', predicted: was, was: `${set}.fit, ${fit?.kind ?? 'none'}`, source: SLOT_COUPON,
43
+ rule: key === 'slot_fit' ? `Clearance each side between a printed part and a bought beam's slot it slides in (a tongue in the opening, a carrier in the cavity): the tightest on ${SLOT_COUPON} that slid the beam's length by hand without rattling. Printed carriers are drawn with it (@rulecad/frames carrierModel) before the general fit`
44
+ : `Clearance each side a slot printed in a part is opened by, so a bought slot nut slides in it: the tightest printed slot on ${SLOT_COUPON} a slide-in nut ran the length of by hand without catching. For printed beams and plates with slots`, kind: 'measured' };
45
+ }
46
+ if (data.part === 'slot' && data.rules?.[key]) return { source: `calipers on your own beam (${SLOT_COUPON}, row 32)` };
47
+ return null;
48
+ }
49
+
33
50
  // The printer's rules the fixings read that a printer's set may not hold yet, each measured on the fixings coupon
34
51
  // (examples/bench/projects/benchmarks/MEASURE.md): what it is, its unit, and what the kit drew before it was measured,
35
52
  // so the ledger shows predicted against measured. A pilot or an insert hole is per thread, and may name a plastic
@@ -76,7 +93,7 @@ export async function recordMeasured(ref, values, { unit, source, rule, date = t
76
93
  if (!project || !name || !fs.existsSync(assemblyPath(ref))) throw new CadError('measured.assembly', `no assembly "${ref}": give <project>/<assembly>, the one whose predictions it moves`);
77
94
  if (!Object.keys(values).length) throw new CadError('measured.usage', 'usage: cad measured <project>/<assembly> <name>=<value> … [--unit mm] [--source "how it was measured"]');
78
95
  const before = await findingsOf(ref), entries = [], predictions = predictionsOf(before);
79
- const writes = []; // (every value is checked before any is written, so a refusal leaves the rule set as it was)
96
+ const writes = [], slots = new Map(); // (every value is checked before any is written, so a refusal leaves the rule sets as they were)
80
97
  for (const [k, value] of Object.entries(values)) {
81
98
  if (!Number.isFinite(value)) throw new CadError('measured.value', `${k}: a measurement is a number (got ${value})`);
82
99
  const named = predictions.filter((x) => x.code === k || x.predict.name === k);
@@ -86,15 +103,18 @@ export async function recordMeasured(ref, values, { unit, source, rule, date = t
86
103
  continue;
87
104
  }
88
105
  const { set, rule: key, data, file } = ruleFile(k);
89
- const old = data.rules?.[key], known = fixingsRule(project, set, key) ?? (old ? null : kitRule(set, key));
106
+ const old = data.rules?.[key], known = slotRule(project, set, key, data) ?? fixingsRule(project, set, key) ?? (old ? null : kitRule(set, key));
90
107
  if (known?.allowed && !known.allowed.includes(value)) throw new CadError('measured.value', `${k} is ${known.allowed.join(' or ')}: the flank forms the coupon prints (got ${value})`);
91
108
  if (!old && !rule && !known) 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'})`);
92
109
  const had = old ?? known, prior = typeof had?.value === 'number' ? had.value : known?.predicted ?? null;
93
110
  if (unit && had?.unit && unit !== had.unit) throw new CadError('measured.unit', `${k} is in ${had.unit}, and this is in ${unit}: give it in ${had.unit}`);
94
111
  const entry = { value, unit: unit ?? had?.unit ?? '', rule: rule ?? had.rule, kind: 'measured', source: source || known?.source || 'measured on the bench', checked: date };
112
+ if (data.part === 'slot') slots.set(set, { data, change: { ...slots.get(set)?.change, [key]: value } });
95
113
  writes.push([file, key, entry]);
96
114
  entries.push({ date, assembly: name, name: k, figure: entry.rule, unit: entry.unit, predicted: prior, was: old ? old.kind : known?.was ?? known?.kind ?? null, measured: value, ratio: prior ? value / prior : null, ...(source ? { source } : {}) });
97
115
  }
116
+ // a slot's figures together still make a slot (an opening narrower than its cavity, lips thinner than it is deep)
117
+ for (const [set, { data, change }] of slots) { try { slotModel(data, change); } catch (e) { throw new CadError('measured.value', `${set}: ${e.message.replace(/^slotModel: /, '')}`); } }
98
118
  for (const [file, key, entry] of writes) fs.writeFileSync(file, setAt(fs.readFileSync(file, 'utf8'), ['rules', key], entry));
99
119
  const after = await findingsOf(ref), was = new Map(before.map((x) => [keyOf(x), x])), moved = [];
100
120
  for (const x of after) {
package/lib/motors.mjs CHANGED
@@ -246,12 +246,24 @@ function mountPlate(s, d, W) {
246
246
  return { fit, other, parts, inv, t, plate, hd };
247
247
  }
248
248
 
249
+ // The screws a motor is held by on a plate this thick: mountModel's (from @rulecad/fixings), at a length sold, the
250
+ // longest that does not take them past mountModel's length into the motor's own thread, or through plain holes the
251
+ // shortest that reaches; or the length the motor item names ("screw": "M3x8 cap"). Where the wall at the holes (t) is
252
+ // thinner than the plate round them, the heads are sunk in counterbores (mount()'s, as deep as the head is high), and
253
+ // the screws are chosen for the plate under them
254
+ function screwsFor(d, plate, t = plate) {
255
+ const here = mountModel(d.model, { plate, ...(t < plate - 0.5 ? { counterbore: true } : {}), ...(d.spec.screw ? { screw: d.spec.screw } : {}) }), fx = here.screw.model, L = here.screwLength, sold = fx.figures.lengths?.value;
256
+ const length = fx.length ?? (!Array.isArray(sold) || !sold.length ? L : d.model.mount.thread ? [...sold].reverse().find((l) => l <= L) ?? sold[0] : sold.find((l) => l >= L) ?? sold.at(-1));
257
+ return { here, fx, length, wanted: L, name: `${fx.thread}x${length} ${fx.head.form}` };
258
+ }
259
+
249
260
  /**
250
261
  * The screws that hold each motor to the part it is fastened to by a fit with "fastens" (a motor named in a "fasten"
251
- * has its screws counted there): as many as its mounting holes, the length mountModel works out for the plate as drawn,
252
- * taken to a length sold (the longest that does not pass it into the motor's own thread; through plain holes, the shortest that reaches).
262
+ * has its screws counted there): as many as its mounting holes, @rulecad/fixings' screw on the thread mountModel takes,
263
+ * at the length mountModel works out for the plate as drawn taken to a length sold (the longest that does not pass it
264
+ * into the motor's own thread; through plain holes, the shortest that reaches), or the length the motor item names.
253
265
  * @param {object} s a built assembly @param {{ placeItems: Function, jointValues: Function }} helpers
254
- * @returns {{ item: string, other: string, thread: string, length: number, wanted: number, count: number }[]}
266
+ * @returns {{ item: string, other: string, fit: object, thread: string, head: string, name: string, key: number | null, length: number, wanted: number, count: number }[]}
255
267
  */
256
268
  export function motorScrews(s, { placeItems, jointValues }) {
257
269
  const drives = s.motion?.drives || [], top = (n) => String(n).split(/[.@]/)[0];
@@ -261,11 +273,9 @@ export function motorScrews(s, { placeItems, jointValues }) {
261
273
  for (const d of drives) {
262
274
  if (named.has(d.id)) continue;
263
275
  const p = mountPlate(s, d, worlds[d.item]); if (!p || p.t === Infinity) continue;
264
- const here = mountModel(d.model, { plate: +p.plate.toFixed(2), ...(d.spec.screw ? { screw: d.spec.screw } : {}) }), thread = here.screw?.thread, L = here.screwLength;
265
- if (!thread || !(L > 0)) continue;
266
- let sold = null; try { sold = peekRuleSet(thread.toLowerCase().replace('.', '_')).rules.lengths?.value ?? null; } catch {}
267
- const length = !sold ? L : d.model.mount.thread ? [...sold].reverse().find((l) => l <= L) ?? sold[0] : sold.find((l) => l >= L) ?? sold.at(-1);
268
- out.push({ item: d.id, other: p.other, thread, length, wanted: L, count: d.model.mount.holes.length });
276
+ const { fx, length, wanted, name } = screwsFor(d, +p.plate.toFixed(2), +p.t.toFixed(2));
277
+ if (!(wanted > 0)) continue;
278
+ out.push({ item: d.id, other: p.other, fit: p.fit, thread: fx.thread, head: fx.head.form, name, key: fx.head.key ?? null, length, wanted, count: d.model.mount.holes.length });
269
279
  }
270
280
  return out;
271
281
  }
@@ -275,8 +285,9 @@ function mountCheck(s, d, f, W, avail, materialName, frame) {
275
285
  if (!at) return;
276
286
  const { other, parts, inv, t, plate, hd } = at;
277
287
  if (t === Infinity) return f('warn', `${d.id}: couldn't find the plate at its screw holes in ${other}`, `${d.id}: mount not found`, { code: 'motor.mount' });
278
- const here = mountModel(m, { plate: +plate.toFixed(2), ...(d.spec.screw ? { screw: d.spec.screw } : {}) }), mat = material(materialName) || material('pla'), each = Math.max(...screwGroup(m.mount.holes, { moment: [0, 0, avail] }).screws.map((x) => x.shear)), bearing = each / (hd * t), margin = mat.strength / bearing;
279
- for (const x of here.findings) f(x.level, `${d.id} on ${other}: ${x.text}`, x.level === 'pass' ? null : `${d.id}: ${x.code.split('.')[1]}`, { code: 'motor.mount' });
288
+ // the screws as bought (screwsFor), so the engagement mountModel checks is the bought screw's
289
+ const sunk = t < plate - 0.5, here = mountModel(m, { plate: +plate.toFixed(2), ...(sunk ? { counterbore: true } : {}), screw: screwsFor(d, +plate.toFixed(2), +t.toFixed(2)).name }), mat = material(materialName) || material('pla'), each = Math.max(...screwGroup(m.mount.holes, { moment: [0, 0, avail] }).screws.map((x) => x.shear)), bearing = each / (hd * t), margin = mat.strength / bearing;
290
+ for (const x of here.findings) f(x.level, `${d.id} on ${other}: ${x.text}`, x.level === 'pass' ? null : `${d.id}: ${x.code.split('.')[1]}`, { code: 'motor.mount', ...(x.values ? { values: x.values } : {}), ...(x.refs ? { refs: { item: d.id, ...x.refs } } : {}) });
280
291
  f(margin < 2 ? 'fail' : 'pass', `${d.id} on ${other}: ${n3(plate, 2)} mm of plate at the screws, each taking ${n3(each, 1)} N against the torque (bearing ${n3(bearing, 1)} MPa, ${n3(margin, 0)} times under ${mat.name.toUpperCase()}'s ${mat.strength} MPa)`, margin < 2 ? `${d.id}: screws pull through` : null, { code: 'motor.mount', values: { plate, bearing, margin } });
281
292
  mountBends(s, d, f, W, avail, mat, { other, parts, inv, plate, hd, ...frame });
282
293
  }
package/lib/order.mjs CHANGED
@@ -11,6 +11,7 @@ import fs from 'node:fs';
11
11
  import { placeItems, jointValues, mul } from '@rulecad/model-link';
12
12
  import { host } from './host.mjs';
13
13
  import { paths } from './workspace.mjs';
14
+ import { motorScrews } from './motors.mjs';
14
15
 
15
16
  const top = (n) => String(n).split(/[.@]/)[0];
16
17
  const round = (v) => v.map((x) => (Math.abs(x) < 1e-9 ? 0 : +x.toFixed(6)));
@@ -120,7 +121,7 @@ export function assemblyOrder(s) {
120
121
  const worlds = placeItems(s.motion, s.jointValues), marks = s.motion.marks, reaches = (u, v, seen = new Set()) => { if (u === v) return true; if (seen.has(u)) return false; seen.add(u); return [...before.get(u).keys()].some((w) => reaches(w, v, seen)); };
121
122
  const R = 1.5, bad = [];
122
123
  for (const x of s.fits.filter((f) => f.access)) {
123
- const [id, name] = String(x.access).split('.'), m = marks.find((k) => k.id === id && k.name === name);
124
+ const [id, name] = String(x.access).split('.'), m = marks.find((k) => k.id === id && k.name === name) ?? (s.items.find((i) => i.id === id)?.beam ? s.motion.address(String(x.access), 'access') : null); // (a beam's address: x1.top@120)
124
125
  if (!m) throw new Error(`fit ${x.note || `${x.a} / ${x.b}`}: access: no anchor "${x.access}" (give <item>.<anchor>${items.includes(id) ? `; ${id} has ${marks.filter((k) => k.id === id).map((k) => k.name).join(', ') || 'none'}` : ''})`);
125
126
  const W = mul(worlds[m.item], m.frame), O = [W[3], W[7], W[11]], D = [W[2], W[6], W[10]], [u, v] = basis(D), starts = [[0, 0], [R, 0], [-R, 0], [0, R], [0, -R]].map(([a, b]) => O.map((c, k) => c + a * u[k] + b * v[k]));
126
127
  const screwed = [top(x.a), top(x.b)].filter((t) => by.has(t)), later = [...screwed].sort(earlier).at(-1);
@@ -197,11 +198,13 @@ export function assemblyOrder(s) {
197
198
  const seq = [], lay = (off) => { for (const x of [...off].reverse()) { if (x.group) { lay(x.sub.off); seq.push({ group: x.group, d: x.d }); } else seq.push(x); } };
198
199
  lay(apart.off);
199
200
  const at = new Map(), steps = [];
201
+ // a motor's mounting screws, on the fit that fastens it (motorScrews): counted, with the key that turns them
202
+ const motorFits = new Map(motorScrews(s, { placeItems, jointValues }).map((m) => [m.fit, { fastener: m.name, count: m.count, ...(m.key != null ? { key: `${+m.key.toFixed(3)} mm hex key` } : {}) }]));
200
203
  seq.forEach((x, i) => { for (const g of x.group ?? [x.p]) at.set(g.id, i); });
201
204
  for (const [i, x] of seq.entries()) {
202
205
  if (x.group) { steps.push({ items: x.group.map((g) => g.id), object: null, dir: round(x.d), fasteners: [], together: true }); continue; }
203
206
  const { p, d } = x, list = [...new Set(s.fits.filter((f) => [...names(f.a), ...names(f.b)].includes(p.id) && (f.fastens || f.seat != null || f.fastener) && [...names(f.a), ...names(f.b)].every((n) => (at.get(n) ?? 0) <= i)))];
204
- steps.push({ items: [p.id], object: p.object, dir: round(d), fasteners: list.map((f) => ({ fit: f.note || f.label || `${f.a} to ${f.b}`, ...(f.fastener ? { fastener: f.fastener } : {}), ...(f.count != null ? { count: f.num(f.count) } : {}), ...(f.key ? { key: f.key } : {}), ...(f.tighten ? { tighten: f.tighten } : {}) })) });
207
+ steps.push({ items: [p.id], object: p.object, dir: round(d), fasteners: list.map((f) => ({ fit: f.note || f.label || `${f.a} to ${f.b}`, ...(f.fastener ? { fastener: f.fastener } : {}), ...(f.count != null ? { count: f.num(f.count) } : {}), ...(f.key ? { key: f.key } : {}), ...(f.tighten ? { tighten: f.tighten } : {}), ...(!f.fastener ? motorFits.get(f) : {}) })) });
205
208
  }
206
209
  // Copies of one thing fitted the same way, one after another, are one step
207
210
  const merged = [];