@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/motors.mjs CHANGED
@@ -11,10 +11,12 @@ import { referenceBuilt } from './bought.mjs';
11
11
  import crypto from 'node:crypto';
12
12
  import { grid as makeGrid, analyse, positions } from '@rulecad/fea';
13
13
  import { threadsBackend } from '@rulecad/fea/threads';
14
- import { host } from './host.mjs';
14
+ import { host, cached } from './host.mjs';
15
15
  import { paths, printerOf } from './workspace.mjs';
16
16
  import { peekRuleSet } from './rules.mjs';
17
+ import { isPlainName } from './names.mjs';
17
18
  import { solidFill } from './optimise.mjs';
19
+ import { axisOf, partMasses, pointMasses, driveLoadAt, countedFor } from './carried.mjs';
18
20
 
19
21
  const require = createRequire(import.meta.url);
20
22
  const n3 = (x, d = 3) => String(Number(x.toFixed(d)));
@@ -23,36 +25,100 @@ const G = 9.80665; // m/s²
23
25
  // A motor item, built: its parts (body and shaft), anchors from its model, its figures as values and rules
24
26
  export function motorBuilt(spec, num, id) {
25
27
  const what = `item ${id}: motor`;
26
- if (!spec || typeof spec !== 'object' || !spec.model) throw new Error(`${what}: give { "model": "nema17", "drives": "<joint>" }`);
27
- const set = Object.fromEntries(Object.entries(spec.set || {}).map(([k, v]) => { if (typeof v !== 'string') return [k, v]; try { return [k, num(v)]; } catch { return [k, v]; } }));
28
- const model = motorModel(spec.model, set), { body, shaft } = motorParts(model);
29
- const parts = named(shaft ? { body, shaft } : { body }, { body: { label: `${model.name} body` }, ...(shaft ? { shaft: { label: `${model.name} shaft` } } : {}) });
30
- const anchors = Object.fromEntries(Object.entries(model.anchors).map(([k, a]) => [k, { at: a.origin, axis: a.axis }]));
31
- const values = Object.fromEntries(Object.entries(model.figures).filter(([, f]) => typeof f.value === 'number').map(([k, f]) => [k, f.value]));
32
- const entries = Object.entries(model.figures).map(([k, f]) => ({ name: `${model.name}.${k}`, value: f.value, unit: f.unit, rule: f.rule, kind: f.kind, source: f.source, checked: f.checked, set: model.name }));
33
- return referenceBuilt({ id, key: 'motor', objName: `motor:${model.name}`, name: model.name, parts, anchors, entries, values, extra: { motor: model, spec, bought: { set: model.name, variant: String(spec.model).toLowerCase() === model.name.toLowerCase() ? null : String(spec.model), part: 'motor', mass: model.mass ?? null } } });
28
+ if (!spec || typeof spec !== 'object' || !spec.model)
29
+ throw new Error(`${what}: give { "model": "nema17", "drives": "<joint>" }`);
30
+ const set = Object.fromEntries(
31
+ Object.entries(spec.set || {}).map(([k, v]) => {
32
+ if (typeof v !== 'string') return [k, v];
33
+ try {
34
+ return [k, num(v)];
35
+ } catch {
36
+ return [k, v];
37
+ }
38
+ }),
39
+ );
40
+ const model = motorModel(spec.model, set),
41
+ { body, shaft } = motorParts(model);
42
+ const parts = named(shaft ? { body, shaft } : { body }, {
43
+ body: { label: `${model.name} body` },
44
+ ...(shaft ? { shaft: { label: `${model.name} shaft` } } : {}),
45
+ });
46
+ const anchors = Object.fromEntries(
47
+ Object.entries(model.anchors).map(([k, a]) => [k, { at: a.origin, axis: a.axis }]),
48
+ );
49
+ const values = Object.fromEntries(
50
+ Object.entries(model.figures)
51
+ .filter(([, f]) => typeof f.value === 'number')
52
+ .map(([k, f]) => [k, f.value]),
53
+ );
54
+ const entries = Object.entries(model.figures).map(([k, f]) => ({
55
+ name: `${model.name}.${k}`,
56
+ value: f.value,
57
+ unit: f.unit,
58
+ rule: f.rule,
59
+ kind: f.kind,
60
+ source: f.source,
61
+ checked: f.checked,
62
+ set: model.name,
63
+ }));
64
+ return referenceBuilt({
65
+ id,
66
+ key: 'motor',
67
+ objName: `motor:${model.name}`,
68
+ name: model.name,
69
+ parts,
70
+ anchors,
71
+ entries,
72
+ values,
73
+ extra: {
74
+ motor: model,
75
+ spec,
76
+ bought: {
77
+ set: model.name,
78
+ variant: String(spec.model).toLowerCase() === model.name.toLowerCase() ? null : String(spec.model),
79
+ part: 'motor',
80
+ mass: model.mass ?? null,
81
+ },
82
+ },
83
+ });
34
84
  }
35
85
 
36
86
  // Which joint each motor drives, checked by name; a servo's range and a stepper's step go on the joint. The shaft
37
87
  // turns in what it drives, so that pair may overlap: the body is still checked against everything.
38
88
  export function motorDrives(a, placed, joints, num) {
39
- const drives = [], taken = new Map();
89
+ const drives = [],
90
+ taken = new Map();
40
91
  placed.forEach(([it, c], k) => {
41
92
  if (!it.motor) return;
42
- const what = `item ${c.id}: motor`, id = it.motor.drives;
43
- if (id == null) { drives.push({ item: k, id: c.id, model: c.src.motor, spec: it.motor, joint: null }); return; } // on the bench, turning nothing
93
+ const what = `item ${c.id}: motor`,
94
+ id = it.motor.drives;
95
+ if (id == null) {
96
+ drives.push({ item: k, id: c.id, model: c.src.motor, spec: it.motor, joint: null });
97
+ return;
98
+ } // on the bench, turning nothing
44
99
  const j = joints.find((x) => x.id === id);
45
- if (!j) throw new Error(`${what}: drives "${id}", which isn't a joint (${joints.map((x) => x.id).join(', ') || 'none'})`);
100
+ if (!j)
101
+ throw new Error(`${what}: drives "${id}", which isn't a joint (${joints.map((x) => x.id).join(', ') || 'none'})`);
46
102
  if (j.type === 'prismatic' && (it.motor.leadscrew || it.motor.belt)) j.slide = slideDrive(it.motor, what, j, num);
47
- else if (j.type !== 'revolute') throw new Error(`${what}: a motor turns a revolute (${j.id} is a ${j.type}): drive the gear and let the slide follow it, or give "leadscrew" or "belt"`);
48
- if (j.follow) throw new Error(`${what}: ${j.id} follows ${j.follow[0]}: a motor drives the joint that leads the train`);
103
+ else if (j.type !== 'revolute')
104
+ throw new Error(
105
+ `${what}: a motor turns a revolute (${j.id} is a ${j.type}): drive the gear and let the slide follow it, or give "leadscrew" or "belt"`,
106
+ );
107
+ if (j.follow)
108
+ throw new Error(`${what}: ${j.id} follows ${j.follow[0]}: a motor drives the joint that leads the train`);
49
109
  if (taken.has(id)) throw new Error(`${what}: ${id} is driven by ${taken.get(id)} already: one motor to a joint`);
50
110
  taken.set(id, c.id);
51
- const model = c.src.motor, spec = (a.joints || []).find((x) => x.id === id);
111
+ const model = c.src.motor,
112
+ spec = (a.joints || []).find((x) => x.id === id);
52
113
  if (model.range != null) {
53
- const half = model.range / 2, d = j.dofs[0];
54
- if (spec.min == null && spec.max == null) { d[0] = -half; d[1] = half; d[2] = Math.min(half, Math.max(-half, d[2])); }
55
- else if (d[0] < -half - 1e-9 || d[1] > half + 1e-9) throw new Error(`${what}: a ${model.name} turns ${model.range}°, and ${j.id} asks for ${d[0]}° to ${d[1]}°`);
114
+ const half = model.range / 2,
115
+ d = j.dofs[0];
116
+ if (spec.min == null && spec.max == null) {
117
+ d[0] = -half;
118
+ d[1] = half;
119
+ d[2] = Math.min(half, Math.max(-half, d[2]));
120
+ } else if (d[0] < -half - 1e-9 || d[1] > half + 1e-9)
121
+ throw new Error(`${what}: a ${model.name} turns ${model.range}°, and ${j.id} asks for ${d[0]}° to ${d[1]}°`);
56
122
  }
57
123
  if (model.stepAngle) j.step = model.stepAngle;
58
124
  drives.push({ item: k, id: c.id, model, spec: it.motor, joint: id });
@@ -64,26 +130,69 @@ export function motorDrives(a, placed, joints, num) {
64
130
  // it holds with the power off. A screw locks when its lead angle is under its friction angle
65
131
  function slideDrive(spec, what, j, num) {
66
132
  if (spec.leadscrew) {
67
- const lead = num(spec.leadscrew.lead), d = num(spec.leadscrew.diameter ?? 8), mu = num(spec.leadscrew.friction ?? 0.2), lambda = Math.atan(lead / (Math.PI * d)), phi = Math.atan(mu);
133
+ const lead = num(spec.leadscrew.lead),
134
+ d = num(spec.leadscrew.diameter ?? 8),
135
+ mu = num(spec.leadscrew.friction ?? 0.2),
136
+ lambda = Math.atan(lead / (Math.PI * d)),
137
+ phi = Math.atan(mu);
68
138
  if (!(lead > 0)) throw new Error(`${what}: a lead screw's lead is above 0 mm (got ${lead})`);
69
- return { kind: 'screw', mmPerTurn: lead, efficiency: Math.tan(lambda) / Math.tan(lambda + phi), locks: lambda < phi ? `the lead screw (its ${n3((lambda * 180) / Math.PI, 1)}° lead is under the ${n3((phi * 180) / Math.PI, 1)}° friction angle)` : null, detail: `a ${lead} mm lead` };
139
+ return {
140
+ kind: 'screw',
141
+ mmPerTurn: lead,
142
+ efficiency: Math.tan(lambda) / Math.tan(lambda + phi),
143
+ locks:
144
+ lambda < phi
145
+ ? `the lead screw (its ${n3((lambda * 180) / Math.PI, 1)}° lead is under the ${n3((phi * 180) / Math.PI, 1)}° friction angle)`
146
+ : null,
147
+ detail: `a ${lead} mm lead`,
148
+ };
70
149
  }
71
- const pitch = num(spec.belt.pitch ?? 2), teeth = num(spec.belt.teeth);
150
+ const pitch = num(spec.belt.pitch ?? 2),
151
+ teeth = num(spec.belt.teeth);
72
152
  if (!(teeth > 0)) throw new Error(`${what}: a belt needs its pulley's "teeth"`);
73
- return { kind: 'belt', mmPerTurn: teeth * pitch, efficiency: 0.95, locks: null, detail: `a ${teeth} T pulley`, stretch: spec.belt.stiffness != null ? { k: num(spec.belt.stiffness), width: num(spec.belt.width ?? 6), length: num(spec.belt.length ?? 300), load: num(spec.belt.load ?? 5) } : null };
153
+ return {
154
+ kind: 'belt',
155
+ mmPerTurn: teeth * pitch,
156
+ efficiency: 0.95,
157
+ locks: null,
158
+ detail: `a ${teeth} T pulley`,
159
+ stretch:
160
+ spec.belt.stiffness != null
161
+ ? {
162
+ k: num(spec.belt.stiffness),
163
+ width: num(spec.belt.width ?? 6),
164
+ length: num(spec.belt.length ?? 300),
165
+ load: num(spec.belt.load ?? 5),
166
+ }
167
+ : null,
168
+ };
74
169
  }
75
170
 
76
171
  // The fits a motor brings with it, in the assembly's own shape
77
- export const shaftFits = (drives, joints, ids) => drives.filter((d) => d.joint && d.model.shaft.length).map((d) => ({ a: `${d.id}.shaft`, b: ids[joints.find((j) => j.id === d.joint).child], min: -1000, silent: true }));
172
+ export const shaftFits = (drives, joints, ids) =>
173
+ drives
174
+ .filter((d) => d.joint && d.model.shaft.length)
175
+ .map((d) => ({ a: `${d.id}.shaft`, b: ids[joints.find((j) => j.id === d.joint).child], min: -1000, silent: true }));
78
176
 
79
177
  // "loads": [{ "joint": "elbow", "torque": 0.5 }, { "joint": "slide", "force": 12 }, { "mass": 0.2, "at": "forearm.tip" }]
80
178
  export function loadsOf(a, anchor, num, joints) {
81
179
  return (a.loads || []).map((l, i) => {
82
180
  const what = `load ${i + 1}`;
83
- if (l.mass != null) { if (l.at == null) throw new Error(`${what}: a mass needs "at", an anchor on what carries it`); const m = num(l.mass); if (!(m > 0)) throw new Error(`${what}: mass is above 0 kg (got ${m})`); return { mass: m, ...anchor(l.at, what), note: l.note }; }
181
+ if (l.mass != null) {
182
+ if (l.at == null) throw new Error(`${what}: a mass needs "at", an anchor on what carries it`);
183
+ const m = num(l.mass);
184
+ if (!(m > 0)) throw new Error(`${what}: mass is above 0 kg (got ${m})`);
185
+ return { mass: m, ...anchor(l.at, what), note: l.note };
186
+ }
84
187
  const j = joints.find((x) => x.id === l.joint);
85
- if (!j) throw new Error(`${what}: give a "mass" and "at", or a "joint" with its "torque" or "force" (joints: ${joints.map((x) => x.id).join(', ')})`);
86
- if (j.type === 'prismatic' ? l.force == null : l.torque == null) throw new Error(`${what}: ${j.id} is a ${j.type}, so give its ${j.type === 'prismatic' ? 'force (N)' : 'torque (N m)'}`);
188
+ if (!j)
189
+ throw new Error(
190
+ `${what}: give a "mass" and "at", or a "joint" with its "torque" or "force" (joints: ${joints.map((x) => x.id).join(', ')})`,
191
+ );
192
+ if (j.type === 'prismatic' ? l.force == null : l.torque == null)
193
+ throw new Error(
194
+ `${what}: ${j.id} is a ${j.type}, so give its ${j.type === 'prismatic' ? 'force (N)' : 'torque (N m)'}`,
195
+ );
87
196
  return { joint: j.id, value: num(j.type === 'prismatic' ? l.force : l.torque), note: l.note };
88
197
  });
89
198
  }
@@ -92,153 +201,425 @@ export function loadsOf(a, anchor, num, joints) {
92
201
  // Walks up the follow links from a joint to the one that leads it: the turns of that lead per turn of this joint
93
202
  // (or per mm, where the joint slides), the share of power that gets through, what's in the way.
94
203
  export function trainFrom(motion, id) {
95
- const stages = [], meshes = motion.meshes || [];
96
- let j = motion.joints.find((x) => x.id === id), ratio = 1, efficiency = 1, slide = j.type === 'prismatic' ? 1 : null, locks = null;
97
- if (j.slide) return { root: j.id, ratio: 1, efficiency: j.slide.efficiency, stages: [{ joint: j.id, kind: j.slide.kind, ratio: 1, efficiency: j.slide.efficiency }], slide: j.slide.mmPerTurn / 360, locks: j.slide.locks };
204
+ const stages = [],
205
+ meshes = motion.meshes || [];
206
+ let j = motion.joints.find((x) => x.id === id),
207
+ ratio = 1,
208
+ efficiency = 1,
209
+ slide = j.type === 'prismatic' ? 1 : null,
210
+ locks = null;
211
+ if (j.slide)
212
+ return {
213
+ root: j.id,
214
+ ratio: 1,
215
+ efficiency: j.slide.efficiency,
216
+ stages: [{ joint: j.id, kind: j.slide.kind, ratio: 1, efficiency: j.slide.efficiency }],
217
+ slide: j.slide.mmPerTurn / 360,
218
+ locks: j.slide.locks,
219
+ };
98
220
  while (j.follow) {
99
- const [lead, r] = j.follow, m = meshes.find((x) => x.joint === j.id) || meshes.find((x) => x.planetary && (x.members || []).includes(j.id));
221
+ const [lead, r] = j.follow,
222
+ m = meshes.find((x) => x.joint === j.id) || meshes.find((x) => x.planetary && (x.members || []).includes(j.id));
100
223
  const kind = m?.kind === 'external' ? 'spur' : m?.kind || 'spur';
101
224
  const eff = m?.efficiency ?? stageEfficiency(kind, kind === 'worm' ? { worm: m.worm } : {});
102
- efficiency *= eff; stages.push({ joint: j.id, kind, ratio: r, efficiency: eff });
103
- if (kind === 'worm' && m.worm.locks) locks = `the worm (its ${n3(m.worm.leadAngle, 1)}° lead is under the friction angle)`;
104
- if (slide != null && stages.length === 1) slide = Math.abs(r); // mm of slide for each degree of the gear
225
+ efficiency *= eff;
226
+ stages.push({ joint: j.id, kind, ratio: r, efficiency: eff });
227
+ if (kind === 'worm' && m.worm.locks)
228
+ locks = `the worm (its ${n3(m.worm.leadAngle, 1)}° lead is under the friction angle)`;
229
+ if (slide != null && stages.length === 1)
230
+ slide = Math.abs(r); // mm of slide for each degree of the gear
105
231
  else ratio *= 1 / Math.abs(r);
106
232
  j = motion.joints.find((x) => x.id === lead);
107
233
  }
108
234
  return { root: j.id, ratio, efficiency, stages, slide, locks };
109
235
  }
110
236
 
111
- // World axis of a joint and the world position of a point on an item
112
- 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]);
113
- export const axisOf = (motion, worlds, j, mul) => { const P = j.parent < 0 ? j.a : mul(worlds[j.parent], j.a); return { O: [P[3], P[7], P[11]], Z: [P[2], P[6], P[10]] }; };
114
- const sub = (a, b) => a.map((x, i) => x - b[i]), dot = (a, b) => a[0] * b[0] + a[1] * b[1] + a[2] * b[2];
237
+ // The world position of a point on an item (a joint's axis, the masses it carries and their sum: lib/carried.mjs)
238
+ const rowsAt = (W, p) =>
239
+ [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]);
240
+ export { axisOf };
241
+ const sub = (a, b) => a.map((x, i) => x - b[i]),
242
+ dot = (a, b) => a[0] * b[0] + a[1] * b[1] + a[2] * b[2];
115
243
  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]];
116
244
 
117
- // The load at one joint, at one set of joint values (N m on a revolute, N on a slide), from every mass carried beyond it
118
- function loadAt(motion, loads, worlds, j, mul) {
119
- const { O, Z } = axisOf(motion, worlds, j, mul), byChild = new Map(motion.joints.map((x) => [x.child, x]));
120
- const beyond = (k) => { for (let i = k, n = 0; i >= 0 && n < 99; n++) { const x = byChild.get(i); if (!x) return false; if (x === j) return true; i = x.parent; } return false; };
121
- let total = 0, push = 0;
122
- for (const l of loads) {
123
- if (l.joint === j.id && l.belt) push += Math.abs(l.value);
124
- else if (l.joint === j.id) total += l.value;
125
- else if (l.mass != null && beyond(l.item)) {
126
- const X = rowsAt(worlds[l.item], [l.frame[3], l.frame[7], l.frame[11]]), g = motion.gravity || [0, 0, -1], F = g.map((c) => (c * l.mass * G) / Math.hypot(...g));
127
- total += j.type === 'prismatic' ? dot(Z, F) : dot(Z, cross(sub(X, O), F)) / 1000;
245
+ // The worst load on a joint (N m, or N on a slide): at each named pose, and with the motor run through its range. The
246
+ // masses are everything the machine carries (pointMasses: its parts, the declared masses, the task's payload); the loads
247
+ // are the torques and forces declared on joints
248
+ function worstLoad(motion, masses, loads, j, drive, { placeItems, jointValues, mul }) {
249
+ let worst = 0,
250
+ where = null;
251
+ const look = (values, label) => {
252
+ const t = driveLoadAt(motion, masses, loads, placeItems(motion, values), j, mul);
253
+ if (Math.abs(t) > Math.abs(worst)) {
254
+ worst = t;
255
+ where = label;
128
256
  }
129
- }
130
- // (a belt's push at the carriage's acceleration goes either way along the travel, so it adds to the rest in the
131
- // direction that makes it worse: on a vertical axis, the weight plus the push upward, never the weight less it)
132
- return push ? total + (total < 0 ? -push : push) : total;
133
- }
134
-
135
- // The worst load on a joint: at each named pose, and with the motor run through its range
136
- function worstLoad(motion, loads, j, drive, { placeItems, jointValues, mul }) {
137
- let worst = 0, where = null;
138
- const look = (values, label) => { const t = loadAt(motion, loads, placeItems(motion, values), j, mul); if (Math.abs(t) > Math.abs(worst)) { worst = t; where = label; } };
257
+ };
139
258
  const poses = Object.keys(motion.poses || {});
140
259
  for (const p of poses.length ? poses : [null]) look(jointValues(motion, p ?? undefined), p);
141
260
  const root = drive && motion.joints.find((x) => x.id === drive.joint);
142
261
  if (root) {
143
- const base = jointValues(motion, motion.pose ?? undefined), [lo, hi] = root.dofs[0];
144
- for (let k = 0; k <= 24; k++) { const a = lo + ((hi - lo) * k) / 24, set = Object.fromEntries(Object.entries(base).filter(([id]) => !motion.joints.find((x) => x.id === id)?.follow)); look(jointValues(motion, { ...set, [root.id]: [a] }), `${root.id} at ${n3(a, 1)}°`); }
262
+ const base = jointValues(motion, motion.pose ?? undefined),
263
+ [lo, hi] = root.dofs[0];
264
+ for (let k = 0; k <= 24; k++) {
265
+ const a = lo + ((hi - lo) * k) / 24,
266
+ set = Object.fromEntries(
267
+ Object.entries(base).filter(([id]) => !motion.joints.find((x) => x.id === id)?.follow),
268
+ );
269
+ look(jointValues(motion, { ...set, [root.id]: [a] }), `${root.id} at ${n3(a, 1)}°`);
270
+ }
145
271
  }
146
272
  return { torque: Math.abs(worst), where };
147
273
  }
148
274
 
149
275
  // What a stepper gives at the current it's set to: torque goes with the current, up to its rating
150
- export const atCurrent = (m, spec, torque) => (m.type === 'stepper' && spec.current != null && m.figures.rated_current?.value ? torque * Math.min(1, spec.current / m.figures.rated_current.value) : torque);
276
+ export const atCurrent = (m, spec, torque) =>
277
+ m.type === 'stepper' && spec.current != null && m.figures.rated_current?.value
278
+ ? torque * Math.min(1, spec.current / m.figures.rated_current.value)
279
+ : torque;
151
280
 
152
281
  /**
153
282
  * The torque a motor puts on its own screws, as a reaction about its shaft: what it gives at its working speed (the
154
283
  * assembly's, else workingSpeed), at the current it's set to. motor.torque, motor.mount and fasten.load all read this one.
155
284
  * @param {{ model: object, spec: object }} d a drive (an assembly's motor item) @returns {number} N m
156
285
  */
157
- export const mountTorque = (d) => atCurrent(d.model, d.spec, performance(d.model, { speed: workingSpeed(d.model, d.spec, d.supply), supply: d.supply }).motor.torque);
286
+ export const mountTorque = (d) =>
287
+ atCurrent(
288
+ d.model,
289
+ d.spec,
290
+ performance(d.model, { speed: workingSpeed(d.model, d.spec, d.supply), supply: d.supply }).motor.torque,
291
+ );
158
292
 
159
293
  // A motor's speed if the assembly doesn't say: its corner speed, its rated speed, or half its free speed (a stepper's
160
294
  // at its driver's supply, volts: the assembly's, else the package's default)
161
295
  export function workingSpeed(model, spec, supply) {
162
296
  if (spec.speed != null) return spec.speed;
163
297
  const p = performance(model, { supply });
164
- return model.type === 'dc' ? p.limit / 2 : model.figures.pull_in_torque ? p.limit : model.type === 'servo' ? p.limit : model.type === 'brushless' ? p.limit / 4 : p.limit / 5;
298
+ return model.type === 'dc'
299
+ ? p.limit / 2
300
+ : model.figures.pull_in_torque
301
+ ? p.limit
302
+ : model.type === 'servo'
303
+ ? p.limit
304
+ : model.type === 'brushless'
305
+ ? p.limit / 4
306
+ : p.limit / 5;
307
+ }
308
+
309
+ const material = (name) => {
310
+ const n = String(name || 'pla')
311
+ .toLowerCase()
312
+ .split(/\s/)[0];
313
+ if (!isPlainName(n)) return null;
314
+ try {
315
+ // (a name from project.json: never a path out of the kit's rules)
316
+ return {
317
+ name: n,
318
+ ...Object.fromEntries(Object.entries(require(`@rulecad/rules/${n}.json`).rules).map(([k, r]) => [k, r.value])),
319
+ };
320
+ } catch {
321
+ return null;
322
+ }
323
+ };
324
+
325
+ // g/cm³ of what the project prints in: given (lib/list.mjs materialOf), or from its rule set by name; PLA's 1.25 when
326
+ // neither says, as materialOf assumes
327
+ function densityOf(printed) {
328
+ if (typeof printed === 'object' && printed?.density > 0) return printed.density;
329
+ const n = String((typeof printed === 'object' ? printed?.name : printed) || 'pla')
330
+ .toLowerCase()
331
+ .split(/\s/)[0];
332
+ try {
333
+ const d = isPlainName(n) ? peekRuleSet(n).rules.density?.value : null;
334
+ return d > 0 ? d : 1.25;
335
+ } catch {
336
+ return 1.25;
337
+ }
165
338
  }
166
339
 
167
- const material = (name) => { const n = String(name || 'pla').toLowerCase().split(/\s/)[0]; try { return { name: n, ...Object.fromEntries(Object.entries(require(`@rulecad/rules/${n}.json`).rules).map(([k, r]) => [k, r.value])) }; } catch { return null; } };
340
+ /**
341
+ * Everything an assembly's motors lift, as points on its items: the parts as drawn and the bought parts (their centres
342
+ * read against the frames the parts were built at), the declared masses and the task's payload. motorChecks and
343
+ * motor.accel (lib/loads.mjs) both read this, so they count the same weight.
344
+ * @param {object} s a built assembly @param {number[][]} worlds each item's world matrix as the parts were built
345
+ * @param {{ density?: number } | string} [printed] the project's material (lib/list.mjs materialOf, or its name)
346
+ */
347
+ export function carriedMasses(s, worlds, printed) {
348
+ return pointMasses(s, partMasses(s, worlds, densityOf(printed)));
349
+ }
168
350
 
169
351
  // The findings: f(level, text, card, extra), as the assembly's check makes them
170
352
  export function motorChecks(s, f, helpers, materialName) {
171
- const motion = s.motion, drives = motion?.drives || [], loads = motion?.loads || [], { placeItems, jointValues, mul } = helpers;
172
- if (!drives.length) { if (loads.length && !s.a.fasten?.length) f('warn', `there are loads, but no motor: nothing has been checked against them (add a "motor" item that "drives" a joint)`, null, { code: 'motor.loads' }); return; }
353
+ const motion = s.motion,
354
+ drives = motion?.drives || [],
355
+ loads = motion?.loads || [],
356
+ { placeItems, jointValues, mul } = helpers;
357
+ if (!drives.length) {
358
+ if (loads.length && !s.a.fasten?.length)
359
+ f(
360
+ 'warn',
361
+ `there are loads, but no motor: nothing has been checked against them (add a "motor" item that "drives" a joint)`,
362
+ null,
363
+ { code: 'motor.loads' },
364
+ );
365
+ return;
366
+ }
173
367
  const worlds = placeItems(motion, s.jointValues ?? jointValues(motion, motion.pose ?? undefined));
368
+ // everything the motors lift: the parts as drawn (their frames as built), the bought parts, the declared masses and the
369
+ // task's payload, under gravity (down, -Z, when the assembly gives none). motor.accel reads the same (lib/loads.mjs)
370
+ const masses = carriedMasses(s, worlds, materialName);
174
371
  for (const d of drives) {
175
- const m = d.model, grams = n3(m.mass * 1000, 1), K = d.spec.margin != null ? d.spec.margin : 2, W = worlds[d.item];
176
- f('info', `${d.id}: ${m.name}, ${grams} g${d.joint ? `, drives ${d.joint}` : ''}${m.stepAngle ? `, ${n3(m.stepAngle, 4)}° a step` : ''}${m.range ? `, ${m.range}° of travel` : ''}`, null, { code: 'motor.model', refs: { item: d.id, joint: d.joint }, values: { model: m.name, grams: m.mass * 1000, stepAngle: m.stepAngle } });
372
+ const m = d.model,
373
+ grams = n3(m.mass * 1000, 1),
374
+ K = d.spec.margin != null ? d.spec.margin : 2,
375
+ W = worlds[d.item];
376
+ f(
377
+ 'info',
378
+ `${d.id}: ${m.name}, ${grams} g${d.joint ? `, drives ${d.joint}` : ''}${m.stepAngle ? `, ${n3(m.stepAngle, 4)}° a step` : ''}${m.range ? `, ${m.range}° of travel` : ''}`,
379
+ null,
380
+ {
381
+ code: 'motor.model',
382
+ refs: { item: d.id, joint: d.joint },
383
+ values: { model: m.name, grams: m.mass * 1000, stepAngle: m.stepAngle },
384
+ },
385
+ );
177
386
  if (!d.joint) continue;
178
387
  // Its shaft on the joint's axis
179
- const j = motion.joints.find((x) => x.id === d.joint), { O, Z } = axisOf(motion, worlds, j, mul), S = rowsAt(W, m.anchors.shaft.origin), A = [W[2], W[6], W[10]];
180
- const off = cross(sub(S, O), Z), apart = Math.hypot(...off), tilt = Math.abs(1 - Math.abs(dot(A, Z)));
388
+ const j = motion.joints.find((x) => x.id === d.joint),
389
+ { O, Z } = axisOf(motion, worlds, j, mul),
390
+ S = rowsAt(W, m.anchors.shaft.origin),
391
+ A = [W[2], W[6], W[10]];
392
+ const off = cross(sub(S, O), Z),
393
+ apart = Math.hypot(...off),
394
+ tilt = Math.abs(1 - Math.abs(dot(A, Z)));
181
395
  // (a belt's pulley turns square to the slide, the belt's line tangent to it: belt.line holds that line; a check drawn
182
396
  // with the motor on the slide's axis, as before, still passes)
183
- if (j.slide?.kind === 'belt' && Math.abs(dot(A, Z)) < 1e-6) { f('pass', `${d.id}'s shaft turns square to ${d.joint}'s travel, as a belt's pulley does`, null, { code: 'motor.axis', at: S }); }
184
- else if (apart > 0.05 || tilt > 1e-6) { f('fail', `${d.id}'s shaft isn't on ${d.joint}'s axis: ${n3(apart, 2)} mm off${tilt > 1e-6 ? ', and not parallel to it' : ''}`, `${d.id}: shaft off axis`, { code: 'motor.axis', at: S, refs: { item: d.id, joint: d.joint } }); continue; }
185
- else f('pass', `${d.id}'s shaft is on ${d.joint}'s axis`, null, { code: 'motor.axis', at: S });
397
+ if (j.slide?.kind === 'belt' && Math.abs(dot(A, Z)) < 1e-6) {
398
+ f('pass', `${d.id}'s shaft turns square to ${d.joint}'s travel, as a belt's pulley does`, null, {
399
+ code: 'motor.axis',
400
+ at: S,
401
+ });
402
+ } else if (apart > 0.05 || tilt > 1e-6) {
403
+ f(
404
+ 'fail',
405
+ `${d.id}'s shaft isn't on ${d.joint}'s axis: ${n3(apart, 2)} mm off${tilt > 1e-6 ? ', and not parallel to it' : ''}`,
406
+ `${d.id}: shaft off axis`,
407
+ { code: 'motor.axis', at: S, refs: { item: d.id, joint: d.joint } },
408
+ );
409
+ continue;
410
+ } else f('pass', `${d.id}'s shaft is on ${d.joint}'s axis`, null, { code: 'motor.axis', at: S });
186
411
  // Everything it drives that carries a load
187
- const driven = motion.joints.filter((x) => trainFrom(motion, x.id).root === d.joint).map((x) => ({ j: x, t: trainFrom(motion, x.id), load: worstLoad(motion, loads, x, d, helpers) })).filter((x) => x.load.torque > 0);
188
- const motorSpeed = workingSpeed(m, d.spec, d.supply), loaded = driven.length ? driven : [];
412
+ const driven = motion.joints
413
+ .filter((x) => trainFrom(motion, x.id).root === d.joint)
414
+ .map((x) => ({ j: x, t: trainFrom(motion, x.id), load: worstLoad(motion, masses, loads, x, d, helpers) }))
415
+ .filter((x) => x.load.torque > 1e-9);
416
+ const motorSpeed = workingSpeed(m, d.spec, d.supply),
417
+ loaded = driven.length ? driven : [];
189
418
  if (!loaded.length) {
190
419
  const here = performance(m, { speed: motorSpeed, supply: d.supply });
191
- f('info', `${d.id} gives ${n3(here.motor.torque)} N m at ${n3(motorSpeed, 1)} rpm; no loads on what it drives, so nothing to check that against (add "loads")`, null, { code: 'motor.torque' });
420
+ f(
421
+ 'info',
422
+ `${d.id} gives ${n3(here.motor.torque)} N m at ${n3(motorSpeed, 1)} rpm; nothing it drives is pushed along its motion (${countedFor(s, masses, loads, j).text}), so nothing to check that against (add "loads" for what it works against)`,
423
+ null,
424
+ { code: 'motor.torque', values: { counted: countedFor(s, masses, loads, j).values } },
425
+ );
192
426
  continue;
193
427
  }
194
428
  // Reflected to the motor's own shaft: what each load needs of it, and what it would take to hold against it
195
- let need = 0, back = 0, backOn = 0;
196
- const lines = [], at = (x) => axisOf(motion, worlds, x, mul).O;
429
+ let need = 0,
430
+ back = 0,
431
+ backOn = 0;
432
+ const lines = [],
433
+ at = (x) => axisOf(motion, worlds, x, mul).O;
197
434
  let locked = null;
198
435
  for (const { j: x, t, load } of loaded) {
199
436
  // the lead's torque for a load here: a slide's force through the pinion, a revolute's torque down the ratio; what
200
437
  // holds it still reads only the loads there at rest (a belt's push at the carriage's acceleration is not, lib/belts.mjs)
201
- const lead = (q) => (t.slide != null ? (q * t.slide * 180) / Math.PI / 1000 : q), atLead = lead(load.torque);
202
- const still = loads.some((l) => l.belt && l.joint === x.id) ? lead(worstLoad(motion, loads.filter((l) => !l.belt), x, d, helpers).torque) : atLead;
203
- const unit = t.slide != null ? 'N' : 'N m', reduction = t.ratio;
204
- const η = t.efficiency, needed = atLead / (reduction * η);
205
- need += needed; const ηback = Math.max(0, 2 - 1 / η);
438
+ const lead = (q) => (t.slide != null ? (q * t.slide * 180) / Math.PI / 1000 : q),
439
+ atLead = lead(load.torque);
440
+ const still = loads.some((l) => l.belt && l.joint === x.id)
441
+ ? lead(
442
+ worstLoad(
443
+ motion,
444
+ masses,
445
+ loads.filter((l) => !l.belt),
446
+ x,
447
+ d,
448
+ helpers,
449
+ ).torque,
450
+ )
451
+ : atLead;
452
+ const unit = t.slide != null ? 'N' : 'N m',
453
+ reduction = t.ratio;
454
+ const η = t.efficiency,
455
+ needed = atLead / (reduction * η);
456
+ need += needed;
457
+ const ηback = Math.max(0, 2 - 1 / η);
206
458
  if (t.locks) locked = t.locks;
207
- else if (η <= 0.5) locked = `the gears (${n3(η * 100, 0)}% forwards, under the 50% where they can't be driven backwards)`;
208
- back += (still / reduction) * ηback; backOn += still / reduction;
209
- lines.push({ x, t, load, unit, reduction, atLead, η });
459
+ else if (η <= 0.5)
460
+ locked = `the gears (${n3(η * 100, 0)}% forwards, under the 50% where they can't be driven backwards)`;
461
+ back += (still / reduction) * ηback;
462
+ backOn += still / reduction;
463
+ lines.push({ x, t, load, unit, reduction, atLead, η, needed });
210
464
  }
211
- const speedOut = motorSpeed / loaded[0].t.ratio, rated = performance(m, { speed: motorSpeed, supply: d.supply }), avail = mountTorque(d), margin = need ? avail / need : Infinity;
212
- const main = lines[0], what = main.unit === 'N m' ? `${n3(main.load.torque)} N m` : `${n3(main.load.torque, 2)} N`, gives = main.unit === 'N m' ? `${n3(avail * main.reduction * main.η)} N m` : `${n3((avail * main.reduction * main.η * Math.PI * 1000) / (main.t.slide * 180), 1)} N`;
213
- const trust = rated.rests.filter((k) => k !== 'spec' && k !== 'measured'), caveat = trust.length ? ` (rests on ${trust.join(' and ')} figures: measure it)` : '';
214
- const level = margin < 1 ? 'fail' : margin < K ? 'warn' : 'pass', fix = margin < 1 && main.t.slide == null ? ` A ratio of ${n3((main.reduction * K) / margin, 1)}:1 would give it ${K} times` : '';
215
- f(level, `${d.id} into ${main.x.id}${lines.length > 1 ? ` and ${lines.length - 1} more` : ''}: ${gives} there against ${what} needed${main.load.where ? ` (worst: ${main.load.where})` : ''}, ${n3(margin, 2)} times over${d.supply ? `, at ${n3(motorSpeed, 1)} rpm on its supply's ${n3(d.supply, 1)} V` : ''}${caveat}.${fix}`, level === 'pass' ? null : `${d.id}: ${n3(margin, 2)}× torque`, { code: 'motor.torque', at: at(main.x), refs: { item: d.id, joint: main.x.id }, values: { available: avail * main.reduction * main.η, needed: main.load.torque, margin, ...(d.supply ? { supply: d.supply, rpm: motorSpeed } : {}) } });
216
- if (d.spec.speed != null && performance(m, { speed: motorSpeed, supply: d.supply }).findings.some((x) => x.code === 'motor.speed')) f('fail', `${d.id} is asked for ${motorSpeed} rpm, past what a ${m.name} does`, `${d.id}: too fast`, { code: 'motor.speed', refs: { item: d.id } });
465
+ const speedOut = motorSpeed / loaded[0].t.ratio,
466
+ rated = performance(m, { speed: motorSpeed, supply: d.supply }),
467
+ avail = mountTorque(d),
468
+ margin = need ? avail / need : Infinity;
469
+ // what reaches the loaded joint, in its own unit: N m about a revolute, N along a slide (the torque at the slide's
470
+ // lead over its mm per radian)
471
+ // the finding names the joint that asks most of the motor (now that the parts' own weight is counted, a gear on the
472
+ // motor's shaft carries a little load of its own, and would otherwise be named with 0 N m needed)
473
+ const main = lines.reduce((a, b) => (b.needed > a.needed ? b : a)),
474
+ atJoint = avail * main.reduction * main.η,
475
+ available = main.unit === 'N m' ? atJoint : (atJoint * Math.PI * 1000) / (main.t.slide * 180),
476
+ what = main.unit === 'N m' ? `${n3(main.load.torque)} N m` : `${n3(main.load.torque, 2)} N`,
477
+ gives = main.unit === 'N m' ? `${n3(available)} N m` : `${n3(available, 1)} N`,
478
+ counted = countedFor(s, masses, loads, main.x);
479
+ const trust = rated.rests.filter((k) => k !== 'spec' && k !== 'measured'),
480
+ caveat = trust.length ? ` (rests on ${trust.join(' and ')} figures: measure it)` : '';
481
+ const level = margin < 1 ? 'fail' : margin < K ? 'warn' : 'pass',
482
+ fix =
483
+ margin < 1 && main.t.slide == null
484
+ ? ` A ratio of ${n3((main.reduction * K) / margin, 1)}:1 would give it ${K} times`
485
+ : '';
486
+ f(
487
+ level,
488
+ `${d.id} into ${main.x.id}${lines.length > 1 ? ` and ${lines.length - 1} more` : ''}: ${gives} there against ${what} needed${main.load.where ? ` (worst: ${main.load.where})` : ''}, ${n3(margin, 2)} times over${d.supply ? `, at ${n3(motorSpeed, 1)} rpm on its supply's ${n3(d.supply, 1)} V` : ''}${caveat}; ${counted.text}.${fix}`,
489
+ level === 'pass' ? null : `${d.id}: ${n3(margin, 2)}× torque`,
490
+ {
491
+ code: 'motor.torque',
492
+ at: at(main.x),
493
+ refs: { item: d.id, joint: main.x.id },
494
+ values: {
495
+ available,
496
+ needed: main.load.torque,
497
+ unit: main.unit,
498
+ shaft: avail,
499
+ margin,
500
+ counted: counted.values,
501
+ ...(d.supply ? { supply: d.supply, rpm: motorSpeed } : {}),
502
+ },
503
+ },
504
+ );
505
+ if (
506
+ d.spec.speed != null &&
507
+ performance(m, { speed: motorSpeed, supply: d.supply }).findings.some((x) => x.code === 'motor.speed')
508
+ )
509
+ f('fail', `${d.id} is asked for ${motorSpeed} rpm, past what a ${m.name} does`, `${d.id}: too fast`, {
510
+ code: 'motor.speed',
511
+ refs: { item: d.id },
512
+ });
217
513
  else {
218
- const slideRate = main.x.type === 'prismatic' ? (speedOut * 360 * main.t.slide) / 60 : null, span = slideRate ? main.x.dofs[0][1] - main.x.dofs[0][0] : 0, time = slideRate ? span / slideRate : 60 / speedOut; // along a slide's travel, or a turn
219
- f('info', `${main.x.id} moves at ${slideRate ? `${n3(slideRate, 2)} mm/s` : `${n3(speedOut, 2)} rpm`} with ${d.id} at ${n3(motorSpeed, 1)} rpm: ${slideRate ? 'its whole range' : 'a turn'} in ${n3(time, 1)} s`, null, { code: 'motor.speed', at: at(main.x), values: { rpm: speedOut, time } });
514
+ const slideRate = main.x.type === 'prismatic' ? (speedOut * 360 * main.t.slide) / 60 : null,
515
+ span = slideRate ? main.x.dofs[0][1] - main.x.dofs[0][0] : 0,
516
+ time = slideRate ? span / slideRate : 60 / speedOut; // along a slide's travel, or a turn
517
+ f(
518
+ 'info',
519
+ `${main.x.id} moves at ${slideRate ? `${n3(slideRate, 2)} mm/s` : `${n3(speedOut, 2)} rpm`} with ${d.id} at ${n3(motorSpeed, 1)} rpm: ${slideRate ? 'its whole range' : 'a turn'} in ${n3(time, 1)} s`,
520
+ null,
521
+ { code: 'motor.speed', at: at(main.x), values: { rpm: speedOut, time } },
522
+ );
220
523
  }
221
524
  mountCheck(s, d, f, W, avail, materialName, { worlds, mul });
222
525
  // Does it hold?
223
- const fig = (k) => m.figures[k]?.value, kt = m.type === 'brushless' ? 60 / (2 * Math.PI * fig('kv')) : 0;
224
- const on = atCurrent(m, d.spec, fig('holding_torque') ?? fig('stall_torque') ?? (kt ? kt * fig('rated_current') : 0)), off_ = fig('detent_torque') ?? fig('friction_torque') ?? null, brake = lines.map((l) => motion.joints.find((x) => x.id === l.x.id)?.brake).find(Boolean) ?? motion.joints.find((x) => x.id === d.joint)?.brake;
225
- const backS = n3(back), pmargin = backOn ? on / backOn : Infinity;
226
- if (locked || brake) f('pass', `${main.x.id} holds with the power off: ${brake ? `its brake (${brake})` : locked} is what holds it`, null, { code: 'motor.holds', at: at(main.x) });
227
- else if (off_ != null && back <= off_) f('pass', `${main.x.id} holds with the power off: ${backS} N m back at the motor against ${n3(off_)} N m of ${fig('detent_torque') != null ? 'detent' : 'gearbox friction'}`, null, { code: 'motor.holds', at: at(main.x) });
228
- else if (off_ != null) f('warn', `${main.x.id} drops with the power off: ${backS} N m back at the motor against ${n3(off_)} N m of ${fig('detent_torque') != null ? 'detent' : 'gearbox friction'}. A worm, a ratchet, or more ratio`, `${main.x.id}: drops unpowered`, { code: 'motor.holds', at: at(main.x), values: { back, holds: off_ } });
229
- else f('warn', `${main.x.id}: there's no figure for what holds it with the power off (${m.name} gives none): assume it can be turned back, and measure it`, `${main.x.id}: unpowered unknown`, { code: 'motor.holds', at: at(main.x) });
230
- if (pmargin < 1) f('fail', `${main.x.id} slips with the power on: ${n3(backOn)} N m back at the motor against ${n3(on)} N m of ${fig('holding_torque') != null ? 'holding' : 'stall'} torque`, `${main.x.id}: slips`, { code: 'motor.holds', at: at(main.x), values: { back: backOn, holds: on } });
231
- else f('pass', `${main.x.id} holds with the power on, ${n3(pmargin, 1)} times over`, null, { code: 'motor.holds', at: at(main.x), values: { margin: pmargin } });
526
+ const fig = (k) => m.figures[k]?.value,
527
+ kt = m.type === 'brushless' ? 60 / (2 * Math.PI * fig('kv')) : 0;
528
+ const on = atCurrent(
529
+ m,
530
+ d.spec,
531
+ fig('holding_torque') ?? fig('stall_torque') ?? (kt ? kt * fig('rated_current') : 0),
532
+ ),
533
+ off_ = fig('detent_torque') ?? fig('friction_torque') ?? null,
534
+ brake =
535
+ lines.map((l) => motion.joints.find((x) => x.id === l.x.id)?.brake).find(Boolean) ??
536
+ motion.joints.find((x) => x.id === d.joint)?.brake;
537
+ const backS = n3(back),
538
+ pmargin = backOn ? on / backOn : Infinity;
539
+ if (locked || brake)
540
+ f(
541
+ 'pass',
542
+ `${main.x.id} holds with the power off: ${brake ? `its brake (${brake})` : locked} is what holds it`,
543
+ null,
544
+ { code: 'motor.holds', at: at(main.x) },
545
+ );
546
+ else if (off_ != null && back <= off_)
547
+ f(
548
+ 'pass',
549
+ `${main.x.id} holds with the power off: ${backS} N m back at the motor against ${n3(off_)} N m of ${fig('detent_torque') != null ? 'detent' : 'gearbox friction'} (${counted.text})`,
550
+ null,
551
+ { code: 'motor.holds', at: at(main.x), values: { back, holds: off_, counted: counted.values } },
552
+ );
553
+ else if (off_ != null)
554
+ f(
555
+ 'warn',
556
+ `${main.x.id} drops with the power off: ${backS} N m back at the motor against ${n3(off_)} N m of ${fig('detent_torque') != null ? 'detent' : 'gearbox friction'} (${counted.text}). A worm, a ratchet, or more ratio`,
557
+ `${main.x.id}: drops unpowered`,
558
+ { code: 'motor.holds', at: at(main.x), values: { back, holds: off_, counted: counted.values } },
559
+ );
560
+ else
561
+ f(
562
+ 'warn',
563
+ `${main.x.id}: there's no figure for what holds it with the power off (${m.name} gives none): assume it can be turned back, and measure it`,
564
+ `${main.x.id}: unpowered unknown`,
565
+ { code: 'motor.holds', at: at(main.x) },
566
+ );
567
+ if (pmargin < 1)
568
+ f(
569
+ 'fail',
570
+ `${main.x.id} slips with the power on: ${n3(backOn)} N m back at the motor against ${n3(on)} N m of ${fig('holding_torque') != null ? 'holding' : 'stall'} torque (${counted.text})`,
571
+ `${main.x.id}: slips`,
572
+ { code: 'motor.holds', at: at(main.x), values: { back: backOn, holds: on, counted: counted.values } },
573
+ );
574
+ else
575
+ f('pass', `${main.x.id} holds with the power on, ${n3(pmargin, 1)} times over (${counted.text})`, null, {
576
+ code: 'motor.holds',
577
+ at: at(main.x),
578
+ values: { margin: pmargin, counted: counted.values },
579
+ });
232
580
  // The case, against what it's bolted to
233
- const mat = material(materialName), rise = fig('temperature_rise');
581
+ const mat = material(materialName),
582
+ rise = fig('temperature_rise');
234
583
  if (mat?.softening != null && rise != null) {
235
584
  // (the rise is the maker's at rated current; the heat goes as the current squared, so a driver set lower runs cooler)
236
- const I = fig('rated_current'), set = d.spec.current != null && I ? Math.min(1, (d.spec.current / I) ** 2) : 1;
237
- const duty = d.spec.duty != null ? d.spec.duty : 1, room = 25, caseT = room + rise * duty * set, ok = caseT <= mat.softening, name = mat.name.toUpperCase();
238
- const how = [set < 1 ? `at ${n3(d.spec.current, 2)} A` : null, duty < 1 ? `at ${n3(duty * 100, 0)}% duty` : null].filter(Boolean).join(' and ') || 'at rated current';
585
+ const I = fig('rated_current'),
586
+ set = d.spec.current != null && I ? Math.min(1, (d.spec.current / I) ** 2) : 1;
587
+ const duty = d.spec.duty != null ? d.spec.duty : 1,
588
+ room = 25,
589
+ caseT = room + rise * duty * set,
590
+ ok = caseT <= mat.softening,
591
+ name = mat.name.toUpperCase();
592
+ const how =
593
+ [set < 1 ? `at ${n3(d.spec.current, 2)} A` : null, duty < 1 ? `at ${n3(duty * 100, 0)}% duty` : null]
594
+ .filter(Boolean)
595
+ .join(' and ') || 'at rated current';
239
596
  const est = `an estimate: ${m.name}'s ${n3(rise, 1)} °C rise at rated current${set < 1 ? ', scaled by the current squared (its copper loss)' : ''}${duty < 1 ? ', by the duty' : ''}, over a ${room} °C room`;
240
- if (ok) f('pass', `${d.id}'s case reaches at most ${n3(caseT, 1)} °C ${how}, under ${name}'s ${mat.softening} °C (${est})`, null, { code: 'motor.heat', at: S, refs: { item: d.id }, values: { case: caseT, softening: mat.softening, rise, room, scale: set * duty } });
241
- else { const k = Math.sqrt((mat.softening - room) / (rise * duty)); f('warn', `${d.id}'s case can reach ${n3(caseT, 1)} °C ${how} (${est}), past where ${name} softens (${mat.softening} °C). Set the driver to ${I ? `${n3(I * k, 2)} A` : `${n3(k * 100, 0)}% of its current`} (${n3(k * 100, 0)}% of the torque), or print the mount in a material that takes it`, `${d.id}: mount will soften`, { code: 'motor.heat', at: S, refs: { item: d.id }, values: { case: caseT, softening: mat.softening, rise, room, scale: set * duty } }); }
597
+ if (ok)
598
+ f(
599
+ 'pass',
600
+ `${d.id}'s case reaches at most ${n3(caseT, 1)} °C ${how}, under ${name}'s ${mat.softening} °C (${est})`,
601
+ null,
602
+ {
603
+ code: 'motor.heat',
604
+ at: S,
605
+ refs: { item: d.id },
606
+ values: { case: caseT, softening: mat.softening, rise, room, scale: set * duty },
607
+ },
608
+ );
609
+ else {
610
+ const k = Math.sqrt((mat.softening - room) / (rise * duty));
611
+ f(
612
+ 'warn',
613
+ `${d.id}'s case can reach ${n3(caseT, 1)} °C ${how} (${est}), past where ${name} softens (${mat.softening} °C). Set the driver to ${I ? `${n3(I * k, 2)} A` : `${n3(k * 100, 0)}% of its current`} (${n3(k * 100, 0)}% of the torque), or print the mount in a material that takes it`,
614
+ `${d.id}: mount will soften`,
615
+ {
616
+ code: 'motor.heat',
617
+ at: S,
618
+ refs: { item: d.id },
619
+ values: { case: caseT, softening: mat.softening, rise, room, scale: set * duty },
620
+ },
621
+ );
622
+ }
242
623
  }
243
624
  }
244
625
  }
@@ -248,14 +629,36 @@ export function motorChecks(s, f, helpers, materialName) {
248
629
  // The part a motor is fastened to, read at its screw holes in the motor's frame: the thinnest wall at a hole (t) and the
249
630
  // plate round them (plate), or null where no fit that fastens names the motor
250
631
  function mountPlate(s, d, W) {
251
- const m = d.model, top = (n) => String(n).split(/[.@]/)[0], fit = s.fits.find((x) => x.fastens && [top(x.a), top(x.b)].includes(d.id));
632
+ const m = d.model,
633
+ top = (n) => String(n).split(/[.@]/)[0],
634
+ fit = s.fits.find((x) => x.fastens && [top(x.a), top(x.b)].includes(d.id));
252
635
  if (!fit || !m.mount.holes.length) return null;
253
- const other = top(fit.a) === d.id ? top(fit.b) : top(fit.a), parts = s.parts.filter((p) => !p.hardware && (p.item === other || p.leaf === other));
636
+ const other = top(fit.a) === d.id ? top(fit.b) : top(fit.a),
637
+ parts = s.parts.filter((p) => !p.hardware && (p.item === other || p.leaf === other));
254
638
  if (!parts.length) return null;
255
- const inv = (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]]; };
256
- const pts = parts.flatMap((p) => p.triangles.flat().map(inv)), side = m.mount.side, nominal = mountModel(m, { plate: 10 }), hd = nominal.holes[0].diameter;
257
- let t = Infinity, plate = 0; // the shortest wall a hole has, and the plate round it (more, if the screw's head is sunk)
258
- for (const [hx, hy] of m.mount.holes) for (const p of pts) { const r = Math.hypot(p[0] - hx, p[1] - hy), z = p[2] * side; if (r < hd / 2 + 2 && z > 0.5) { t = Math.min(t, z); plate = Math.max(plate, z); } }
639
+ const inv = (p) => {
640
+ const q = [p[0] - W[3], p[1] - W[7], p[2] - W[11]];
641
+ return [
642
+ W[0] * q[0] + W[4] * q[1] + W[8] * q[2],
643
+ W[1] * q[0] + W[5] * q[1] + W[9] * q[2],
644
+ W[2] * q[0] + W[6] * q[1] + W[10] * q[2],
645
+ ];
646
+ };
647
+ const pts = parts.flatMap((p) => p.triangles.flat().map(inv)),
648
+ side = m.mount.side,
649
+ nominal = mountModel(m, { plate: 10 }),
650
+ hd = nominal.holes[0].diameter;
651
+ let t = Infinity,
652
+ plate = 0; // the shortest wall a hole has, and the plate round it (more, if the screw's head is sunk)
653
+ for (const [hx, hy] of m.mount.holes)
654
+ for (const p of pts) {
655
+ const r = Math.hypot(p[0] - hx, p[1] - hy),
656
+ z = p[2] * side;
657
+ if (r < hd / 2 + 2 && z > 0.5) {
658
+ t = Math.min(t, z);
659
+ plate = Math.max(plate, z);
660
+ }
661
+ }
259
662
  return { fit, other, parts, inv, t, plate, hd };
260
663
  }
261
664
 
@@ -265,8 +668,21 @@ function mountPlate(s, d, W) {
265
668
  // thinner than the plate round them, the heads are sunk in counterbores (mount()'s, as deep as the head is high), and
266
669
  // the screws are chosen for the plate under them
267
670
  function screwsFor(d, plate, t = plate) {
268
- const here = mountModel(d.model, { plate, ...(t < plate - 0.5 ? { counterbore: true } : {}), ...(d.spec.screw ? { screw: d.spec.screw } : {}) }), fx = here.screw.model, L = here.screwLength, sold = fx.figures.lengths?.value;
269
- const length = fx.length ?? (!Array.isArray(sold) || !sold.length ? L : d.model.mount.thread ? [...sold].reverse().find((l) => l <= L) ?? sold[0] : sold.find((l) => l >= L) ?? sold.at(-1));
671
+ const here = mountModel(d.model, {
672
+ plate,
673
+ ...(t < plate - 0.5 ? { counterbore: true } : {}),
674
+ ...(d.spec.screw ? { screw: d.spec.screw } : {}),
675
+ }),
676
+ fx = here.screw.model,
677
+ L = here.screwLength,
678
+ sold = fx.figures.lengths?.value;
679
+ const length =
680
+ fx.length ??
681
+ (!Array.isArray(sold) || !sold.length
682
+ ? L
683
+ : d.model.mount.thread
684
+ ? ([...sold].reverse().find((l) => l <= L) ?? sold[0])
685
+ : (sold.find((l) => l >= L) ?? sold.at(-1)));
270
686
  return { here, fx, length, wanted: L, name: `${fx.thread}x${length} ${fx.head.form}` };
271
687
  }
272
688
 
@@ -280,30 +696,73 @@ function screwsFor(d, plate, t = plate) {
280
696
  * tool: what turns them, as the order says it: a hex key in a socket head, a socket or spanner on a hexagon head
281
697
  */
282
698
  export function motorScrews(s, { placeItems, jointValues }) {
283
- const drives = s.motion?.drives || [], top = (n) => String(n).split(/[.@]/)[0];
699
+ const drives = s.motion?.drives || [],
700
+ top = (n) => String(n).split(/[.@]/)[0];
284
701
  if (!drives.length) return [];
285
702
  const named = new Set((s.a.fasten || []).flatMap((x) => [...(x.through || []), x.into].map(top)));
286
- const worlds = placeItems(s.motion, s.jointValues ?? jointValues(s.motion, s.motion.pose ?? undefined)), out = [];
703
+ const worlds = placeItems(s.motion, s.jointValues ?? jointValues(s.motion, s.motion.pose ?? undefined)),
704
+ out = [];
287
705
  for (const d of drives) {
288
706
  if (named.has(d.id)) continue;
289
- const p = mountPlate(s, d, worlds[d.item]); if (!p || p.t === Infinity) continue;
707
+ const p = mountPlate(s, d, worlds[d.item]);
708
+ if (!p || p.t === Infinity) continue;
290
709
  const { fx, length, wanted, name } = screwsFor(d, +p.plate.toFixed(2), +p.t.toFixed(2));
291
710
  if (!(wanted > 0)) continue;
292
- const tool = fx.head.form === 'hex' && fx.head.flats ? `${+fx.head.flats.toFixed(3)} mm socket or spanner` : fx.head.key != null ? `${+fx.head.key.toFixed(3)} mm hex key` : null;
293
- out.push({ item: d.id, other: p.other, fit: p.fit, thread: fx.thread, head: fx.head.form, name, key: fx.head.key ?? null, tool, length, wanted, count: d.model.mount.holes.length });
711
+ const tool =
712
+ fx.head.form === 'hex' && fx.head.flats
713
+ ? `${+fx.head.flats.toFixed(3)} mm socket or spanner`
714
+ : fx.head.key != null
715
+ ? `${+fx.head.key.toFixed(3)} mm hex key`
716
+ : null;
717
+ out.push({
718
+ item: d.id,
719
+ other: p.other,
720
+ fit: p.fit,
721
+ thread: fx.thread,
722
+ head: fx.head.form,
723
+ name,
724
+ key: fx.head.key ?? null,
725
+ tool,
726
+ length,
727
+ wanted,
728
+ count: d.model.mount.holes.length,
729
+ });
294
730
  }
295
731
  return out;
296
732
  }
297
733
 
298
734
  function mountCheck(s, d, f, W, avail, materialName, frame) {
299
- const m = d.model, at = mountPlate(s, d, W);
735
+ const m = d.model,
736
+ at = mountPlate(s, d, W);
300
737
  if (!at) return;
301
738
  const { other, parts, inv, t, plate, hd } = at;
302
- if (t === Infinity) return f('warn', `${d.id}: couldn't find the plate at its screw holes in ${other}`, `${d.id}: mount not found`, { code: 'motor.mount' });
739
+ if (t === Infinity)
740
+ return f('warn', `${d.id}: couldn't find the plate at its screw holes in ${other}`, `${d.id}: mount not found`, {
741
+ code: 'motor.mount',
742
+ });
303
743
  // the screws as bought (screwsFor), so the engagement mountModel checks is the bought screw's
304
- const sunk = t < plate - 0.5, here = mountModel(m, { plate: +plate.toFixed(2), ...(sunk ? { counterbore: true } : {}), screw: screwsFor(d, +plate.toFixed(2), +t.toFixed(2)).name }), mat = material(materialName) || material('pla'), each = Math.max(...screwGroup(m.mount.holes, { moment: [0, 0, avail] }).screws.map((x) => x.shear)), bearing = each / (hd * t), margin = mat.strength / bearing;
305
- for (const x of here.findings) f(x.level, `${d.id} on ${other}: ${x.text}`, x.level === 'pass' ? null : `${d.id}: ${x.code.split('.')[1]}`, { code: 'motor.mount', ...(x.values ? { values: x.values } : {}), ...(x.refs ? { refs: { item: d.id, ...x.refs } } : {}) });
306
- f(margin < 2 ? 'fail' : 'pass', `${d.id} on ${other}: ${n3(plate, 2)} mm of plate at the screws, each taking ${n3(each, 1)} N against the torque (bearing ${n3(bearing, 1)} MPa, ${n3(margin, 0)} times under ${mat.name.toUpperCase()}'s ${mat.strength} MPa)`, margin < 2 ? `${d.id}: screws pull through` : null, { code: 'motor.mount', values: { plate, bearing, margin } });
744
+ const sunk = t < plate - 0.5,
745
+ here = mountModel(m, {
746
+ plate: +plate.toFixed(2),
747
+ ...(sunk ? { counterbore: true } : {}),
748
+ screw: screwsFor(d, +plate.toFixed(2), +t.toFixed(2)).name,
749
+ }),
750
+ mat = material(materialName) || material('pla'),
751
+ each = Math.max(...screwGroup(m.mount.holes, { moment: [0, 0, avail] }).screws.map((x) => x.shear)),
752
+ bearing = each / (hd * t),
753
+ margin = mat.strength / bearing;
754
+ for (const x of here.findings)
755
+ f(x.level, `${d.id} on ${other}: ${x.text}`, x.level === 'pass' ? null : `${d.id}: ${x.code.split('.')[1]}`, {
756
+ code: 'motor.mount',
757
+ ...(x.values ? { values: x.values } : {}),
758
+ ...(x.refs ? { refs: { item: d.id, ...x.refs } } : {}),
759
+ });
760
+ f(
761
+ margin < 2 ? 'fail' : 'pass',
762
+ `${d.id} on ${other}: ${n3(plate, 2)} mm of plate at the screws, each taking ${n3(each, 1)} N against the torque (bearing ${n3(bearing, 1)} MPa, ${n3(margin, 0)} times under ${mat.name.toUpperCase()}'s ${mat.strength} MPa)`,
763
+ margin < 2 ? `${d.id}: screws pull through` : null,
764
+ { code: 'motor.mount', values: { plate, bearing, margin } },
765
+ );
307
766
  mountBends(s, d, f, W, avail, mat, { other, parts, inv, plate, hd, ...frame });
308
767
  }
309
768
 
@@ -314,16 +773,34 @@ function mountCheck(s, d, f, W, avail, materialName, frame) {
314
773
  // or at the joint it turns on; failing both, where it stands (its lowest face). Reported: how far the shaft's tip moves,
315
774
  // against the printer's fit clearance (what the parts it drives are drawn with), and the peak stress against the
316
775
  // material's strength. Kept in .cache, like the other FE checks.
317
- const sub3 = (a, b) => [a[0] - b[0], a[1] - b[1], a[2] - b[2]], add3 = (a, b) => [a[0] + b[0], a[1] + b[1], a[2] + b[2]];
776
+ const sub3 = (a, b) => [a[0] - b[0], a[1] - b[1], a[2] - b[2]],
777
+ add3 = (a, b) => [a[0] + b[0], a[1] + b[1], a[2] + b[2]];
318
778
  const len3 = (a) => Math.hypot(a[0], a[1], a[2]);
319
- function box3(pts) { const lo = [Infinity, Infinity, Infinity], hi = [-Infinity, -Infinity, -Infinity]; for (const p of pts) 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 }; }
779
+ function box3(pts) {
780
+ const lo = [Infinity, Infinity, Infinity],
781
+ hi = [-Infinity, -Infinity, -Infinity];
782
+ for (const p of pts)
783
+ for (let k = 0; k < 3; k++) {
784
+ if (p[k] < lo[k]) lo[k] = p[k];
785
+ if (p[k] > hi[k]) hi[k] = p[k];
786
+ }
787
+ return { lo, hi };
788
+ }
320
789
  // A small dense solve (Gaussian elimination, partial pivoting); a pivot near nothing is held at a hair, not divided by
321
790
  function solveSmall(A, b) {
322
- const n = b.length, M = A.map((r, i) => [...r, b[i]]), big = Math.max(1e-30, ...A.map((r, i) => Math.abs(r[i])));
791
+ const n = b.length,
792
+ M = A.map((r, i) => [...r, b[i]]),
793
+ big = Math.max(1e-30, ...A.map((r, i) => Math.abs(r[i])));
323
794
  for (let c = 0; c < n; c++) {
324
- let p = c; for (let r = c + 1; r < n; r++) if (Math.abs(M[r][c]) > Math.abs(M[p][c])) p = r;
325
- [M[c], M[p]] = [M[p], M[c]]; if (Math.abs(M[c][c]) < 1e-12 * big) M[c][c] = 1e-12 * big;
326
- for (let r = 0; r < n; r++) if (r !== c) { const k = M[r][c] / M[c][c]; for (let q = c; q <= n; q++) M[r][q] -= k * M[c][q]; }
795
+ let p = c;
796
+ for (let r = c + 1; r < n; r++) if (Math.abs(M[r][c]) > Math.abs(M[p][c])) p = r;
797
+ [M[c], M[p]] = [M[p], M[c]];
798
+ if (Math.abs(M[c][c]) < 1e-12 * big) M[c][c] = 1e-12 * big;
799
+ for (let r = 0; r < n; r++)
800
+ if (r !== c) {
801
+ const k = M[r][c] / M[c][c];
802
+ for (let q = c; q <= n; q++) M[r][q] -= k * M[c][q];
803
+ }
327
804
  }
328
805
  return M.map((r, i) => r[n] / r[i]);
329
806
  }
@@ -334,155 +811,488 @@ function solveSmall(A, b) {
334
811
  * lowest face along `down`; weight: N at `centre`, along `down`; torque: N mm about z; tip: the shaft's tip.
335
812
  * @returns {{ deflection: number, stress: number, atHoles: boolean, cell: number, across: number, held: string } | { missing: string }}
336
813
  */
337
- export function mountFE({ tris, holes, hole, plate, side, held, down, weight, centre, torque, tip, ref = null, E, nu, budget = 9000 }) {
338
- const key = crypto.createHash('sha256').update(JSON.stringify([3, tris, holes, hole, plate, side, held, down, weight, centre, torque, tip, ref, E, nu, budget])).digest('hex').slice(0, 24), file = paths.cache('mount', `${key}.json`);
339
- if (!process.env.CAD_NO_CACHE && host.exists(file)) return JSON.parse(host.readText(file));
340
- const { lo, hi } = box3(tris.flat()), span = sub3(hi, lo);
814
+ export function mountFE({
815
+ tris,
816
+ holes,
817
+ hole,
818
+ plate,
819
+ side,
820
+ held,
821
+ down,
822
+ weight,
823
+ centre,
824
+ torque,
825
+ tip,
826
+ ref = null,
827
+ E,
828
+ nu,
829
+ budget = 9000,
830
+ }) {
831
+ const key = crypto
832
+ .createHash('sha256')
833
+ .update(
834
+ JSON.stringify([
835
+ 4,
836
+ tris,
837
+ holes,
838
+ hole,
839
+ plate,
840
+ side,
841
+ held,
842
+ down,
843
+ weight,
844
+ centre,
845
+ torque,
846
+ tip,
847
+ ref,
848
+ E,
849
+ nu,
850
+ budget,
851
+ ]),
852
+ )
853
+ .digest('hex')
854
+ .slice(0, 24),
855
+ file = paths.cache('mount', `${key}.json`);
856
+ if (!process.env.CAD_NO_CACHE && cached(file)) return JSON.parse(host.readText(file));
857
+ const { lo, hi } = box3(tris.flat()),
858
+ span = sub3(hi, lo);
341
859
  let cell = Math.max(0.4, plate / 2);
342
860
  const count = (h) => span.reduce((t, x) => t * Math.max(1, Math.ceil(x / h)), 1);
343
861
  while (count(cell) > budget) cell *= 1.1;
344
- const n = span.map((x) => Math.max(1, Math.ceil(x / cell))), gr = { nx: n[0], ny: n[1], nz: n[2], h: cell };
345
- const density = solidFill(tris, gr, lo), g = makeGrid(gr), at = positions(g), pos = (id) => add3(lo, at[id]), onPart = new Uint8Array(g.nodes);
346
- 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;
862
+ const n = span.map((x) => Math.max(1, Math.ceil(x / cell))),
863
+ gr = { nx: n[0], ny: n[1], nz: n[2], h: cell };
864
+ const density = solidFill(tris, gr, lo),
865
+ g = makeGrid(gr),
866
+ at = positions(g),
867
+ pos = (id) => add3(lo, at[id]),
868
+ onPart = new Uint8Array(g.nodes);
869
+ for (let e = 0; e < density.length; e++)
870
+ if (density[e] >= 0.5) for (let k = 0; k < 8; k++) onPart[g.edof[e * 24 + 3 * k] / 3] = 1;
347
871
  // Clamped: the plate round each screw, under its head (about twice the hole across), through the plate's thickness
348
- const grip = hole / 2 + Math.max(hole / 2, 1.5 * cell), clamp = [], hold = [];
349
- const inHeld = (p) => held.some((b) => (b.r != null ? len3(sub3(p, b.at)) <= Math.max(b.r, 2.5 * cell) : p.every((x, k) => x >= b.lo[k] - cell && x <= b.hi[k] + cell)));
350
- let lowest = Infinity; if (!held) for (const t of tris) for (const p of t) lowest = Math.min(lowest, -(p[0] * down[0] + p[1] * down[1] + p[2] * down[2]));
872
+ const grip = hole / 2 + Math.max(hole / 2, 1.5 * cell),
873
+ clamp = [],
874
+ hold = [];
875
+ const inHeld = (p) =>
876
+ held.some((b) =>
877
+ b.r != null
878
+ ? len3(sub3(p, b.at)) <= Math.max(b.r, 2.5 * cell)
879
+ : p.every((x, k) => x >= b.lo[k] - cell && x <= b.hi[k] + cell),
880
+ );
881
+ let lowest = Infinity;
882
+ if (!held)
883
+ for (const t of tris)
884
+ for (const p of t) lowest = Math.min(lowest, -(p[0] * down[0] + p[1] * down[1] + p[2] * down[2]));
351
885
  for (let id = 0; id < g.nodes; id++) {
352
886
  if (!onPart[id]) continue;
353
- const p = pos(id), z = p[2] * side; // (the screws' clamp first: a part held all over its face is still loaded at them)
354
- if (z >= -cell && z <= plate + cell && holes.some(([x, y]) => Math.hypot(p[0] - x, p[1] - y) <= grip)) clamp.push(id);
355
- else if (held ? inHeld(p) : -(p[0] * down[0] + p[1] * down[1] + p[2] * down[2]) <= lowest + cell * 0.75) hold.push(id);
887
+ const p = pos(id),
888
+ z = p[2] * side; // (the screws' clamp first: a part held all over its face is still loaded at them)
889
+ if (z >= -cell && z <= plate + cell && holes.some(([x, y]) => Math.hypot(p[0] - x, p[1] - y) <= grip))
890
+ clamp.push(id);
891
+ else if (held ? inHeld(p) : -(p[0] * down[0] + p[1] * down[1] + p[2] * down[2]) <= lowest + cell * 0.75)
892
+ hold.push(id);
356
893
  }
357
- const heldBy = !held ? 'on its lowest face' : held.some((b) => b.r != null) ? 'at the joint that carries it' : 'where it is fastened';
894
+ const heldBy = !held
895
+ ? 'on its lowest face'
896
+ : held.some((b) => b.r != null)
897
+ ? 'at the joint that carries it'
898
+ : 'where it is fastened';
358
899
  if (!hold.length) return { missing: `nothing of it is held ${heldBy}` };
359
900
  if (!clamp.length) return { missing: 'the screws are where it is held', cell };
360
901
  // The motor's weight and torque, shared over the clamped nodes as a rigid body would put them there
361
- const P = clamp.map(pos), c = P.reduce((t, p) => add3(t, p), [0, 0, 0]).map((x) => x / P.length), R = P.map((p) => sub3(p, c));
362
- const J = [[0, 0, 0], [0, 0, 0], [0, 0, 0]]; for (const r of R) { const rr = r[0] * r[0] + r[1] * r[1] + r[2] * r[2]; for (let a = 0; a < 3; a++) for (let b = 0; b < 3; b++) J[a][b] += (a === b ? rr : 0) - r[a] * r[b]; }
363
- const Fw = down.map((x) => x * weight), arm = sub3(centre, c), Mw = cross(arm, Fw);
902
+ const P = clamp.map(pos),
903
+ c = P.reduce((t, p) => add3(t, p), [0, 0, 0]).map((x) => x / P.length),
904
+ R = P.map((p) => sub3(p, c));
905
+ const J = [
906
+ [0, 0, 0],
907
+ [0, 0, 0],
908
+ [0, 0, 0],
909
+ ];
910
+ for (const r of R) {
911
+ const rr = r[0] * r[0] + r[1] * r[1] + r[2] * r[2];
912
+ for (let a = 0; a < 3; a++) for (let b = 0; b < 3; b++) J[a][b] += (a === b ? rr : 0) - r[a] * r[b];
913
+ }
914
+ const Fw = down.map((x) => x * weight),
915
+ arm = sub3(centre, c),
916
+ Mw = cross(arm, Fw);
364
917
  const loads = [1, -1].map((sign) => {
365
- const M = [Mw[0], Mw[1], Mw[2] + sign * torque], w = solveSmall(J, M), out = new Float64Array(g.dofs);
366
- clamp.forEach((id, i) => { const t = cross(w, R[i]); for (let k = 0; k < 3; k++) out[3 * id + k] = Fw[k] / clamp.length + t[k]; });
918
+ const M = [Mw[0], Mw[1], Mw[2] + sign * torque],
919
+ w = solveSmall(J, M),
920
+ out = new Float64Array(g.dofs);
921
+ clamp.forEach((id, i) => {
922
+ const t = cross(w, R[i]);
923
+ for (let k = 0; k < 3; k++) out[3 * id + k] = Fw[k] / clamp.length + t[k];
924
+ });
367
925
  return out;
368
926
  });
369
- const fixed = new Uint8Array(g.dofs); for (const id of hold) for (let k = 0; k < 3; k++) fixed[3 * id + k] = 1;
370
- let a; try { a = analyse({ grid: g, density, material: { E, nu }, fixed, loads, backend: threadsBackend }); } catch (e) { return { missing: e.code === 'fea.unheld' ? `it isn't held still ${heldBy}` : e.message, cell }; }
927
+ const fixed = new Uint8Array(g.dofs);
928
+ for (const id of hold) for (let k = 0; k < 3; k++) fixed[3 * id + k] = 1;
929
+ let a;
930
+ try {
931
+ a = analyse({ grid: g, density, material: { E, nu }, fixed, loads, backend: threadsBackend });
932
+ } catch (e) {
933
+ return { missing: e.code === 'fea.unheld' ? `it isn't held still ${heldBy}` : e.message, cell };
934
+ }
371
935
  // The motor moves as a rigid body with the clamped plate: the best fit of a shift and a small turn, at the shaft's tip
372
936
  // Where the driven joint stands on this same part, the shaft is measured against the part there (they move together)
373
937
  let base = null;
374
- if (ref) { let best = Infinity; for (let id = 0; id < g.nodes; id++) if (onPart[id]) best = Math.min(best, len3(sub3(pos(id), ref))); base = []; for (let id = 0; id < g.nodes; id++) if (onPart[id] && len3(sub3(pos(id), ref)) <= best + cell) base.push(id); }
938
+ if (ref) {
939
+ let best = Infinity;
940
+ for (let id = 0; id < g.nodes; id++) if (onPart[id]) best = Math.min(best, len3(sub3(pos(id), ref)));
941
+ base = [];
942
+ for (let id = 0; id < g.nodes; id++) if (onPart[id] && len3(sub3(pos(id), ref)) <= best + cell) base.push(id);
943
+ }
375
944
  const rigid = (u) => {
376
- const A = Array.from({ length: 6 }, () => new Array(6).fill(0)), b = new Array(6).fill(0);
945
+ const A = Array.from({ length: 6 }, () => new Array(6).fill(0)),
946
+ b = new Array(6).fill(0);
377
947
  clamp.forEach((id, i) => {
378
- const [x, y, z] = R[i], rows = [[1, 0, 0, 0, z, -y], [0, 1, 0, -z, 0, x], [0, 0, 1, y, -x, 0]]; // u = t + θ × r
379
- rows.forEach((row, k) => { for (let p = 0; p < 6; p++) { b[p] += row[p] * u[3 * id + k]; for (let q = 0; q < 6; q++) A[p][q] += row[p] * row[q]; } });
948
+ const [x, y, z] = R[i],
949
+ rows = [
950
+ [1, 0, 0, 0, z, -y],
951
+ [0, 1, 0, -z, 0, x],
952
+ [0, 0, 1, y, -x, 0],
953
+ ]; // u = t + θ × r
954
+ rows.forEach((row, k) => {
955
+ for (let p = 0; p < 6; p++) {
956
+ b[p] += row[p] * u[3 * id + k];
957
+ for (let q = 0; q < 6; q++) A[p][q] += row[p] * row[q];
958
+ }
959
+ });
380
960
  });
381
- const s6 = solveSmall(A, b), moved = add3(s6.slice(0, 3), cross(s6.slice(3), sub3(tip, c)));
382
- return len3(base ? sub3(moved, [0, 1, 2].map((q) => base.reduce((t, id) => t + u[3 * id + q], 0) / base.length)) : moved);
961
+ const s6 = solveSmall(A, b),
962
+ moved = add3(s6.slice(0, 3), cross(s6.slice(3), sub3(tip, c)));
963
+ return len3(
964
+ base
965
+ ? sub3(
966
+ moved,
967
+ [0, 1, 2].map((q) => base.reduce((t, id) => t + u[3 * id + q], 0) / base.length),
968
+ )
969
+ : moved,
970
+ );
383
971
  };
384
972
  const deflection = Math.max(...a.u.map(rigid));
385
- // A cell's stress is read at its centre, inside the surface: across k cells, bending reads (k - 1) / k of the surface's
386
- const across = Math.max(2, Math.round(plate / cell)), lift = across / (across - 1);
387
- let stress = 0, atHoles = false;
388
- for (const st of a.stress) for (let e = 0; e < density.length; e++) {
389
- if (density[e] < 0.5 || st[e] * lift <= stress) continue;
390
- const p = add3(lo, [((e % n[0]) + 0.5) * cell, ((Math.floor(e / n[0]) % n[1]) + 0.5) * cell, (Math.floor(e / (n[0] * n[1])) + 0.5) * cell]);
391
- stress = st[e] * lift; atHoles = holes.some(([x, y]) => Math.hypot(p[0] - x, p[1] - y) <= grip + cell);
392
- }
973
+ // The stress at the plate's surface (fea's analyse().surface), where bending puts its peak: a cell's centre stress,
974
+ // half a cell inside, reads it low (it was once lifted here by k / (k - 1) for k cells across, which fea now does
975
+ // properly for every caller)
976
+ const across = Math.max(2, Math.round(plate / cell));
977
+ let stress = 0,
978
+ atHoles = false;
979
+ for (const st of a.surface)
980
+ for (let e = 0; e < density.length; e++) {
981
+ if (density[e] < 0.5 || st[e] <= stress) continue;
982
+ const p = add3(lo, [
983
+ ((e % n[0]) + 0.5) * cell,
984
+ ((Math.floor(e / n[0]) % n[1]) + 0.5) * cell,
985
+ (Math.floor(e / (n[0] * n[1])) + 0.5) * cell,
986
+ ]);
987
+ stress = st[e];
988
+ atHoles = holes.some(([x, y]) => Math.hypot(p[0] - x, p[1] - y) <= grip + cell);
989
+ }
393
990
  const out = { deflection, relative: !!base, stress, atHoles, cell, across, held: heldBy, cells: g.cells };
394
- host.writeText(file, JSON.stringify(out)); return out;
991
+ host.writeText(file, JSON.stringify(out));
992
+ return out;
395
993
  }
396
994
 
397
995
  function mountBends(s, d, f, W, avail, mat, { other, parts, inv, plate, hd, worlds, mul }) {
398
- const m = d.model, top = (x) => String(x).split(/[.@]/)[0], motion = s.motion, ids = motion.items.map((x) => x[0]);
996
+ const m = d.model,
997
+ top = (x) => String(x).split(/[.@]/)[0],
998
+ motion = s.motion,
999
+ ids = motion.items.map((x) => x[0]);
399
1000
  if (!(mat?.modulus > 0) || !(mat?.strength > 0)) return;
400
1001
  const tris = parts.filter((p) => p.role !== 'support').flatMap((p) => p.triangles.map((t) => t.map(inv)));
401
1002
  // Where it's held: at the joint it hangs from, if it's carried by one (fixed to a link, or turning on a joint); else at
402
1003
  // the printed parts it's fastened to that sit below it (along gravity), not the motor nor anything bought
403
- const g = motion.gravity || [0, 0, -1], gl = Math.hypot(...g) || 1, down = [0, 1, 2].map((r) => (W[r] * g[0] + W[4 + r] * g[1] + W[8 + r] * g[2]) / gl);
404
- const k = ids.indexOf(other), from = motion.joints.find((j) => j.child === k), boxes = [];
1004
+ const g = motion.gravity || [0, 0, -1],
1005
+ gl = Math.hypot(...g) || 1,
1006
+ down = [0, 1, 2].map((r) => (W[r] * g[0] + W[4 + r] * g[1] + W[8 + r] * g[2]) / gl);
1007
+ const k = ids.indexOf(other),
1008
+ from = motion.joints.find((j) => j.child === k),
1009
+ boxes = [];
405
1010
  if (from && worlds) boxes.push({ at: inv(axisOf(motion, worlds, from, mul).O), r: 8 });
406
1011
  else {
407
- const motors = new Set((motion.drives || []).map((x) => x.id)), mine = box3(tris.flat()), depth = (b) => [0, 1, 2].reduce((t, q) => t + ((b.lo[q] + b.hi[q]) / 2) * down[q], 0);
1012
+ const motors = new Set((motion.drives || []).map((x) => x.id)),
1013
+ mine = box3(tris.flat()),
1014
+ depth = (b) => [0, 1, 2].reduce((t, q) => t + ((b.lo[q] + b.hi[q]) / 2) * down[q], 0);
408
1015
  for (const x of s.fits) {
409
1016
  if (!x.fastens || ![top(x.a), top(x.b)].includes(other)) continue;
410
- const them = top(x.a) === other ? top(x.b) : top(x.a); if (them === d.id || motors.has(them)) continue;
411
- const theirs = s.parts.filter((p) => (p.item === them || p.leaf === them) && p.role !== 'reference' && p.role !== 'support');
1017
+ const them = top(x.a) === other ? top(x.b) : top(x.a);
1018
+ if (them === d.id || motors.has(them)) continue;
1019
+ const theirs = s.parts.filter(
1020
+ (p) => (p.item === them || p.leaf === them) && p.role !== 'reference' && p.role !== 'support',
1021
+ );
412
1022
  const b = theirs.length && box3(theirs.flatMap((p) => p.triangles.flat().map(inv)));
413
1023
  if (b && depth(b) > depth(mine)) boxes.push(b);
414
1024
  }
415
1025
  }
416
- const fig = (x) => m.figures[x]?.value, hold = atCurrent(m, d.spec, fig('holding_torque') ?? fig('stall_torque') ?? 0), T = Math.max(avail, hold); // N m: the most it can put on its screws
417
- const side = m.mount.side, centre = [m.body.centre[0], m.body.centre[1], (-side * m.body.length) / 2], tip = m.anchors.tip?.origin ?? [0, 0, m.shaft.tip];
418
- const driven = motion.joints.find((j) => j.id === d.joint), ref = driven && driven.parent === k && worlds ? inv(axisOf(motion, worlds, driven, mul).O) : null;
419
- const fe = mountFE({ tris, holes: m.mount.holes, hole: hd, plate, side, held: boxes.length ? boxes : null, down, weight: (m.mass ?? 0) * G, centre, torque: T * 1000, tip, ref, E: mat.modulus, nu: mat.poisson ?? 0.36 });
420
- const S = rowsAt(W, tip), refs = { item: d.id, part: other }, name = mat.name.toUpperCase();
421
- if (fe.missing) return f('warn', `${d.id} on ${other}: couldn't bend the part under the motor: ${fe.missing}. Fasten it to what holds it (a "fastens" fit)`, `${d.id}: mount not solved`, { code: 'motor.mount', at: S, refs });
422
- let limit = 0.2; try { limit = d.spec.deflection != null ? s.num(d.spec.deflection) : peekRuleSet(printerOf(s.project)).rules.fit?.value ?? 0.2; } catch {}
423
- const bend = limit / Math.max(fe.deflection, 1e-9), strong = mat.strength / Math.max(fe.stress, 1e-9), margin = Math.min(bend, strong), K = 2, bad = margin < K;
1026
+ const fig = (x) => m.figures[x]?.value,
1027
+ hold = atCurrent(m, d.spec, fig('holding_torque') ?? fig('stall_torque') ?? 0),
1028
+ T = Math.max(avail, hold); // N m: the most it can put on its screws
1029
+ const side = m.mount.side,
1030
+ centre = [m.body.centre[0], m.body.centre[1], (-side * m.body.length) / 2],
1031
+ tip = m.anchors.tip?.origin ?? [0, 0, m.shaft.tip];
1032
+ const driven = motion.joints.find((j) => j.id === d.joint),
1033
+ ref = driven && driven.parent === k && worlds ? inv(axisOf(motion, worlds, driven, mul).O) : null;
1034
+ const fe = mountFE({
1035
+ tris,
1036
+ holes: m.mount.holes,
1037
+ hole: hd,
1038
+ plate,
1039
+ side,
1040
+ held: boxes.length ? boxes : null,
1041
+ down,
1042
+ weight: (m.mass ?? 0) * G,
1043
+ centre,
1044
+ torque: T * 1000,
1045
+ tip,
1046
+ ref,
1047
+ E: mat.modulus,
1048
+ nu: mat.poisson ?? 0.36,
1049
+ });
1050
+ const S = rowsAt(W, tip),
1051
+ refs = { item: d.id, part: other },
1052
+ name = mat.name.toUpperCase();
1053
+ if (fe.missing)
1054
+ return f(
1055
+ 'warn',
1056
+ `${d.id} on ${other}: couldn't bend the part under the motor: ${fe.missing}. Fasten it to what holds it (a "fastens" fit)`,
1057
+ `${d.id}: mount not solved`,
1058
+ { code: 'motor.mount', at: S, refs },
1059
+ );
1060
+ let limit = 0.2;
1061
+ try {
1062
+ limit =
1063
+ d.spec.deflection != null
1064
+ ? s.num(d.spec.deflection)
1065
+ : (peekRuleSet(printerOf(s.project)).rules.fit?.value ?? 0.2);
1066
+ } catch {
1067
+ // (no printer rule set, or a deflection that doesn't read as a number: the usual 0.2 mm fit is the limit)
1068
+ }
1069
+ const bend = limit / Math.max(fe.deflection, 1e-9),
1070
+ strong = mat.strength / Math.max(fe.stress, 1e-9),
1071
+ margin = Math.min(bend, strong),
1072
+ K = 2,
1073
+ bad = margin < K;
424
1074
  const where = fe.atHoles ? 'at the screw holes' : 'in the part, away from the screws';
425
1075
  const how = `FE on ${n3(fe.cell, 2)} mm cubes, ${fe.across} across the plate, held ${fe.held}; an estimate: cells this coarse read a plate 10 to 20% stiffer than it is`;
426
1076
  const said = `${d.id} on ${other}: under the motor's ${n3((m.mass ?? 0) * 1000, 0)} g and ${n3(T, 3)} N m, the shaft's tip moves ${n3(fe.deflection, 3)} mm${fe.relative ? ` against ${d.joint}'s seat on ${other}` : ''}, ${bend >= 1 ? `${n3(bend, 1)} times inside` : `${n3(1 / bend, 1)} times`} the ${n3(limit, 2)} mm fit the parts it drives are drawn with, and the stress peaks at ${n3(fe.stress, 2)} MPa ${where}, ${strong >= 1 ? `${n3(strong, 1)} times under` : `${n3(1 / strong, 1)} times`} ${name}'s ${mat.strength} MPa (${how})`;
427
1077
  let fix = '';
428
1078
  if (bad) {
429
- const grow = Math.max(bend < K ? Math.cbrt(K / bend) : 1, strong < K ? Math.sqrt(K / strong) : 1), want = Math.ceil(plate * grow * 5) / 5; // bending goes with the cube of the thickness, stress with its square
430
- fix = `. A plate about ${n3(want, 1)} mm thick where it bends (${n3(plate, 2)} mm at the screws now), or ribs under it, or a stiffer material (${bend < K ? `${n3((K / bend), 1)} times ${name}'s ${mat.modulus} MPa modulus` : `${n3((mat.strength * K) / strong, 0)} MPa strength or more`}), or hold it closer to the motor`;
1079
+ const grow = Math.max(bend < K ? Math.cbrt(K / bend) : 1, strong < K ? Math.sqrt(K / strong) : 1),
1080
+ want = Math.ceil(plate * grow * 5) / 5; // bending goes with the cube of the thickness, stress with its square
1081
+ fix = `. A plate about ${n3(want, 1)} mm thick where it bends (${n3(plate, 2)} mm at the screws now), or ribs under it, or a stiffer material (${bend < K ? `${n3(K / bend, 1)} times ${name}'s ${mat.modulus} MPa modulus` : `${n3((mat.strength * K) / strong, 0)} MPa strength or more`}), or hold it closer to the motor`;
431
1082
  }
432
- f(bad ? 'fail' : 'pass', said + fix, bad ? `${d.id}: mount ${bend < strong ? 'bends' : 'overstressed'} ${n3(margin, 1)}×` : null, { code: 'motor.mount', at: S, refs, values: { deflection: fe.deflection, relative: fe.relative, limit, stress: fe.stress, strength: mat.strength, margin, cell: fe.cell, held: fe.held } });
1083
+ f(
1084
+ bad ? 'fail' : 'pass',
1085
+ said + fix,
1086
+ bad ? `${d.id}: mount ${bend < strong ? 'bends' : 'overstressed'} ${n3(margin, 1)}×` : null,
1087
+ {
1088
+ code: 'motor.mount',
1089
+ at: S,
1090
+ refs,
1091
+ values: {
1092
+ deflection: fe.deflection,
1093
+ relative: fe.relative,
1094
+ limit,
1095
+ stress: fe.stress,
1096
+ strength: mat.strength,
1097
+ margin,
1098
+ cell: fe.cell,
1099
+ held: fe.held,
1100
+ },
1101
+ },
1102
+ );
433
1103
  }
434
1104
 
435
1105
  // A "shaft" fit: a motor's shaft in the bore of a part. Reads the bore from the part as drawn: a slice across the
436
1106
  // shaft at the grip, a ray out from the axis every few degrees, the wall inside and outside.
437
- export function shaftFit(x, s, f, { placeItems, jointValues, mul, materialName, holeComp = 0.1 }) {
1107
+ export function shaftFit(x, s, f, { placeItems, jointValues, materialName, holeComp = 0.1 }) {
438
1108
  // (a printed hole comes out holeComp smaller across, so a drawn bore is that much tighter on the real shaft)
439
- const motion = s.motion, top = (n) => String(n).split(/[.@]/)[0], drives = motion?.drives || [], d = drives.find((y) => y.id === top(x.a) || y.id === top(x.b)), other = d && (top(x.a) === d.id ? top(x.b) : top(x.a)), label = x.note || `${d?.id ?? x.a}'s shaft in ${other ?? x.b}`;
1109
+ const motion = s.motion,
1110
+ top = (n) => String(n).split(/[.@]/)[0],
1111
+ drives = motion?.drives || [],
1112
+ d = drives.find((y) => y.id === top(x.a) || y.id === top(x.b)),
1113
+ other = d && (top(x.a) === d.id ? top(x.b) : top(x.a)),
1114
+ label = x.note || `${d?.id ?? x.a}'s shaft in ${other ?? x.b}`;
440
1115
  if (!d) return f('fail', `${label}: neither ${x.a} nor ${x.b} is a motor`, null, { code: 'shaft.motor' });
441
- const worlds = placeItems(motion, s.jointValues ?? jointValues(motion, motion.pose ?? undefined)), W = worlds[d.item], m = d.model, S = m.shaft, r = S.diameter / 2;
442
- const inv = (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]]; };
1116
+ const worlds = placeItems(motion, s.jointValues ?? jointValues(motion, motion.pose ?? undefined)),
1117
+ W = worlds[d.item],
1118
+ m = d.model,
1119
+ S = m.shaft,
1120
+ r = S.diameter / 2;
1121
+ const inv = (p) => {
1122
+ const q = [p[0] - W[3], p[1] - W[7], p[2] - W[11]];
1123
+ return [
1124
+ W[0] * q[0] + W[4] * q[1] + W[8] * q[2],
1125
+ W[1] * q[0] + W[5] * q[1] + W[9] * q[2],
1126
+ W[2] * q[0] + W[6] * q[1] + W[10] * q[2],
1127
+ ];
1128
+ };
443
1129
  const parts = s.parts.filter((p) => p.item === other || p.leaf === other);
444
1130
  if (!parts.length) return f('fail', `${label}: no part "${other}"`, null, { code: 'shaft.part' });
445
1131
  const tris = parts.flatMap((p) => p.triangles).map((t) => t.map(inv));
446
1132
  // How far along the shaft the part reaches, near the axis
447
- let lo = Infinity, hi = -Infinity; for (const t of tris) for (const p of t) if (Math.hypot(p[0], p[1]) < r + 6) { lo = Math.min(lo, p[2]); hi = Math.max(hi, p[2]); }
448
- const from = Math.max(lo, S.base), to = Math.min(hi, S.tip), on = to - from;
449
- if (!(on > 0.05)) return f('fail', `${label}: the part isn't on the shaft (it reaches ${n3(lo, 2)} to ${n3(hi, 2)} mm along it; the shaft runs ${n3(S.base, 2)} to ${n3(S.tip, 2)})`, `${label}: not on the shaft`, { code: 'shaft.seat' });
450
- const flatFrom = S.flats ? S.tip - S.flatLength : S.tip, flatOn = Math.max(0, to - Math.max(from, flatFrom)), z = S.flats && flatOn > 0.2 ? (Math.max(from, flatFrom) + to) / 2 : (from + to) / 2;
1133
+ let lo = Infinity,
1134
+ hi = -Infinity;
1135
+ for (const t of tris)
1136
+ for (const p of t)
1137
+ if (Math.hypot(p[0], p[1]) < r + 6) {
1138
+ lo = Math.min(lo, p[2]);
1139
+ hi = Math.max(hi, p[2]);
1140
+ }
1141
+ const from = Math.max(lo, S.base),
1142
+ to = Math.min(hi, S.tip),
1143
+ on = to - from;
1144
+ if (!(on > 0.05))
1145
+ return f(
1146
+ 'fail',
1147
+ `${label}: the part isn't on the shaft (it reaches ${n3(lo, 2)} to ${n3(hi, 2)} mm along it; the shaft runs ${n3(S.base, 2)} to ${n3(S.tip, 2)})`,
1148
+ `${label}: not on the shaft`,
1149
+ { code: 'shaft.seat' },
1150
+ );
1151
+ const flatFrom = S.flats ? S.tip - S.flatLength : S.tip,
1152
+ flatOn = Math.max(0, to - Math.max(from, flatFrom)),
1153
+ z = S.flats && flatOn > 0.2 ? (Math.max(from, flatFrom) + to) / 2 : (from + to) / 2;
451
1154
  // The slice at z, as segments
452
1155
  const segs = [];
453
- for (const t of tris) { const c = []; for (let i = 0; i < 3; i++) { const a = t[i], b = t[(i + 1) % 3]; if ((a[2] - z) * (b[2] - z) < 0) { const u = (z - a[2]) / (b[2] - a[2]); c.push([a[0] + u * (b[0] - a[0]), a[1] + u * (b[1] - a[1])]); } } if (c.length === 2) segs.push(c); }
1156
+ for (const t of tris) {
1157
+ const c = [];
1158
+ for (let i = 0; i < 3; i++) {
1159
+ const a = t[i],
1160
+ b = t[(i + 1) % 3];
1161
+ if ((a[2] - z) * (b[2] - z) < 0) {
1162
+ const u = (z - a[2]) / (b[2] - a[2]);
1163
+ c.push([a[0] + u * (b[0] - a[0]), a[1] + u * (b[1] - a[1])]);
1164
+ }
1165
+ }
1166
+ if (c.length === 2) segs.push(c);
1167
+ }
454
1168
  // Each ray: the nearest wall out from the axis, and the part's outside beyond it
455
- const hits = (ang) => { const dx = Math.cos(ang), dy = Math.sin(ang), out = []; for (const [p, q] of segs) { const ex = q[0] - p[0], ey = q[1] - p[1], den = dx * ey - dy * ex; if (Math.abs(den) < 1e-12) continue; const t = (p[0] * ey - p[1] * ex) / den, u = (p[0] * dy - p[1] * dx) / den; if (t > 1e-6 && u >= 0 && u <= 1) out.push(t); } return out.sort((a, b) => a - b); };
1169
+ const hits = (ang) => {
1170
+ const dx = Math.cos(ang),
1171
+ dy = Math.sin(ang),
1172
+ out = [];
1173
+ for (const [p, q] of segs) {
1174
+ const ex = q[0] - p[0],
1175
+ ey = q[1] - p[1],
1176
+ den = dx * ey - dy * ex;
1177
+ if (Math.abs(den) < 1e-12) continue;
1178
+ const t = (p[0] * ey - p[1] * ex) / den,
1179
+ u = (p[0] * dy - p[1] * dx) / den;
1180
+ if (t > 1e-6 && u >= 0 && u <= 1) out.push(t);
1181
+ }
1182
+ return out.sort((a, b) => a - b);
1183
+ };
456
1184
  // The shaft's section at an angle, its flat turned to psi: the shaft turns to meet the bore as it goes on, so the flat is
457
1185
  // read from the bore. Rays at every 5°; the best angle is the one that leaves the most room at the closest point.
458
1186
  const flatY = S.flats === 2 ? S.across / 2 : S.across - r;
459
- const section = (ang, psi) => { const a = Math.sin(ang - psi); if (S.flats === 2) return Math.min(r, flatY / Math.abs(a || 1e-9)); if (S.flats === 1 && a > 0) return Math.min(r, flatY / a); return r; };
460
- const N = 72, inner = [];
1187
+ const section = (ang, psi) => {
1188
+ const a = Math.sin(ang - psi);
1189
+ if (S.flats === 2) return Math.min(r, flatY / Math.abs(a || 1e-9));
1190
+ if (S.flats === 1 && a > 0) return Math.min(r, flatY / a);
1191
+ return r;
1192
+ };
1193
+ const N = 72,
1194
+ inner = [];
461
1195
  let minWall = Infinity;
462
- for (let k = 0; k < N; k++) { const ang = (2 * Math.PI * k) / N, h = hits(ang); if (!h.length) return f('fail', `${label}: at ${n3(z, 1)} mm along the shaft, the part doesn't go round it`, `${label}: no bore`, { code: 'shaft.bore' }); inner.push([ang, h[0]]); if (h.length > 1) minWall = Math.min(minWall, h[1] - h[0]); }
1196
+ for (let k = 0; k < N; k++) {
1197
+ const ang = (2 * Math.PI * k) / N,
1198
+ h = hits(ang);
1199
+ if (!h.length)
1200
+ return f(
1201
+ 'fail',
1202
+ `${label}: at ${n3(z, 1)} mm along the shaft, the part doesn't go round it`,
1203
+ `${label}: no bore`,
1204
+ { code: 'shaft.bore' },
1205
+ );
1206
+ inner.push([ang, h[0]]);
1207
+ if (h.length > 1) minWall = Math.min(minWall, h[1] - h[0]);
1208
+ }
463
1209
  const gapAt = (psi) => Math.min(...inner.map(([a, h]) => h - section(a, psi)));
464
1210
  let gap = S.flats ? -Infinity : gapAt(0);
465
1211
  if (S.flats) for (let k = 0; k < N; k++) gap = Math.max(gap, gapAt((2 * Math.PI * k) / N));
466
- const code = (c) => ({ code: c, refs: { item: d.id, part: other } }), press = x.shaft === 'press' || (x.shaft !== 'slide' && gap < 0);
1212
+ const code = (c) => ({ code: c, refs: { item: d.id, part: other } }),
1213
+ press = x.shaft === 'press' || (x.shaft !== 'slide' && gap < 0);
467
1214
  if (S.flats) {
468
1215
  const radial = inner.map(([, h]) => h);
469
- if (Math.max(...radial) - Math.min(...radial) < 0.2) return f('fail', `${label}: the bore is round and the shaft has a flat: nothing turns the part but friction. Cut the flat in the bore (bore() in @rulecad/motors), or add a grub screw`, `${label}: round bore`, { ...code('shaft.flat') });
1216
+ if (Math.max(...radial) - Math.min(...radial) < 0.2)
1217
+ return f(
1218
+ 'fail',
1219
+ `${label}: the bore is round and the shaft has a flat: nothing turns the part but friction. Cut the flat in the bore (bore() in @rulecad/motors), or add a grub screw`,
1220
+ `${label}: round bore`,
1221
+ { ...code('shaft.flat') },
1222
+ );
470
1223
  }
471
1224
  // A slide fit, as a part printed in place needs (it can't be pressed on: the push would go through its teeth, or
472
1225
  // whatever holds it in place): the bore as printed, hole_comp smaller across than drawn, still clear of the shaft
473
1226
  if (x.shaft === 'slide') {
474
1227
  const printed = gap - holeComp / 2;
475
- if (printed < 0) f('fail', `${label}: a slide fit, but printed the bore comes out ${n3(holeComp, 2)} mm smaller across than drawn, ${n3(-printed, 3)} mm a side tighter than the shaft: it won't slide on, and it can't be pressed on. Draw the bore as bore() in @rulecad/motors does for a slide (the shaft, its fit each side and hole_comp)`, `${label}: no slide`, { ...code('shaft.slide'), values: { drawn: gap, printed, holeComp } });
476
- else f('pass', `${label}: slides on by hand, ${n3(printed, 3)} mm a side as printed (${n3(gap, 3)} mm drawn, less half of hole_comp's ${n3(holeComp, 2)} mm)`, null, { ...code('shaft.slide'), values: { drawn: gap, printed, holeComp } });
1228
+ if (printed < 0)
1229
+ f(
1230
+ 'fail',
1231
+ `${label}: a slide fit, but printed the bore comes out ${n3(holeComp, 2)} mm smaller across than drawn, ${n3(-printed, 3)} mm a side tighter than the shaft: it won't slide on, and it can't be pressed on. Draw the bore as bore() in @rulecad/motors does for a slide (the shaft, its fit each side and hole_comp)`,
1232
+ `${label}: no slide`,
1233
+ { ...code('shaft.slide'), values: { drawn: gap, printed, holeComp } },
1234
+ );
1235
+ else
1236
+ f(
1237
+ 'pass',
1238
+ `${label}: slides on by hand, ${n3(printed, 3)} mm a side as printed (${n3(gap, 3)} mm drawn, less half of hole_comp's ${n3(holeComp, 2)} mm)`,
1239
+ null,
1240
+ { ...code('shaft.slide'), values: { drawn: gap, printed, holeComp } },
1241
+ );
477
1242
  }
478
- if (gap > 0.5) f('fail', `${label}: the bore is ${n3(gap, 2)} mm clear of the shaft at its closest: too slack to hold`, `${label}: slack`, code('shaft.bore'));
479
- if (gap < -0.2) f('fail', `${label}: the bore is ${n3(-gap, 2)} mm tighter than the shaft: it won't go on`, `${label}: too tight`, code('shaft.bore'));
480
- const grip = S.flats ? Math.min(flatOn, on) : on, want = S.flats ? Math.min(1.5 * S.diameter, 0.8 * S.flatLength) : 1.5 * S.diameter;
481
- if (grip < want) f('warn', `${label}: only ${n3(grip, 1)} mm of ${S.flats ? 'the flat' : 'the shaft'} is in the bore: ${n3(want, 1)} mm or more, or it rocks and rounds out`, `${label}: short grip`, code('shaft.grip'));
482
- else f('pass', `${label}: ${n3(grip, 1)} mm of ${S.flats ? 'the flat' : 'the shaft'} in the bore, ${n3(gap, 2)} mm of play at the closest`, null, code('shaft.grip'));
1243
+ if (gap > 0.5)
1244
+ f(
1245
+ 'fail',
1246
+ `${label}: the bore is ${n3(gap, 2)} mm clear of the shaft at its closest: too slack to hold`,
1247
+ `${label}: slack`,
1248
+ code('shaft.bore'),
1249
+ );
1250
+ if (gap < -0.2)
1251
+ f(
1252
+ 'fail',
1253
+ `${label}: the bore is ${n3(-gap, 2)} mm tighter than the shaft: it won't go on`,
1254
+ `${label}: too tight`,
1255
+ code('shaft.bore'),
1256
+ );
1257
+ const grip = S.flats ? Math.min(flatOn, on) : on,
1258
+ want = S.flats ? Math.min(1.5 * S.diameter, 0.8 * S.flatLength) : 1.5 * S.diameter;
1259
+ if (grip < want)
1260
+ f(
1261
+ 'warn',
1262
+ `${label}: only ${n3(grip, 1)} mm of ${S.flats ? 'the flat' : 'the shaft'} is in the bore: ${n3(want, 1)} mm or more, or it rocks and rounds out`,
1263
+ `${label}: short grip`,
1264
+ code('shaft.grip'),
1265
+ );
1266
+ else
1267
+ f(
1268
+ 'pass',
1269
+ `${label}: ${n3(grip, 1)} mm of ${S.flats ? 'the flat' : 'the shaft'} in the bore, ${n3(gap, 2)} mm of play at the closest`,
1270
+ null,
1271
+ code('shaft.grip'),
1272
+ );
483
1273
  if (press && minWall < Infinity) {
484
- const a = r, u = Math.max(0, holeComp / 2 - gap), b = a + minWall, Kf = (b * b + a * a) / (b * b - a * a), mat = material(materialName) || material('pla'), E = mat.modulus, nu = mat.poisson ?? 0.36, sigma = (E * (u / a) * Kf) / (Kf + nu), limit = mat.strength;
485
- if (sigma > limit) f('fail', `${label}: pressing it on stretches a ${n3(minWall, 2)} mm wall to ${n3(sigma, 1)} MPa, past ${mat.name.toUpperCase()}'s ${limit} MPa: it splits. A thicker hub or a slide fit`, `${label}: hub splits`, { ...code('shaft.hoop'), values: { stress: sigma, strength: limit } });
486
- else f('pass', `${label}: pressing it on stretches the wall to ${n3(sigma, 1)} MPa (${mat.name.toUpperCase()} takes ${limit} MPa)`, null, { ...code('shaft.hoop') });
1274
+ const a = r,
1275
+ u = Math.max(0, holeComp / 2 - gap),
1276
+ b = a + minWall,
1277
+ Kf = (b * b + a * a) / (b * b - a * a),
1278
+ mat = material(materialName) || material('pla'),
1279
+ E = mat.modulus,
1280
+ nu = mat.poisson ?? 0.36,
1281
+ sigma = (E * (u / a) * Kf) / (Kf + nu),
1282
+ limit = mat.strength;
1283
+ if (sigma > limit)
1284
+ f(
1285
+ 'fail',
1286
+ `${label}: pressing it on stretches a ${n3(minWall, 2)} mm wall to ${n3(sigma, 1)} MPa, past ${mat.name.toUpperCase()}'s ${limit} MPa: it splits. A thicker hub or a slide fit`,
1287
+ `${label}: hub splits`,
1288
+ { ...code('shaft.hoop'), values: { stress: sigma, strength: limit } },
1289
+ );
1290
+ else
1291
+ f(
1292
+ 'pass',
1293
+ `${label}: pressing it on stretches the wall to ${n3(sigma, 1)} MPa (${mat.name.toUpperCase()} takes ${limit} MPa)`,
1294
+ null,
1295
+ { ...code('shaft.hoop') },
1296
+ );
487
1297
  }
488
1298
  }