@rulecad/cad 0.8.0 → 0.10.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (102) hide show
  1. package/AGENTS.md +45 -16
  2. package/CHANGELOG.md +724 -0
  3. package/EXAMPLES.md +61 -54
  4. package/README.md +376 -98
  5. package/TUTORIAL.md +2 -2
  6. package/bin/cad.mjs +2664 -541
  7. package/lib/animate.mjs +173 -49
  8. package/lib/assembly.mjs +1883 -435
  9. package/lib/beams.mjs +256 -52
  10. package/lib/belts.mjs +66 -15
  11. package/lib/board-work.mjs +12 -0
  12. package/lib/bought.mjs +309 -53
  13. package/lib/buildpage.mjs +179 -29
  14. package/lib/cache-file.mjs +105 -0
  15. package/lib/carried.mjs +201 -0
  16. package/lib/clone.mjs +194 -42
  17. package/lib/code-text.mjs +28 -0
  18. package/lib/design-imports.mjs +127 -0
  19. package/lib/design.mjs +871 -147
  20. package/lib/designshapes.mjs +142 -0
  21. package/lib/drive.mjs +187 -63
  22. package/lib/edit.mjs +922 -192
  23. package/lib/errors.mjs +16 -3
  24. package/lib/estimates.mjs +51 -0
  25. package/lib/explain.mjs +62 -13
  26. package/lib/fasten.mjs +2708 -507
  27. package/lib/fe-key.mjs +29 -0
  28. package/lib/fittings.mjs +721 -122
  29. package/lib/fixings.mjs +38 -13
  30. package/lib/framebuild.mjs +790 -175
  31. package/lib/framecheck.mjs +1901 -368
  32. package/lib/framegen.mjs +108 -22
  33. package/lib/frameheat.mjs +225 -42
  34. package/lib/frameprint.mjs +513 -108
  35. package/lib/frames.mjs +86 -18
  36. package/lib/framesize.mjs +719 -120
  37. package/lib/frametip.mjs +235 -0
  38. package/lib/gait.mjs +135 -23
  39. package/lib/grip.mjs +62 -13
  40. package/lib/guides.mjs +1403 -230
  41. package/lib/host.mjs +129 -23
  42. package/lib/inplace.mjs +171 -36
  43. package/lib/jigs.mjs +360 -78
  44. package/lib/joins.mjs +697 -118
  45. package/lib/jsonedit.mjs +88 -26
  46. package/lib/kept.mjs +84 -0
  47. package/lib/kit.mjs +439 -69
  48. package/lib/layout.mjs +2 -1
  49. package/lib/links.mjs +149 -42
  50. package/lib/list.mjs +334 -64
  51. package/lib/live-guard.mjs +68 -0
  52. package/lib/live-shape.mjs +96 -24
  53. package/lib/live.mjs +189 -59
  54. package/lib/loads.mjs +597 -136
  55. package/lib/machine.mjs +372 -74
  56. package/lib/magnets.mjs +162 -44
  57. package/lib/measured.mjs +1080 -117
  58. package/lib/mesh.mjs +526 -119
  59. package/lib/meshcmd.mjs +215 -60
  60. package/lib/motors.mjs +1002 -214
  61. package/lib/motorsvg.mjs +114 -32
  62. package/lib/names.mjs +18 -1
  63. package/lib/optimise.mjs +991 -287
  64. package/lib/order.mjs +515 -114
  65. package/lib/panels.mjs +482 -94
  66. package/lib/parts.mjs +81 -23
  67. package/lib/pins.mjs +163 -44
  68. package/lib/plates.mjs +223 -35
  69. package/lib/player.mjs +37 -9
  70. package/lib/power.mjs +64 -13
  71. package/lib/preview.mjs +83 -16
  72. package/lib/profilemeasure.mjs +572 -129
  73. package/lib/rules.mjs +17 -6
  74. package/lib/sandbox-hooks.mjs +179 -27
  75. package/lib/sandbox-lock.mjs +225 -0
  76. package/lib/sandbox-preload.mjs +2 -2
  77. package/lib/sandbox-run.mjs +122 -25
  78. package/lib/sandbox.mjs +667 -75
  79. package/lib/schema.mjs +42 -11
  80. package/lib/seats.mjs +227 -49
  81. package/lib/services.mjs +261 -52
  82. package/lib/sheet.mjs +963 -179
  83. package/lib/slotnuts.mjs +213 -34
  84. package/lib/targets/gist.mjs +4 -1
  85. package/lib/targets.mjs +22 -4
  86. package/lib/task.mjs +376 -79
  87. package/lib/versions.mjs +285 -39
  88. package/lib/wires.mjs +228 -45
  89. package/lib/workspace.mjs +200 -14
  90. package/package.json +19 -19
  91. package/schemas/assembly.schema.json +2 -2
  92. package/schemas/project.schema.json +6 -0
  93. package/templates/coupons/MEASURE.md +109 -0
  94. package/templates/coupons/assemblies/fixings-test.json +20 -0
  95. package/templates/coupons/assemblies/slot-test.json +11 -0
  96. package/templates/coupons/objects/fixings-coupon.js +88 -0
  97. package/templates/coupons/objects/fixings-coupon.json +26 -0
  98. package/templates/coupons/objects/holds-coupon.js +130 -0
  99. package/templates/coupons/objects/holds-coupon.json +42 -0
  100. package/templates/coupons/objects/slot-coupon.js +89 -0
  101. package/templates/coupons/objects/slot-coupon.json +29 -0
  102. package/templates/coupons/project.json +10 -0
package/lib/motors.mjs CHANGED
@@ -8,14 +8,15 @@ import { stageEfficiency } from '@rulecad/gears';
8
8
  import { screwGroup } from '@rulecad/fixings';
9
9
  import { named } from './parts.mjs';
10
10
  import { referenceBuilt } from './bought.mjs';
11
- import crypto from 'node:crypto';
12
11
  import { grid as makeGrid, analyse, positions } from '@rulecad/fea';
13
12
  import { threadsBackend } from '@rulecad/fea/threads';
14
- import { host } from './host.mjs';
13
+ import { writeCacheFile, readCacheJson } from './cache-file.mjs';
14
+ import { feKey } from './fe-key.mjs';
15
15
  import { paths, printerOf } from './workspace.mjs';
16
16
  import { peekRuleSet } from './rules.mjs';
17
17
  import { isPlainName } from './names.mjs';
18
18
  import { solidFill } from './optimise.mjs';
19
+ import { axisOf, partMasses, pointMasses, driveLoadAt, countedFor } from './carried.mjs';
19
20
 
20
21
  const require = createRequire(import.meta.url);
21
22
  const n3 = (x, d = 3) => String(Number(x.toFixed(d)));
@@ -24,36 +25,100 @@ const G = 9.80665; // m/s²
24
25
  // A motor item, built: its parts (body and shaft), anchors from its model, its figures as values and rules
25
26
  export function motorBuilt(spec, num, id) {
26
27
  const what = `item ${id}: motor`;
27
- if (!spec || typeof spec !== 'object' || !spec.model) throw new Error(`${what}: give { "model": "nema17", "drives": "<joint>" }`);
28
- 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]; } }));
29
- const model = motorModel(spec.model, set), { body, shaft } = motorParts(model);
30
- const parts = named(shaft ? { body, shaft } : { body }, { body: { label: `${model.name} body` }, ...(shaft ? { shaft: { label: `${model.name} shaft` } } : {}) });
31
- const anchors = Object.fromEntries(Object.entries(model.anchors).map(([k, a]) => [k, { at: a.origin, axis: a.axis }]));
32
- const values = Object.fromEntries(Object.entries(model.figures).filter(([, f]) => typeof f.value === 'number').map(([k, f]) => [k, f.value]));
33
- 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 }));
34
- 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
+ });
35
84
  }
36
85
 
37
86
  // Which joint each motor drives, checked by name; a servo's range and a stepper's step go on the joint. The shaft
38
87
  // turns in what it drives, so that pair may overlap: the body is still checked against everything.
39
88
  export function motorDrives(a, placed, joints, num) {
40
- const drives = [], taken = new Map();
89
+ const drives = [],
90
+ taken = new Map();
41
91
  placed.forEach(([it, c], k) => {
42
92
  if (!it.motor) return;
43
- const what = `item ${c.id}: motor`, id = it.motor.drives;
44
- 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
45
99
  const j = joints.find((x) => x.id === id);
46
- 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'})`);
47
102
  if (j.type === 'prismatic' && (it.motor.leadscrew || it.motor.belt)) j.slide = slideDrive(it.motor, what, j, num);
48
- 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"`);
49
- 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`);
50
109
  if (taken.has(id)) throw new Error(`${what}: ${id} is driven by ${taken.get(id)} already: one motor to a joint`);
51
110
  taken.set(id, c.id);
52
- 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);
53
113
  if (model.range != null) {
54
- const half = model.range / 2, d = j.dofs[0];
55
- if (spec.min == null && spec.max == null) { d[0] = -half; d[1] = half; d[2] = Math.min(half, Math.max(-half, d[2])); }
56
- 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]}°`);
57
122
  }
58
123
  if (model.stepAngle) j.step = model.stepAngle;
59
124
  drives.push({ item: k, id: c.id, model, spec: it.motor, joint: id });
@@ -65,26 +130,69 @@ export function motorDrives(a, placed, joints, num) {
65
130
  // it holds with the power off. A screw locks when its lead angle is under its friction angle
66
131
  function slideDrive(spec, what, j, num) {
67
132
  if (spec.leadscrew) {
68
- 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);
69
138
  if (!(lead > 0)) throw new Error(`${what}: a lead screw's lead is above 0 mm (got ${lead})`);
70
- 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
+ };
71
149
  }
72
- 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);
73
152
  if (!(teeth > 0)) throw new Error(`${what}: a belt needs its pulley's "teeth"`);
74
- 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
+ };
75
169
  }
76
170
 
77
171
  // The fits a motor brings with it, in the assembly's own shape
78
- 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 }));
79
176
 
80
177
  // "loads": [{ "joint": "elbow", "torque": 0.5 }, { "joint": "slide", "force": 12 }, { "mass": 0.2, "at": "forearm.tip" }]
81
178
  export function loadsOf(a, anchor, num, joints) {
82
179
  return (a.loads || []).map((l, i) => {
83
180
  const what = `load ${i + 1}`;
84
- 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
+ }
85
187
  const j = joints.find((x) => x.id === l.joint);
86
- 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(', ')})`);
87
- 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
+ );
88
196
  return { joint: j.id, value: num(j.type === 'prismatic' ? l.force : l.torque), note: l.note };
89
197
  });
90
198
  }
@@ -93,154 +201,425 @@ export function loadsOf(a, anchor, num, joints) {
93
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
94
202
  // (or per mm, where the joint slides), the share of power that gets through, what's in the way.
95
203
  export function trainFrom(motion, id) {
96
- const stages = [], meshes = motion.meshes || [];
97
- let j = motion.joints.find((x) => x.id === id), ratio = 1, efficiency = 1, slide = j.type === 'prismatic' ? 1 : null, locks = null;
98
- 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
+ };
99
220
  while (j.follow) {
100
- 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));
101
223
  const kind = m?.kind === 'external' ? 'spur' : m?.kind || 'spur';
102
224
  const eff = m?.efficiency ?? stageEfficiency(kind, kind === 'worm' ? { worm: m.worm } : {});
103
- efficiency *= eff; stages.push({ joint: j.id, kind, ratio: r, efficiency: eff });
104
- if (kind === 'worm' && m.worm.locks) locks = `the worm (its ${n3(m.worm.leadAngle, 1)}° lead is under the friction angle)`;
105
- 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
106
231
  else ratio *= 1 / Math.abs(r);
107
232
  j = motion.joints.find((x) => x.id === lead);
108
233
  }
109
234
  return { root: j.id, ratio, efficiency, stages, slide, locks };
110
235
  }
111
236
 
112
- // World axis of a joint and the world position of a point on an item
113
- 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]);
114
- 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]] }; };
115
- 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];
116
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]];
117
244
 
118
- // 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
119
- function loadAt(motion, loads, worlds, j, mul) {
120
- const { O, Z } = axisOf(motion, worlds, j, mul), byChild = new Map(motion.joints.map((x) => [x.child, x]));
121
- 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; };
122
- let total = 0, push = 0;
123
- for (const l of loads) {
124
- if (l.joint === j.id && l.belt) push += Math.abs(l.value);
125
- else if (l.joint === j.id) total += l.value;
126
- else if (l.mass != null && beyond(l.item)) {
127
- 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));
128
- 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;
129
256
  }
130
- }
131
- // (a belt's push at the carriage's acceleration goes either way along the travel, so it adds to the rest in the
132
- // direction that makes it worse: on a vertical axis, the weight plus the push upward, never the weight less it)
133
- return push ? total + (total < 0 ? -push : push) : total;
134
- }
135
-
136
- // The worst load on a joint: at each named pose, and with the motor run through its range
137
- function worstLoad(motion, loads, j, drive, { placeItems, jointValues, mul }) {
138
- let worst = 0, where = null;
139
- 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
+ };
140
258
  const poses = Object.keys(motion.poses || {});
141
259
  for (const p of poses.length ? poses : [null]) look(jointValues(motion, p ?? undefined), p);
142
260
  const root = drive && motion.joints.find((x) => x.id === drive.joint);
143
261
  if (root) {
144
- const base = jointValues(motion, motion.pose ?? undefined), [lo, hi] = root.dofs[0];
145
- 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
+ }
146
271
  }
147
272
  return { torque: Math.abs(worst), where };
148
273
  }
149
274
 
150
275
  // What a stepper gives at the current it's set to: torque goes with the current, up to its rating
151
- 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;
152
280
 
153
281
  /**
154
282
  * The torque a motor puts on its own screws, as a reaction about its shaft: what it gives at its working speed (the
155
283
  * assembly's, else workingSpeed), at the current it's set to. motor.torque, motor.mount and fasten.load all read this one.
156
284
  * @param {{ model: object, spec: object }} d a drive (an assembly's motor item) @returns {number} N m
157
285
  */
158
- 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
+ );
159
292
 
160
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
161
294
  // at its driver's supply, volts: the assembly's, else the package's default)
162
295
  export function workingSpeed(model, spec, supply) {
163
296
  if (spec.speed != null) return spec.speed;
164
297
  const p = performance(model, { supply });
165
- 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
+ }
166
338
  }
167
339
 
168
- const material = (name) => { const n = String(name || 'pla').toLowerCase().split(/\s/)[0]; if (!isPlainName(n)) return null; try { // (a name from project.json: never a path out of the kit's rules)
169
- 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
+ }
170
350
 
171
351
  // The findings: f(level, text, card, extra), as the assembly's check makes them
172
352
  export function motorChecks(s, f, helpers, materialName) {
173
- const motion = s.motion, drives = motion?.drives || [], loads = motion?.loads || [], { placeItems, jointValues, mul } = helpers;
174
- 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
+ }
175
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);
176
371
  for (const d of drives) {
177
- const m = d.model, grams = n3(m.mass * 1000, 1), K = d.spec.margin != null ? d.spec.margin : 2, W = worlds[d.item];
178
- 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
+ );
179
386
  if (!d.joint) continue;
180
387
  // Its shaft on the joint's axis
181
- 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]];
182
- 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)));
183
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
184
396
  // with the motor on the slide's axis, as before, still passes)
185
- 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 }); }
186
- 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; }
187
- 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 });
188
411
  // Everything it drives that carries a load
189
- 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);
190
- 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 : [];
191
418
  if (!loaded.length) {
192
419
  const here = performance(m, { speed: motorSpeed, supply: d.supply });
193
- 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
+ );
194
426
  continue;
195
427
  }
196
428
  // Reflected to the motor's own shaft: what each load needs of it, and what it would take to hold against it
197
- let need = 0, back = 0, backOn = 0;
198
- 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;
199
434
  let locked = null;
200
435
  for (const { j: x, t, load } of loaded) {
201
436
  // the lead's torque for a load here: a slide's force through the pinion, a revolute's torque down the ratio; what
202
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)
203
- const lead = (q) => (t.slide != null ? (q * t.slide * 180) / Math.PI / 1000 : q), atLead = lead(load.torque);
204
- const still = loads.some((l) => l.belt && l.joint === x.id) ? lead(worstLoad(motion, loads.filter((l) => !l.belt), x, d, helpers).torque) : atLead;
205
- const unit = t.slide != null ? 'N' : 'N m', reduction = t.ratio;
206
- const η = t.efficiency, needed = atLead / (reduction * η);
207
- 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 / η);
208
458
  if (t.locks) locked = t.locks;
209
- else if (η <= 0.5) locked = `the gears (${n3(η * 100, 0)}% forwards, under the 50% where they can't be driven backwards)`;
210
- back += (still / reduction) * ηback; backOn += still / reduction;
211
- 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 });
212
464
  }
213
- const speedOut = motorSpeed / loaded[0].t.ratio, rated = performance(m, { speed: motorSpeed, supply: d.supply }), avail = mountTorque(d), margin = need ? avail / need : Infinity;
214
- 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`;
215
- const trust = rated.rests.filter((k) => k !== 'spec' && k !== 'measured'), caveat = trust.length ? ` (rests on ${trust.join(' and ')} figures: measure it)` : '';
216
- 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` : '';
217
- 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 } : {}) } });
218
- 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
+ });
219
513
  else {
220
- 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
221
- 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
+ );
222
523
  }
223
524
  mountCheck(s, d, f, W, avail, materialName, { worlds, mul });
224
525
  // Does it hold?
225
- const fig = (k) => m.figures[k]?.value, kt = m.type === 'brushless' ? 60 / (2 * Math.PI * fig('kv')) : 0;
226
- 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;
227
- const backS = n3(back), pmargin = backOn ? on / backOn : Infinity;
228
- 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) });
229
- 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) });
230
- 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_ } });
231
- 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) });
232
- 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 } });
233
- 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
+ });
234
580
  // The case, against what it's bolted to
235
- const mat = material(materialName), rise = fig('temperature_rise');
581
+ const mat = material(materialName),
582
+ rise = fig('temperature_rise');
236
583
  if (mat?.softening != null && rise != null) {
237
584
  // (the rise is the maker's at rated current; the heat goes as the current squared, so a driver set lower runs cooler)
238
- const I = fig('rated_current'), set = d.spec.current != null && I ? Math.min(1, (d.spec.current / I) ** 2) : 1;
239
- 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();
240
- 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';
241
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`;
242
- 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 } });
243
- 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
+ }
244
623
  }
245
624
  }
246
625
  }
@@ -250,14 +629,36 @@ export function motorChecks(s, f, helpers, materialName) {
250
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
251
630
  // plate round them (plate), or null where no fit that fastens names the motor
252
631
  function mountPlate(s, d, W) {
253
- 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));
254
635
  if (!fit || !m.mount.holes.length) return null;
255
- 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));
256
638
  if (!parts.length) return null;
257
- 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]]; };
258
- const pts = parts.flatMap((p) => p.triangles.flat().map(inv)), side = m.mount.side, nominal = mountModel(m, { plate: 10 }), hd = nominal.holes[0].diameter;
259
- let t = Infinity, plate = 0; // the shortest wall a hole has, and the plate round it (more, if the screw's head is sunk)
260
- 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
+ }
261
662
  return { fit, other, parts, inv, t, plate, hd };
262
663
  }
263
664
 
@@ -267,8 +668,21 @@ function mountPlate(s, d, W) {
267
668
  // thinner than the plate round them, the heads are sunk in counterbores (mount()'s, as deep as the head is high), and
268
669
  // the screws are chosen for the plate under them
269
670
  function screwsFor(d, plate, t = plate) {
270
- 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;
271
- 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)));
272
686
  return { here, fx, length, wanted: L, name: `${fx.thread}x${length} ${fx.head.form}` };
273
687
  }
274
688
 
@@ -282,30 +696,73 @@ function screwsFor(d, plate, t = plate) {
282
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
283
697
  */
284
698
  export function motorScrews(s, { placeItems, jointValues }) {
285
- const drives = s.motion?.drives || [], top = (n) => String(n).split(/[.@]/)[0];
699
+ const drives = s.motion?.drives || [],
700
+ top = (n) => String(n).split(/[.@]/)[0];
286
701
  if (!drives.length) return [];
287
702
  const named = new Set((s.a.fasten || []).flatMap((x) => [...(x.through || []), x.into].map(top)));
288
- 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 = [];
289
705
  for (const d of drives) {
290
706
  if (named.has(d.id)) continue;
291
- 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;
292
709
  const { fx, length, wanted, name } = screwsFor(d, +p.plate.toFixed(2), +p.t.toFixed(2));
293
710
  if (!(wanted > 0)) continue;
294
- 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;
295
- 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
+ });
296
730
  }
297
731
  return out;
298
732
  }
299
733
 
300
734
  function mountCheck(s, d, f, W, avail, materialName, frame) {
301
- const m = d.model, at = mountPlate(s, d, W);
735
+ const m = d.model,
736
+ at = mountPlate(s, d, W);
302
737
  if (!at) return;
303
738
  const { other, parts, inv, t, plate, hd } = at;
304
- 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
+ });
305
743
  // the screws as bought (screwsFor), so the engagement mountModel checks is the bought screw's
306
- 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;
307
- 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 } } : {}) });
308
- 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
+ );
309
766
  mountBends(s, d, f, W, avail, mat, { other, parts, inv, plate, hd, ...frame });
310
767
  }
311
768
 
@@ -316,16 +773,34 @@ function mountCheck(s, d, f, W, avail, materialName, frame) {
316
773
  // or at the joint it turns on; failing both, where it stands (its lowest face). Reported: how far the shaft's tip moves,
317
774
  // against the printer's fit clearance (what the parts it drives are drawn with), and the peak stress against the
318
775
  // material's strength. Kept in .cache, like the other FE checks.
319
- 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]];
320
778
  const len3 = (a) => Math.hypot(a[0], a[1], a[2]);
321
- 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
+ }
322
789
  // A small dense solve (Gaussian elimination, partial pivoting); a pivot near nothing is held at a hair, not divided by
323
790
  function solveSmall(A, b) {
324
- 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])));
325
794
  for (let c = 0; c < n; c++) {
326
- let p = c; for (let r = c + 1; r < n; r++) if (Math.abs(M[r][c]) > Math.abs(M[p][c])) p = r;
327
- [M[c], M[p]] = [M[p], M[c]]; if (Math.abs(M[c][c]) < 1e-12 * big) M[c][c] = 1e-12 * big;
328
- 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
+ }
329
804
  }
330
805
  return M.map((r, i) => r[n] / r[i]);
331
806
  }
@@ -336,155 +811,468 @@ function solveSmall(A, b) {
336
811
  * lowest face along `down`; weight: N at `centre`, along `down`; torque: N mm about z; tip: the shaft's tip.
337
812
  * @returns {{ deflection: number, stress: number, atHoles: boolean, cell: number, across: number, held: string } | { missing: string }}
338
813
  */
339
- export function mountFE({ tris, holes, hole, plate, side, held, down, weight, centre, torque, tip, ref = null, E, nu, budget = 9000 }) {
340
- 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`);
341
- if (!process.env.CAD_NO_CACHE && host.exists(file)) return JSON.parse(host.readText(file));
342
- 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 file = paths.cache(
832
+ 'mount',
833
+ `${feKey('mount', [tris, holes, hole, plate, side, held, down, weight, centre, torque, tip, ref, E, nu, budget])}.json`,
834
+ );
835
+ const kept = !process.env.CAD_NO_CACHE && readCacheJson(file);
836
+ if (kept) return kept;
837
+ const { lo, hi } = box3(tris.flat()),
838
+ span = sub3(hi, lo);
343
839
  let cell = Math.max(0.4, plate / 2);
344
840
  const count = (h) => span.reduce((t, x) => t * Math.max(1, Math.ceil(x / h)), 1);
345
841
  while (count(cell) > budget) cell *= 1.1;
346
- const n = span.map((x) => Math.max(1, Math.ceil(x / cell))), gr = { nx: n[0], ny: n[1], nz: n[2], h: cell };
347
- const density = solidFill(tris, gr, lo), g = makeGrid(gr), at = positions(g), pos = (id) => add3(lo, at[id]), onPart = new Uint8Array(g.nodes);
348
- 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;
842
+ const n = span.map((x) => Math.max(1, Math.ceil(x / cell))),
843
+ gr = { nx: n[0], ny: n[1], nz: n[2], h: cell };
844
+ const density = solidFill(tris, gr, lo),
845
+ g = makeGrid(gr),
846
+ at = positions(g),
847
+ pos = (id) => add3(lo, at[id]),
848
+ onPart = new Uint8Array(g.nodes);
849
+ for (let e = 0; e < density.length; e++)
850
+ if (density[e] >= 0.5) for (let k = 0; k < 8; k++) onPart[g.edof[e * 24 + 3 * k] / 3] = 1;
349
851
  // Clamped: the plate round each screw, under its head (about twice the hole across), through the plate's thickness
350
- const grip = hole / 2 + Math.max(hole / 2, 1.5 * cell), clamp = [], hold = [];
351
- 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)));
352
- 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]));
852
+ const grip = hole / 2 + Math.max(hole / 2, 1.5 * cell),
853
+ clamp = [],
854
+ hold = [];
855
+ const inHeld = (p) =>
856
+ held.some((b) =>
857
+ b.r != null
858
+ ? len3(sub3(p, b.at)) <= Math.max(b.r, 2.5 * cell)
859
+ : p.every((x, k) => x >= b.lo[k] - cell && x <= b.hi[k] + cell),
860
+ );
861
+ let lowest = Infinity;
862
+ if (!held)
863
+ for (const t of tris)
864
+ for (const p of t) lowest = Math.min(lowest, -(p[0] * down[0] + p[1] * down[1] + p[2] * down[2]));
353
865
  for (let id = 0; id < g.nodes; id++) {
354
866
  if (!onPart[id]) continue;
355
- const p = pos(id), z = p[2] * side; // (the screws' clamp first: a part held all over its face is still loaded at them)
356
- if (z >= -cell && z <= plate + cell && holes.some(([x, y]) => Math.hypot(p[0] - x, p[1] - y) <= grip)) clamp.push(id);
357
- else if (held ? inHeld(p) : -(p[0] * down[0] + p[1] * down[1] + p[2] * down[2]) <= lowest + cell * 0.75) hold.push(id);
867
+ const p = pos(id),
868
+ z = p[2] * side; // (the screws' clamp first: a part held all over its face is still loaded at them)
869
+ if (z >= -cell && z <= plate + cell && holes.some(([x, y]) => Math.hypot(p[0] - x, p[1] - y) <= grip))
870
+ clamp.push(id);
871
+ else if (held ? inHeld(p) : -(p[0] * down[0] + p[1] * down[1] + p[2] * down[2]) <= lowest + cell * 0.75)
872
+ hold.push(id);
358
873
  }
359
- const heldBy = !held ? 'on its lowest face' : held.some((b) => b.r != null) ? 'at the joint that carries it' : 'where it is fastened';
874
+ const heldBy = !held
875
+ ? 'on its lowest face'
876
+ : held.some((b) => b.r != null)
877
+ ? 'at the joint that carries it'
878
+ : 'where it is fastened';
360
879
  if (!hold.length) return { missing: `nothing of it is held ${heldBy}` };
361
880
  if (!clamp.length) return { missing: 'the screws are where it is held', cell };
362
881
  // The motor's weight and torque, shared over the clamped nodes as a rigid body would put them there
363
- 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));
364
- 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]; }
365
- const Fw = down.map((x) => x * weight), arm = sub3(centre, c), Mw = cross(arm, Fw);
882
+ const P = clamp.map(pos),
883
+ c = P.reduce((t, p) => add3(t, p), [0, 0, 0]).map((x) => x / P.length),
884
+ R = P.map((p) => sub3(p, c));
885
+ const J = [
886
+ [0, 0, 0],
887
+ [0, 0, 0],
888
+ [0, 0, 0],
889
+ ];
890
+ for (const r of R) {
891
+ const rr = r[0] * r[0] + r[1] * r[1] + r[2] * r[2];
892
+ 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];
893
+ }
894
+ const Fw = down.map((x) => x * weight),
895
+ arm = sub3(centre, c),
896
+ Mw = cross(arm, Fw);
366
897
  const loads = [1, -1].map((sign) => {
367
- const M = [Mw[0], Mw[1], Mw[2] + sign * torque], w = solveSmall(J, M), out = new Float64Array(g.dofs);
368
- 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]; });
898
+ const M = [Mw[0], Mw[1], Mw[2] + sign * torque],
899
+ w = solveSmall(J, M),
900
+ out = new Float64Array(g.dofs);
901
+ clamp.forEach((id, i) => {
902
+ const t = cross(w, R[i]);
903
+ for (let k = 0; k < 3; k++) out[3 * id + k] = Fw[k] / clamp.length + t[k];
904
+ });
369
905
  return out;
370
906
  });
371
- const fixed = new Uint8Array(g.dofs); for (const id of hold) for (let k = 0; k < 3; k++) fixed[3 * id + k] = 1;
372
- 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 }; }
907
+ const fixed = new Uint8Array(g.dofs);
908
+ for (const id of hold) for (let k = 0; k < 3; k++) fixed[3 * id + k] = 1;
909
+ let a;
910
+ try {
911
+ a = analyse({ grid: g, density, material: { E, nu }, fixed, loads, backend: threadsBackend });
912
+ } catch (e) {
913
+ return { missing: e.code === 'fea.unheld' ? `it isn't held still ${heldBy}` : e.message, cell };
914
+ }
373
915
  // 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
374
916
  // Where the driven joint stands on this same part, the shaft is measured against the part there (they move together)
375
917
  let base = null;
376
- 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); }
918
+ if (ref) {
919
+ let best = Infinity;
920
+ for (let id = 0; id < g.nodes; id++) if (onPart[id]) best = Math.min(best, len3(sub3(pos(id), ref)));
921
+ base = [];
922
+ for (let id = 0; id < g.nodes; id++) if (onPart[id] && len3(sub3(pos(id), ref)) <= best + cell) base.push(id);
923
+ }
377
924
  const rigid = (u) => {
378
- const A = Array.from({ length: 6 }, () => new Array(6).fill(0)), b = new Array(6).fill(0);
925
+ const A = Array.from({ length: 6 }, () => new Array(6).fill(0)),
926
+ b = new Array(6).fill(0);
379
927
  clamp.forEach((id, i) => {
380
- 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
381
- 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]; } });
928
+ const [x, y, z] = R[i],
929
+ rows = [
930
+ [1, 0, 0, 0, z, -y],
931
+ [0, 1, 0, -z, 0, x],
932
+ [0, 0, 1, y, -x, 0],
933
+ ]; // u = t + θ × r
934
+ rows.forEach((row, k) => {
935
+ for (let p = 0; p < 6; p++) {
936
+ b[p] += row[p] * u[3 * id + k];
937
+ for (let q = 0; q < 6; q++) A[p][q] += row[p] * row[q];
938
+ }
939
+ });
382
940
  });
383
- const s6 = solveSmall(A, b), moved = add3(s6.slice(0, 3), cross(s6.slice(3), sub3(tip, c)));
384
- return len3(base ? sub3(moved, [0, 1, 2].map((q) => base.reduce((t, id) => t + u[3 * id + q], 0) / base.length)) : moved);
941
+ const s6 = solveSmall(A, b),
942
+ moved = add3(s6.slice(0, 3), cross(s6.slice(3), sub3(tip, c)));
943
+ return len3(
944
+ base
945
+ ? sub3(
946
+ moved,
947
+ [0, 1, 2].map((q) => base.reduce((t, id) => t + u[3 * id + q], 0) / base.length),
948
+ )
949
+ : moved,
950
+ );
385
951
  };
386
952
  const deflection = Math.max(...a.u.map(rigid));
387
- // A cell's stress is read at its centre, inside the surface: across k cells, bending reads (k - 1) / k of the surface's
388
- const across = Math.max(2, Math.round(plate / cell)), lift = across / (across - 1);
389
- let stress = 0, atHoles = false;
390
- for (const st of a.stress) for (let e = 0; e < density.length; e++) {
391
- if (density[e] < 0.5 || st[e] * lift <= stress) continue;
392
- 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]);
393
- stress = st[e] * lift; atHoles = holes.some(([x, y]) => Math.hypot(p[0] - x, p[1] - y) <= grip + cell);
394
- }
953
+ // The stress at the plate's surface (fea's analyse().surface), where bending puts its peak: a cell's centre stress,
954
+ // half a cell inside, reads it low (it was once lifted here by k / (k - 1) for k cells across, which fea now does
955
+ // properly for every caller)
956
+ const across = Math.max(2, Math.round(plate / cell));
957
+ let stress = 0,
958
+ atHoles = false;
959
+ for (const st of a.surface)
960
+ for (let e = 0; e < density.length; e++) {
961
+ if (density[e] < 0.5 || st[e] <= stress) continue;
962
+ const p = add3(lo, [
963
+ ((e % n[0]) + 0.5) * cell,
964
+ ((Math.floor(e / n[0]) % n[1]) + 0.5) * cell,
965
+ (Math.floor(e / (n[0] * n[1])) + 0.5) * cell,
966
+ ]);
967
+ stress = st[e];
968
+ atHoles = holes.some(([x, y]) => Math.hypot(p[0] - x, p[1] - y) <= grip + cell);
969
+ }
395
970
  const out = { deflection, relative: !!base, stress, atHoles, cell, across, held: heldBy, cells: g.cells };
396
- host.writeText(file, JSON.stringify(out)); return out;
971
+ writeCacheFile(file, JSON.stringify(out));
972
+ return out;
397
973
  }
398
974
 
399
975
  function mountBends(s, d, f, W, avail, mat, { other, parts, inv, plate, hd, worlds, mul }) {
400
- const m = d.model, top = (x) => String(x).split(/[.@]/)[0], motion = s.motion, ids = motion.items.map((x) => x[0]);
976
+ const m = d.model,
977
+ top = (x) => String(x).split(/[.@]/)[0],
978
+ motion = s.motion,
979
+ ids = motion.items.map((x) => x[0]);
401
980
  if (!(mat?.modulus > 0) || !(mat?.strength > 0)) return;
402
981
  const tris = parts.filter((p) => p.role !== 'support').flatMap((p) => p.triangles.map((t) => t.map(inv)));
403
982
  // 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
404
983
  // the printed parts it's fastened to that sit below it (along gravity), not the motor nor anything bought
405
- 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);
406
- const k = ids.indexOf(other), from = motion.joints.find((j) => j.child === k), boxes = [];
984
+ const g = motion.gravity || [0, 0, -1],
985
+ gl = Math.hypot(...g) || 1,
986
+ down = [0, 1, 2].map((r) => (W[r] * g[0] + W[4 + r] * g[1] + W[8 + r] * g[2]) / gl);
987
+ const k = ids.indexOf(other),
988
+ from = motion.joints.find((j) => j.child === k),
989
+ boxes = [];
407
990
  if (from && worlds) boxes.push({ at: inv(axisOf(motion, worlds, from, mul).O), r: 8 });
408
991
  else {
409
- 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);
992
+ const motors = new Set((motion.drives || []).map((x) => x.id)),
993
+ mine = box3(tris.flat()),
994
+ depth = (b) => [0, 1, 2].reduce((t, q) => t + ((b.lo[q] + b.hi[q]) / 2) * down[q], 0);
410
995
  for (const x of s.fits) {
411
996
  if (!x.fastens || ![top(x.a), top(x.b)].includes(other)) continue;
412
- const them = top(x.a) === other ? top(x.b) : top(x.a); if (them === d.id || motors.has(them)) continue;
413
- const theirs = s.parts.filter((p) => (p.item === them || p.leaf === them) && p.role !== 'reference' && p.role !== 'support');
997
+ const them = top(x.a) === other ? top(x.b) : top(x.a);
998
+ if (them === d.id || motors.has(them)) continue;
999
+ const theirs = s.parts.filter(
1000
+ (p) => (p.item === them || p.leaf === them) && p.role !== 'reference' && p.role !== 'support',
1001
+ );
414
1002
  const b = theirs.length && box3(theirs.flatMap((p) => p.triangles.flat().map(inv)));
415
1003
  if (b && depth(b) > depth(mine)) boxes.push(b);
416
1004
  }
417
1005
  }
418
- 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
419
- 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];
420
- const driven = motion.joints.find((j) => j.id === d.joint), ref = driven && driven.parent === k && worlds ? inv(axisOf(motion, worlds, driven, mul).O) : null;
421
- 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 });
422
- const S = rowsAt(W, tip), refs = { item: d.id, part: other }, name = mat.name.toUpperCase();
423
- 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 });
424
- 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 {}
425
- 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;
1006
+ const fig = (x) => m.figures[x]?.value,
1007
+ hold = atCurrent(m, d.spec, fig('holding_torque') ?? fig('stall_torque') ?? 0),
1008
+ T = Math.max(avail, hold); // N m: the most it can put on its screws
1009
+ const side = m.mount.side,
1010
+ centre = [m.body.centre[0], m.body.centre[1], (-side * m.body.length) / 2],
1011
+ tip = m.anchors.tip?.origin ?? [0, 0, m.shaft.tip];
1012
+ const driven = motion.joints.find((j) => j.id === d.joint),
1013
+ ref = driven && driven.parent === k && worlds ? inv(axisOf(motion, worlds, driven, mul).O) : null;
1014
+ const fe = mountFE({
1015
+ tris,
1016
+ holes: m.mount.holes,
1017
+ hole: hd,
1018
+ plate,
1019
+ side,
1020
+ held: boxes.length ? boxes : null,
1021
+ down,
1022
+ weight: (m.mass ?? 0) * G,
1023
+ centre,
1024
+ torque: T * 1000,
1025
+ tip,
1026
+ ref,
1027
+ E: mat.modulus,
1028
+ nu: mat.poisson ?? 0.36,
1029
+ });
1030
+ const S = rowsAt(W, tip),
1031
+ refs = { item: d.id, part: other },
1032
+ name = mat.name.toUpperCase();
1033
+ if (fe.missing)
1034
+ return f(
1035
+ 'warn',
1036
+ `${d.id} on ${other}: couldn't bend the part under the motor: ${fe.missing}. Fasten it to what holds it (a "fastens" fit)`,
1037
+ `${d.id}: mount not solved`,
1038
+ { code: 'motor.mount', at: S, refs },
1039
+ );
1040
+ let limit = 0.2;
1041
+ try {
1042
+ limit =
1043
+ d.spec.deflection != null
1044
+ ? s.num(d.spec.deflection)
1045
+ : (peekRuleSet(printerOf(s.project)).rules.fit?.value ?? 0.2);
1046
+ } catch {
1047
+ // (no printer rule set, or a deflection that doesn't read as a number: the usual 0.2 mm fit is the limit)
1048
+ }
1049
+ const bend = limit / Math.max(fe.deflection, 1e-9),
1050
+ strong = mat.strength / Math.max(fe.stress, 1e-9),
1051
+ margin = Math.min(bend, strong),
1052
+ K = 2,
1053
+ bad = margin < K;
426
1054
  const where = fe.atHoles ? 'at the screw holes' : 'in the part, away from the screws';
427
1055
  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`;
428
1056
  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})`;
429
1057
  let fix = '';
430
1058
  if (bad) {
431
- 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
432
- 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`;
1059
+ const grow = Math.max(bend < K ? Math.cbrt(K / bend) : 1, strong < K ? Math.sqrt(K / strong) : 1),
1060
+ want = Math.ceil(plate * grow * 5) / 5; // bending goes with the cube of the thickness, stress with its square
1061
+ 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`;
433
1062
  }
434
- 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 } });
1063
+ f(
1064
+ bad ? 'fail' : 'pass',
1065
+ said + fix,
1066
+ bad ? `${d.id}: mount ${bend < strong ? 'bends' : 'overstressed'} ${n3(margin, 1)}×` : null,
1067
+ {
1068
+ code: 'motor.mount',
1069
+ at: S,
1070
+ refs,
1071
+ values: {
1072
+ deflection: fe.deflection,
1073
+ relative: fe.relative,
1074
+ limit,
1075
+ stress: fe.stress,
1076
+ strength: mat.strength,
1077
+ margin,
1078
+ cell: fe.cell,
1079
+ held: fe.held,
1080
+ },
1081
+ },
1082
+ );
435
1083
  }
436
1084
 
437
1085
  // 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
438
1086
  // shaft at the grip, a ray out from the axis every few degrees, the wall inside and outside.
439
- export function shaftFit(x, s, f, { placeItems, jointValues, mul, materialName, holeComp = 0.1 }) {
1087
+ export function shaftFit(x, s, f, { placeItems, jointValues, materialName, holeComp = 0.1 }) {
440
1088
  // (a printed hole comes out holeComp smaller across, so a drawn bore is that much tighter on the real shaft)
441
- 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}`;
1089
+ const motion = s.motion,
1090
+ top = (n) => String(n).split(/[.@]/)[0],
1091
+ drives = motion?.drives || [],
1092
+ d = drives.find((y) => y.id === top(x.a) || y.id === top(x.b)),
1093
+ other = d && (top(x.a) === d.id ? top(x.b) : top(x.a)),
1094
+ label = x.note || `${d?.id ?? x.a}'s shaft in ${other ?? x.b}`;
442
1095
  if (!d) return f('fail', `${label}: neither ${x.a} nor ${x.b} is a motor`, null, { code: 'shaft.motor' });
443
- 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;
444
- 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]]; };
1096
+ const worlds = placeItems(motion, s.jointValues ?? jointValues(motion, motion.pose ?? undefined)),
1097
+ W = worlds[d.item],
1098
+ m = d.model,
1099
+ S = m.shaft,
1100
+ r = S.diameter / 2;
1101
+ const inv = (p) => {
1102
+ const q = [p[0] - W[3], p[1] - W[7], p[2] - W[11]];
1103
+ return [
1104
+ W[0] * q[0] + W[4] * q[1] + W[8] * q[2],
1105
+ W[1] * q[0] + W[5] * q[1] + W[9] * q[2],
1106
+ W[2] * q[0] + W[6] * q[1] + W[10] * q[2],
1107
+ ];
1108
+ };
445
1109
  const parts = s.parts.filter((p) => p.item === other || p.leaf === other);
446
1110
  if (!parts.length) return f('fail', `${label}: no part "${other}"`, null, { code: 'shaft.part' });
447
1111
  const tris = parts.flatMap((p) => p.triangles).map((t) => t.map(inv));
448
1112
  // How far along the shaft the part reaches, near the axis
449
- 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]); }
450
- const from = Math.max(lo, S.base), to = Math.min(hi, S.tip), on = to - from;
451
- 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' });
452
- 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;
1113
+ let lo = Infinity,
1114
+ hi = -Infinity;
1115
+ for (const t of tris)
1116
+ for (const p of t)
1117
+ if (Math.hypot(p[0], p[1]) < r + 6) {
1118
+ lo = Math.min(lo, p[2]);
1119
+ hi = Math.max(hi, p[2]);
1120
+ }
1121
+ const from = Math.max(lo, S.base),
1122
+ to = Math.min(hi, S.tip),
1123
+ on = to - from;
1124
+ if (!(on > 0.05))
1125
+ return f(
1126
+ 'fail',
1127
+ `${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)})`,
1128
+ `${label}: not on the shaft`,
1129
+ { code: 'shaft.seat' },
1130
+ );
1131
+ const flatFrom = S.flats ? S.tip - S.flatLength : S.tip,
1132
+ flatOn = Math.max(0, to - Math.max(from, flatFrom)),
1133
+ z = S.flats && flatOn > 0.2 ? (Math.max(from, flatFrom) + to) / 2 : (from + to) / 2;
453
1134
  // The slice at z, as segments
454
1135
  const segs = [];
455
- 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); }
1136
+ for (const t of tris) {
1137
+ const c = [];
1138
+ for (let i = 0; i < 3; i++) {
1139
+ const a = t[i],
1140
+ b = t[(i + 1) % 3];
1141
+ if ((a[2] - z) * (b[2] - z) < 0) {
1142
+ const u = (z - a[2]) / (b[2] - a[2]);
1143
+ c.push([a[0] + u * (b[0] - a[0]), a[1] + u * (b[1] - a[1])]);
1144
+ }
1145
+ }
1146
+ if (c.length === 2) segs.push(c);
1147
+ }
456
1148
  // Each ray: the nearest wall out from the axis, and the part's outside beyond it
457
- 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); };
1149
+ const hits = (ang) => {
1150
+ const dx = Math.cos(ang),
1151
+ dy = Math.sin(ang),
1152
+ out = [];
1153
+ for (const [p, q] of segs) {
1154
+ const ex = q[0] - p[0],
1155
+ ey = q[1] - p[1],
1156
+ den = dx * ey - dy * ex;
1157
+ if (Math.abs(den) < 1e-12) continue;
1158
+ const t = (p[0] * ey - p[1] * ex) / den,
1159
+ u = (p[0] * dy - p[1] * dx) / den;
1160
+ if (t > 1e-6 && u >= 0 && u <= 1) out.push(t);
1161
+ }
1162
+ return out.sort((a, b) => a - b);
1163
+ };
458
1164
  // 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
459
1165
  // read from the bore. Rays at every 5°; the best angle is the one that leaves the most room at the closest point.
460
1166
  const flatY = S.flats === 2 ? S.across / 2 : S.across - r;
461
- 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; };
462
- const N = 72, inner = [];
1167
+ const section = (ang, psi) => {
1168
+ const a = Math.sin(ang - psi);
1169
+ if (S.flats === 2) return Math.min(r, flatY / Math.abs(a || 1e-9));
1170
+ if (S.flats === 1 && a > 0) return Math.min(r, flatY / a);
1171
+ return r;
1172
+ };
1173
+ const N = 72,
1174
+ inner = [];
463
1175
  let minWall = Infinity;
464
- 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]); }
1176
+ for (let k = 0; k < N; k++) {
1177
+ const ang = (2 * Math.PI * k) / N,
1178
+ h = hits(ang);
1179
+ if (!h.length)
1180
+ return f(
1181
+ 'fail',
1182
+ `${label}: at ${n3(z, 1)} mm along the shaft, the part doesn't go round it`,
1183
+ `${label}: no bore`,
1184
+ { code: 'shaft.bore' },
1185
+ );
1186
+ inner.push([ang, h[0]]);
1187
+ if (h.length > 1) minWall = Math.min(minWall, h[1] - h[0]);
1188
+ }
465
1189
  const gapAt = (psi) => Math.min(...inner.map(([a, h]) => h - section(a, psi)));
466
1190
  let gap = S.flats ? -Infinity : gapAt(0);
467
1191
  if (S.flats) for (let k = 0; k < N; k++) gap = Math.max(gap, gapAt((2 * Math.PI * k) / N));
468
- const code = (c) => ({ code: c, refs: { item: d.id, part: other } }), press = x.shaft === 'press' || (x.shaft !== 'slide' && gap < 0);
1192
+ const code = (c) => ({ code: c, refs: { item: d.id, part: other } }),
1193
+ press = x.shaft === 'press' || (x.shaft !== 'slide' && gap < 0);
469
1194
  if (S.flats) {
470
1195
  const radial = inner.map(([, h]) => h);
471
- 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') });
1196
+ if (Math.max(...radial) - Math.min(...radial) < 0.2)
1197
+ return f(
1198
+ 'fail',
1199
+ `${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`,
1200
+ `${label}: round bore`,
1201
+ { ...code('shaft.flat') },
1202
+ );
472
1203
  }
473
1204
  // A slide fit, as a part printed in place needs (it can't be pressed on: the push would go through its teeth, or
474
1205
  // whatever holds it in place): the bore as printed, hole_comp smaller across than drawn, still clear of the shaft
475
1206
  if (x.shaft === 'slide') {
476
1207
  const printed = gap - holeComp / 2;
477
- 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 } });
478
- 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 } });
1208
+ if (printed < 0)
1209
+ f(
1210
+ 'fail',
1211
+ `${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)`,
1212
+ `${label}: no slide`,
1213
+ { ...code('shaft.slide'), values: { drawn: gap, printed, holeComp } },
1214
+ );
1215
+ else
1216
+ f(
1217
+ 'pass',
1218
+ `${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)`,
1219
+ null,
1220
+ { ...code('shaft.slide'), values: { drawn: gap, printed, holeComp } },
1221
+ );
479
1222
  }
480
- 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'));
481
- 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'));
482
- 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;
483
- 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'));
484
- 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'));
1223
+ if (gap > 0.5)
1224
+ f(
1225
+ 'fail',
1226
+ `${label}: the bore is ${n3(gap, 2)} mm clear of the shaft at its closest: too slack to hold`,
1227
+ `${label}: slack`,
1228
+ code('shaft.bore'),
1229
+ );
1230
+ if (gap < -0.2)
1231
+ f(
1232
+ 'fail',
1233
+ `${label}: the bore is ${n3(-gap, 2)} mm tighter than the shaft: it won't go on`,
1234
+ `${label}: too tight`,
1235
+ code('shaft.bore'),
1236
+ );
1237
+ const grip = S.flats ? Math.min(flatOn, on) : on,
1238
+ want = S.flats ? Math.min(1.5 * S.diameter, 0.8 * S.flatLength) : 1.5 * S.diameter;
1239
+ if (grip < want)
1240
+ f(
1241
+ 'warn',
1242
+ `${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`,
1243
+ `${label}: short grip`,
1244
+ code('shaft.grip'),
1245
+ );
1246
+ else
1247
+ f(
1248
+ 'pass',
1249
+ `${label}: ${n3(grip, 1)} mm of ${S.flats ? 'the flat' : 'the shaft'} in the bore, ${n3(gap, 2)} mm of play at the closest`,
1250
+ null,
1251
+ code('shaft.grip'),
1252
+ );
485
1253
  if (press && minWall < Infinity) {
486
- 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;
487
- 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 } });
488
- 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') });
1254
+ const a = r,
1255
+ u = Math.max(0, holeComp / 2 - gap),
1256
+ b = a + minWall,
1257
+ Kf = (b * b + a * a) / (b * b - a * a),
1258
+ mat = material(materialName) || material('pla'),
1259
+ E = mat.modulus,
1260
+ nu = mat.poisson ?? 0.36,
1261
+ sigma = (E * (u / a) * Kf) / (Kf + nu),
1262
+ limit = mat.strength;
1263
+ if (sigma > limit)
1264
+ f(
1265
+ 'fail',
1266
+ `${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`,
1267
+ `${label}: hub splits`,
1268
+ { ...code('shaft.hoop'), values: { stress: sigma, strength: limit } },
1269
+ );
1270
+ else
1271
+ f(
1272
+ 'pass',
1273
+ `${label}: pressing it on stretches the wall to ${n3(sigma, 1)} MPa (${mat.name.toUpperCase()} takes ${limit} MPa)`,
1274
+ null,
1275
+ { ...code('shaft.hoop') },
1276
+ );
489
1277
  }
490
1278
  }