@rulecad/cad 0.7.57 → 0.7.59

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/links.mjs CHANGED
@@ -9,6 +9,8 @@ import { pcbEngine } from './design.mjs';
9
9
  import { shapes, motionData, checkAssembly, wireRoutesOf } from './assembly.mjs';
10
10
  import { slotOf } from './threemf.mjs';
11
11
  import { taskData, stepsData, buildData, ledgerRows } from './buildpage.mjs';
12
+ import { beamSheet } from '@rulecad/frames';
13
+ import { cutListOf } from './beams.mjs';
12
14
 
13
15
  /** The project's filaments: { base: { slot: 1, … }, legend: { slot: 2, … } } in project.json. @param {string} project */
14
16
  export const filaments = (project) => readJson(path.join(paths.project(project), 'project.json')).filaments || {};
@@ -57,11 +59,11 @@ export async function objectModel(b, { title, version, src, set, filaments: fil
57
59
  // Each board's fab zip (cad export's: Gerbers, drill files, BOM, placement), for the page to offer as a download. A
58
60
  // board whose files can't be made here (one that needs KiCad, without it) goes without, and says why
59
61
  async function fabOf(boards) {
60
- const pcb = await pcbEngine(), { zip } = await import('@rulecad/model-link'), fab = [];
62
+ const pcb = await pcbEngine(), { zip, fabName } = await import('@rulecad/model-link'), fab = [];
61
63
  for (const [name, version, b] of boards) {
62
64
  try {
63
65
  const files = await pcb.fabFiles(b.circuit, name, { source: b.source });
64
- fab.push({ name: `${name}${version ? `@${version}` : ''}-fab.zip`.replace(/[^\w@.+-]/g, '-'), zip: Buffer.from(await zip(Object.entries(files))).toString('base64') });
66
+ fab.push({ name: fabName(`${name}${version ? `@${version}` : ''}-fab`), zip: Buffer.from(await zip(Object.entries(files))).toString('base64') });
65
67
  } catch (e) { console.error(` ${name}: no fab zip in the link (${String(e.message || e).split('\n')[0]})`); }
66
68
  }
67
69
  return fab.length ? { fab } : {};
@@ -69,7 +71,10 @@ async function fabOf(boards) {
69
71
 
70
72
  /** A built assembly as a model: each shape once and placed (nine keys cost one keycap), its boards' views, its joints. */
71
73
  export async function assemblyModel(s, { title, versions, filaments: fil = {}, noRules = false, steps }) {
72
- const placed = shapes(s.parts), list = placed.shapes.length ? placed.place.map(([i, ...m], n) => { const p = placed.shapes[i].part; return { shape: i, role: p.role, label: p.object || p.label, slot: slotOf(fil, p.filament), triangles: triangles(placed.shapes[i].triangles), matrix: m, name: s.parts[n].name }; }) : [];
74
+ // a beam is labelled by its mark (beams that are the same share one, as the cut list and the sheets name them), so the
75
+ // parts list groups them and a beam picked shows its mark
76
+ const marks = new Map(s.objects.filter((o) => o.mark).map((o) => [o.id, o.mark])), labelOf = (q, p) => (marks.has(q.item) ? `mark ${marks.get(q.item)}: ${String(q.label).replace(/^[^:]*: mark \w+, /, '')}` : p.object || p.label);
77
+ const placed = shapes(s.parts), list = placed.shapes.length ? placed.place.map(([i, ...m], n) => { const p = placed.shapes[i].part; return { shape: i, role: p.role, label: labelOf(s.parts[n], p), slot: slotOf(fil, p.filament), triangles: triangles(placed.shapes[i].triangles), matrix: m, name: s.parts[n].name }; }) : [];
73
78
  // A pose that sets items' variables draws some parts differently (a flexure bent): each such part's shape in that
74
79
  // pose goes in the link as a "pose" part, placed as the part is, to be swapped in when the page shows the pose
75
80
  const alts = [];
@@ -84,6 +89,7 @@ export async function assemblyModel(s, { title, versions, filaments: fil = {}, n
84
89
  }
85
90
  const model = {
86
91
  title, version: versions, src: `${s.project}/${s.name}`, // object versions are in version: the file name stays short
92
+ ...(s.a?.show === 'built' ? { show: 'built' } : {}), // its references drawn solid on the page
87
93
  rules: [],
88
94
  ...sheet([...new Map(s.objects.filter((o) => o.built?.entries).map((o) => [o.objName, o.built.entries])).entries()], { noRules }),
89
95
  // Its boards' 2D views (copper, schematic), so one link holds the whole build: tabs over the 3D model
@@ -96,6 +102,9 @@ export async function assemblyModel(s, { title, versions, filaments: fil = {}, n
96
102
  })()),
97
103
  ...fromShapes(list),
98
104
  };
105
+ // each mark's cut-and-drill sheet, as a 2D view (Beams: A, B ..): a beam picked in the model opens its own
106
+ const cut = marks.size ? cutListOf(s) : null;
107
+ if (cut) model.views = [...(model.views ?? []), ...cut.marks.map((m) => [`Beams: ${m.mark}`, beamSheet(m.beam, { mark: m.mark, items: m.items, grams: m.grams }).svg])];
99
108
  Object.assign(model, motionData(s));
100
109
  if (alts.length) { // the shapes parts take in other poses, on the same items, and which pose shows which
101
110
  model.motion.part.push(...alts.map((x) => model.motion.part[x.of]));
package/lib/list.mjs CHANGED
@@ -12,6 +12,7 @@ import { readJson } from './host.mjs';
12
12
  import path from 'node:path';
13
13
  import { volume } from './mesh.mjs';
14
14
  import { wiresFor } from './assembly.mjs';
15
+ import { companions } from './fittings.mjs';
15
16
  import { cutListOf, cutListData } from './beams.mjs';
16
17
  import { cutListText, printedCost } from '@rulecad/frames';
17
18
 
@@ -30,9 +31,12 @@ export function printedParts(s) {
30
31
  const by = new Map();
31
32
  for (const p of s.parts) {
32
33
  if (p.role !== 'part' && p.role != null) continue;
33
- const key = p.leaf ?? p.item, mm3 = volume(p.triangles), o = by.get(key) ?? { id: key, object: p.object ?? null, volume: 0 };
34
+ // (a printed beam's part is drawn solid and printed with walls and infill: its fill is the share of plastic laid)
35
+ const key = p.leaf ?? p.item, mm3 = volume(p.triangles) * (p.fill ?? 1), o = by.get(key) ?? { id: key, object: p.object ?? null, volume: 0 };
34
36
  o.volume += mm3; by.set(key, o);
35
37
  }
38
+ // and what comes with a placed part, printed beside it (a levelling foot's pad), by its model's grams
39
+ for (const c of companions(s)) if (c.grams > 0) by.set(c.id, { id: c.id, object: null, volume: (c.grams / mat.density) * 1000, with: c.of });
36
40
  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) }));
37
41
  }
38
42
 
@@ -87,7 +91,7 @@ export function listText(ref, l) {
87
91
  if (l.totals.pack) out.push(` (packs of ${l.totals.pack.size}: ${l.totals.pack.rule}, ${/^[aeiou]/.test(l.totals.pack.kind) ? 'an' : 'a'} ${l.totals.pack.kind}; masses are estimates from each piece's outline)`);
88
92
  }
89
93
  if (l.wires.length) { out.push('', 'Wire'); for (const w of l.wires) row([` ${w.length} mm of`, w.gauge ?? 'gauge not given', `in ${w.runs.join(', ')}`]); }
90
- if (l.printed.length) { out.push('', `Printed (${l.totals.material})`); for (const p of l.printed) row([` ${String(p.grams).padStart(7)} g`, `about ${p.minutes} min`, `${p.id}${p.object && p.object !== p.id ? ` (${p.object})` : ''}`]); }
94
+ if (l.printed.length) { out.push('', `Printed (${l.totals.material})`); for (const p of l.printed) row([` ${String(p.grams).padStart(7)} g`, `about ${p.minutes} min`, `${p.id}${p.object && p.object !== p.id ? ` (${p.object})` : ''}${p.with ? ` (comes with ${p.with}: printed beside it, screwed into it by hand)` : ''}`]); }
91
95
  out.push('', `Total: ${l.totals.printedGrams} g printed, about ${l.totals.minutes} min of printing (an estimate from volume and the printer's flow), ${l.totals.fixingsGrams ? `${l.totals.fixingsGrams} g of fixings, ` : ''}${l.totals.machineGrams} g as a machine${l.totals.noMassFor ? ` (no mass given for ${l.totals.noMassFor.join(', ')})` : ''}`);
92
96
  if (l.cost) {
93
97
  const c = l.cost, parts = [];
package/lib/loads.mjs CHANGED
@@ -162,14 +162,15 @@ export function deflectionChecks(s, f, helpers, masses, payload) {
162
162
  if (!m) return;
163
163
  const O = axisOf(motion, W, j, mul).O, nextJ = links[i + 1], end = nextJ ? axisOf(motion, W, nextJ, mul).O : tool, Wc = W[j.child];
164
164
  const local = parts.flatMap((p) => { const Wp = W[ids.indexOf(p.item)]; return p.localTriangles && Wp ? p.localTriangles.map((t) => t.map((q) => invAt(Wc, rowsAt(Wp, q)))) : p.triangles.map((t) => t.map((q) => invAt(Wc, q))); }), Lo = invAt(Wc, O), Le = invAt(Wc, end), F = [dir[0] * Wc[0] + dir[1] * Wc[4] + dir[2] * Wc[8], dir[0] * Wc[1] + dir[1] * Wc[5] + dir[2] * Wc[9], dir[0] * Wc[2] + dir[1] * Wc[6] + dir[2] * Wc[10]].map((q) => q * m * G);
165
- const e = extent(local), box = [0, 1, 2].map((k) => e.hi[k] - e.lo[k]), sup = s.a.joints?.find((x) => x.id === j.id)?.support, cell = sup?.cell != null ? s.num(sup.cell) : Math.max(1, Math.min(4, Math.min(...box) / 3)), fe = linkFE(local, Lo, Le, F, E, nu, cell), L = norm(sub(Lo, Le)) || 1, beyondLength = norm(sub(tool, end)), drop = fe.deflection + (1.5 * fe.deflection * beyondLength) / L;
165
+ // the link's own cell: a clip's "cell" (a 2 mm clip at 0.5 mm) on a 170 mm link was 130 000 cells, 3 GB and ten minutes
166
+ const e = extent(local), box = [0, 1, 2].map((k) => e.hi[k] - e.lo[k]), sup = s.a.joints?.find((x) => x.id === j.id)?.support, cell = sup?.linkCell != null ? s.num(sup.linkCell) : Math.max(1, Math.min(4, Math.min(...box) / 3)), fe = linkFE(local, Lo, Le, F, E, nu, cell), L = norm(sub(Lo, Le)) || 1, beyondLength = norm(sub(tool, end)), drop = fe.deflection + (1.5 * fe.deflection * beyondLength) / L;
166
167
  total += drop; carried = Math.max(carried, m); rows.push({ link: ids[j.child], deflection: fe.deflection, at_tool: drop, cell: fe.cell, stress: fe.stress });
167
168
  });
168
169
  return { label, total, carried, rows };
169
170
  };
170
171
  const stretch = at(far, 'at full stretch'), folded = at(near, 'folded'), worst = stretch.total >= folded.total ? stretch : folded;
171
172
  if (!worst.rows.length) return 0;
172
- f('info', `the tool drops ${n3(worst.total, 3)} mm ${worst.label}: ${worst.rows.map((x) => `${x.link} ${n3(x.at_tool, 3)} mm`).join(', ')} (FE from the parts as drawn, cells ${worst.rows.map((x) => n3(x.cell, 1)).join(', ')} mm: a person can refine with "cell" on the joint's support)`, null, { code: 'link.deflection', predict: { name: 'link.deflection', figure: `drop at ${s.task.tool}`, value: worst.total, unit: 'mm' }, values: { total: worst.total, rows: worst.rows, label: worst.label } });
173
+ f('info', `the tool drops ${n3(worst.total, 3)} mm ${worst.label}: ${worst.rows.map((x) => `${x.link} ${n3(x.at_tool, 3)} mm`).join(', ')} (FE from the parts as drawn, cells ${worst.rows.map((x) => n3(x.cell, 1)).join(', ')} mm: a person can refine with "linkCell" on the joint's support)`, null, { code: 'link.deflection', predict: { name: 'link.deflection', figure: `drop at ${s.task.tool}`, value: worst.total, unit: 'mm' }, values: { total: worst.total, rows: worst.rows, label: worst.label } });
173
174
  const finds = [stretch, folded].filter((x) => x.rows.length).map((x) => { const k = (x.carried * G) / (x.total || 1e-9), Hz = Math.sqrt((k * 1000) / x.carried) / (2 * Math.PI); return { ...x, Hz }; }), low = finds.reduce((a, b) => (b.Hz < a.Hz ? b : a));
174
175
  const rings = s.task.speed != null ? ` Expect visible ringing past about ${n3(Math.max(20, low.Hz * 3), 0)} mm/s.` : '';
175
176
  f('info', `the lowest mode is about ${n3(low.Hz, 0)} Hz ${low.label}, from the tool's stiffness and the mass it carries.${rings}`, null, { code: 'assembly.frequency', values: { Hz: low.Hz, label: low.label } });
package/lib/measured.mjs CHANGED
@@ -6,7 +6,9 @@
6
6
  // along its slot need no --rule: what each is comes from here; a slot's figures go in the workspace's copy of its set,
7
7
  // checked as a slot. A drop measured on the joint rig (join.drop's <beam>.drop) also writes the join's spring, worked
8
8
  // out from it, to the rule the spring came from: the joins set (the workspace's copy, started from @rulecad/frames'
9
- // estimates), a bought fitting's set, or a printed fitting's share of its finite-element figure.
9
+ // estimates), a bought fitting's set, or a printed fitting's share of its finite-element figure. The beam coupon's sag
10
+ // and the mass it broke at (beam.coupon's <beam>.sag and <beam>.break) write the modulus and strength a printed beam has
11
+ // to its plastic's set (beam_modulus, beam_strength; _z standing up).
10
12
  import fs from 'node:fs';
11
13
  import path from 'node:path';
12
14
  import { setAt } from './jsonedit.mjs';
@@ -17,6 +19,7 @@ import { buildAssembly, checkAssembly, assemblyPath } from './assembly.mjs';
17
19
  import { slotModel, JOIN_SET, joinRuleSet } from '@rulecad/frames';
18
20
  import { fixingsContext } from './design.mjs';
19
21
  import { fixingsFor, threads } from '@rulecad/fixings';
22
+ import { couponFigure } from './frameprint.mjs';
20
23
 
21
24
  const today = () => new Date().toISOString().slice(0, 10), n = (x) => String(Number(Number(x).toFixed(4)));
22
25
  export const ledgerFile = (project) => path.join(paths.project(project), 'ledger.jsonl');
@@ -76,6 +79,19 @@ function rigRule(set, key, data) {
76
79
  return null;
77
80
  }
78
81
 
82
+ // The beam coupon (examples/bench/projects/benchmarks/MEASURE.md, rows 38 and 39): the modulus a printed beam bends at
83
+ // and the stress it breaks at, which no plastic's data sheet gives for a beam of walls and infill, so a plastic's set has
84
+ // no rule for them until the coupon is measured
85
+ const BEAM_COUPON = 'the beam coupon (examples/bench/projects/benchmarks/MEASURE.md)';
86
+ function couponRule(set, key, data) {
87
+ const m = key.match(/^beam_(modulus|strength)(_z)?$/);
88
+ if (!m || data.rules?.density == null) return null;
89
+ const how = m[2] ? 'printed standing up, bent across its layers' : 'printed lying down, its layers along it';
90
+ return { unit: 'MPa', source: BEAM_COUPON, predicted: data.rules?.[m[2] && data.rules[`${m[1]}_z`] ? `${m[1]}_z` : m[1]]?.value ?? null, was: `${set}.${m[1]}${m[2] && data.rules[`${m[1]}_z`] ? '_z' : ''}, the data sheet's`,
91
+ measuredRule: m[1] === 'modulus' ? `The modulus a printed beam of ${set.toUpperCase()} bends at, ${how}, with its section counted from its walls and infill (@rulecad/frames printedSection): the sag of ${BEAM_COUPON} under a hung mass, measured with a dial, and the solve's sag scaled to it. A printed beam takes it before the plastic's own modulus`
92
+ : `The stress a printed beam of ${set.toUpperCase()} breaks at in bending, ${how}, its section counted from its walls and infill: the mass ${BEAM_COUPON} broke at, as the stress the solve gives under it. A printed beam takes it before the plastic's own strength, and its creep limit follows it` };
93
+ }
94
+
79
95
  // The printer's rules the fixings read that a printer's set may not hold yet, each measured on the fixings coupon
80
96
  // (examples/bench/projects/benchmarks/MEASURE.md): what it is, its unit, and what the kit drew before it was measured,
81
97
  // so the ledger shows predicted against measured. A pilot or an insert hole is per thread, and may name a plastic
@@ -126,7 +142,7 @@ export async function recordMeasured(ref, values, { unit, source, rule, date = t
126
142
  // a rule's new value, checked before anything is written (a refusal leaves the rule sets as they were)
127
143
  const writeRule = (k, value, { from = null, unit: u = unit } = {}) => {
128
144
  const { set, rule: key, data, file, text, copied } = ruleFile(k);
129
- const old = data.rules?.[key], known = slotRule(project, set, key, data) ?? rigRule(set, key, data) ?? fixingsRule(project, set, key) ?? (old ? null : kitRule(set, key));
145
+ const old = data.rules?.[key], known = slotRule(project, set, key, data) ?? rigRule(set, key, data) ?? couponRule(set, key, data) ?? fixingsRule(project, set, key) ?? (old ? null : kitRule(set, key));
130
146
  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})`);
131
147
  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'})`);
132
148
  const had = old ?? known, prior = typeof had?.value === 'number' ? had.value : known?.predicted ?? null;
@@ -150,6 +166,12 @@ export async function recordMeasured(ref, values, { unit, source, rule, date = t
150
166
  const spring = (r.force * r.arm * r.arm) / (value - r.beam), figure = Number((spring * r.per).toPrecision(4));
151
167
  writeRule(r.rule, figure, { unit: r.unit, from: `${n(value)} mm drop of ${k.replace(/\.drop$/, '')} under ${n(r.force)} N at ${n(r.arm)} mm (${r.join}), less the beam's own ${n(r.beam)} mm, is a spring of ${(spring / 1e6).toFixed(3)} N·m/mrad` });
152
168
  }
169
+ // the beam coupon: the modulus from its sag, the strength from the mass it broke at
170
+ if (p.coupon) {
171
+ const c = p.coupon, figure = couponFigure(c, p.value, value);
172
+ if (!(value > 0)) throw new CadError('measured.value', `${k}: a ${c.kind === 'modulus' ? 'sag' : 'mass'} is above 0 (got ${value})`);
173
+ writeRule(c.rule, figure, { unit: c.unit, from: c.kind === 'modulus' ? `${n(value)} mm sag of ${k.replace(/\.sag$/, '')} under ${c.what}, against ${n(p.value)} mm at ${n(c.base)} MPa` : `broke at ${n(value)} kg ${c.what}, ${n(c.perKg)} MPa a kilogram on its own weight's ${n(c.self)} MPa` });
174
+ }
153
175
  continue;
154
176
  }
155
177
  writeRule(k, value);
package/lib/optimise.mjs CHANGED
@@ -105,15 +105,30 @@ function holdEmpty(spec) {
105
105
  for (let m = 0; m < g.nodes; m++) if (!on[m]) for (let a = 0; a < dim; a++) spec.fixed[dim * m + a] = 1;
106
106
  return spec;
107
107
  }
108
+ const digest = (x) => crypto.createHash('sha256').update(JSON.stringify(x)).digest('hex');
109
+ /**
110
+ * The code an optimisation's densities are made by, each piece by name: this file's VERSION, topopt's solver (its file
111
+ * up to its shapes from results), the FE's code and its threads backend (the solver's products), and cad's own code
112
+ * that readies the problem for the solver (holdEmpty). Drawing a shape from the densities is not in it.
113
+ * @returns {{ version: number, solver: string, fea: string, threads: string, cad: string }}
114
+ */
115
+ export const densityCode = () => ({ version: VERSION, solver: source('@rulecad/topopt').split('// ---------- shapes from results ----------')[0], fea: source('@rulecad/fea'), threads: source('@rulecad/fea/threads'), cad: `${holdEmpty.toString()}\n${optimised.toString()}` });
116
+ /**
117
+ * The key an optimisation's densities are kept by (.cache/densities/<key>.json): the problem and every piece of
118
+ * densityCode (cad's own share is holdEmpty and optimised, which readies the problem and calls the solver with its
119
+ * settings), so a change to any of them optimises again, in this checkout or in another commit's copy that shares
120
+ * the folder (scripts/dimension-diff.mjs).
121
+ * @param {object} problem readProblem's problem @param {ReturnType<typeof densityCode>} [code] @returns {string}
122
+ */
123
+ export const densitiesKey = (problem, code = densityCode()) => digest([code.version, problem, code.solver, code.fea, code.threads, code.cad]);
108
124
  export async function optimised(project, ref, { onStep, onRun, fresh = false } = {}) {
109
- const r = await readProblem(project, ref), topopt = source('@rulecad/topopt'), [solver] = topopt.split('// ---------- shapes from results ----------');
110
- const digest = (x) => crypto.createHash('sha256').update(JSON.stringify(x)).digest('hex');
125
+ const r = await readProblem(project, ref), topopt = source('@rulecad/topopt');
111
126
  // Two keeps: the densities, by the problem and the code that decides them (the slow part), and the shape drawn from
112
127
  // them, by everything: a change to how shapes are drawn redraws them without optimising again
113
128
  // The shape's key holds this file too, so a change to how cad draws a result (anchored below) redraws it
114
129
  const hash = digest([VERSION, r.problem, r.outline, topopt, source('@rulecad/fea'), fs.readFileSync(new URL(import.meta.url), 'utf8')]), file = paths.cache('optimise', `${hash}.json`);
115
130
  if (!fresh && !process.env.CAD_NO_CACHE && host.exists(file)) return { ...JSON.parse(host.readText(file)), cached: true };
116
- const spec = holdEmpty(discretise(r.problem)), densities = paths.cache('densities', `${digest([VERSION, r.problem, solver, source('@rulecad/fea')])}.json`);
131
+ const spec = holdEmpty(discretise(r.problem)), densities = paths.cache('densities', `${densitiesKey(r.problem)}.json`);
117
132
  // A mark that this problem has been optimised before (by any solver), so a run can say whether it's the solver that changed
118
133
  const seen = paths.cache('densities', `${digest([VERSION, r.problem])}.seen`);
119
134
  if (!fresh && !process.env.CAD_NO_CACHE && !host.exists(densities)) onRun?.(host.exists(seen) ? 'the solver has changed since its last result' : 'no result yet');
package/lib/order.mjs CHANGED
@@ -12,6 +12,8 @@ import { placeItems, jointValues, mul } from '@rulecad/model-link';
12
12
  import { host } from './host.mjs';
13
13
  import { paths } from './workspace.mjs';
14
14
  import { motorScrews } from './motors.mjs';
15
+ import jscad from '@jscad/modeling';
16
+ const { geom3 } = jscad.geometries;
15
17
 
16
18
  const top = (n) => String(n).split(/[.@]/)[0];
17
19
  const round = (v) => v.map((x) => (Math.abs(x) < 1e-9 ? 0 : +x.toFixed(6)));
@@ -24,12 +26,14 @@ function basis(d) {
24
26
  }
25
27
 
26
28
  // One thing that gets placed: its triangles, its box, what a part is known as
29
+ // (a fitting whose tongue or pegs stand in a beam's slot, an end cap's in its end, is taken without them, as the overlap
30
+ // check takes it: they slide out along the slot or the beam, and would otherwise hold it to its beam from every side)
27
31
  function groups(s) {
28
- const by = new Map();
32
+ const by = new Map(), beams = new Set(s.objects.filter((o) => o.beam).map((o) => o.id));
29
33
  s.parts.forEach((p, order) => {
30
34
  if (!by.has(p.item)) by.set(p.item, { id: p.item, order, parts: [], tris: [] });
31
35
  const g = by.get(p.item); g.parts.push(p);
32
- for (const t of p.triangles) g.tris.push(...fan(t));
36
+ for (const t of p.collide && !beams.has(p.item) ? geom3.toPolygons(p.collide).map((q) => q.vertices) : p.triangles) g.tris.push(...fan(t));
33
37
  });
34
38
  const objs = new Map(s.objects.map((o) => [o.id, o]));
35
39
  for (const g of by.values()) { const o = objs.get(g.id); g.object = o?.objName ?? null; g.bought = o?.bought ?? null; g.motor = !!o?.motor; }
@@ -116,7 +120,9 @@ export function assemblyOrder(s) {
116
120
  const a = top(A), b = top(B), [u, v] = earlier(a, b) <= 0 ? [a, b] : [b, a];
117
121
  if (x.seat != null && (bearing(a) || bearing(b))) { const [h, r] = bearing(a) ? [b, a] : [a, b]; add(h, r, `${r} is pressed into ${h}`); continue; }
118
122
  if ((x.shaft != null || x.engage != null) && (bearing(a) || bearing(b))) { const [r, shaft] = bearing(a) ? [a, b] : [b, a]; add(r, shaft, `${r} goes in before ${shaft}`); continue; }
119
- if (x.fastens) add(u, v, x.note || `${v} fastens to ${u}`);
123
+ // (a part placed on another, as a fitting at a beam's address is, goes on after it: its joint says so, and a fastening
124
+ // between the two does not turn that round, however far each is from the base)
125
+ if (x.fastens && !before.get(v)?.has(u)) add(u, v, x.note || `${v} fastens to ${u}`);
120
126
  }
121
127
  // Screws: what stands on the tool's line goes on after the screw, and if it must already be there, nothing can
122
128
  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)); };
@@ -223,7 +229,7 @@ export const fastenerText = (f) => `${f.fit}${f.fastener ? ` (${f.count != null
223
229
 
224
230
  // Cached by what the parts are and where they are, with everything else that changes the answer
225
231
  function orderFile(s) {
226
- const key = crypto.createHash('sha256').update(JSON.stringify([6, s.parts.map((p) => [p.item, p.hash ?? p.shape, Array.from(p.m ?? []).map((x) => +x.toFixed(4))]), s.fits.map(({ num, ...x }) => x), s.motion.joints.map((j) => [j.id, j.child, j.parent])])).digest('hex');
232
+ const key = crypto.createHash('sha256').update(JSON.stringify([8, s.parts.map((p) => [p.item, p.hash ?? p.shape, Array.from(p.m ?? []).map((x) => +x.toFixed(4))]), s.fits.map(({ num, ...x }) => x), s.motion.joints.map((j) => [j.id, j.child, j.parent])])).digest('hex');
227
233
  return paths.cache('order', `${key}.json`);
228
234
  }
229
235
  export function orderOf(s) {
package/lib/panels.mjs CHANGED
@@ -108,7 +108,7 @@ export function expandPanels(a, num, context = framesContext(), material = 'pla'
108
108
  return { at: `${e.id}.${e.place.name}@${dist}`, ...(dot(ylocal, yIn) > 0 ? {} : { rotate: [0, 0, 180] }), dist, x: dot(ylocal, yIn) > 0 ? e.d : e.d.map((c) => -c), part };
109
109
  };
110
110
  const pointOn = (e, s) => add(add(add([0, 0, 0], e.ax, e.c), span(e).q, s), out, h); // the slot line at s along the edge
111
- const record = { id: it.id, sheet, thickness: T, door: !!door, items: [], fasten: [] };
111
+ const record = { id: it.id, sheet, thickness: T, door: !!door, bay: [...P.bay], items: [], fasten: [] };
112
112
  if (!door) {
113
113
  const pitch = P.pitch != null ? num(P.pitch) : PANEL_DEFAULTS.pitch.value;
114
114
  if (!(pitch > 0)) throw new Error(`${what}: pitch is the most between clips along an edge, in mm, above 0 (got ${shown(P.pitch)})`);
package/lib/plates.mjs CHANGED
@@ -9,9 +9,9 @@ import { paths, printerOf } from './workspace.mjs';
9
9
  import { peekRuleSet } from './rules.mjs';
10
10
  import { CadError } from './errors.mjs';
11
11
  import { assemblyPath, buildAssembly, checkAssembly } from './assembly.mjs';
12
- import { printedParts } from './list.mjs';
13
- import { fittingBuilt, plasticOf } from './fittings.mjs';
14
- import { framesContext } from './beams.mjs';
12
+ import { printedParts, materialOf } from './list.mjs';
13
+ import { fittingBuilt, plasticOf, companions } from './fittings.mjs';
14
+ import { framesContext, beamBuilt, laidSpec } from './beams.mjs';
15
15
 
16
16
  const n3 = (x) => +x.toFixed(3);
17
17
 
@@ -24,17 +24,30 @@ function rulesOf(project, gap) {
24
24
 
25
25
  // Every printed thing to go on a plate: built as printed, its filaments, how big
26
26
  // (a printed fitting, a join's, a guide's or an item's own, goes on as its item's fitting laid as it prints: "pose": "print")
27
+ // (each with its material: the project's, or a printed beam's own "material", so a plate is one plastic)
27
28
  async function plateParts(s) {
28
- const out = [], items = new Map((s.items ?? []).map((it) => [it.id, it]));
29
+ const out = [], items = new Map((s.items ?? []).map((it) => [it.id, it])), own = materialOf(s.project).name;
29
30
  for (const o of s.objects) {
30
31
  if (o.unplaced || o.role !== 'part' || !o.objName) continue;
32
+ if (o.beam?.printed) { // a printed beam, laid as it prints (lib/beams.mjs)
33
+ const bi = (s.a.items || []).find((x) => x.id === o.id); // (the item as written: the built one holds the beam's model)
34
+ if (!bi?.beam?.profile) continue;
35
+ const beamSpec = laidSpec(bi, s.num, o.beam.length), b = beamBuilt({ id: o.id, beam: beamSpec }, s.num, o.id).b, tris = b.parts.flatMap((p) => p.triangles), { lo, hi } = bounds(tris);
36
+ out.push({ id: o.id.replace(/\./g, '_'), source: o.id, object: o.objName, beam: beamSpec, set: {}, filament: 'base', material: String(bi.beam.material ?? own).toLowerCase(), hash: b.hash, lo, size: [hi[0] - lo[0], hi[1] - lo[1]], height: hi[2] - lo[2] });
37
+ continue;
38
+ }
31
39
  const it = o.fitting ? items.get(o.id) : null;
32
40
  if (o.fitting && !it?.fitting) continue;
33
41
  const fitting = it ? { ...it.fitting, pose: 'print' } : null;
34
42
  const b = fitting ? (await fittingBuilt({ ...it, fitting }, o.id, framesContext(), plasticOf(s.project))).b : await build({ ...locate(`${s.project}/${o.objName}`), ...(o.variant ? { variant: o.variant } : {}) }, o.set || {});
35
43
  const tris = b.parts.flatMap((p) => p.triangles), { lo, hi } = bounds(tris);
36
44
  const fil = [...new Set(b.parts.filter((p) => p.role !== 'support').map((p) => p.filament || 'base'))].sort().join('+') || 'base';
37
- out.push({ id: o.id.replace(/\./g, '_'), source: o.id, object: o.objName, ...(fitting ? { fitting } : {}), variant: o.variant, set: o.set || {}, filament: fil, hash: b.hash, lo, size: [hi[0] - lo[0], hi[1] - lo[1]], height: hi[2] - lo[2] });
45
+ out.push({ id: o.id.replace(/\./g, '_'), source: o.id, object: o.objName, ...(fitting ? { fitting } : {}), variant: o.variant, set: o.set || {}, filament: fil, material: own, hash: b.hash, lo, size: [hi[0] - lo[0], hi[1] - lo[1]], height: hi[2] - lo[2] });
46
+ }
47
+ // what comes with a placed part and is printed beside it (a levelling foot's pad: lib/fittings.mjs companions)
48
+ for (const c of companions(s)) {
49
+ const fitting = { ...c.fitting, pose: 'print' }, b = (await fittingBuilt({ id: c.id, fitting }, c.id, framesContext(), plasticOf(s.project))).b, tris = b.parts.flatMap((p) => p.triangles), { lo, hi } = bounds(tris);
50
+ out.push({ id: c.id.replace(/\./g, '_'), source: c.of, object: b.object.name, fitting, set: {}, filament: 'base', material: own, hash: b.hash, lo, size: [hi[0] - lo[0], hi[1] - lo[1]], height: hi[2] - lo[2] });
38
51
  }
39
52
  return out;
40
53
  }
@@ -62,13 +75,14 @@ function existing(s) {
62
75
  for (const f of fs.existsSync(dir) ? fs.readdirSync(dir) : []) { if (!f.endsWith('.json')) continue; let a; try { a = JSON.parse(fs.readFileSync(path.join(dir, f), 'utf8')); } catch { continue; } if (a.packed?.of === s.name) out.push({ name: f.slice(0, -5), a }); }
63
76
  return out.sort((a, b) => a.name.localeCompare(b.name, undefined, { numeric: true }));
64
77
  }
65
- const nameOf = (s, filament, k) => `${s.name}-${filament.replace(/\+/g, '-')}-${k}`;
78
+ // <assembly>-<filament>-<n>; a plate in another material than the project's has it in its name too
79
+ const nameOf = (s, filament, k, material, own) => `${s.name}-${material && material !== own ? `${material}-` : ''}${filament.replace(/\+/g, '-')}-${k}`;
66
80
 
67
81
  function plateJson(s, plate, { bed, gap }) {
68
82
  const origin = (bed - 2 * gap) / 2;
69
83
  return { title: `${s.a.title || s.name}: ${plate.filament}, plate ${plate.n}`, kind: 'plate', note: `Generated by cad plates from ${s.name}. Hand edits are replaced when a part on it changes.`,
70
- packed: { of: s.name, filament: plate.filament, gap, parts: Object.fromEntries(plate.items.map(({ p }) => [p.id, p.hash])) },
71
- items: plate.items.map(({ p, x, y }) => ({ id: p.id, ...(p.fitting ? { fitting: p.fitting } : { object: p.object }), ...(p.variant ? { variant: p.variant } : {}), ...(Object.keys(p.set).length ? { set: p.set } : {}), at: [n3(x - origin - p.lo[0]), n3(y - origin - p.lo[1]), n3(-p.lo[2])] })) };
84
+ packed: { of: s.name, filament: plate.filament, material: plate.material, gap, parts: Object.fromEntries(plate.items.map(({ p }) => [p.id, p.hash])) },
85
+ items: plate.items.map(({ p, x, y }) => ({ id: p.id, ...(p.fitting ? { fitting: p.fitting } : p.beam ? { beam: p.beam } : { object: p.object }), ...(p.variant ? { variant: p.variant } : {}), ...(Object.keys(p.set).length ? { set: p.set } : {}), at: [n3(x - origin - p.lo[0]), n3(y - origin - p.lo[1]), n3(-p.lo[2])] })) };
72
86
  }
73
87
 
74
88
  /**
@@ -77,7 +91,7 @@ function plateJson(s, plate, { bed, gap }) {
77
91
  * @returns {Promise<{ plates: object[], touched: string[], removed: string[], gap: number, bed: number, findings: object[] }>}
78
92
  */
79
93
  export async function platesOf(s, { write = false, gap: asked } = {}) {
80
- const parts = await plateParts(s), { bed, gap } = rulesOf(s.project, asked), findings = [], plates = [], touched = [], removed = [];
94
+ const parts = await plateParts(s), { bed, gap } = rulesOf(s.project, asked), findings = [], plates = [], touched = [], removed = [], own = materialOf(s.project).name;
81
95
  if (!parts.length) throw new CadError('plates.empty', `${s.project}/${s.name} has nothing printed to put on a plate`);
82
96
  const big = parts.filter((p) => p.size[0] > bed - 2 * gap || p.size[1] > bed - 2 * gap);
83
97
  for (const p of big) findings.push({ level: 'fail', text: `${p.id} (${p.object}) is ${Number(p.size[0].toFixed(1))} × ${Number(p.size[1].toFixed(1))} mm: bigger than the ${bed} mm bed, so it has no plate: split it or turn it`, code: 'plate.bed', refs: { item: p.id }, values: { size: p.size, bed } });
@@ -86,16 +100,16 @@ export async function platesOf(s, { write = false, gap: asked } = {}) {
86
100
  for (const e of had) {
87
101
  const on = Object.entries(e.a.packed.parts || {}), ok = on.length && on.every(([id, h]) => by.get(id)?.hash === h) && e.a.packed.gap === gap;
88
102
  if (!ok) continue;
89
- kept.add(e.name); on.forEach(([id]) => used.add(id)); plates.push({ name: e.name, filament: e.a.packed.filament, a: e.a, items: e.a.items.map((it) => { const p = by.get(it.id), origin = (bed - 2 * gap) / 2; return { p, x: it.at[0] + p.lo[0] + origin, y: it.at[1] + p.lo[1] + origin }; }), stood: true });
103
+ kept.add(e.name); on.forEach(([id]) => used.add(id)); plates.push({ name: e.name, filament: e.a.packed.filament, material: e.a.packed.material ?? own, a: e.a, items: e.a.items.map((it) => { const p = by.get(it.id), origin = (bed - 2 * gap) / 2; return { p, x: it.at[0] + p.lo[0] + origin, y: it.at[1] + p.lo[1] + origin }; }), stood: true });
90
104
  }
91
- // Everything else, packed by filament; names reused from the plates that are going, so a changed part keeps its name
105
+ // Everything else, packed by material and filament; names reused from the plates that are going, so a changed part keeps its name
92
106
  const free = [...by.values()].filter((p) => !used.has(p.id)), byFilament = new Map();
93
- for (const p of free) { if (!byFilament.has(p.filament)) byFilament.set(p.filament, []); byFilament.get(p.filament).push(p); }
107
+ for (const p of free) { const key = `${p.material}|${p.filament}`; if (!byFilament.has(key)) byFilament.set(key, []); byFilament.get(key).push(p); }
94
108
  const goingNames = had.filter((e) => !kept.has(e.name)).map((e) => e.name);
95
- for (const [filament, list] of byFilament) {
96
- const beds = pack(list, { bed, gap }); let k = 0;
97
- const next = () => { const reuse = goingNames.find((n) => had.find((e) => e.name === n)?.a.packed.filament === filament); if (reuse) { goingNames.splice(goingNames.indexOf(reuse), 1); return reuse; } let name; do name = nameOf(s, filament, ++k); while (kept.has(name) || plates.some((x) => x.name === name)); return name; };
98
- for (const b of beds) { const name = next(), n = Number(name.match(/-(\d+)$/)?.[1]) || 1, plate = { name, filament, n, items: b.items }; plate.a = plateJson(s, plate, { bed, gap }); plates.push(plate); touched.push(name); }
109
+ for (const [key, list] of byFilament) {
110
+ const [material, filament] = [key.slice(0, key.indexOf('|')), key.slice(key.indexOf('|') + 1)], beds = pack(list, { bed, gap }); let k = 0;
111
+ const next = () => { const reuse = goingNames.find((n) => { const e = had.find((x) => x.name === n); return e?.a.packed.filament === filament && (e.a.packed.material ?? own) === material; }); if (reuse) { goingNames.splice(goingNames.indexOf(reuse), 1); return reuse; } let name; do name = nameOf(s, filament, ++k, material, own); while (kept.has(name) || plates.some((x) => x.name === name)); return name; };
112
+ for (const b of beds) { const name = next(), n = Number(name.match(/-(\d+)$/)?.[1]) || 1, plate = { name, filament, material, n, items: b.items }; plate.a = plateJson(s, plate, { bed, gap }); plates.push(plate); touched.push(name); }
99
113
  }
100
114
  for (const n of goingNames) removed.push(n);
101
115
  plates.sort((a, b) => a.name.localeCompare(b.name, undefined, { numeric: true }));
@@ -105,7 +119,7 @@ export async function platesOf(s, { write = false, gap: asked } = {}) {
105
119
  for (const n of removed) fs.rmSync(plateFile(s.project, n), { force: true });
106
120
  }
107
121
  const grams = new Map(printedParts(s).map((x) => [x.id.replace(/\./g, '_'), x]));
108
- return { bed, gap, touched, removed, findings, plates: plates.map((p) => ({ name: p.name, filament: p.filament, parts: p.items.map(({ p: q, x, y }) => ({ id: q.id, object: q.object, x: n3(x + gap), y: n3(y + gap), w: n3(q.size[0]), d: n3(q.size[1]) })), grams: n3(p.items.reduce((t, { p: q }) => t + (grams.get(q.id)?.grams ?? 0), 0)), minutes: p.items.reduce((t, { p: q }) => t + (grams.get(q.id)?.minutes ?? 0), 0), stood: !!p.stood })) };
122
+ return { bed, gap, touched, removed, findings, plates: plates.map((p) => ({ name: p.name, filament: p.filament, material: p.material, parts: p.items.map(({ p: q, x, y }) => ({ id: q.id, object: q.object, x: n3(x + gap), y: n3(y + gap), w: n3(q.size[0]), d: n3(q.size[1]) })), grams: n3(p.items.reduce((t, { p: q }) => t + (grams.get(q.id)?.grams ?? 0), 0)), minutes: p.items.reduce((t, { p: q }) => t + (grams.get(q.id)?.minutes ?? 0), 0), stood: !!p.stood })) };
109
123
  }
110
124
 
111
125
  /** Each plate's checks: what check says of a plate, the print check over the whole bed included. */
package/lib/preview.mjs CHANGED
@@ -1,5 +1,6 @@
1
1
  // preview(parts, { title, meta, out, explode }) -> out: a 1800 × 1200 PNG of six views (front, side, 3/4, top, bottom, 3/4 below),
2
- // parts: [{ name, role, label, item, triangles }]; supports and references are drawn faint (lines only); explode drops
2
+ // parts: [{ name, role, label, item, triangles }]; supports and references are drawn faint (lines only), but references
3
+ // solid with built (an assembly with show: built); explode drops
3
4
  // supports below and, in an assembly, lifts each kind of object above the one before (plate, switches, keycaps); a part
4
5
  // with `lift` (a screw, a nut: lib/fasten.mjs) goes with the part it sits in (`with`) and then out along its own axis.
5
6
  // rendered by headless Chrome from lib/preview/page.html, served on this Mac only for the few seconds it takes.
@@ -19,9 +20,9 @@ const CHROME = process.env.CAD_CHROME || [
19
20
  ].find((f) => fs.existsSync(f));
20
21
  const THREE = path.dirname(createRequire(import.meta.url).resolve('three')); // wherever npm put it
21
22
 
22
- export async function preview(parts, { title = '', meta = '', out, explode = false, marks = null }) {
23
+ export async function preview(parts, { title = '', meta = '', out, explode = false, marks = null, built = false }) {
23
24
  const flat = (tris) => { const positions = []; for (const t of tris) for (let i = 1; i < t.length - 1; i++) positions.push(...t[0], ...t[i], ...t[i + 1]); return positions; };
24
- const data = JSON.stringify({ title, meta, explode, marks, parts: parts.map((p) => ({ name: p.name, role: p.role, label: p.label, item: p.object || p.item, ...(p.lift ? { lift: p.lift, with: p.with } : {}), positions: flat(p.triangles) })) });
25
+ const data = JSON.stringify({ title, meta, explode, marks, parts: parts.map((p) => ({ name: p.name, role: built && p.role === 'reference' ? 'part' : p.role, label: p.label, item: p.object || p.item, ...(p.lift ? { lift: p.lift, with: p.with } : {}), positions: flat(p.triangles) })) });
25
26
  const server = http.createServer((req, res) => {
26
27
  const u = new URL(req.url, 'http://x').pathname;
27
28
  const send = (type, body) => { res.writeHead(200, { 'Content-Type': type }); res.end(body); };
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 }} */
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];
@@ -128,9 +129,45 @@ export function terms(s, c) {
128
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` });
129
130
  for (const [term, expr] of Object.entries(spec?.errors ?? {})) out.push({ term, value: s.num(expr), kind: kindOf(expr), expr });
130
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 }; }
131
133
  return { joint: id, terms: out, geared: t.stages.length > 0 };
132
134
  });
133
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
+ }
134
171
  function kindOf(expr) {
135
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'; } });
136
173
  return kinds.length ? (kinds.includes('estimate') ? 'estimate' : kinds[0]) : 'estimate';
@@ -156,7 +193,8 @@ function accuracyCheck(s, f, picture) {
156
193
  const t = s.task, code = 'task.accuracy'; if (t.accuracy == null) return null;
157
194
  const { list, at, worst } = accuracyOf(s); if (!worst) return null;
158
195
  const big = [...worst.e.parts].sort((a, b) => b.mm - a.mm)[0], soft = worst.e.parts.filter((p) => p.kind === 'estimate');
159
- 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)}°)` : ''}`;
160
198
  const unmeasured = list.filter((j) => j.geared && !j.terms.some((x) => /play|backlash/.test(x.term))).map((j) => j.joint);
161
199
  const predict = { name: code, figure: `${t.tool} error at its worst point`, value: worst.e.worst, unit: 'mm' };
162
200
  const margin = worst.e.worst / t.accuracy, level = margin > 1 ? 'fail' : margin > 0.8 ? 'warn' : 'pass';
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@rulecad/cad",
3
- "version": "0.7.57",
3
+ "version": "0.7.59",
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": {
@@ -65,17 +65,17 @@
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.16",
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.8"
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"