@rulecad/cad 0.7.97 → 0.9.0

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.
Files changed (86) hide show
  1. package/AGENTS.md +26 -10
  2. package/CHANGELOG.md +442 -2
  3. package/EXAMPLES.md +48 -42
  4. package/README.md +226 -73
  5. package/TUTORIAL.md +2 -2
  6. package/bin/cad.mjs +2253 -514
  7. package/lib/animate.mjs +173 -49
  8. package/lib/assembly.mjs +1854 -437
  9. package/lib/beams.mjs +256 -52
  10. package/lib/belts.mjs +66 -15
  11. package/lib/board-work.mjs +12 -0
  12. package/lib/bought.mjs +309 -53
  13. package/lib/buildpage.mjs +179 -29
  14. package/lib/carried.mjs +201 -0
  15. package/lib/clone.mjs +194 -42
  16. package/lib/design.mjs +734 -113
  17. package/lib/drive.mjs +187 -63
  18. package/lib/edit.mjs +900 -191
  19. package/lib/errors.mjs +16 -3
  20. package/lib/explain.mjs +62 -13
  21. package/lib/fasten.mjs +2710 -502
  22. package/lib/fittings.mjs +715 -121
  23. package/lib/fixings.mjs +21 -9
  24. package/lib/framebuild.mjs +792 -176
  25. package/lib/framecheck.mjs +1901 -368
  26. package/lib/framegen.mjs +100 -22
  27. package/lib/frameheat.mjs +225 -42
  28. package/lib/frameprint.mjs +513 -108
  29. package/lib/frames.mjs +81 -17
  30. package/lib/framesize.mjs +792 -120
  31. package/lib/frametip.mjs +235 -0
  32. package/lib/gait.mjs +135 -23
  33. package/lib/grip.mjs +62 -13
  34. package/lib/guides.mjs +1403 -230
  35. package/lib/host.mjs +149 -18
  36. package/lib/inplace.mjs +171 -36
  37. package/lib/jigs.mjs +360 -78
  38. package/lib/joins.mjs +697 -118
  39. package/lib/jsonedit.mjs +88 -26
  40. package/lib/kept.mjs +84 -0
  41. package/lib/kit.mjs +438 -68
  42. package/lib/layout.mjs +3 -1
  43. package/lib/links.mjs +149 -42
  44. package/lib/list.mjs +326 -64
  45. package/lib/live-guard.mjs +68 -0
  46. package/lib/live-shape.mjs +96 -24
  47. package/lib/live.mjs +189 -59
  48. package/lib/loads.mjs +579 -130
  49. package/lib/machine.mjs +372 -74
  50. package/lib/magnets.mjs +162 -44
  51. package/lib/measured.mjs +417 -94
  52. package/lib/mesh.mjs +526 -119
  53. package/lib/meshcmd.mjs +215 -60
  54. package/lib/motors.mjs +1022 -212
  55. package/lib/motorsvg.mjs +114 -32
  56. package/lib/names.mjs +41 -0
  57. package/lib/optimise.mjs +979 -283
  58. package/lib/order.mjs +519 -112
  59. package/lib/panels.mjs +482 -94
  60. package/lib/parts.mjs +78 -23
  61. package/lib/pins.mjs +163 -44
  62. package/lib/plates.mjs +224 -36
  63. package/lib/player.mjs +37 -9
  64. package/lib/power.mjs +64 -13
  65. package/lib/preview.mjs +83 -16
  66. package/lib/profilemeasure.mjs +572 -129
  67. package/lib/rules.mjs +38 -4
  68. package/lib/sandbox-hooks.mjs +154 -12
  69. package/lib/sandbox-preload.mjs +2 -2
  70. package/lib/sandbox-run.mjs +127 -12
  71. package/lib/sandbox.mjs +632 -35
  72. package/lib/schema.mjs +43 -11
  73. package/lib/seats.mjs +227 -49
  74. package/lib/services.mjs +261 -52
  75. package/lib/sheet.mjs +851 -178
  76. package/lib/slotnuts.mjs +213 -34
  77. package/lib/targets/gist.mjs +4 -1
  78. package/lib/targets.mjs +42 -6
  79. package/lib/task.mjs +376 -79
  80. package/lib/versions.mjs +113 -28
  81. package/lib/wires.mjs +228 -45
  82. package/lib/workspace.mjs +216 -17
  83. package/package.json +19 -19
  84. package/schemas/assembly.schema.json +2 -2
  85. package/schemas/object.schema.json +1 -1
  86. package/schemas/project.schema.json +1 -1
package/lib/loads.mjs CHANGED
@@ -5,124 +5,252 @@ import crypto from 'node:crypto';
5
5
  import { grid as makeGrid, analyse, positions } from '@rulecad/fea';
6
6
  import { jacobian } from '@rulecad/robots';
7
7
  import { performance } from '@rulecad/motors';
8
- import { host } from './host.mjs';
8
+ import { host, cached } from './host.mjs';
9
9
  import { paths } from './workspace.mjs';
10
10
  import { peekRuleSet } from './rules.mjs';
11
11
  import { solidFill } from './optimise.mjs';
12
12
  import { materialOf } from './list.mjs';
13
- import { axisOf, trainFrom, workingSpeed, atCurrent } from './motors.mjs';
13
+ import { trainFrom, workingSpeed, atCurrent, carriedMasses } from './motors.mjs';
14
+ import { axisOf, beyond, partMasses, loadAt as carriedLoadAt, driveLoadAt, countedFor } from './carried.mjs';
14
15
  import { sample, chainOf } from './task.mjs';
15
16
  import { carriageChecks } from './guides.mjs';
16
17
 
17
- const G = 9.80665, sub = (a, b) => [a[0] - b[0], a[1] - b[1], a[2] - b[2]], dot = (a, b) => a[0] * b[0] + a[1] * b[1] + a[2] * b[2];
18
- const cross = (a, b) => [a[1] * b[2] - a[2] * b[1], a[2] * b[0] - a[0] * b[2], a[0] * b[1] - a[1] * b[0]], add = (a, b) => [a[0] + b[0], a[1] + b[1], a[2] + b[2]], scale = (a, k) => a.map((x) => x * k);
19
- const norm = (a) => Math.hypot(a[0], a[1], a[2]), n3 = (x, d = 2) => String(Number(x.toFixed(d)));
20
- const rowsAt = (W, p) => [0, 1, 2].map((k) => W[4 * k] * p[0] + W[4 * k + 1] * p[1] + W[4 * k + 2] * p[2] + W[4 * k + 3]);
21
- const invAt = (W, p) => { const q = [p[0] - W[3], p[1] - W[7], p[2] - W[11]]; return [W[0] * q[0] + W[4] * q[1] + W[8] * q[2], W[1] * q[0] + W[5] * q[1] + W[9] * q[2], W[2] * q[0] + W[6] * q[1] + W[10] * q[2]]; };
18
+ const G = 9.80665,
19
+ sub = (a, b) => [a[0] - b[0], a[1] - b[1], a[2] - b[2]],
20
+ dot = (a, b) => a[0] * b[0] + a[1] * b[1] + a[2] * b[2];
21
+ const scale = (a, k) => a.map((x) => x * k);
22
+ const norm = (a) => Math.hypot(a[0], a[1], a[2]),
23
+ n3 = (x, d = 2) => String(Number(x.toFixed(d)));
24
+ const rowsAt = (W, p) =>
25
+ [0, 1, 2].map((k) => W[4 * k] * p[0] + W[4 * k + 1] * p[1] + W[4 * k + 2] * p[2] + W[4 * k + 3]);
26
+ const invAt = (W, p) => {
27
+ const q = [p[0] - W[3], p[1] - W[7], p[2] - W[11]];
28
+ return [
29
+ W[0] * q[0] + W[4] * q[1] + W[8] * q[2],
30
+ W[1] * q[0] + W[5] * q[1] + W[9] * q[2],
31
+ W[2] * q[0] + W[6] * q[1] + W[10] * q[2],
32
+ ];
33
+ };
22
34
 
23
- // A mesh's volume and centroid: signed tetrahedra from the origin
24
- function solidOf(tris) {
25
- let V = 0; const c = [0, 0, 0];
26
- for (const [a, b, d] of tris) { const v = dot(a, cross(b, d)) / 6; V += v; for (let k = 0; k < 3; k++) c[k] += (v * (a[k] + b[k] + d[k])) / 4; }
27
- return { volume: Math.abs(V), centroid: V ? c.map((x) => x / V) : [0, 0, 0] };
28
- }
29
-
30
- /** Each moving thing's mass in kg and its centre in its item's frame. */
35
+ /** Each moving thing's mass in kg and its centre in its item's frame (lib/carried.mjs partMasses). */
31
36
  export function massesOf(s, { placeItems, jointValues }) {
32
- const motion = s.motion, ids = motion.items.map((x) => x[0]), W = placeItems(motion, jointValues(motion, motion.pose ?? undefined)), density = materialOf(s.project).density, out = [];
33
- ids.forEach((id, k) => {
34
- const parts = s.parts.filter((p) => p.item === id && p.role !== 'support'); if (!parts.length) return;
35
- const o = s.objects.find((x) => x.id === id || String(x.id).startsWith(`${id}.`)), reference = parts.every((p) => p.role === 'reference');
36
- let total = 0, c = [0, 0, 0];
37
- for (const p of parts) { const q = solidOf(p.triangles); const kg = reference ? 0 : (q.volume / 1000) * density / 1000; total += kg; c = add(c, scale(q.centroid, kg || q.volume)); }
38
- const weightSum = reference ? parts.reduce((t, p) => t + solidOf(p.triangles).volume, 0) : total;
39
- const bought = reference ? o?.bought?.mass ?? null : null;
40
- out.push({ item: k, id, kg: reference ? bought ?? 0 : total, centre: invAt(W[k], weightSum ? scale(c, 1 / weightSum) : c), known: !reference || bought != null });
41
- });
42
- return out;
37
+ const W = placeItems(s.motion, jointValues(s.motion, s.motion.pose ?? undefined));
38
+ return partMasses(s, W, materialOf(s.project).density);
43
39
  }
44
40
 
45
41
  // A joint's value set through its leader when it follows a motor off the chain (a gearbox's output): the model moves by its leader
46
- const chainSet = (motion, names, q) => Object.fromEntries(names.map((n, i) => { const j = motion.joints.find((x) => x.id === n), lead = j?.follow && !names.includes(j.follow[0]) ? j.follow : null; return lead ? [lead[0], [(q[i] - (lead[2] ?? 0)) / (lead[1] ?? 1)]] : [n, [q[i]]]; }));
42
+ const chainSet = (motion, names, q) =>
43
+ Object.fromEntries(
44
+ names.map((n, i) => {
45
+ const j = motion.joints.find((x) => x.id === n),
46
+ lead = j?.follow && !names.includes(j.follow[0]) ? j.follow : null;
47
+ return lead ? [lead[0], [(q[i] - (lead[2] ?? 0)) / (lead[1] ?? 1)]] : [n, [q[i]]];
48
+ }),
49
+ );
47
50
  // A mesh's bounding box, as lo and hi: a loop, as a large part's triangles overflow Math.min(...spread)
48
- function extent(tris) { const lo = [Infinity, Infinity, Infinity], hi = [-Infinity, -Infinity, -Infinity]; for (const t of tris) for (const p of t) for (let k = 0; k < 3; k++) { if (p[k] < lo[k]) lo[k] = p[k]; if (p[k] > hi[k]) hi[k] = p[k]; } return { lo, hi }; }
49
- /** Whether an item moves with a joint: the joint is on its chain to the base. */
50
- export const beyond = (motion, j, item) => { const by = new Map(motion.joints.map((x) => [x.child, x])); for (let i = item, n = 0; i >= 0 && n < 99; n++) { const x = by.get(i); if (!x) return false; if (x === j) return true; i = x.parent; } return false; };
51
-
52
- // Force and moment about a joint's origin, at one pose
53
- function loadAt(motion, masses, payload, worlds, j, mul) {
54
- const { O, Z } = axisOf(motion, worlds, j, mul), g = motion.gravity || [0, 0, -1], dir = scale(g, 1 / norm(g));
55
- let F = [0, 0, 0], M = [0, 0, 0], carried = 0;
56
- const addMass = (kg, X) => { const f = scale(dir, kg * G); F = add(F, f); M = add(M, scale(cross(sub(X, O), f), 1 / 1000)); carried += kg; };
57
- for (const m of masses) if (beyond(motion, j, m.item)) addMass(m.kg, rowsAt(worlds[m.item], m.centre));
58
- if (payload && beyond(motion, j, payload.item)) addMass(payload.kg, rowsAt(worlds[payload.item], payload.point));
59
- const axial = dot(F, Z), radial = norm(sub(F, scale(Z, axial))), torque = dot(M, Z), tipping = norm(sub(M, scale(Z, torque)));
60
- return { axial: Math.abs(axial), radial, tipping, torque, carried, F, O, Z };
51
+ function extent(tris) {
52
+ const lo = [Infinity, Infinity, Infinity],
53
+ hi = [-Infinity, -Infinity, -Infinity];
54
+ for (const t of tris)
55
+ for (const p of t)
56
+ for (let k = 0; k < 3; k++) {
57
+ if (p[k] < lo[k]) lo[k] = p[k];
58
+ if (p[k] > hi[k]) hi[k] = p[k];
59
+ }
60
+ return { lo, hi };
61
61
  }
62
+ export { beyond };
63
+
64
+ // Force and moment about a joint's origin, at one pose: the parts' masses and the task's payload (the sum the motor
65
+ // checks read too, lib/carried.mjs)
66
+ const loadAt = (motion, masses, payload, worlds, j, mul) =>
67
+ carriedLoadAt(
68
+ motion,
69
+ [
70
+ ...masses.map((m) => ({ item: m.item, kg: m.kg, point: m.centre })),
71
+ ...(payload ? [{ item: payload.item, kg: payload.kg, point: payload.point }] : []),
72
+ ],
73
+ worlds,
74
+ j,
75
+ mul,
76
+ );
62
77
 
63
78
  // The poses the machine will be in: the task's samples, the named poses, or each joint at its ends
64
79
  /** The poses the machine will be in: the task's samples, the named poses, or each joint at its ends; and as drawn. */
65
80
  export function posesOf(s, jointValues) {
66
- const motion = s.motion, base = jointValues(motion, motion.pose ?? undefined), leads = Object.fromEntries(Object.entries(base).filter(([id]) => !motion.joints.find((x) => x.id === id)?.follow)), out = [];
81
+ const motion = s.motion,
82
+ base = jointValues(motion, motion.pose ?? undefined),
83
+ leads = Object.fromEntries(Object.entries(base).filter(([id]) => !motion.joints.find((x) => x.id === id)?.follow)),
84
+ out = [];
67
85
  for (const p of Object.keys(motion.poses || {})) out.push({ label: `pose ${p}`, values: jointValues(motion, p) });
68
- if (s.task) { const { c, r } = sample(s), every = Math.max(1, Math.ceil(r.samples.length / 40)); r.samples.filter((x, i) => x.reachable && !(i % every)).forEach((x) => out.push({ label: 'on the task', point: x.point, values: jointValues(motion, { ...leads, ...chainSet(motion, c.names, x.q) }) })); }
69
- if (!out.length) for (const j of motion.joints.filter((x) => !x.follow && x.dofs.length === 1)) for (const v of j.dofs[0].slice(0, 2)) out.push({ label: `${j.id} at ${n3(v, 1)}`, values: jointValues(motion, { ...leads, [j.id]: [v] }) });
86
+ if (s.task) {
87
+ const { c, r } = sample(s),
88
+ every = Math.max(1, Math.ceil(r.samples.length / 40));
89
+ r.samples
90
+ .filter((x, i) => x.reachable && !(i % every))
91
+ .forEach((x) =>
92
+ out.push({
93
+ label: 'on the task',
94
+ point: x.point,
95
+ values: jointValues(motion, { ...leads, ...chainSet(motion, c.names, x.q) }),
96
+ }),
97
+ );
98
+ }
99
+ if (!out.length)
100
+ for (const j of motion.joints.filter((x) => !x.follow && x.dofs.length === 1))
101
+ for (const v of j.dofs[0].slice(0, 2))
102
+ out.push({ label: `${j.id} at ${n3(v, 1)}`, values: jointValues(motion, { ...leads, [j.id]: [v] }) });
70
103
  out.push({ label: 'as drawn', values: base });
71
104
  return out;
72
105
  }
73
106
 
74
- const X0 = 0.6, Y0 = 0.5; // ISO 76, a single deep-groove ball bearing's static factors
107
+ const X0 = 0.6,
108
+ Y0 = 0.5; // ISO 76, a single deep-groove ball bearing's static factors
75
109
  function bearingMargin(rows, loads) {
76
- const [first] = rows, pair = rows.length >= 2;
110
+ const [first] = rows,
111
+ pair = rows.length >= 2;
77
112
  const span = pair ? Math.abs(rows[1].along - rows[0].along) : (first.bore + first.outer) / 2; // mm: a pair's spacing, or the balls' pitch circle
78
- const radial = pair ? loads.radial / rows.length + (loads.tipping * 1000) / span : loads.radial + (2 * loads.tipping * 1000) / span;
113
+ const radial = pair
114
+ ? loads.radial / rows.length + (loads.tipping * 1000) / span
115
+ : loads.radial + (2 * loads.tipping * 1000) / span;
79
116
  const P0 = Math.max(radial, X0 * radial + Y0 * (loads.axial / (pair ? 2 : 1)));
80
117
  return { P0, C0: first.C0, margin: first.C0 / P0, span };
81
118
  }
82
119
 
83
120
  // A printed location's weakest clip, from FE on the part as drawn: fixed at its foot, the load at its head
84
121
  function clipStress(tris, force, modulus, nu, cell) {
85
- const key = crypto.createHash('sha256').update(JSON.stringify([tris.length, tris[0], force, modulus, cell])).digest('hex').slice(0, 20), file = paths.cache('clip', key);
86
- if (!process.env.CAD_NO_CACHE && host.exists(file)) return JSON.parse(host.readText(file));
87
- const { lo, hi } = extent(tris), n = hi.map((h, k) => Math.max(1, Math.ceil((h - lo[k]) / cell)));
88
- const gr = { nx: n[0], ny: n[1], nz: n[2], h: cell }, density = solidFill(tris, gr, lo), g = makeGrid(gr), fixed = new Uint8Array(g.dofs), f = new Float64Array(g.dofs);
122
+ const key = crypto
123
+ .createHash('sha256')
124
+ .update(JSON.stringify(['surface', tris.length, tris[0], force, modulus, cell]))
125
+ .digest('hex')
126
+ .slice(0, 20),
127
+ file = paths.cache('clip', key);
128
+ if (!process.env.CAD_NO_CACHE && cached(file)) return JSON.parse(host.readText(file));
129
+ const { lo, hi } = extent(tris),
130
+ n = hi.map((h, k) => Math.max(1, Math.ceil((h - lo[k]) / cell)));
131
+ const gr = { nx: n[0], ny: n[1], nz: n[2], h: cell },
132
+ density = solidFill(tris, gr, lo),
133
+ g = makeGrid(gr),
134
+ fixed = new Uint8Array(g.dofs),
135
+ f = new Float64Array(g.dofs);
89
136
  // nodes at the foot (the lowest two layers) are held, and the load shared over the top two layers
90
- const at = positions(g), nodeZ = (id) => Math.round(at[id][2] / cell), onPart = new Uint8Array(g.nodes);
91
- for (let e = 0; e < density.length; e++) if (density[e] >= 0.5) for (let k = 0; k < 8; k++) onPart[g.edof[e * 24 + 3 * k] / 3] = 1;
92
- const tops = []; for (let id = 0; id < g.nodes; id++) { if (!onPart[id]) continue; const z = nodeZ(id); if (z <= 1) for (let k = 0; k < 3; k++) fixed[3 * id + k] = 1; if (z >= n[2] - 1) tops.push(id); }
137
+ const at = positions(g),
138
+ nodeZ = (id) => Math.round(at[id][2] / cell),
139
+ onPart = new Uint8Array(g.nodes);
140
+ for (let e = 0; e < density.length; e++)
141
+ if (density[e] >= 0.5) for (let k = 0; k < 8; k++) onPart[g.edof[e * 24 + 3 * k] / 3] = 1;
142
+ const tops = [];
143
+ for (let id = 0; id < g.nodes; id++) {
144
+ if (!onPart[id]) continue;
145
+ const z = nodeZ(id);
146
+ if (z <= 1) for (let k = 0; k < 3; k++) fixed[3 * id + k] = 1;
147
+ if (z >= n[2] - 1) tops.push(id);
148
+ }
93
149
  if (!tops.length) return { stress: 0, thin: true };
94
150
  for (const id of tops) for (let k = 0; k < 3; k++) f[3 * id + k] = force[k] / tops.length;
95
151
  const a = analyse({ grid: g, density, material: { E: modulus, nu }, fixed, loads: [f] });
96
- let most = 0; for (let e = 0; e < density.length; e++) if (density[e] >= 0.5 && a.stress[0][e] > most) most = a.stress[0][e];
97
- const out = { stress: most, deflection: a.deflection[0].most }; host.writeText(file, JSON.stringify(out)); return out;
152
+ // the stress at the clip's surface (fea's analyse().surface): its cells' centres, half a cell inside, read a bent
153
+ // clip 10 to 30% low on cells this size
154
+ let most = 0;
155
+ for (let e = 0; e < density.length; e++) if (density[e] >= 0.5 && a.surface[0][e] > most) most = a.surface[0][e];
156
+ const out = { stress: most, deflection: a.deflection[0].most };
157
+ host.writeText(file, JSON.stringify(out));
158
+ return out;
98
159
  }
99
160
 
100
161
  export function momentChecks(s, f, helpers, masses, payload) {
101
- const motion = s.motion, { placeItems, mul, jointValues } = helpers, specs = new Map((s.a.joints || []).map((j) => [j.id, j])), poses = posesOf(s, jointValues), out = {};
102
- const mat = (() => { const n = materialOf(s.project).name; try { return Object.fromEntries(Object.entries(peekRuleSet(n).rules).map(([k, r]) => [k, r.value])); } catch { return null; } })();
162
+ const motion = s.motion,
163
+ { placeItems, mul, jointValues } = helpers,
164
+ specs = new Map((s.a.joints || []).map((j) => [j.id, j])),
165
+ poses = posesOf(s, jointValues),
166
+ out = {};
167
+ const mat = (() => {
168
+ const n = materialOf(s.project).name;
169
+ try {
170
+ return Object.fromEntries(Object.entries(peekRuleSet(n).rules).map(([k, r]) => [k, r.value]));
171
+ } catch {
172
+ return null;
173
+ }
174
+ })();
103
175
  for (const j of motion.joints) {
104
176
  if (j.type !== 'revolute' && j.type !== 'prismatic') continue;
105
177
  if (specs.get(j.id)?._guide) continue; // (a guide's carriage: carriageChecks holds it to its ratings)
106
178
  let worst = null;
107
- for (const p of poses) { const w = placeItems(motion, p.values), L = loadAt(motion, masses, payload, w, j, mul); if (!worst || L.tipping + L.radial / 50 > worst.L.tipping + worst.L.radial / 50) worst = { L, p, w }; }
179
+ for (const p of poses) {
180
+ const w = placeItems(motion, p.values),
181
+ L = loadAt(motion, masses, payload, w, j, mul);
182
+ if (!worst || L.tipping + L.radial / 50 > worst.L.tipping + worst.L.radial / 50) worst = { L, p, w };
183
+ }
108
184
  if (!worst || !worst.L.carried) continue;
109
- const { L, p } = worst, spec = specs.get(j.id) ?? {}, at = L.O, refs = { joint: j.id }, say = `${n3(L.carried * 1000, 0)} g carried: ${n3(L.tipping, 3)} N m tipping, ${n3(L.radial, 2)} N across and ${n3(L.axial, 2)} N along it, worst ${p.label}`, values = { axial: L.axial, radial: L.radial, tipping: L.tipping, carried: L.carried };
185
+ const { L, p } = worst,
186
+ spec = specs.get(j.id) ?? {},
187
+ at = L.O,
188
+ refs = { joint: j.id },
189
+ say = `${n3(L.carried * 1000, 0)} g carried: ${n3(L.tipping, 3)} N m tipping, ${n3(L.radial, 2)} N across and ${n3(L.axial, 2)} N along it, worst ${p.label}`,
190
+ values = { axial: L.axial, radial: L.radial, tipping: L.tipping, carried: L.carried };
110
191
  out[j.id] = { ...values, pose: p.label };
111
192
  if (spec.support?.bearings?.length) {
112
- const rows = spec.support.bearings.map((id) => { const o = s.objects.find((x) => x.id === id); if (!o || !['bearing', 'linear_bearing'].includes(o.bought?.part)) throw new Error(`joint ${j.id}: support names "${id}", which isn't a bought bearing`); const v = o.built.values, W = worst.w[motion.items.findIndex((x) => x[0] === id)]; return { id, bore: v.bore, outer: v.outer_diameter, C0: v.static_rating, along: dot(sub([W[3], W[7], W[11]], L.O), L.Z) }; });
113
- const m = bearingMargin(rows, L), level = m.margin < 1 ? 'fail' : m.margin < 2 ? 'warn' : 'pass';
114
- f(level, `${j.id}: ${say}. ${rows.map((r) => r.id).join(' and ')} take ${n3(m.P0, 1)} N equivalent against ${n3(m.C0, 0)} N static, ${n3(m.margin, 1)} times over`, level === 'pass' ? null : `${j.id}: bearing ${n3(m.margin, 1)}×`, { code: 'joint.moment', at, refs: { ...refs, bearings: rows.map((r) => r.id) }, values: { ...values, equivalent: m.P0, rating: m.C0, margin: m.margin } });
193
+ const rows = spec.support.bearings.map((id) => {
194
+ const o = s.objects.find((x) => x.id === id);
195
+ if (!o || !['bearing', 'linear_bearing'].includes(o.bought?.part))
196
+ throw new Error(`joint ${j.id}: support names "${id}", which isn't a bought bearing`);
197
+ const v = o.built.values,
198
+ W = worst.w[motion.items.findIndex((x) => x[0] === id)];
199
+ return {
200
+ id,
201
+ bore: v.bore,
202
+ outer: v.outer_diameter,
203
+ C0: v.static_rating,
204
+ along: dot(sub([W[3], W[7], W[11]], L.O), L.Z),
205
+ };
206
+ });
207
+ const m = bearingMargin(rows, L),
208
+ level = m.margin < 1 ? 'fail' : m.margin < 2 ? 'warn' : 'pass';
209
+ f(
210
+ level,
211
+ `${j.id}: ${say}. ${rows.map((r) => r.id).join(' and ')} take ${n3(m.P0, 1)} N equivalent against ${n3(m.C0, 0)} N static, ${n3(m.margin, 1)} times over`,
212
+ level === 'pass' ? null : `${j.id}: bearing ${n3(m.margin, 1)}×`,
213
+ {
214
+ code: 'joint.moment',
215
+ at,
216
+ refs: { ...refs, bearings: rows.map((r) => r.id) },
217
+ values: { ...values, equivalent: m.P0, rating: m.C0, margin: m.margin },
218
+ },
219
+ );
115
220
  } else if (spec.support?.clips?.length) {
116
- const clips = spec.support.clips, D = s.num(spec.support.pitch ?? 40) / 2, share = L.axial / clips.length + (L.tipping * 1000 * 2) / (clips.length * D), cell = s.num(spec.support.cell ?? 0.8);
221
+ const clips = spec.support.clips,
222
+ D = s.num(spec.support.pitch ?? 40) / 2,
223
+ share = L.axial / clips.length + (L.tipping * 1000 * 2) / (clips.length * D),
224
+ cell = s.num(spec.support.cell ?? 0.8);
117
225
  let worstClip = null;
118
226
  for (const id of clips) {
119
- const parts = s.parts.filter((x) => x.item === id || x.leaf === id); if (!parts.length) throw new Error(`joint ${j.id}: support names a clip "${id}", which isn't a part`);
120
- const tris = parts.flatMap((x) => x.triangles), r = clipStress(tris, scale(L.Z, -share), mat?.modulus ?? 2500, mat?.poisson ?? 0.36, cell);
227
+ const parts = s.parts.filter((x) => x.item === id || x.leaf === id);
228
+ if (!parts.length) throw new Error(`joint ${j.id}: support names a clip "${id}", which isn't a part`);
229
+ const tris = parts.flatMap((x) => x.triangles),
230
+ r = clipStress(tris, scale(L.Z, -share), mat?.modulus ?? 2500, mat?.poisson ?? 0.36, cell);
121
231
  if (!worstClip || r.stress > worstClip.stress) worstClip = { id, ...r };
122
232
  }
123
- const strength = mat?.strength ?? 30, margin = strength / worstClip.stress, level = margin < 1 ? 'fail' : margin < 2 ? 'warn' : 'pass';
124
- f(level, `${j.id}: ${say}. ${clips.length} printed clips, the worst (${worstClip.id}) at ${n3(worstClip.stress, 2)} MPa against ${strength} MPa (FE on ${cell} mm cells, an estimate), ${n3(margin, 1)} times over`, level === 'pass' ? null : `${j.id}: clip ${n3(margin, 1)}×`, { code: 'joint.moment', at, refs: { ...refs, clips }, values: { ...values, stress: worstClip.stress, strength, margin } });
125
- } else f(s.task && (s.a.gravity || s.task.payload != null) ? 'warn' : 'info', `${j.id}: ${say}, and nothing named takes it: give the joint a "support" (bearings, or printed clips)`, `${j.id}: no support named`, { code: 'joint.moment', at, refs, values });
233
+ const strength = mat?.strength ?? 30,
234
+ margin = strength / worstClip.stress,
235
+ level = margin < 1 ? 'fail' : margin < 2 ? 'warn' : 'pass';
236
+ f(
237
+ level,
238
+ `${j.id}: ${say}. ${clips.length} printed clips, the worst (${worstClip.id}) at ${n3(worstClip.stress, 2)} MPa against ${strength} MPa (FE on ${cell} mm cells, an estimate), ${n3(margin, 1)} times over`,
239
+ level === 'pass' ? null : `${j.id}: clip ${n3(margin, 1)}×`,
240
+ {
241
+ code: 'joint.moment',
242
+ at,
243
+ refs: { ...refs, clips },
244
+ values: { ...values, stress: worstClip.stress, strength, margin },
245
+ },
246
+ );
247
+ } else
248
+ f(
249
+ s.task && (s.a.gravity || s.task.payload != null) ? 'warn' : 'info',
250
+ `${j.id}: ${say}, and nothing named takes it: give the joint a "support" (bearings, or printed clips)`,
251
+ `${j.id}: no support named`,
252
+ { code: 'joint.moment', at, refs, values },
253
+ );
126
254
  }
127
255
  return out;
128
256
  }
@@ -130,103 +258,424 @@ export function momentChecks(s, f, helpers, masses, payload) {
130
258
  // A link bent: held at its parent joint, the carried weight at its far end. δ from the FE, the tilt from a cantilever's
131
259
  // relation (1.5 δ / L), carried on to the tool. Kept in .cache, as this is the slow part.
132
260
  function linkFE(tris, O, far, force, E, nu, cell) {
133
- const key = crypto.createHash('sha256').update(JSON.stringify([tris.length, tris.slice(0, 4), O, far, force, E, cell])).digest('hex').slice(0, 20), file = paths.cache('link', key);
134
- if (!process.env.CAD_NO_CACHE && host.exists(file)) return JSON.parse(host.readText(file));
135
- const { lo, hi } = extent(tris), n = hi.map((h, k) => Math.max(1, Math.ceil((h - lo[k]) / cell)));
136
- const gr = { nx: n[0], ny: n[1], nz: n[2], h: cell }, density = solidFill(tris, gr, lo), g = makeGrid(gr), fixed = new Uint8Array(g.dofs), f = new Float64Array(g.dofs), onPart = new Uint8Array(g.nodes);
137
- for (let e = 0; e < density.length; e++) if (density[e] >= 0.5) for (let k = 0; k < 8; k++) onPart[g.edof[e * 24 + 3 * k] / 3] = 1;
138
- const nodeAt = positions(g), pos = (id) => [lo[0] + nodeAt[id][0], lo[1] + nodeAt[id][1], lo[2] + nodeAt[id][2]];
139
- const R = 3 * cell, held = [], near = [];
140
- for (let id = 0; id < g.nodes; id++) if (onPart[id]) { const p = pos(id); if (norm(sub(p, O)) <= R + 4) held.push(id); if (norm(sub(p, far)) <= R + 4) near.push(id); }
261
+ const key = crypto
262
+ .createHash('sha256')
263
+ .update(JSON.stringify(['surface', tris.length, tris.slice(0, 4), O, far, force, E, cell]))
264
+ .digest('hex')
265
+ .slice(0, 20),
266
+ file = paths.cache('link', key);
267
+ if (!process.env.CAD_NO_CACHE && cached(file)) return JSON.parse(host.readText(file));
268
+ const { lo, hi } = extent(tris),
269
+ n = hi.map((h, k) => Math.max(1, Math.ceil((h - lo[k]) / cell)));
270
+ const gr = { nx: n[0], ny: n[1], nz: n[2], h: cell },
271
+ density = solidFill(tris, gr, lo),
272
+ g = makeGrid(gr),
273
+ fixed = new Uint8Array(g.dofs),
274
+ f = new Float64Array(g.dofs),
275
+ onPart = new Uint8Array(g.nodes);
276
+ for (let e = 0; e < density.length; e++)
277
+ if (density[e] >= 0.5) for (let k = 0; k < 8; k++) onPart[g.edof[e * 24 + 3 * k] / 3] = 1;
278
+ const nodeAt = positions(g),
279
+ pos = (id) => [lo[0] + nodeAt[id][0], lo[1] + nodeAt[id][1], lo[2] + nodeAt[id][2]];
280
+ const R = 3 * cell,
281
+ held = [],
282
+ near = [];
283
+ for (let id = 0; id < g.nodes; id++)
284
+ if (onPart[id]) {
285
+ const p = pos(id);
286
+ if (norm(sub(p, O)) <= R + 4) held.push(id);
287
+ if (norm(sub(p, far)) <= R + 4) near.push(id);
288
+ }
141
289
  if (!held.length || !near.length) return { deflection: 0, cell, missing: true };
142
290
  for (const id of held) for (let k = 0; k < 3; k++) fixed[3 * id + k] = 1;
143
291
  for (const id of near) for (let k = 0; k < 3; k++) f[3 * id + k] = force[k] / near.length;
144
- const size = norm(force), a = analyse({ grid: g, density, material: { E, nu }, fixed, loads: [f] }), out = { deflection: size ? a.compliance[0] / size : 0, stress: Array.from(a.stress[0]).reduce((m, x, e) => (density[e] >= 0.5 && x > m ? x : m), 0), cell };
145
- host.writeText(file, JSON.stringify(out)); return out;
292
+ const size = norm(force),
293
+ a = analyse({ grid: g, density, material: { E, nu }, fixed, loads: [f] }),
294
+ out = {
295
+ deflection: size ? a.compliance[0] / size : 0,
296
+ // its peak stress at the surface (fea's analyse().surface), not at the cells' centres, which read it low
297
+ stress: Array.from(a.surface[0]).reduce((m, x, e) => (density[e] >= 0.5 && x > m ? x : m), 0),
298
+ cell,
299
+ };
300
+ host.writeText(file, JSON.stringify(out));
301
+ return out;
146
302
  }
147
303
 
148
304
  export function deflectionChecks(s, f, helpers, masses, payload) {
149
305
  if (!s.task) return 0;
150
- const motion = s.motion, { placeItems, mul, jointValues } = helpers, { c, r } = sample(s), ids = motion.items.map((x) => x[0]), mat = (() => { try { return Object.fromEntries(Object.entries(peekRuleSet(materialOf(s.project).name).rules).map(([k, x]) => [k, x.value])); } catch { return {}; } })(), E = mat.modulus ?? 2500, nu = mat.poisson ?? 0.36;
151
- const reached = r.samples.filter((x) => x.reachable); if (!reached.length) return 0;
152
- const lever = (x) => norm(sub(x.point, rowsAt(placeItems(motion, jointValues(motion, motion.pose ?? undefined))[0] || [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0], [0, 0, 0])));
153
- const far = reached.reduce((a, b) => (lever(b) > lever(a) ? b : a)), near = reached.reduce((a, b) => (lever(b) < lever(a) ? b : a));
306
+ const motion = s.motion,
307
+ { placeItems, mul, jointValues } = helpers,
308
+ { c, r } = sample(s),
309
+ ids = motion.items.map((x) => x[0]),
310
+ mat = (() => {
311
+ try {
312
+ return Object.fromEntries(
313
+ Object.entries(peekRuleSet(materialOf(s.project).name).rules).map(([k, x]) => [k, x.value]),
314
+ );
315
+ } catch {
316
+ return {};
317
+ }
318
+ })(),
319
+ E = mat.modulus ?? 2500,
320
+ nu = mat.poisson ?? 0.36;
321
+ const reached = r.samples.filter((x) => x.reachable);
322
+ if (!reached.length) return 0;
323
+ const lever = (x) =>
324
+ norm(
325
+ sub(
326
+ x.point,
327
+ rowsAt(
328
+ placeItems(motion, jointValues(motion, motion.pose ?? undefined))[0] || [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0],
329
+ [0, 0, 0],
330
+ ),
331
+ ),
332
+ );
333
+ const far = reached.reduce((a, b) => (lever(b) > lever(a) ? b : a)),
334
+ near = reached.reduce((a, b) => (lever(b) < lever(a) ? b : a));
154
335
  const links = motion.joints.filter((j) => c.names.includes(j.id));
155
336
  const at = (x, label) => {
156
- const v = jointValues(motion, chainSet(motion, c.names, x.q)), W = placeItems(motion, v), rows = [];
157
- let total = 0, carried = 0, tool = x.point, dir = (() => { const g = motion.gravity || [0, 0, -1], l = norm(g); return g.map((q) => q / l); })();
337
+ const v = jointValues(motion, chainSet(motion, c.names, x.q)),
338
+ W = placeItems(motion, v),
339
+ rows = [];
340
+ let total = 0,
341
+ carried = 0,
342
+ tool = x.point,
343
+ dir = (() => {
344
+ const g = motion.gravity || [0, 0, -1],
345
+ l = norm(g);
346
+ return g.map((q) => q / l);
347
+ })();
158
348
  links.forEach((j, i) => {
159
- const group = new Set([j.child]); for (let more = true; more;) { more = false; for (const x of motion.joints) if (x.type === 'fixed' && group.has(x.parent) && !group.has(x.child)) { group.add(x.child); more = true; } } // the link is everything bolted to the joint's child
160
- const parts = s.parts.filter((p) => group.has(ids.indexOf(p.item)) && p.role !== 'support' && p.role !== 'reference'); if (!parts.length) return;
161
- const m = masses.filter((q) => beyond(motion, j, q.item)).reduce((t, q) => t + q.kg, 0) + (payload && beyond(motion, j, payload.item) ? payload.kg : 0);
349
+ const group = new Set([j.child]);
350
+ for (let more = true; more;) {
351
+ more = false;
352
+ for (const x of motion.joints)
353
+ if (x.type === 'fixed' && group.has(x.parent) && !group.has(x.child)) {
354
+ group.add(x.child);
355
+ more = true;
356
+ }
357
+ } // the link is everything bolted to the joint's child
358
+ const parts = s.parts.filter(
359
+ (p) => group.has(ids.indexOf(p.item)) && p.role !== 'support' && p.role !== 'reference',
360
+ );
361
+ if (!parts.length) return;
362
+ const m =
363
+ masses.filter((q) => beyond(motion, j, q.item)).reduce((t, q) => t + q.kg, 0) +
364
+ (payload && beyond(motion, j, payload.item) ? payload.kg : 0);
162
365
  if (!m) return;
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
- 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);
366
+ const O = axisOf(motion, W, j, mul).O,
367
+ nextJ = links[i + 1],
368
+ end = nextJ ? axisOf(motion, W, nextJ, mul).O : tool,
369
+ Wc = W[j.child];
370
+ const local = parts.flatMap((p) => {
371
+ const Wp = W[ids.indexOf(p.item)];
372
+ return p.localTriangles && Wp
373
+ ? p.localTriangles.map((t) => t.map((q) => invAt(Wc, rowsAt(Wp, q))))
374
+ : p.triangles.map((t) => t.map((q) => invAt(Wc, q)));
375
+ }),
376
+ Lo = invAt(Wc, O),
377
+ Le = invAt(Wc, end),
378
+ F = [
379
+ dir[0] * Wc[0] + dir[1] * Wc[4] + dir[2] * Wc[8],
380
+ dir[0] * Wc[1] + dir[1] * Wc[5] + dir[2] * Wc[9],
381
+ dir[0] * Wc[2] + dir[1] * Wc[6] + dir[2] * Wc[10],
382
+ ].map((q) => q * m * G);
165
383
  // 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;
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 });
384
+ const e = extent(local),
385
+ box = [0, 1, 2].map((k) => e.hi[k] - e.lo[k]),
386
+ sup = s.a.joints?.find((x) => x.id === j.id)?.support,
387
+ cell = sup?.linkCell != null ? s.num(sup.linkCell) : Math.max(1, Math.min(4, Math.min(...box) / 3)),
388
+ fe = linkFE(local, Lo, Le, F, E, nu, cell),
389
+ L = norm(sub(Lo, Le)) || 1,
390
+ beyondLength = norm(sub(tool, end)),
391
+ drop = fe.deflection + (1.5 * fe.deflection * beyondLength) / L;
392
+ total += drop;
393
+ carried = Math.max(carried, m);
394
+ rows.push({ link: ids[j.child], deflection: fe.deflection, at_tool: drop, cell: fe.cell, stress: fe.stress });
168
395
  });
169
396
  return { label, total, carried, rows };
170
397
  };
171
- const stretch = at(far, 'at full stretch'), folded = at(near, 'folded'), worst = stretch.total >= folded.total ? stretch : folded;
398
+ const stretch = at(far, 'at full stretch'),
399
+ folded = at(near, 'folded'),
400
+ worst = stretch.total >= folded.total ? stretch : folded;
172
401
  if (!worst.rows.length) return 0;
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 } });
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));
175
- const rings = s.task.speed != null ? ` Expect visible ringing past about ${n3(Math.max(20, low.Hz * 3), 0)} mm/s.` : '';
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 } });
402
+ f(
403
+ 'info',
404
+ `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)`,
405
+ null,
406
+ {
407
+ code: 'link.deflection',
408
+ predict: { name: 'link.deflection', figure: `drop at ${s.task.tool}`, value: worst.total, unit: 'mm' },
409
+ values: { total: worst.total, rows: worst.rows, label: worst.label },
410
+ },
411
+ );
412
+ const finds = [stretch, folded]
413
+ .filter((x) => x.rows.length)
414
+ .map((x) => {
415
+ const k = (x.carried * G) / (x.total || 1e-9),
416
+ Hz = Math.sqrt((k * 1000) / x.carried) / (2 * Math.PI);
417
+ return { ...x, Hz };
418
+ }),
419
+ low = finds.reduce((a, b) => (b.Hz < a.Hz ? b : a));
420
+ const rings =
421
+ s.task.speed != null ? ` Expect visible ringing past about ${n3(Math.max(20, low.Hz * 3), 0)} mm/s.` : '';
422
+ f(
423
+ 'info',
424
+ `the lowest mode is about ${n3(low.Hz, 0)} Hz ${low.label}, from the tool's stiffness and the mass it carries.${rings}`,
425
+ null,
426
+ { code: 'assembly.frequency', values: { Hz: low.Hz, label: low.label } },
427
+ );
177
428
  return worst.total;
178
429
  }
179
430
 
180
- // What the motors can do to the arm's inertia: the worst acceleration at the tool, and the time a move across the task takes
181
- export function accelChecks(s, f, helpers, masses, payload) {
182
- const motion = s.motion, { placeItems, jointValues, mul } = helpers; if (!motion.drives?.length) return null;
183
- const c = s.task ? chainOf(s) : null, names = c ? c.names : motion.joints.filter((j) => !j.follow).map((j) => j.id), base = placeItems(motion, jointValues(motion, motion.pose ?? undefined)), limits = [];
184
- for (const id of names) {
185
- const j = motion.joints.find((x) => x.id === id), t = trainFrom(motion, id), d = motion.drives.find((x) => x.joint === t.root); if (!d) { limits.push(null); continue; }
186
- const axis = axisOf(motion, base, j, mul);
187
- let I = 0, gravity = 0; // kg mm² about the joint
188
- for (const m of masses) if (beyond(motion, j, m.item)) { const X = rowsAt(base[m.item], m.centre), r = sub(X, axis.O), rad = norm(sub(r, scale(axis.Z, dot(r, axis.Z)))); I += m.kg * rad * rad; }
189
- if (payload && beyond(motion, j, payload.item)) { const X = rowsAt(base[payload.item], payload.point), r = sub(X, axis.O), rad = norm(sub(r, scale(axis.Z, dot(r, axis.Z)))); I += payload.kg * rad * rad; }
190
- for (const p of posesOf(s, jointValues).slice(0, 30)) gravity = Math.max(gravity, Math.abs(loadAt(motion, masses, payload, placeItems(motion, p.values), j, mul).torque));
191
- const m = d.model, speed = workingSpeed(m, d.spec, d.supply), ratio = t.ratio, eff = t.efficiency, rotor = (m.figures.rotor_inertia?.value ?? 0) * 0.1, kgmm2 = I / (ratio * ratio * eff) + rotor; // kg mm²
192
- const avail = atCurrent(m, d.spec, performance(m, { speed, supply: d.supply }).motor.torque), left = avail - gravity / (ratio * eff), refs = { joint: id, item: d.id }, at = axis.O;
193
- if (left <= 0) { f('fail', `${id} stalls: ${d.id} gives ${n3(avail, 3)} N m at ${n3(speed, 0)} rpm, and the load takes ${n3(gravity / (ratio * eff), 3)} N m of it through ${n3(ratio, 1)}:1`, `${id}: stalls`, { code: 'motor.accel', at, refs, values: { available: avail, gravity } }); limits.push(0); continue; }
194
- const alphaMotor = (left * 1e6) / kgmm2, alpha = (alphaMotor / ratio) * (180 / Math.PI); // rad/s² at the motor, deg/s² at the joint
195
- limits.push(alpha);
196
- f('info', `${id} can accelerate at ${n3(alpha, 0)} °/s² (reflected inertia ${n3(kgmm2, 1)} kg mm², ${n3(left, 3)} N m left after the load)`, null, { code: 'motor.accel', at, refs, values: { alpha, inertia: kgmm2, torque: left } });
431
+ // The inertia a joint's motor turns and the gravity it holds, both at the joint that leads it: kg mm² and N m. A
432
+ // revolute's masses by their distance from its axis; a slide's through its lever (mm per radian of its lead), so a
433
+ // lead screw's mass reflects as m (lead / 2π)², and the weight along the travel takes the force times the same lever.
434
+ // The inertia reads the masses this joint owns (each counted once along the train); the gravity reads every mass beyond
435
+ // the joint, as motor.torque does: a weight beyond two joints of one train loads the motor through both
436
+ function inertiaAt(motion, carried, loads, j, { base, poses, slide, lever, placeItems, mul, all = carried }) {
437
+ const axis = axisOf(motion, base, j, mul);
438
+ let I = 0,
439
+ gravity = 0;
440
+ for (const m of carried)
441
+ if (beyond(motion, j, m.item)) {
442
+ if (slide) I += m.kg * lever * lever;
443
+ else {
444
+ const r = sub(rowsAt(base[m.item], m.point), axis.O),
445
+ rad = norm(sub(r, scale(axis.Z, dot(r, axis.Z))));
446
+ I += m.kg * rad * rad;
447
+ }
448
+ }
449
+ for (const p of poses) {
450
+ // the weight along the slide, or its moment about the axis, with what is declared on the joint (lib/carried.mjs)
451
+ const q = Math.abs(driveLoadAt(motion, all, loads, placeItems(motion, p.values), j, mul));
452
+ gravity = Math.max(gravity, slide ? (q * lever) / 1000 : q);
453
+ }
454
+ return { I, gravity, at: axis.O };
455
+ }
456
+
457
+ // One joint's motor.accel: the acceleration its motor can give it (°/s², or mm/s² on a slide), 0 where it stalls, null
458
+ // where no motor leads it
459
+ function jointAccel(s, f, { placeItems, mul }, carried, { id, base, poses, loads }) {
460
+ const motion = s.motion,
461
+ j = motion.joints.find((x) => x.id === id),
462
+ t = trainFrom(motion, id),
463
+ d = motion.drives.find((x) => x.joint === t.root);
464
+ if (!d) return null;
465
+ // a slide moves t.slide mm for each degree of the joint that leads it: its lever, in mm per radian
466
+ const leverOf = (x, tx) => (x.type === 'prismatic' && tx.slide != null ? (tx.slide * 180) / Math.PI : null);
467
+ const slide = leverOf(j, t) != null,
468
+ lever = leverOf(j, t),
469
+ at = axisOf(motion, base, j, mul).O;
470
+ // Everything the motor turns: each joint of its train (the gears it drives and what they drive, as motor.torque sums
471
+ // them), each mass's inertia counted once, at the nearest joint of the train up its chain, and its weight at every
472
+ // joint of the train it is beyond, as motor.torque counts it. Summed at the motor's shaft, then
473
+ // given at this joint (through its own ratio), so a single joint reads as it did
474
+ const train = motion.joints.filter((x) => x === j || trainFrom(motion, x.id).root === t.root),
475
+ nearest = (item) => {
476
+ const by = new Map(motion.joints.map((x) => [x.child, x]));
477
+ for (let i = item, n = 0; i >= 0 && n < 99; n++) {
478
+ const x = by.get(i);
479
+ if (!x) return null;
480
+ if (train.includes(x)) return x;
481
+ i = x.parent;
482
+ }
483
+ return null;
484
+ },
485
+ owner = new Map(carried.map((c) => [c, nearest(c.item)]));
486
+ let atMotorI = 0,
487
+ atMotorG = 0;
488
+ for (const x of train) {
489
+ const tx = x === j ? t : trainFrom(motion, x.id),
490
+ lx = leverOf(x, tx),
491
+ q = inertiaAt(
492
+ motion,
493
+ carried.filter((c) => owner.get(c) === x),
494
+ loads,
495
+ x,
496
+ { base, poses, slide: lx != null, lever: lx, placeItems, mul, all: carried },
497
+ );
498
+ atMotorI += q.I / (tx.ratio * tx.ratio * tx.efficiency);
499
+ atMotorG += q.gravity / (tx.ratio * tx.efficiency);
500
+ }
501
+ const m = d.model,
502
+ speed = workingSpeed(m, d.spec, d.supply),
503
+ ratio = t.ratio,
504
+ eff = t.efficiency,
505
+ I = atMotorI * ratio * ratio * eff, // kg mm² at this joint
506
+ gravity = atMotorG * ratio * eff, // N m at the joint that leads it
507
+ rotor = (m.figures.rotor_inertia?.value ?? 0) * 0.1,
508
+ kgmm2 = atMotorI + rotor; // kg mm² at the motor
509
+ const avail = atCurrent(m, d.spec, performance(m, { speed, supply: d.supply }).motor.torque),
510
+ left = avail - atMotorG,
511
+ counted = countedFor(s, carried, loads, j),
512
+ refs = { joint: id, item: d.id };
513
+ if (left <= 0) {
514
+ f(
515
+ 'fail',
516
+ `${id} stalls: ${d.id} gives ${n3(avail, 3)} N m at ${n3(speed, 0)} rpm, and the load takes ${n3(atMotorG, 3)} N m of it through ${slide ? `${n3(t.slide * 360, 2)} mm a turn` : `${n3(ratio, 1)}:1`} (${counted.text})`,
517
+ `${id}: stalls`,
518
+ { code: 'motor.accel', at, refs, values: { available: avail, gravity, counted: counted.values } },
519
+ );
520
+ return 0;
197
521
  }
522
+ const alphaLead = (left * 1e6) / kgmm2 / ratio, // rad/s² at the joint that leads (the motor's, over the ratio)
523
+ alpha = slide ? alphaLead * lever : alphaLead * (180 / Math.PI), // mm/s² along a slide, °/s² about a revolute
524
+ unit = slide ? 'mm/s²' : '°/s²';
525
+ f(
526
+ 'info',
527
+ `${id} can accelerate at ${n3(alpha, 0)} ${unit} (reflected inertia ${n3(kgmm2, 1)} kg mm², ${n3(left, 3)} N m left after the load; ${counted.text})`,
528
+ null,
529
+ {
530
+ code: 'motor.accel',
531
+ at,
532
+ refs,
533
+ values: {
534
+ alpha,
535
+ unit,
536
+ available: avail,
537
+ inertia: kgmm2,
538
+ load: I,
539
+ rotor,
540
+ torque: left,
541
+ gravity,
542
+ counted: counted.values,
543
+ },
544
+ },
545
+ );
546
+ return alpha;
547
+ }
548
+
549
+ // What the motors can do to the arm's inertia: the worst acceleration at the tool, and the time a move across the task
550
+ // takes. The masses are everything the motors lift (lib/motors.mjs carriedMasses: the parts, the bought parts, the
551
+ // declared masses, the task's payload), the sum motor.torque reads too. A revolute's limit is in °/s², a slide's in mm/s².
552
+ export function accelChecks(s, f, helpers, carried) {
553
+ const motion = s.motion,
554
+ { placeItems, jointValues } = helpers;
555
+ if (!motion.drives?.length) return null;
556
+ const c = s.task ? chainOf(s) : null,
557
+ // with no task, one finding a motor, named for the far end of its train (the joint that turns slowest, the reel or
558
+ // the output of its gears), as jointAccel sums the whole train
559
+ names = c
560
+ ? c.names
561
+ : motion.drives
562
+ .map((d) => motion.joints.filter((j) => j.id === d.joint || trainFrom(motion, j.id).root === d.joint))
563
+ .filter((t) => t.length)
564
+ .map(
565
+ (t) =>
566
+ t.reduce((a, b) => (trainFrom(motion, b.id).ratio > trainFrom(motion, a.id).ratio + 1e-9 ? b : a)).id,
567
+ ),
568
+ base = placeItems(motion, s.jointValues ?? jointValues(motion, motion.pose ?? undefined)),
569
+ poses = posesOf(s, jointValues).slice(0, 30),
570
+ loads = motion.loads || [],
571
+ limits = [];
572
+ for (const id of names) limits.push(jointAccel(s, f, helpers, carried, { id, base, poses, loads }));
198
573
  if (!s.task || limits.some((x) => x == null)) return limits;
199
- const { r } = sample(s), frame = s.task.sheet ? s.task : null;
574
+ const { r } = sample(s),
575
+ frame = s.task.sheet ? s.task : null;
200
576
  let worst = Infinity;
201
- for (const x of r.samples) if (x.reachable) {
202
- const J = jacobian(c, x.q), N = names.length, rows = J.map((row) => row.slice(0, N));
203
- for (let d = 0; d < 12; d++) { const th = (d * Math.PI) / 6, v = [Math.cos(th), Math.sin(th), 0], lam = pinv2(rows, v); if (!lam) continue; let k = Infinity; for (let i = 0; i < N; i++) if (Math.abs(lam[i]) > 1e-12) k = Math.min(k, limits[i] / Math.abs(lam[i])); worst = Math.min(worst, k); }
204
- }
577
+ for (const x of r.samples)
578
+ if (x.reachable) {
579
+ const J = jacobian(c, x.q),
580
+ N = names.length,
581
+ rows = J.map((row) => row.slice(0, N));
582
+ for (let d = 0; d < 12; d++) {
583
+ const th = (d * Math.PI) / 6,
584
+ v = [Math.cos(th), Math.sin(th), 0],
585
+ lam = pinv2(rows, v);
586
+ if (!lam) continue;
587
+ let k = Infinity;
588
+ for (let i = 0; i < N; i++) if (Math.abs(lam[i]) > 1e-12) k = Math.min(k, limits[i] / Math.abs(lam[i]));
589
+ worst = Math.min(worst, k);
590
+ }
591
+ }
205
592
  if (worst === Infinity) return limits;
206
- const accel = 0.7 * worst; s.task.accel = s.a.task.accel != null ? s.num(s.a.task.accel) : accel; void frame;
593
+ const accel = 0.7 * worst;
594
+ s.task.accel = s.a.task.accel != null ? s.num(s.a.task.accel) : accel;
595
+ void frame;
207
596
  if (s.task.speed != null) {
208
- const L = s.task.sheet ? Math.hypot(...(() => { const c0 = r.summary.corners; const a = c0[0].point, b = c0[2].point; return sub(a, b); })()) : 100, v = s.task.speed, a = s.task.accel, t = L > (v * v) / a ? v / a + L / v : 2 * Math.sqrt(L / a);
209
- f('info', `a move across the task (${n3(L, 0)} mm) takes ${n3(t, 2)} s, at up to ${n3(worst, 0)} mm/s² at the tool, planned at ${n3(s.task.accel, 0)}`, null, { code: 'task.time', values: { time: t, accel: s.task.accel, limit: worst } });
597
+ const L = s.task.sheet
598
+ ? Math.hypot(
599
+ ...(() => {
600
+ const c0 = r.summary.corners;
601
+ const a = c0[0].point,
602
+ b = c0[2].point;
603
+ return sub(a, b);
604
+ })(),
605
+ )
606
+ : 100,
607
+ v = s.task.speed,
608
+ a = s.task.accel,
609
+ t = L > (v * v) / a ? v / a + L / v : 2 * Math.sqrt(L / a);
610
+ f(
611
+ 'info',
612
+ `a move across the task (${n3(L, 0)} mm) takes ${n3(t, 2)} s, at up to ${n3(worst, 0)} mm/s² at the tool, planned at ${n3(s.task.accel, 0)}`,
613
+ null,
614
+ { code: 'task.time', values: { time: t, accel: s.task.accel, limit: worst } },
615
+ );
210
616
  }
211
617
  return limits;
212
618
  }
213
619
  function pinv2(J, v) {
214
620
  // Minimum-norm joint rates for a tool velocity, from a 2-row or 3-row Jacobian
215
- const R = J.map((r) => r), n = R.length, M = R.map((a) => R.map((b) => a.reduce((t, x, i) => t + x * b[i], 0)));
216
- const y = solveN(M.map((row, i) => [...row, v[i]])); return y && J[0].map((_, i) => R.reduce((t, r, k) => t + r[i] * y[k], 0));
217
- function solveN(A) { const m = A.length; for (let c = 0; c < m; c++) { let p = c; for (let r = c + 1; r < m; r++) if (Math.abs(A[r][c]) > Math.abs(A[p][c])) p = r; [A[c], A[p]] = [A[p], A[c]]; if (Math.abs(A[c][c]) < 1e-9) { A[c][c] = 1e-9; } for (let r = 0; r < m; r++) if (r !== c) { const f = A[r][c] / A[c][c]; for (let k = c; k <= m; k++) A[r][k] -= f * A[c][k]; } } return A.map((r, i) => r[m] / r[i]); }
621
+ const R = J.map((r) => r),
622
+ M = R.map((a) => R.map((b) => a.reduce((t, x, i) => t + x * b[i], 0)));
623
+ const y = solveN(M.map((row, i) => [...row, v[i]]));
624
+ return y && J[0].map((_, i) => R.reduce((t, r, k) => t + r[i] * y[k], 0));
625
+ function solveN(A) {
626
+ const m = A.length;
627
+ for (let c = 0; c < m; c++) {
628
+ let p = c;
629
+ for (let r = c + 1; r < m; r++) if (Math.abs(A[r][c]) > Math.abs(A[p][c])) p = r;
630
+ [A[c], A[p]] = [A[p], A[c]];
631
+ if (Math.abs(A[c][c]) < 1e-9) {
632
+ A[c][c] = 1e-9;
633
+ }
634
+ for (let r = 0; r < m; r++)
635
+ if (r !== c) {
636
+ const f = A[r][c] / A[c][c];
637
+ for (let k = c; k <= m; k++) A[r][k] -= f * A[c][k];
638
+ }
639
+ }
640
+ return A.map((r, i) => r[m] / r[i]);
641
+ }
218
642
  }
219
643
 
220
644
  export function loadChecks(s, f, helpers) {
221
645
  const motion = s.motion;
222
646
  // a guide's carriages are held to their ratings whether or not the machine has a task: they carry what is on them
223
647
  // (the masses' centres read against the frames of the pose the parts were built at, which a pose's own check is)
224
- if (s.guides?.length && motion?.joints?.length) carriageChecks(s, f, helpers, { masses: massesOf(s, { ...helpers, jointValues: (m, p) => s.jointValues ?? helpers.jointValues(m, p) }), beyond, poses: posesOf(s, helpers.jointValues) });
225
- if (!motion?.joints?.length || !(s.task || s.a.gravity)) return;
226
- const masses = massesOf(s, helpers), payload = s.task?.payload ? { kg: s.task.payload, item: motion.items.findIndex((x) => x[0] === s.task.item), point: s.task.point } : null;
648
+ if (s.guides?.length && motion?.joints?.length)
649
+ carriageChecks(s, f, helpers, {
650
+ masses: massesOf(s, { ...helpers, jointValues: (m, p) => s.jointValues ?? helpers.jointValues(m, p) }),
651
+ beyond,
652
+ poses: posesOf(s, helpers.jointValues),
653
+ });
654
+ if (!motion?.joints?.length) return;
655
+ // a driven joint is checked for what its motor can accelerate whether or not the assembly gives a task or gravity:
656
+ // the parts weigh what they weigh, and gravity is down (-Z) unless the assembly says otherwise
657
+ const worlds = helpers.placeItems(motion, s.jointValues ?? helpers.jointValues(motion, motion.pose ?? undefined)),
658
+ carried = motion.drives?.length ? carriedMasses(s, worlds, materialOf(s.project)) : null;
659
+ if (!(s.task || s.a.gravity)) {
660
+ if (carried) accelChecks(s, f, helpers, carried);
661
+ return;
662
+ }
663
+ const masses = massesOf(s, helpers),
664
+ payload = s.task?.payload
665
+ ? { kg: s.task.payload, item: motion.items.findIndex((x) => x[0] === s.task.item), point: s.task.point }
666
+ : null;
227
667
  const unknown = masses.filter((m) => !m.known).map((m) => m.id);
228
- if (unknown.length && s.task) f('warn', `no mass known for ${unknown.join(', ')}: their rule sets give none, so they weigh nothing here`, 'masses unknown', { code: 'joint.moment.mass', refs: { items: unknown } });
668
+ if (unknown.length && s.task)
669
+ f(
670
+ 'warn',
671
+ `no mass known for ${unknown.join(', ')}: their rule sets give none, so they weigh nothing here`,
672
+ 'masses unknown',
673
+ { code: 'joint.moment.mass', refs: { items: unknown } },
674
+ );
229
675
  s.jointLoads = momentChecks(s, f, helpers, masses, payload);
230
- if (s.task?.payload != null || s.a.gravity) { const d = deflectionChecks(s, f, helpers, masses, payload); if (d && s.a.task?.deflection == null) s.task.deflection = d; }
231
- accelChecks(s, f, helpers, masses, payload);
676
+ if (s.task?.payload != null || s.a.gravity) {
677
+ const d = deflectionChecks(s, f, helpers, masses, payload);
678
+ if (d && s.a.task?.deflection == null) s.task.deflection = d;
679
+ }
680
+ if (carried) accelChecks(s, f, helpers, carried);
232
681
  }