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