@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/assembly.mjs CHANGED
@@ -21,11 +21,13 @@
21
21
  // Beams are held to each other by joins (lib/joins.mjs): { "kind": "blind", "a": "y1.a", "b": "x1.back@120" }. Each puts
22
22
  // its operations on both beams and its screws into fasten before anything is built, and is checked once it is.
23
23
  import { host, readJson } from './host.mjs';
24
+ import { writeCacheFile, readCacheJson } from './cache-file.mjs';
24
25
  import fs from 'node:fs';
25
26
  import crypto from 'node:crypto';
26
27
  import path from 'node:path';
27
28
  import { fileURLToPath } from 'node:url';
28
29
  import { evaluate, loadRuleSet } from './rules.mjs';
30
+ import { estimatesFinding } from './estimates.mjs';
29
31
  import { paths, printerOf } from './workspace.mjs';
30
32
  import { plainName, isPlainName } from './names.mjs';
31
33
  import { locateIn, build, readObject, jscad } from './design.mjs';
@@ -33,9 +35,22 @@ import { materialise } from './versions.mjs';
33
35
  import { satisfies } from '@rulecad/versions';
34
36
  import { bounds } from '@rulecad/printcheck';
35
37
  import { closest, closestAt, inside, distanceToFace, overlapAt } from '@rulecad/fit';
36
- import { keys as keyCentres, readLayout, hasLayout } from './layout.mjs';
38
+ import { keys as keyCentres, readLayout } from './layout.mjs';
37
39
  import { DOFS, frame, turn, mul, inv, pathLength, jointValues, placeItems, jointMatrix } from '@rulecad/model-link';
38
- import { gearModel, internalModel, rackModel, mesh as meshOf, phase, rackPhase, contact, wormModel, wormMesh, bevelModel, bevelMesh, compoundEfficiency } from '@rulecad/gears';
40
+ import {
41
+ gearModel,
42
+ internalModel,
43
+ rackModel,
44
+ mesh as meshOf,
45
+ phase,
46
+ rackPhase,
47
+ contact,
48
+ wormModel,
49
+ wormMesh,
50
+ bevelModel,
51
+ bevelMesh,
52
+ compoundEfficiency,
53
+ } from '@rulecad/gears';
39
54
  import { ops as booleans } from '@rulecad/shapes';
40
55
  import { motorBuilt, motorDrives, shaftFits, loadsOf, motorChecks, shaftFit, axisOf } from './motors.mjs';
41
56
  import { runningChecks, seatFit, printerRules } from './seats.mjs';
@@ -50,8 +65,8 @@ import { gaitOf, gaitChecks, gaitSequence } from './gait.mjs';
50
65
  import { boughtBuilt, boughtFindings, boughtSets } from './bought.mjs';
51
66
  import { orderChecks } from './order.mjs';
52
67
  import { beamBuilt, beamPlace, beamAddress, beamFindings, marksOf, framesContext } from './beams.mjs';
53
- import { fittingBuilt, fittingFindings, plasticOf } from './fittings.mjs';
54
- import { expandJoins, joinChecks } from './joins.mjs';
68
+ import { fittingBuilt, fittingFindings, footFindings, plasticOf } from './fittings.mjs';
69
+ import { expandJoins, joinChecks, joinDropChecks } from './joins.mjs';
55
70
  import { expandFrame, frameText } from './framegen.mjs';
56
71
  import { frameChecks } from './framecheck.mjs';
57
72
  import { sizeChecks } from './framesize.mjs';
@@ -65,8 +80,57 @@ import { frameSquareChecks, frameBuild } from './framebuild.mjs';
65
80
  let pinning = null; // lib/pins.mjs, loaded with the first assembly whose fits name pins
66
81
  let fastening = null; // lib/fasten.mjs, loaded with the first assembly that has a fasten: the rest start as fast as before
67
82
 
68
- export const assemblyPath = (ref) => { const [project, name] = String(ref).split('/'); return path.join(paths.project(project), 'assemblies', `${plainName(name, 'assembly name')}.json`); };
69
- export const isAssembly = (ref) => { const [project, name] = String(ref).split('@')[0].split('/'); return isPlainName(project) && isPlainName(name) && host.exists(assemblyPath(`${project}/${name}`)); }; // (a path or a name that climbs is not an assembly: locate() says what it is)
83
+ export const assemblyPath = (ref) => {
84
+ const [project, name] = String(ref).split('/');
85
+ return path.join(paths.project(project), 'assemblies', `${plainName(name, 'assembly name')}.json`);
86
+ };
87
+ export const isAssembly = (ref) => {
88
+ const [project, name] = String(ref).split('@')[0].split('/');
89
+ return isPlainName(project) && isPlainName(name) && host.exists(assemblyPath(`${project}/${name}`));
90
+ }; // (a path or a name that climbs is not an assembly: locate() says what it is)
91
+
92
+ /**
93
+ * The command line's --set on an assembly, { "hook.reach": "60" }, as the overrides buildAssembly takes,
94
+ * { hook: { reach: "60" } }: each name is an item of the assembly's own and one of that item's object's variables.
95
+ * Anything else is refused by name, never passed over: a component, a bought part, a beam or a motor takes no --set
96
+ * (set the object inside it with its own "set" in the assembly file). The values stay as typed: the build reads each by
97
+ * its variable's kind, and holds it to the variable's tweak range, as it does for an object's --set.
98
+ * @param {string} ref project/assembly @param {Record<string, string | undefined>} set @returns {Record<string, Record<string, string>>}
99
+ */
100
+ export function assemblyOverrides(ref, set) {
101
+ const names = Object.keys(set);
102
+ if (!names.length) return {};
103
+ const [project] = ref.split('/'),
104
+ a = readJson(assemblyPath(ref)),
105
+ items = (a.items || []).filter((it) => it && typeof it.id === 'string'),
106
+ out = {};
107
+ for (const [k, v] of Object.entries(set)) {
108
+ const said = `--set ${k}${v === undefined ? '' : `=${v}`}`,
109
+ dot = k.indexOf('.');
110
+ if (dot < 0)
111
+ throw new Error(
112
+ `${said}: on an assembly, name an item's variable as <item>.<variable> (items: ${items.map((it) => it.id).join(', ') || 'none'})`,
113
+ );
114
+ if (v === undefined || v === '') throw new Error(`${said}: give the value after an =, as ${k}=…`);
115
+ const id = k.slice(0, dot),
116
+ name = k.slice(dot + 1),
117
+ it = items.find((x) => x.id === id);
118
+ if (!it)
119
+ throw new Error(`${said}: ${ref} has no item "${id}" (items: ${items.map((x) => x.id).join(', ') || 'none'})`);
120
+ if (!it.object)
121
+ throw new Error(
122
+ `${said}: item ${id} is ${it.assembly ? `the assembly ${it.assembly}` : 'not an object'}, and --set reaches an object item's own variables only: set it in ${ref}'s file, in the item's "set"`,
123
+ );
124
+ const objName = String(it.object).split(/[:@]/)[0],
125
+ vars = readObject(locateIn(project, objName, `${assemblyPath(ref)}, item ${id}'s "object"`)).variables || {};
126
+ if (!Object.hasOwn(vars, name))
127
+ throw new Error(
128
+ `${said}: item ${id} (${objName}) has no variable "${name}" (variables: ${Object.keys(vars).join(', ') || 'none'})`,
129
+ );
130
+ (out[id] ||= {})[name] = v;
131
+ }
132
+ return out;
133
+ }
70
134
 
71
135
  export { satisfies }; // from @rulecad/versions
72
136
 
@@ -89,40 +153,60 @@ export { satisfies }; // from @rulecad/versions
89
153
  // checked or printed.
90
154
  // An object item can be a variant: "object": "keycap:oem-r3" (or "variant": "oem-r3"), and pin a release: "keycap@0.4.0".
91
155
  // overrides: { itemId: { variable: value } }, set on this assembly's items by the assembly that uses it.
92
- // opts: { mirror: true } builds each object with its mirror settings (cad show).
156
+ // opts: { mirror: true } builds each object with its mirror settings (cad show); { assembly } builds that assembly, as
157
+ // read, in place of the file's (cad frame --size --write checks what it would write before writing it).
93
158
  export async function buildAssembly(ref, stack = [], overrides = {}, opts = {}) {
94
159
  await measurer();
95
160
  const outer = overrides;
96
161
  const [project, name] = ref.split('/');
97
162
  if (stack.includes(ref)) throw new Error(`assembly ${ref} contains itself (${[...stack, ref].join(' → ')})`);
98
- let a = readJson(assemblyPath(ref));
163
+ let a = opts.assembly ? structuredClone(opts.assembly) : readJson(assemblyPath(ref));
99
164
  // A pose may set items' variables as well as joints ("cocked": { "run": -30, "action.travel": 25 }): a flexure bent
100
165
  // as the pose bends it, while the part itself is printed as drawn. The pose being built sets them on its items.
101
- const itemSets = (name) => { const out = {}; for (const [k, v] of Object.entries(a.poses?.[name] || {})) if (k.includes('.')) { const [item, ...rest] = k.split('.'); (out[item] ||= {})[rest.join('.')] = v; } return out; };
166
+ const itemSets = (name) => {
167
+ const out = {};
168
+ for (const [k, v] of Object.entries(a.poses?.[name] || {}))
169
+ if (k.includes('.')) {
170
+ const [item, ...rest] = k.split('.');
171
+ (out[item] ||= {})[rest.join('.')] = v;
172
+ }
173
+ return out;
174
+ };
102
175
  const builtPose = opts.pose ?? a.pose ?? Object.keys(a.poses || {})[0];
103
176
  const ownSets = typeof builtPose === 'string' ? itemSets(builtPose) : {};
104
177
  overrides = { ...overrides };
105
178
  const printer = printerOf(project);
106
179
  if (a.kind === 'plate' && !(a.uses || []).includes(printer)) a.uses = [...(a.uses || []), printer]; // a plate is checked as a print
107
- const values = Object.fromEntries((a.uses || []).map((u) => { const s = loadRuleSet(u); return [u, Object.fromEntries(Object.entries(s.rules).map(([k, r]) => [k, r.value]))]; }));
180
+ const values = Object.fromEntries(
181
+ (a.uses || []).map((u) => {
182
+ const s = loadRuleSet(u);
183
+ return [u, Object.fromEntries(Object.entries(s.rules).map(([k, r]) => [k, r.value]))];
184
+ }),
185
+ );
108
186
 
109
187
  // Names in positions: rule sets (mx.pitch), items' variables (cap.lift), or into components (key-0-0.cap.lift).
110
188
  // Rule values may still be expressions (rules referring to rules): resolved on demand.
111
- const seen = new Set(), ids = [];
189
+ const seen = new Set(),
190
+ ids = [];
112
191
  const lookup = (n) => {
113
192
  const path = n.split('.');
114
193
  if ((a.uses || []).includes(path[0])) seen.add(n);
115
- if (!(path[0] in values)) throw new Error(`"${n}": no item or rule set "${path[0]}" (items: ${ids.join(', ') || 'none yet'}; uses: ${(a.uses || []).join(', ') || 'none'})`);
194
+ if (!(path[0] in values))
195
+ throw new Error(
196
+ `"${n}": no item or rule set "${path[0]}" (items: ${ids.join(', ') || 'none yet'}; uses: ${(a.uses || []).join(', ') || 'none'})`,
197
+ );
116
198
  let v = values;
117
199
  for (const k of path) v = v?.[k];
118
- if (typeof v === 'string') v = evaluate(v, (k) => lookup(k.includes('.') ? k : `${path.slice(0, -1).join('.')}.${k}`));
200
+ if (typeof v === 'string')
201
+ v = evaluate(v, (k) => lookup(k.includes('.') ? k : `${path.slice(0, -1).join('.')}.${k}`));
119
202
  if (typeof v !== 'number') throw new Error(`"${n}" isn't a number`);
120
203
  return v;
121
204
  };
122
205
  const num = (x) => evaluate(x, lookup);
123
206
  // A generated frame (lib/framegen.mjs): "frame": { "kind": "box", "inside": [..] } into beams, joins and their ends, first
124
207
  let generated = null;
125
- if (a.frame && typeof a.frame === 'object' && !Array.isArray(a.frame)) ({ a, frame: generated } = expandFrame(a, num, framesContext()));
208
+ if (a.frame && typeof a.frame === 'object' && !Array.isArray(a.frame))
209
+ ({ a, frame: generated } = expandFrame(a, num, framesContext()));
126
210
  // Joins between beams (lib/joins.mjs): their operations go on the beams and their screws into fasten before anything is built
127
211
  let joins = [];
128
212
  if (a.joins != null) ({ a, joins } = expandJoins(a, num, undefined, plasticOf(project)));
@@ -130,25 +214,60 @@ export async function buildAssembly(ref, stack = [], overrides = {}, opts = {})
130
214
  let panels = [];
131
215
  if ((a.items || []).some((it) => it?.panel)) ({ a, panels } = expandPanels(a, num, undefined, plasticOf(project)));
132
216
  // Services (lib/services.mjs): a bought board or supply on its printed mount, a wire's run along a slot held by clips
133
- let mounts = [], runs = [];
134
- if ((a.items || []).some((it) => it?.mount != null) || (a.wires || []).some((w) => (w?.via ?? []).some((v) => v && typeof v === 'object'))) ({ a, mounts, runs } = expandServices(a, num, undefined, plasticOf(project)));
217
+ let mounts = [],
218
+ runs = [];
219
+ if (
220
+ (a.items || []).some((it) => it?.mount != null) ||
221
+ (a.wires || []).some((w) => (w?.via ?? []).some((v) => v && typeof v === 'object'))
222
+ )
223
+ ({ a, mounts, runs } = expandServices(a, num, undefined, plasticOf(project)));
135
224
  // Guides (lib/guides.mjs): a rail on a beam's face, its screws into the slot, each carriage on its own sliding joint
136
225
  let guides = [];
137
226
  if (a.guides != null) ({ a, guides } = expandGuides(a, num, undefined, plasticOf(project)));
138
- const { translate, rotate, transform } = jscad.transforms, deg = Math.PI / 180;
227
+ const { transform } = jscad.transforms;
139
228
 
140
- const items = [], parts = [], objects = [], fits = [], requires = [];
229
+ const items = [],
230
+ parts = [],
231
+ objects = [],
232
+ fits = [],
233
+ requires = [];
141
234
  for (const [k, r] of Object.entries(a.requires || {})) requires.push({ object: k, range: r, from: ref });
142
235
  const built = new Map(); // each object or component is built once per set of values, however many copies are placed
143
236
  const source = async (it, extra) => {
144
- if (it.motor) { const key = JSON.stringify(['motor', it.id, it.motor]); if (!built.has(key)) built.set(key, motorBuilt(it.motor, num, it.id)); return built.get(key); }
145
- if (it.beam) { const b = beamBuilt(it, num, it.id); if (!built.has(b.key)) built.set(b.key, b); return built.get(b.key); } // (lib/beams.mjs)
146
- if (it.fitting) { const b = await fittingBuilt(it, it.id, framesContext(), plasticOf(project)); if (!built.has(b.key)) built.set(b.key, b); return built.get(b.key); } // (lib/fittings.mjs)
147
- if (it.panel) { const b = await panelBuilt(it, it.id); if (!built.has(b.key)) built.set(b.key, b); return built.get(b.key); } // (lib/panels.mjs)
148
- if (it._guide) { const b = guideBuilt(it, it.id); if (!built.has(b.key)) built.set(b.key, b); return built.get(b.key); } // (lib/guides.mjs)
237
+ if (it.motor) {
238
+ const key = JSON.stringify(['motor', it.id, it.motor]);
239
+ if (!built.has(key)) built.set(key, motorBuilt(it.motor, num, it.id));
240
+ return built.get(key);
241
+ }
242
+ if (it.beam) {
243
+ const b = beamBuilt(it, num, it.id);
244
+ if (!built.has(b.key)) built.set(b.key, b);
245
+ return built.get(b.key);
246
+ } // (lib/beams.mjs)
247
+ if (it.fitting) {
248
+ const b = await fittingBuilt(it, it.id, framesContext(), plasticOf(project));
249
+ if (!built.has(b.key)) built.set(b.key, b);
250
+ return built.get(b.key);
251
+ } // (lib/fittings.mjs)
252
+ if (it.panel) {
253
+ const b = await panelBuilt(it, it.id);
254
+ if (!built.has(b.key)) built.set(b.key, b);
255
+ return built.get(b.key);
256
+ } // (lib/panels.mjs)
257
+ if (it._guide) {
258
+ const b = guideBuilt(it, it.id);
259
+ if (!built.has(b.key)) built.set(b.key, b);
260
+ return built.get(b.key);
261
+ } // (lib/guides.mjs)
149
262
  if (it.bought) {
150
263
  const key = JSON.stringify(['bought', it.id, it.bought, it.variant, it.set]);
151
- if (!built.has(key)) built.set(key, boughtSets().get(it.bought) === 'motor' ? motorBuilt({ model: it.bought }, num, it.id) : boughtBuilt(it.bought, it, num, it.id));
264
+ if (!built.has(key))
265
+ built.set(
266
+ key,
267
+ boughtSets().get(it.bought) === 'motor'
268
+ ? motorBuilt({ model: it.bought }, num, it.id)
269
+ : boughtBuilt(it.bought, it, num, it.id),
270
+ );
152
271
  return built.get(key);
153
272
  }
154
273
  // from: inputs worked out from items built before this one ({ "usb_y": "board.pcb.pico_y" }): numbers, in this
@@ -160,25 +279,75 @@ export async function buildAssembly(ref, stack = [], overrides = {}, opts = {})
160
279
  let own = null;
161
280
  const ownValue = async (x) => {
162
281
  if (typeof x !== 'string') return x;
163
- try { return num(x); } catch {}
282
+ try {
283
+ return num(x);
284
+ } catch {
285
+ // (not a plain number: read below as an address on another item)
286
+ }
164
287
  if (!it.object || !new RegExp(`\\b${it.id}\\.`).test(x)) return x;
165
- if (!own) { const [r, named] = String(it.object).split(':'), [objName, pin] = r.split('@'), d = locateIn(project, objName, `projects/${project}/assemblies/${name}.json, item ${it.id}'s "object"`); own = (await build({ ...(pin ? materialise(d, pin) : d), ...((named || it.variant) ? { variant: named || it.variant } : {}) }, base, opts)).values; }
166
- return evaluate(x, (n) => { if (n.startsWith(`${it.id}.`)) { const v = own[n.slice(it.id.length + 1)]; if (typeof v === 'number') return v; } return lookup(n); });
288
+ if (!own) {
289
+ const [r, named] = String(it.object).split(':'),
290
+ [objName, pin] = r.split('@'),
291
+ d = locateIn(project, objName, `projects/${project}/assemblies/${name}.json, item ${it.id}'s "object"`);
292
+ own = (
293
+ await build(
294
+ { ...(pin ? materialise(d, pin) : d), ...(named || it.variant ? { variant: named || it.variant } : {}) },
295
+ base,
296
+ opts,
297
+ )
298
+ ).values;
299
+ }
300
+ return evaluate(x, (n) => {
301
+ if (n.startsWith(`${it.id}.`)) {
302
+ const v = own[n.slice(it.id.length + 1)];
303
+ if (typeof v === 'number') return v;
304
+ }
305
+ return lookup(n);
306
+ });
167
307
  };
168
308
  const posed = {};
169
309
  for (const [k, x] of Object.entries(ownSets[it.id] || {})) posed[k] = await ownValue(x);
170
310
  const set = { ...(it.set || {}), ...from, ...posed, ...(overrides[it.id] || {}), ...(it.assembly ? {} : extra) };
171
311
  // Built for the mirror, an object's mirror settings win (no legends), so copies that differ only there are one shape
172
- if (opts.mirror && it.object) for (const k of Object.keys(readObject(locateIn(project, String(it.object).split(/[:@]/)[0], `projects/${project}/assemblies/${name}.json, item ${it.id}'s "object"`)).mirror || {})) delete set[k];
312
+ if (opts.mirror && it.object)
313
+ for (const k of Object.keys(
314
+ readObject(
315
+ locateIn(
316
+ project,
317
+ String(it.object).split(/[:@]/)[0],
318
+ `projects/${project}/assemblies/${name}.json, item ${it.id}'s "object"`,
319
+ ),
320
+ ).mirror || {},
321
+ ))
322
+ delete set[k];
173
323
  const sub = it.assembly ? extra : {}; // a component's values go to its items: { cap: { units: 1.5 } }
174
324
  const key = JSON.stringify([it.object, it.variant, it.assembly, set, sub]);
175
325
  if (!built.has(key)) {
176
- if (it.assembly) built.set(key, { key, sub: await buildAssembly(`${project}/${it.assembly}`, [...stack, ref], sub, { ...opts, pose: undefined }) }); // a pose names the outer assembly's joints
326
+ if (it.assembly)
327
+ built.set(key, {
328
+ key,
329
+ sub: await buildAssembly(`${project}/${it.assembly}`, [...stack, ref], sub, {
330
+ ...opts,
331
+ pose: undefined,
332
+ assembly: undefined,
333
+ }),
334
+ }); // a pose names the outer assembly's joints; an assembly given in place of a file is this one, not its items'
177
335
  else {
178
- const [ref, named] = String(it.object).split(':'), [objName, pin] = ref.split('@'), variant = named || it.variant;
179
- const d = locateIn(project, objName, `projects/${project}/assemblies/${name}.json, item ${it.id}'s "object"`), at = { ...(pin ? materialise(d, pin) : d), ...(variant ? { variant } : {}) };
336
+ const [ref, named] = String(it.object).split(':'),
337
+ [objName, pin] = ref.split('@'),
338
+ variant = named || it.variant;
339
+ const d = locateIn(project, objName, `projects/${project}/assemblies/${name}.json, item ${it.id}'s "object"`),
340
+ at = { ...(pin ? materialise(d, pin) : d), ...(variant ? { variant } : {}) };
180
341
  const b = await build(at, set, opts);
181
- built.set(key, { key, objName, b, version: pin || b.object.version, variant, role: ['reference', 'board'].includes(b.object.role) ? 'reference' : 'part', set: base }); // a board is made by a fab: checked, never printed. set: what it's made with, as printed (not bent by a pose)
342
+ built.set(key, {
343
+ key,
344
+ objName,
345
+ b,
346
+ version: pin || b.object.version,
347
+ variant,
348
+ role: ['reference', 'board'].includes(b.object.role) ? 'reference' : 'part',
349
+ set: base,
350
+ }); // a board is made by a fab: checked, never printed. set: what it's made with, as printed (not bent by a pose)
182
351
  }
183
352
  }
184
353
  return built.get(key);
@@ -186,46 +355,87 @@ export async function buildAssembly(ref, stack = [], overrides = {}, opts = {})
186
355
  const placing = [];
187
356
  let builtCount = 0;
188
357
  for (const it of a.items || []) {
189
- if (!/^[a-z][\w-]*$/.test(it.id || '')) throw new Error(`each item needs an id (letters, digits, - or _): got ${JSON.stringify(it.id)}`);
190
- if ([it.object, it.assembly, it.motor, it.bought, it.beam, it.fitting, it.panel].filter(Boolean).length !== 1) throw new Error(`item ${it.id}: give one of "object", "assembly", "motor", "bought", "beam", "fitting" or "panel"`);
191
- if (!it.beam && (it.to != null || it.roll != null)) throw new Error(`item ${it.id}: to and roll place a beam by its ends: place ${it.object || it.assembly || it.motor?.model || it.bought} with at and rotate`);
358
+ if (!/^[a-z][\w-]*$/.test(it.id || ''))
359
+ throw new Error(`each item needs an id (letters, digits, - or _): got ${JSON.stringify(it.id)}`);
360
+ if ([it.object, it.assembly, it.motor, it.bought, it.beam, it.fitting, it.panel].filter(Boolean).length !== 1)
361
+ throw new Error(
362
+ `item ${it.id}: give one of "object", "assembly", "motor", "bought", "beam", "fitting" or "panel"`,
363
+ );
364
+ if (!it.beam && (it.to != null || it.roll != null))
365
+ throw new Error(
366
+ `item ${it.id}: to and roll place a beam by its ends: place ${it.object || it.assembly || it.motor?.model || it.bought} with at and rotate`,
367
+ );
192
368
  // Copies: one, a grid from repeat x/y, or a layout's keys. Each: { id, offset (from at), extra (values to set) }
193
- const rx = it.repeat?.x, ry = it.repeat?.y, rl = it.repeat?.layout, copies = [];
369
+ const rx = it.repeat?.x,
370
+ ry = it.repeat?.y,
371
+ rl = it.repeat?.layout,
372
+ copies = [];
194
373
  if (rl) {
195
374
  // A layout file in the project's layouts/, or (older assemblies) object/name: a layout kept in an object's .json
196
375
  const [lp, ln] = String(rl).includes('/') ? String(rl).split('/') : [null, rl];
197
- const data = lp ? readObject(locateIn(project, lp, `projects/${project}/assemblies/${name}.json, item ${it.id}'s "repeat" layout`)).layouts?.[ln] : readLayout(project, ln);
376
+ const data = lp
377
+ ? readObject(
378
+ locateIn(project, lp, `projects/${project}/assemblies/${name}.json, item ${it.id}'s "repeat" layout`),
379
+ ).layouts?.[ln]
380
+ : readLayout(project, ln);
198
381
  if (!data) throw new Error(`item ${it.id}: no layout "${ln}" in ${lp}.json`);
199
382
  const step = num(it.repeat.step);
200
383
  // Values each copy sets: its width, a value for its row (rows: { "cap.row": ["R1", …] }) and constants (each)
201
384
  // per: { "cap.legend": "legend" } sets an input from each key's own property (skipped where the key has none)
202
- const per = (k) => Object.fromEntries(Object.entries(it.repeat.per || {}).filter(([, f]) => k[f] != null).map(([n, f]) => [n, k[f]]));
203
- const values = (k) => ({ ...(it.repeat.width ? { [it.repeat.width]: k.units } : {}), ...(it.repeat.each || {}), ...per(k),
204
- ...Object.fromEntries(Object.entries(it.repeat.rows || {}).map(([n, list]) => {
205
- if (k.index >= list.length) throw new Error(`item ${it.id}: repeat.rows ${n} has ${list.length} values, the layout ${rows(data)} rows`);
206
- return [n, list[k.index]];
207
- })) });
385
+ const per = (k) =>
386
+ Object.fromEntries(
387
+ Object.entries(it.repeat.per || {})
388
+ .filter(([, f]) => k[f] != null)
389
+ .map(([n, f]) => [n, k[f]]),
390
+ );
391
+ const values = (k) => ({
392
+ ...(it.repeat.width ? { [it.repeat.width]: k.units } : {}),
393
+ ...(it.repeat.each || {}),
394
+ ...per(k),
395
+ ...Object.fromEntries(
396
+ Object.entries(it.repeat.rows || {}).map(([n, list]) => {
397
+ if (k.index >= list.length)
398
+ throw new Error(
399
+ `item ${it.id}: repeat.rows ${n} has ${list.length} values, the layout ${rows(data)} rows`,
400
+ );
401
+ return [n, list[k.index]];
402
+ }),
403
+ ),
404
+ });
208
405
  const rows = (l) => (l.rows || []).length;
209
406
  for (const k of keyCentres(data)) {
210
407
  const extra = {};
211
408
  for (const [n, val] of Object.entries(values(k))) {
212
- if (!it.assembly) { extra[n] = val; continue; }
409
+ if (!it.assembly) {
410
+ extra[n] = val;
411
+ continue;
412
+ }
213
413
  const [item, name] = n.split('.'); // in a component: <item>.<variable>
214
- if (!name) throw new Error(`item ${it.id}: name a component's variable as <item>.<variable>, e.g. cap.units (got ${n})`);
414
+ if (!name)
415
+ throw new Error(
416
+ `item ${it.id}: name a component's variable as <item>.<variable>, e.g. cap.units (got ${n})`,
417
+ );
215
418
  (extra[item] ||= {})[name] = val;
216
419
  }
217
420
  copies.push({ id: `${it.id}-${k.index}-${k.col}`, offset: [k.x * step, k.y * step], extra, label: k.label });
218
421
  }
219
422
  } else {
220
- const nx = rx ? Math.round(num(rx.count)) : 1, ny = ry ? Math.round(num(ry.count)) : 1;
221
- for (let i = 0; i < nx; i++) for (let j = 0; j < ny; j++) {
222
- copies.push({ id: it.repeat ? `${it.id}-${i}${ry ? `-${j}` : ''}` : it.id, offset: [rx ? i * num(rx.step) : 0, ry ? j * num(ry.step) : 0], extra: {} });
223
- }
423
+ const nx = rx ? Math.round(num(rx.count)) : 1,
424
+ ny = ry ? Math.round(num(ry.count)) : 1;
425
+ for (let i = 0; i < nx; i++)
426
+ for (let j = 0; j < ny; j++) {
427
+ copies.push({
428
+ id: it.repeat ? `${it.id}-${i}${ry ? `-${j}` : ''}` : it.id,
429
+ offset: [rx ? i * num(rx.step) : 0, ry ? j * num(ry.step) : 0],
430
+ extra: {},
431
+ });
432
+ }
224
433
  }
225
434
  const first = await source(it, copies[0].extra);
226
435
  values[it.id] = first.sub ? first.sub.values : first.b.values; // a repeated item's own name works too: cap.base, not only cap-0-0
227
436
  for (const c of copies) {
228
- c.src = await source(it, c.extra); values[c.id] = c.src.sub ? c.src.sub.values : c.src.b.values;
437
+ c.src = await source(it, c.extra);
438
+ values[c.id] = c.src.sub ? c.src.sub.values : c.src.b.values;
229
439
  opts.progress?.({ stage: 'build', assembly: ref, item: c.id, done: ++builtCount }); // progress: for a caller to show (cad --progress)
230
440
  }
231
441
  placing.push([it, copies]);
@@ -235,29 +445,80 @@ export async function buildAssembly(ref, stack = [], overrides = {}, opts = {})
235
445
  // placed by at and rotate, or by the joint whose child it is.
236
446
  const placed = []; // [it, copy], each a motion item, in order
237
447
  for (const [it, copies] of placing) {
238
- if (it.have != null && !it.bought && !it.motor) throw new Error(`item ${it.id}: "have" marks a bought part or a motor as in hand, and ${it.id} is ${it.object ? `printed (object ${it.object})` : it.beam ? 'a beam, cut from the bar on the cut list' : 'neither'}`);
239
- if (it.place === false) { // built only for its values ("place": false): a board a print plate's case is sized from
240
- for (const c of copies) if (!c.src.sub) objects.push({ id: c.id, objName: c.src.objName, version: c.src.version, built: c.src.b, role: c.src.role, unplaced: true });
448
+ if (it.have != null && !it.bought && !it.motor)
449
+ throw new Error(
450
+ `item ${it.id}: "have" marks a bought part or a motor as in hand, and ${it.id} is ${it.object ? `printed (object ${it.object})` : it.beam ? 'a beam, cut from the bar on the cut list' : 'neither'}`,
451
+ );
452
+ if (it.place === false) {
453
+ // built only for its values ("place": false): a board a print plate's case is sized from
454
+ for (const c of copies)
455
+ if (!c.src.sub)
456
+ objects.push({
457
+ id: c.id,
458
+ objName: c.src.objName,
459
+ version: c.src.version,
460
+ built: c.src.b,
461
+ role: c.src.role,
462
+ unplaced: true,
463
+ });
241
464
  continue;
242
465
  }
243
- for (const c of copies) { placed.push([it, c]); ids.push(c.id); }
466
+ for (const c of copies) {
467
+ placed.push([it, c]);
468
+ ids.push(c.id);
469
+ }
244
470
  }
245
- const motion = motionOf(a, placed, num, ref), wires = wiresOf(a, placed, motion.joints), task = taskOf(a, motion, num), gait = gaitOf(a, motion, num);
471
+ const motion = motionOf(a, placed, num, ref),
472
+ wires = wiresOf(a, placed, motion.joints),
473
+ task = taskOf(a, motion, num),
474
+ gait = gaitOf(a, motion, num);
246
475
  // (items printed together in place, which the assembly order never takes apart: each by its id)
247
- for (const id of a.printInPlace || []) if (!motion.items.some((x) => x[0] === id)) throw new Error(`printInPlace names "${id}", which isn't an item (${motion.items.map((x) => x[0]).join(', ')})`);
248
- fits.push(...shaftFits(motion.drives, motion.joints, placed.map(([, c]) => c.id)).map((x) => ({ ...x, num })));
476
+ for (const id of a.printInPlace || [])
477
+ if (!motion.items.some((x) => x[0] === id))
478
+ throw new Error(`printInPlace names "${id}", which isn't an item (${motion.items.map((x) => x[0]).join(', ')})`);
479
+ fits.push(
480
+ ...shaftFits(
481
+ motion.drives,
482
+ motion.joints,
483
+ placed.map(([, c]) => c.id),
484
+ ).map((x) => ({ ...x, num })),
485
+ );
249
486
  for (const [it, c] of placed) {
250
- const src = c.src, id = c.id;
487
+ const src = c.src,
488
+ id = c.id;
251
489
  if (src.sub) {
252
490
  const sub = src.sub;
253
491
  for (const o of sub.objects) objects.push({ ...o, id: `${id}.${o.id}` });
254
- for (const x of sub.fits) fits.push({ ...x, a: `${id}.${x.a}`, b: `${id}.${x.b}`, label: x.label && `${x.label} (${id})` });
492
+ for (const x of sub.fits)
493
+ fits.push({ ...x, a: `${id}.${x.a}`, b: `${id}.${x.b}`, label: x.label && `${x.label} (${id})` });
255
494
  requires.push(...sub.requires);
256
495
  for (const n of sub.seen) seen.add(n);
257
496
  items.push({ ...it, id, sub, role: 'part' });
258
497
  } else {
259
- objects.push({ id, objName: src.objName, version: src.version, built: src.b, role: src.role, ...(src.set ? { set: src.set } : {}), ...(src.variant ? { variant: src.variant } : {}), ...(src.bought ? { bought: src.bought } : {}), ...(src.motor ? { motor: src.motor } : {}), ...(src.beam ? { beam: src.beam } : {}), ...(src.fitting ? { fitting: src.fitting } : {}), ...(src.panel ? { panel: src.panel } : {}), ...(it.have === true ? { have: true } : {}) }); // ("have" on the object: a repeat's copies and a component's parts keep it)
260
- items.push({ ...it, id, objName: src.objName, built: src.b, version: src.version, role: src.role, ...(src.beam ? { beam: src.beam } : {}) });
498
+ objects.push({
499
+ id,
500
+ objName: src.objName,
501
+ version: src.version,
502
+ built: src.b,
503
+ role: src.role,
504
+ ...(src.set ? { set: src.set } : {}),
505
+ ...(src.variant ? { variant: src.variant } : {}),
506
+ ...(src.bought ? { bought: src.bought } : {}),
507
+ ...(src.motor ? { motor: src.motor } : {}),
508
+ ...(src.beam ? { beam: src.beam } : {}),
509
+ ...(src.fitting ? { fitting: src.fitting } : {}),
510
+ ...(src.panel ? { panel: src.panel } : {}),
511
+ ...(it.have === true ? { have: true } : {}),
512
+ }); // ("have" on the object: a repeat's copies and a component's parts keep it)
513
+ items.push({
514
+ ...it,
515
+ id,
516
+ objName: src.objName,
517
+ built: src.b,
518
+ version: src.version,
519
+ role: src.role,
520
+ ...(src.beam ? { beam: src.beam } : {}),
521
+ });
261
522
  }
262
523
  }
263
524
  // Every part, with its item where the joints put it at these values (jointValues); then the hardware of its fasten
@@ -266,31 +527,72 @@ export async function buildAssembly(ref, stack = [], overrides = {}, opts = {})
266
527
  const partsAt = (worlds) => {
267
528
  const out = [];
268
529
  placed.forEach(([, c], k) => {
269
- const src = c.src, id = c.id, key = src.key, m = toMat4(worlds[k]);
530
+ const src = c.src,
531
+ id = c.id,
532
+ key = src.key,
533
+ m = toMat4(worlds[k]);
270
534
  items[k].m = m;
271
535
  // Faces are moved as they are, not re-triangulated in place: triangulating again after a move rounds differently
272
536
  const move = (polys) => polys.map((poly) => poly.map((v) => jscad.maths.vec3.transform([0, 0, 0], v, m)));
273
537
  if (src.sub) {
274
538
  for (const p of src.sub.parts) {
275
539
  if (p.role === 'support' && a.kind !== 'plate') continue;
276
- out.push({ ...p, name: `${id}.${p.name}`, item: id, leaf: `${id}.${p.leaf}`, label: `${id} ${p.label}`,
277
- geometry: transform(m, p.geometry), polygons: move(p.polygons), triangles: move(p.triangles), ...(p.collide ? { collide: transform(m, p.collide) } : {}), m: jscad.maths.mat4.multiply(jscad.maths.mat4.create(), m, p.m),
278
- ...(p.hardware ? { moves: id, allow: p.allow.map((l) => `${id}.${l}`), lift: jscad.maths.vec3.transform([0, 0, 0], p.lift, [...m.slice(0, 12), 0, 0, 0, 1]) } : {}) }); // (a component's screws move with it)
540
+ out.push({
541
+ ...p,
542
+ name: `${id}.${p.name}`,
543
+ item: id,
544
+ leaf: `${id}.${p.leaf}`,
545
+ label: `${id} ${p.label}`,
546
+ geometry: transform(m, p.geometry),
547
+ polygons: move(p.polygons),
548
+ triangles: move(p.triangles),
549
+ ...(p.collide ? { collide: transform(m, p.collide) } : {}),
550
+ m: jscad.maths.mat4.multiply(jscad.maths.mat4.create(), m, p.m),
551
+ ...(p.hardware
552
+ ? {
553
+ moves: id,
554
+ allow: p.allow.map((l) => `${id}.${l}`),
555
+ lift: jscad.maths.vec3.transform([0, 0, 0], p.lift, [...m.slice(0, 12), 0, 0, 0, 1]),
556
+ }
557
+ : {}),
558
+ }); // (a component's screws move with it)
279
559
  }
280
560
  } else {
281
561
  for (const p of src.b.parts) {
282
562
  if (p.role === 'support' && a.kind !== 'plate') continue; // supports are snipped off before parts go together
283
- out.push({ name: `${id}.${p.name}`, item: id, leaf: id, object: src.objName, role: src.role === 'reference' ? 'reference' : p.role, label: `${id}: ${marks.has(id) ? `mark ${marks.get(id)}, ` : ''}${p.label}`,
284
- ...(p.filament ? { filament: p.filament } : {}), ...(p.mirror === false ? { mirror: false } : {}), ...(p.fill != null ? { fill: p.fill } : {}), part: p.name,
285
- geometry: transform(m, p.geometry), ...(p.collide ? { collide: transform(m, p.collide) } : {}), polygons: move(p.polygons), triangles: move(p.triangles),
286
- shape: `${key}:${p.name}`, hash: `${src.b.hash}:${p.name}`, local: p.polygons, localTriangles: p.triangles, m });
563
+ out.push({
564
+ name: `${id}.${p.name}`,
565
+ item: id,
566
+ leaf: id,
567
+ object: src.objName,
568
+ role: src.role === 'reference' ? 'reference' : p.role,
569
+ label: `${id}: ${marks.has(id) ? `mark ${marks.get(id)}, ` : ''}${p.label}`,
570
+ ...(p.filament ? { filament: p.filament } : {}),
571
+ ...(p.mirror === false ? { mirror: false } : {}),
572
+ ...(p.fill != null ? { fill: p.fill } : {}),
573
+ part: p.name,
574
+ geometry: transform(m, p.geometry),
575
+ ...(p.collide ? { collide: transform(m, p.collide) } : {}),
576
+ polygons: move(p.polygons),
577
+ triangles: move(p.triangles),
578
+ shape: `${key}:${p.name}`,
579
+ hash: `${src.b.hash}:${p.name}`,
580
+ local: p.polygons,
581
+ localTriangles: p.triangles,
582
+ m,
583
+ });
287
584
  }
288
585
  }
289
586
  });
290
587
  for (const h of hardware) out.push(fastening.hardwarePart(h, toMat4(worlds[h.host])));
291
588
  return out;
292
589
  };
293
- for (const x of a.fits || []) for (const p of x.poses || []) if (!motion.poses[p]) throw new Error(`fit ${x.note || x.label || `${x.a} / ${x.b}`}: no pose "${p}" (poses: ${Object.keys(motion.poses).join(', ') || 'none'})`);
590
+ for (const x of a.fits || [])
591
+ for (const p of x.poses || [])
592
+ if (!motion.poses[p])
593
+ throw new Error(
594
+ `fit ${x.note || x.label || `${x.a} / ${x.b}`}: no pose "${p}" (poses: ${Object.keys(motion.poses).join(', ') || 'none'})`,
595
+ );
294
596
  // each beam's mark on the cut list and its sheet (beams that are the same share one), shown in its label
295
597
  const marks = marksOf(objects);
296
598
  for (const o of objects) if (marks.has(o.id)) o.mark = marks.get(o.id);
@@ -304,7 +606,9 @@ export async function buildAssembly(ref, stack = [], overrides = {}, opts = {})
304
606
  if (a.fits?.some((x) => x.holes)) fastening ||= await import('./fasten.mjs'); // (a holes fit with a fit that fastens: the fasten that says both is suggested)
305
607
  if (a.fasten?.length && a.kind !== 'plate') {
306
608
  fastening ||= await import('./fasten.mjs');
307
- fastened = fastening.fastenOf({ a, project, parts, objects, motion, num }, worlds0, { access: pose === motion.pose });
609
+ fastened = fastening.fastenOf({ a, project, parts, objects, motion, num }, worlds0, {
610
+ access: pose === motion.pose,
611
+ });
308
612
  hardware = fastened.hardware;
309
613
  parts.push(...hardware.map((h) => fastening.hardwarePart(h, toMat4(worlds0[h.host]))));
310
614
  fits.push(...fastened.fits.map((x) => ({ ...x, num })));
@@ -313,41 +617,94 @@ export async function buildAssembly(ref, stack = [], overrides = {}, opts = {})
313
617
  // With * on both sides, each copy is checked against all the others: { "a": "key-*.cap", "b": "key-*.cap" }
314
618
  // A beam's address in a fit or an access is read now, so one past the beam's end is refused by name when it is built
315
619
  const beamIds = new Set(placed.filter(([it]) => it.beam).map(([, c]) => c.id));
316
- for (const x of a.fits || []) for (const n of [x.a, x.b, x.access].flat()) {
317
- if (typeof n === 'string' && beamIds.has(n.split('.')[0]) && n.includes('.') && !/\.body$/.test(n)) motion.address(n, `fit ${x.note || x.label || `${x.a} / ${x.b}`}`);
318
- }
620
+ for (const x of a.fits || [])
621
+ for (const n of [x.a, x.b, x.access].flat()) {
622
+ if (typeof n === 'string' && beamIds.has(n.split('.')[0]) && n.includes('.') && !/\.body$/.test(n))
623
+ motion.address(n, `fit ${x.note || x.label || `${x.a} / ${x.b}`}`);
624
+ }
319
625
  if (a.fits?.some((x) => x.fastener && typeof x.fastener === 'object')) pinning ||= await import('./pins.mjs');
320
626
  for (let x of a.fits || []) {
321
627
  if (x.fastener && typeof x.fastener === 'object') x = pinning.pinOfFit(x, project); // (pins or magnets by the schema's form: the fit's pin or magnet, and the fastener's name)
322
628
  if (x.seat != null && x.min == null) x = { ...x, min: -1000 }; // a seat presses, so the pair may overlap
323
629
  if (x.holes) x = { ...x, a: x.holes, b: x.into }; // a holes fit: a board's holes (a) over what its screws go into (b)
324
630
  const star = [x.a, x.b].find((n) => n.includes('*'));
325
- if (!star) { fits.push({ ...x, num }); continue; }
326
- const match = (n) => { const re = new RegExp(`^${n.split('.')[0].replace(/[-]/g, '\\-').replace('*', '([\\w-]+)')}$`); return ids.filter((id) => re.test(id)); };
327
- const copies = match(star), at = (id, n) => [id, ...n.split('.').slice(1)].join('.');
631
+ if (!star) {
632
+ fits.push({ ...x, num });
633
+ continue;
634
+ }
635
+ const match = (n) => {
636
+ const re = new RegExp(`^${n.split('.')[0].replace(/[-]/g, '\\-').replace('*', '([\\w-]+)')}$`);
637
+ return ids.filter((id) => re.test(id));
638
+ };
639
+ const copies = match(star),
640
+ at = (id, n) => [id, ...n.split('.').slice(1)].join('.');
328
641
  if (!copies.length) throw new Error(`fit ${x.a} / ${x.b}: nothing matches ${star}`);
329
642
  if (x.a.includes('*') && x.b.includes('*')) {
330
643
  const others = match(x.b);
331
- for (const id of copies) fits.push({ ...x, a: at(id, x.a), b: others.filter((o) => o !== id).map((o) => at(o, x.b)), num });
644
+ for (const id of copies)
645
+ fits.push({ ...x, a: at(id, x.a), b: others.filter((o) => o !== id).map((o) => at(o, x.b)), num });
332
646
  continue;
333
647
  }
334
- for (const id of copies) { const swap = (n) => (n === star ? at(id, n) : n); fits.push({ ...x, a: swap(x.a), b: swap(x.b), num }); }
648
+ for (const id of copies) {
649
+ const swap = (n) => (n === star ? at(id, n) : n);
650
+ fits.push({ ...x, a: swap(x.a), b: swap(x.b), num });
651
+ }
335
652
  }
336
653
  // at(pose): the same assembly in another pose (a name, or { joint: values }), nothing built again
337
654
  const same = (x, y) => JSON.stringify(x) === JSON.stringify(y);
338
655
  const others = {};
339
- if (!opts.onePose) for (const n of Object.keys(a.poses || {})) if (n !== builtPose && !same(itemSets(n), ownSets)) others[n] = await buildAssembly(ref, stack, outer, { ...opts, pose: n, onePose: true });
656
+ if (!opts.onePose)
657
+ for (const n of Object.keys(a.poses || {}))
658
+ if (n !== builtPose && !same(itemSets(n), ownSets))
659
+ others[n] = await buildAssembly(ref, stack, outer, { ...opts, pose: n, onePose: true });
340
660
  const at = (p) => {
341
661
  if (typeof p === 'string' && others[p]) return others[p];
342
- const v = jointValues(motion, p), moved = partsAt(placeItems(motion, v));
343
- return { ...s, parts: moved, fastened: null, pose: typeof p === 'string' ? p : null, jointValues: v, polygons: moved.flatMap((x) => x.polygons), triangles: moved.flatMap((x) => x.triangles) };
662
+ const v = jointValues(motion, p),
663
+ moved = partsAt(placeItems(motion, v));
664
+ return {
665
+ ...s,
666
+ parts: moved,
667
+ fastened: null,
668
+ pose: typeof p === 'string' ? p : null,
669
+ jointValues: v,
670
+ polygons: moved.flatMap((x) => x.polygons),
671
+ triangles: moved.flatMap((x) => x.triangles),
672
+ };
344
673
  };
345
674
  // A stepper's torque at speed follows its driver's supply: the bought supply's volts, where the assembly has one
346
675
  // (power.mjs holds the same supply against the draw); with none, @rulecad/motors' default
347
676
  const psu = objects.find((o) => o.bought?.part === 'supply' && !o.unplaced)?.built.values.output_voltage;
348
677
  if (psu > 0) for (const d of motion?.drives ?? []) if (d.model?.type === 'stepper') d.supply = psu;
349
- const s = { a, project, name, items, parts, objects, fits, requires, values, num, seen, motion, wires, task, gait, fastened, hardware, joins, generated, panels, mounts, runs, guides, pose: typeof pose === 'string' ? pose : null, jointValues: jv, at,
350
- polygons: parts.flatMap((p) => p.polygons), triangles: parts.flatMap((p) => p.triangles) };
678
+ const s = {
679
+ a,
680
+ project,
681
+ name,
682
+ items,
683
+ parts,
684
+ objects,
685
+ fits,
686
+ requires,
687
+ values,
688
+ num,
689
+ seen,
690
+ motion,
691
+ wires,
692
+ task,
693
+ gait,
694
+ fastened,
695
+ hardware,
696
+ joins,
697
+ generated,
698
+ panels,
699
+ mounts,
700
+ runs,
701
+ guides,
702
+ pose: typeof pose === 'string' ? pose : null,
703
+ jointValues: jv,
704
+ at,
705
+ polygons: parts.flatMap((p) => p.polygons),
706
+ triangles: parts.flatMap((p) => p.triangles),
707
+ };
351
708
  return s;
352
709
  }
353
710
 
@@ -376,117 +733,265 @@ const rows = (m) => [m[0], m[4], m[8], m[12], m[1], m[5], m[9], m[13], m[2], m[6
376
733
  const toMat4 = (r) => [r[0], r[4], r[8], 0, r[1], r[5], r[9], 0, r[2], r[6], r[10], 0, r[3], r[7], r[11], 1];
377
734
  export const LIMITS = { angle: [-180, 180] };
378
735
  function motionOf(a, placed, num, ref) {
379
- const { translate, rotate } = jscad.transforms, deg = Math.PI / 180;
736
+ const { translate, rotate } = jscad.transforms,
737
+ deg = Math.PI / 180;
380
738
  const index = new Map(placed.map(([, c], k) => [c.id, k]));
381
- const where = (n, what) => { if (!index.has(n)) throw new Error(`${what}: no item "${n}" (items: ${[...index.keys()].join(', ')})`); return index.get(n); };
382
- const evalIn = (values, label) => (x) => evaluate(x, (n) => {
383
- let v = values;
384
- for (const k of n.split('.')) v = v?.[k];
385
- if (typeof v !== 'number') throw new Error(`${label}: "${n}" isn't one of its numbers`);
386
- return v;
387
- });
739
+ const where = (n, what) => {
740
+ if (!index.has(n)) throw new Error(`${what}: no item "${n}" (items: ${[...index.keys()].join(', ')})`);
741
+ return index.get(n);
742
+ };
743
+ const evalIn = (values, label) => (x) =>
744
+ evaluate(x, (n) => {
745
+ let v = values;
746
+ for (const k of n.split('.')) v = v?.[k];
747
+ if (typeof v !== 'number') throw new Error(`${label}: "${n}" isn't one of its numbers`);
748
+ return v;
749
+ });
388
750
  const frameOf = (spec, ev) => {
389
751
  const at = (spec.at || [0, 0, 0]).map(ev);
390
- if (spec.rotate) { const m = turn(spec.rotate.map(ev)); m[3] = at[0]; m[7] = at[1]; m[11] = at[2]; return m; }
752
+ if (spec.rotate) {
753
+ const m = turn(spec.rotate.map(ev));
754
+ m[3] = at[0];
755
+ m[7] = at[1];
756
+ m[11] = at[2];
757
+ return m;
758
+ }
391
759
  return frame(at, (spec.axis || [0, 0, 1]).map(ev), spec.ref && spec.ref.map(ev));
392
760
  };
393
761
  // An anchor: { item (index, -1 the world), frame (12 numbers, in the item's own frame) }
394
762
  const anchor = (spec, what) => {
395
- if (spec && typeof spec === 'object') return { item: spec.item ? where(spec.item, what) : -1, frame: frameOf(spec, num) };
396
- const bits = String(spec).split('.'), id = bits[0];
397
- if (bits.length < 2 || !id || !bits.at(-1)) throw new Error(`${what}: name an anchor as <item>.<anchor> (got "${spec}")`);
763
+ if (spec && typeof spec === 'object')
764
+ return { item: spec.item ? where(spec.item, what) : -1, frame: frameOf(spec, num) };
765
+ const bits = String(spec).split('.'),
766
+ id = bits[0];
767
+ if (bits.length < 2 || !id || !bits.at(-1))
768
+ throw new Error(`${what}: name an anchor as <item>.<anchor> (got "${spec}")`);
398
769
  const k = where(id, what);
399
- let src = placed[k][1].src, pre = [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0], i = 1;
400
- for (; i < bits.length - 1 && !src.beam; i++) { // into a component: its item's place there
401
- const n = bits[i], sub = src.sub?.items.find((x) => x.id === n);
770
+ let src = placed[k][1].src,
771
+ pre = [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0],
772
+ i = 1;
773
+ for (; i < bits.length - 1 && !src.beam; i++) {
774
+ // into a component: its item's place there
775
+ const n = bits[i],
776
+ sub = src.sub?.items.find((x) => x.id === n);
402
777
  if (!sub) throw new Error(`${what}: ${bits.slice(0, i).join('.')} has no item "${n}"`);
403
778
  pre = mul(pre, rows(sub.m));
404
779
  src = sub.sub ? { sub: sub.sub } : { b: sub.built, objName: sub.objName, beam: sub.beam };
405
780
  }
406
781
  // A beam's address, the rest of the name: an end (a, b), an end's bore (a.1), a face with a distance (top.2@120)
407
- if (src.beam) return { item: k, frame: mul(pre, beamAddress(src.beam, bits.slice(i).join('.'), `${what}: ${bits.slice(0, i).join('.')}`)) };
782
+ if (src.beam)
783
+ return {
784
+ item: k,
785
+ frame: mul(pre, beamAddress(src.beam, bits.slice(i).join('.'), `${what}: ${bits.slice(0, i).join('.')}`)),
786
+ };
408
787
  const name = bits[i];
409
788
  const anchors = src.b?.object.anchors || {};
410
- if (!anchors[name]) throw new Error(`${what}: ${src.objName || id} has no anchor "${name}" (anchors: ${Object.keys(anchors).join(', ') || 'none'})`);
789
+ if (!anchors[name])
790
+ throw new Error(
791
+ `${what}: ${src.objName || id} has no anchor "${name}" (anchors: ${Object.keys(anchors).join(', ') || 'none'})`,
792
+ );
411
793
  return { item: k, frame: mul(pre, frameOf(anchors[name], evalIn(src.b.values, `${src.objName} anchor ${name}`))) };
412
794
  };
413
- const joints = [], children = new Set();
795
+ const joints = [],
796
+ children = new Set();
414
797
  // An item at an address ("at": "x1.top@50%") is held there as by a fixed joint: its own origin on the anchor, its z
415
798
  // out of the face and its x along the beam toward end b, turned by its rotate in that frame; it moves with the beam
416
- const atAddress = placed.map(([it]) => it).filter((it, k, all) => typeof it.at === 'string' && all.indexOf(it) === k).map((it) => {
417
- if (it.repeat) throw new Error(`item ${it.id}: an item at an address ("${it.at}") is one copy: place a repeat with at [x, y, z]`);
418
- if (it.beam) throw new Error(`item ${it.id}: a beam is placed by its ends (from, to) or at a point [x, y, z], not at an address`);
419
- return { id: `${it.id}@`, type: 'fixed', parent: it.at, child: { item: it.id, at: [0, 0, 0], ...(it.rotate ? { rotate: it.rotate } : {}) }, at: true };
420
- });
799
+ const atAddress = placed
800
+ .map(([it]) => it)
801
+ .filter((it, k, all) => typeof it.at === 'string' && all.indexOf(it) === k)
802
+ .map((it) => {
803
+ if (it.repeat)
804
+ throw new Error(
805
+ `item ${it.id}: an item at an address ("${it.at}") is one copy: place a repeat with at [x, y, z]`,
806
+ );
807
+ if (it.beam)
808
+ throw new Error(
809
+ `item ${it.id}: a beam is placed by its ends (from, to) or at a point [x, y, z], not at an address`,
810
+ );
811
+ return {
812
+ id: `${it.id}@`,
813
+ type: 'fixed',
814
+ parent: it.at,
815
+ child: { item: it.id, at: [0, 0, 0], ...(it.rotate ? { rotate: it.rotate } : {}) },
816
+ at: true,
817
+ };
818
+ });
421
819
  for (const j of [...atAddress, ...(a.joints || [])]) {
422
820
  const what = `joint ${j.id}`;
423
- if (!j.at && !/^[a-z][\w-]*$/.test(j.id || '')) throw new Error(`each joint needs an id (letters, digits, - or _): got ${JSON.stringify(j.id)}`);
424
- if (!Object.hasOwn(DOFS, j.type)) throw new Error(`${what}: type is one of ${Object.keys(DOFS).join(', ')} (got ${JSON.stringify(j.type)})`);
425
- const p = j.parent == null ? { item: -1, frame: frame([0, 0, 0]) } : anchor(j.parent, j.at ? `item ${j.child.item}: at` : what), c = anchor(j.child, what);
821
+ if (!j.at && !/^[a-z][\w-]*$/.test(j.id || ''))
822
+ throw new Error(`each joint needs an id (letters, digits, - or _): got ${JSON.stringify(j.id)}`);
823
+ if (!Object.hasOwn(DOFS, j.type))
824
+ throw new Error(`${what}: type is one of ${Object.keys(DOFS).join(', ')} (got ${JSON.stringify(j.type)})`);
825
+ const p =
826
+ j.parent == null
827
+ ? { item: -1, frame: frame([0, 0, 0]) }
828
+ : anchor(j.parent, j.at ? `item ${j.child.item}: at` : what),
829
+ c = anchor(j.child, what);
426
830
  if (j.at) c.frame = inv(c.frame); // (the item turned by its rotate in the anchor's frame: the joint's child anchor is that turn undone)
427
831
  if (c.item < 0) throw new Error(`${what}: its child must be an item`);
428
832
  if (j.at && p.item === c.item) throw new Error(`item ${j.child.item}: at "${j.parent}" is on the item itself`);
429
- if (children.has(c.item)) throw new Error(`${what}: ${placed[c.item][1].id} is already placed by ${joints.find((x) => x.child === c.item)?.at ? `its at (${placed[c.item][0].at})` : 'another joint'} (two joints to one item make a ring: use loops)`);
833
+ if (children.has(c.item))
834
+ throw new Error(
835
+ `${what}: ${placed[c.item][1].id} is already placed by ${joints.find((x) => x.child === c.item)?.at ? `its at (${placed[c.item][0].at})` : 'another joint'} (two joints to one item make a ring: use loops)`,
836
+ );
430
837
  const [it] = placed[c.item];
431
- if (!j.at && (it.at || it.rotate || it.repeat || it.from != null && it.beam)) throw new Error(`${what}: ${it.id} is placed by the joint, so it can't have at, rotate, repeat${it.beam ? ', or from and to' : ''}`);
838
+ if (!j.at && (it.at || it.rotate || it.repeat || (it.from != null && it.beam)))
839
+ throw new Error(
840
+ `${what}: ${it.id} is placed by the joint, so it can't have at, rotate, repeat${it.beam ? ', or from and to' : ''}`,
841
+ );
432
842
  children.add(c.item);
433
843
  const path = j.type === 'path' ? (j.path || []).map((pt) => pt.map(num)) : undefined;
434
844
  if (path && path.length < 2) throw new Error(`${what}: a path joint needs "path": two points or more`);
435
- const kinds = DOFS[j.type], list = (x) => (x == null ? [] : [].concat(x));
436
- const lo = list(j.min), hi = list(j.max), val = list(j.value);
845
+ const kinds = DOFS[j.type],
846
+ list = (x) => (x == null ? [] : [].concat(x));
847
+ const lo = list(j.min),
848
+ hi = list(j.max),
849
+ val = list(j.value);
437
850
  const dofs = kinds.map((kind, i) => {
438
851
  const range = j.type === 'path' ? [0, pathLength(path)] : kind === 'angle' ? LIMITS.angle : null;
439
- const mn = lo[i] != null ? num(lo[i]) : range?.[0], mx = hi[i] != null ? num(hi[i]) : range?.[1];
852
+ const mn = lo[i] != null ? num(lo[i]) : range?.[0],
853
+ mx = hi[i] != null ? num(hi[i]) : range?.[1];
440
854
  if (mn == null || mx == null) throw new Error(`${what}: give its ${kind} a min and max`);
441
855
  if (mn > mx) throw new Error(`${what}: min ${mn} is above max ${mx}`);
442
856
  return [mn, mx, val[i] != null ? num(val[i]) : Math.min(mx, Math.max(mn, 0))];
443
857
  });
444
- joints.push({ id: j.id, type: j.type, parent: p.item, child: c.item, a: p.frame, b: c.frame, dofs, ...(j.at ? { at: true } : {}),
445
- ...(j.label ? { label: j.label } : {}), ...(path ? { path } : {}), ...(j.cone != null ? { cone: num(j.cone) } : {}),
446
- ...(j.follow ? { follow: [j.follow, j.ratio != null ? num(j.ratio) : 1, j.offset != null ? num(j.offset) : 0] } : {}),
447
- ...(j.mesh ? { meshSpec: j.mesh } : {}), ...(j.brake ? { brake: j.brake } : {}) });
448
- }
449
- for (const j of joints) if (j.follow) {
450
- const l = joints.find((x) => x.id === j.follow[0]);
451
- if (!l) throw new Error(`joint ${j.id}: follows "${j.follow[0]}", which isn't a joint (${joints.map((x) => x.id).join(', ')})`);
452
- if (l.dofs.length !== j.dofs.length) throw new Error(`joint ${j.id} (${j.type}) takes ${j.dofs.length} values, but follows ${l.id} (${l.type}), which takes ${l.dofs.length}`);
858
+ joints.push({
859
+ id: j.id,
860
+ type: j.type,
861
+ parent: p.item,
862
+ child: c.item,
863
+ a: p.frame,
864
+ b: c.frame,
865
+ dofs,
866
+ ...(j.at ? { at: true } : {}),
867
+ ...(j.label ? { label: j.label } : {}),
868
+ ...(path ? { path } : {}),
869
+ ...(j.cone != null ? { cone: num(j.cone) } : {}),
870
+ ...(j.follow
871
+ ? { follow: [j.follow, j.ratio != null ? num(j.ratio) : 1, j.offset != null ? num(j.offset) : 0] }
872
+ : {}),
873
+ ...(j.mesh ? { meshSpec: j.mesh } : {}),
874
+ ...(j.brake ? { brake: j.brake } : {}),
875
+ });
453
876
  }
877
+ for (const j of joints)
878
+ if (j.follow) {
879
+ const l = joints.find((x) => x.id === j.follow[0]);
880
+ if (!l)
881
+ throw new Error(
882
+ `joint ${j.id}: follows "${j.follow[0]}", which isn't a joint (${joints.map((x) => x.id).join(', ')})`,
883
+ );
884
+ if (l.dofs.length !== j.dofs.length)
885
+ throw new Error(
886
+ `joint ${j.id} (${j.type}) takes ${j.dofs.length} values, but follows ${l.id} (${l.type}), which takes ${l.dofs.length}`,
887
+ );
888
+ }
454
889
  const items = placed.map(([it, c], k) => {
455
890
  if (children.has(k)) return [c.id];
456
891
  const ends = it.beam ? beamPlace(it, num) : null; // a beam by its ends (lib/beams.mjs)
457
892
  if (ends) return [c.id, ...ends];
458
- const base = (it.at || [0, 0, 0]).map(num), rot = (it.rotate || [0, 0, 0]).map((r) => num(r) * deg);
893
+ const base = (it.at || [0, 0, 0]).map(num),
894
+ rot = (it.rotate || [0, 0, 0]).map((r) => num(r) * deg);
459
895
  // A repeated item turns as a whole about its at: each copy's offset turns with it (keys on a tilted plate)
460
- return [c.id, ...rows(translate(base, rotate(rot, translate([c.offset[0], c.offset[1], 0], jscad.geometries.geom3.create()))).transforms)];
896
+ return [
897
+ c.id,
898
+ ...rows(
899
+ translate(base, rotate(rot, translate([c.offset[0], c.offset[1], 0], jscad.geometries.geom3.create())))
900
+ .transforms,
901
+ ),
902
+ ];
461
903
  });
462
904
  const meshes = [...gearMeshes(joints, items, num), ...planetaries(a.planetary || [], joints, items, num)];
463
- const drives = motorDrives(a, placed, joints, num), loads = loadsOf(a, anchor, num, joints);
464
- const poses = Object.fromEntries(Object.entries(a.poses || {}).map(([n, set]) => [n, Object.fromEntries(Object.entries(set).filter(([id]) => !id.includes('.')).map(([id, v]) => {
465
- if (!joints.some((j) => j.id === id)) throw new Error(`pose ${n}: no joint "${id}"`);
466
- return [id, Array.isArray(v) ? v.map(num) : num(v)];
467
- }))]));
468
- if (a.pose && !poses[a.pose]) throw new Error(`pose "${a.pose}" isn't one of the poses (${Object.keys(poses).join(', ') || 'none'})`);
469
- const loops = (a.loops || []).map((l, i) => ({ label: l.label || `${typeof l.a === 'string' ? l.a : 'anchor'} meets ${typeof l.b === 'string' ? l.b : 'anchor'}`,
470
- a: anchor(l.a, `loop ${i + 1}`), b: anchor(l.b, `loop ${i + 1}`), tolerance: l.tolerance != null ? num(l.tolerance) : 0.01 }));
905
+ const drives = motorDrives(a, placed, joints, num),
906
+ loads = loadsOf(a, anchor, num, joints);
907
+ const poses = Object.fromEntries(
908
+ Object.entries(a.poses || {}).map(([n, set]) => [
909
+ n,
910
+ Object.fromEntries(
911
+ Object.entries(set)
912
+ .filter(([id]) => !id.includes('.'))
913
+ .map(([id, v]) => {
914
+ if (!joints.some((j) => j.id === id)) throw new Error(`pose ${n}: no joint "${id}"`);
915
+ return [id, Array.isArray(v) ? v.map(num) : num(v)];
916
+ }),
917
+ ),
918
+ ]),
919
+ );
920
+ if (a.pose && !poses[a.pose])
921
+ throw new Error(`pose "${a.pose}" isn't one of the poses (${Object.keys(poses).join(', ') || 'none'})`);
922
+ const loops = (a.loops || []).map((l, i) => ({
923
+ label: l.label || `${typeof l.a === 'string' ? l.a : 'anchor'} meets ${typeof l.b === 'string' ? l.b : 'anchor'}`,
924
+ a: anchor(l.a, `loop ${i + 1}`),
925
+ b: anchor(l.b, `loop ${i + 1}`),
926
+ tolerance: l.tolerance != null ? num(l.tolerance) : 0.01,
927
+ }));
471
928
  // Every object item's anchors, to say where things are: a finding near one names it (keyboard@pivot)
472
- const marks = placed.flatMap(([, c], k) => Object.entries(c.src?.b?.object.anchors || {}).map(([name, spec]) => {
473
- try { return { item: k, id: c.id, name, frame: frameOf(spec, evalIn(c.src.b.values, `${c.src.objName} anchor ${name}`)) }; } catch { return null; }
474
- })).filter(Boolean);
929
+ const marks = placed
930
+ .flatMap(([, c], k) =>
931
+ Object.entries(c.src?.b?.object.anchors || {}).map(([name, spec]) => {
932
+ try {
933
+ return {
934
+ item: k,
935
+ id: c.id,
936
+ name,
937
+ frame: frameOf(spec, evalIn(c.src.b.values, `${c.src.objName} anchor ${name}`)),
938
+ };
939
+ } catch {
940
+ return null;
941
+ }
942
+ }),
943
+ )
944
+ .filter(Boolean);
475
945
  // address(name): any anchor by name, a beam's addresses too (x1.top@120), as { item, frame }: for fits and the build order
476
946
  // Where each screw of a fasten goes, where it says so with anchors: a point on its axis, the anchor's z along it
477
- const fasten = (a.fasten || []).map((x, i) => (Array.isArray(x.at) ? x.at : []).map((n) => ({ ...anchor(n, `fasten ${i + 1}`), name: typeof n === 'string' ? n : null })));
478
- return { items, joints, poses, pose: a.pose || Object.keys(poses)[0], loops, ref, marks, meshes, drives, loads, fasten, gravity: (a.gravity || [0, 0, -1]).map(num), address: (n, what = 'address') => anchor(n, what) };
947
+ const fasten = (a.fasten || []).map((x, i) =>
948
+ (Array.isArray(x.at) ? x.at : []).map((n) => ({
949
+ ...anchor(n, `fasten ${i + 1}`),
950
+ name: typeof n === 'string' ? n : null,
951
+ })),
952
+ );
953
+ return {
954
+ items,
955
+ joints,
956
+ poses,
957
+ pose: a.pose || Object.keys(poses)[0],
958
+ loops,
959
+ ref,
960
+ marks,
961
+ meshes,
962
+ drives,
963
+ loads,
964
+ fasten,
965
+ gravity: (a.gravity || [0, 0, -1]).map(num),
966
+ address: (n, what = 'address') => anchor(n, what),
967
+ };
479
968
  }
480
969
 
481
970
  // A pair measured from its drawn teeth (@rulecad/gears contact: backlash, transmission error, interference), kept in
482
971
  // .cache/gears/ by the pair, the centre distance and the gears package's code, as it takes half a second
483
972
  let gearsCode = null;
484
973
  function measured(a, b, centre) {
485
- gearsCode ||= (() => { const dir = path.dirname(fileURLToPath(import.meta.resolve('@rulecad/gears'))); return fs.readdirSync(dir).filter((f) => f.endsWith('.mjs') && f !== 'test.mjs' && !f.startsWith('.')).sort().map((f) => fs.readFileSync(path.join(dir, f), 'utf8')).join(''); })();
486
- const file = paths.cache('gears', `${crypto.createHash('sha256').update(JSON.stringify([gearsCode, a, b, +centre.toFixed(6)])).digest('hex')}.json`);
487
- if (!process.env.CAD_NO_CACHE && host.exists(file)) return JSON.parse(host.readText(file));
488
- const r = contact(a, b, { centre, steps: 12 }), keep = { findings: r.findings, backlash: r.backlash, error: r.error };
489
- try { host.writeText(file, JSON.stringify(keep)); } catch {} // (only slower without it)
974
+ gearsCode ||= (() => {
975
+ const dir = path.dirname(fileURLToPath(import.meta.resolve('@rulecad/gears')));
976
+ return fs
977
+ .readdirSync(dir)
978
+ .filter((f) => f.endsWith('.mjs') && f !== 'test.mjs' && !f.startsWith('.'))
979
+ .sort()
980
+ .map((f) => fs.readFileSync(path.join(dir, f), 'utf8'))
981
+ .join('');
982
+ })();
983
+ const file = paths.cache(
984
+ 'gears',
985
+ `${crypto
986
+ .createHash('sha256')
987
+ .update(JSON.stringify([gearsCode, a, b, +centre.toFixed(6)]))
988
+ .digest('hex')}.json`,
989
+ );
990
+ const kept = !process.env.CAD_NO_CACHE && readCacheJson(file);
991
+ if (kept) return kept;
992
+ const r = contact(a, b, { centre, steps: 12 }),
993
+ keep = { findings: r.findings, backlash: r.backlash, error: r.error };
994
+ writeCacheFile(file, JSON.stringify(keep)); // (one that can't be written is only slower)
490
995
  return keep;
491
996
  }
492
997
 
@@ -496,100 +1001,278 @@ function measured(a, b, centre) {
496
1001
  // follows it. With one held, each turns in proportion to the driver (Willis), so each is a follow: its ratio from the
497
1002
  // teeth, its offset from where the parts are with their joints at 0, so a tooth sits in a gap everywhere.
498
1003
  function planetaries(list, joints, items, num) {
499
- const out = [], DEG = Math.PI / 180;
500
- const col = (W, k) => [W[k], W[4 + k], W[8 + k]], org = (W) => [W[3], W[7], W[11]];
501
- const dot = (a, b) => a[0] * b[0] + a[1] * b[1] + a[2] * b[2], sub = (a, b) => [a[0] - b[0], a[1] - b[1], a[2] - b[2]];
1004
+ const out = [],
1005
+ DEG = Math.PI / 180;
1006
+ const col = (W, k) => [W[k], W[4 + k], W[8 + k]],
1007
+ org = (W) => [W[3], W[7], W[11]];
1008
+ const dot = (a, b) => a[0] * b[0] + a[1] * b[1] + a[2] * b[2],
1009
+ sub = (a, b) => [a[0] - b[0], a[1] - b[1], a[2] - b[2]];
502
1010
  const crossP = (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]];
503
- const flat = (v, z) => sub(v, z.map((x) => x * dot(v, z))), len = (v) => Math.hypot(...v);
1011
+ const flat = (v, z) =>
1012
+ sub(
1013
+ v,
1014
+ z.map((x) => x * dot(v, z)),
1015
+ ),
1016
+ len = (v) => Math.hypot(...v);
504
1017
  const ang = (v, x0, z) => Math.atan2(dot(crossP(x0, v), z), dot(x0, v)); // radians
505
1018
  list.forEach((g, n) => {
506
- const what = `planetary ${n + 1}`, index = (id, role) => { const k = items.findIndex((x) => x[0] === id); if (k < 0) throw new Error(`${what}: ${role} "${id}" isn't an item (${items.map((x) => x[0]).join(', ')})`); return k; };
1019
+ const what = `planetary ${n + 1}`,
1020
+ index = (id, role) => {
1021
+ const k = items.findIndex((x) => x[0] === id);
1022
+ if (k < 0) throw new Error(`${what}: ${role} "${id}" isn't an item (${items.map((x) => x[0]).join(', ')})`);
1023
+ return k;
1024
+ };
507
1025
  const idx = { sun: index(g.sun, 'sun'), carrier: index(g.carrier, 'carrier'), ring: index(g.ring, 'ring') };
508
1026
  const planets = [].concat(g.planets || []).map((id) => index(id, 'planet'));
509
1027
  if (!planets.length) throw new Error(`${what}: planets names the planet items`);
510
- const jointOf = (k) => joints.find((j) => j.child === k), moving = (k) => { const j = jointOf(k); return j && j.type !== 'fixed' ? j : null; };
1028
+ const jointOf = (k) => joints.find((j) => j.child === k),
1029
+ moving = (k) => {
1030
+ const j = jointOf(k);
1031
+ return j && j.type !== 'fixed' ? j : null;
1032
+ };
511
1033
  const held = ['sun', 'carrier', 'ring'].filter((m) => !moving(idx[m]));
512
- if (held.length !== 1) throw new Error(`${what}: hold one of the sun, carrier and ring (no joint, or a fixed one), and turn the other two on revolutes (held now: ${held.join(', ') || 'none'})`);
1034
+ if (held.length !== 1)
1035
+ throw new Error(
1036
+ `${what}: hold one of the sun, carrier and ring (no joint, or a fixed one), and turn the other two on revolutes (held now: ${held.join(', ') || 'none'})`,
1037
+ );
513
1038
  const drive = g.drive ?? ['carrier', 'sun', 'ring'].find((m) => m !== held[0]);
514
- if (!['sun', 'carrier', 'ring'].includes(drive) || drive === held[0]) throw new Error(`${what}: drive is the sun, the carrier or the ring, and not the one held (${held[0]})`);
515
- const third = ['sun', 'carrier', 'ring'].find((m) => m !== held[0] && m !== drive), lead = moving(idx[drive]), follower = moving(idx[third]);
516
- for (const [m, j] of [[drive, lead], [third, follower]]) if (j.type !== 'revolute') throw new Error(`${what}: the ${m} turns on a revolute (its joint ${j.id} is a ${j.type})`);
517
- if (follower.follow || follower.meshSpec) throw new Error(`${what}: ${follower.id} turns the ${third}, which follows the ${drive} here: give it no follow or mesh of its own`);
518
- const planetJoints = planets.map((k) => { const j = jointOf(k); if (!j || j.type !== 'revolute' || j.parent !== idx.carrier) throw new Error(`${what}: planet ${items[k][0]} turns on a revolute on the carrier (${items[idx.carrier][0]})`); return j; });
1039
+ if (!['sun', 'carrier', 'ring'].includes(drive) || drive === held[0])
1040
+ throw new Error(`${what}: drive is the sun, the carrier or the ring, and not the one held (${held[0]})`);
1041
+ const third = ['sun', 'carrier', 'ring'].find((m) => m !== held[0] && m !== drive),
1042
+ lead = moving(idx[drive]),
1043
+ follower = moving(idx[third]);
1044
+ for (const [m, j] of [
1045
+ [drive, lead],
1046
+ [third, follower],
1047
+ ])
1048
+ if (j.type !== 'revolute')
1049
+ throw new Error(`${what}: the ${m} turns on a revolute (its joint ${j.id} is a ${j.type})`);
1050
+ if (follower.follow || follower.meshSpec)
1051
+ throw new Error(
1052
+ `${what}: ${follower.id} turns the ${third}, which follows the ${drive} here: give it no follow or mesh of its own`,
1053
+ );
1054
+ const planetJoints = planets.map((k) => {
1055
+ const j = jointOf(k);
1056
+ if (!j || j.type !== 'revolute' || j.parent !== idx.carrier)
1057
+ throw new Error(`${what}: planet ${items[k][0]} turns on a revolute on the carrier (${items[idx.carrier][0]})`);
1058
+ return j;
1059
+ });
519
1060
  const teeth = [].concat(g.teeth || []).map(num);
520
1061
  if (teeth.length !== 3) throw new Error(`${what}: teeth is [sun, planet, ring] (got ${JSON.stringify(g.teeth)})`);
521
- const [S, P, R] = teeth, common = { module: num(g.module), ...(g.pressureAngle != null ? { pressureAngle: num(g.pressureAngle) } : {}), ...(g.backlash != null ? { backlash: num(g.backlash) } : {}) };
522
- let sun, planet, ring;
523
- try { sun = gearModel({ ...common, teeth: S }); planet = gearModel({ ...common, teeth: P }); ring = internalModel({ ...common, teeth: R }); } catch (e) { throw new Error(`${what}: ${e.message}`); }
524
- if (R !== S + 2 * P) throw new Error(`${what}: a ring of ${R} isn't the sun and two planets across (${S} + 2 × ${P} = ${S + 2 * P})`);
1062
+ const [S, P, R] = teeth,
1063
+ common = {
1064
+ module: num(g.module),
1065
+ ...(g.pressureAngle != null ? { pressureAngle: num(g.pressureAngle) } : {}),
1066
+ ...(g.backlash != null ? { backlash: num(g.backlash) } : {}),
1067
+ };
1068
+ let sun, planet;
1069
+ try {
1070
+ sun = gearModel({ ...common, teeth: S });
1071
+ planet = gearModel({ ...common, teeth: P });
1072
+ internalModel({ ...common, teeth: R }); // (made only to refuse a ring that can't be cut: its figures aren't needed here)
1073
+ } catch (e) {
1074
+ throw new Error(`${what}: ${e.message}`);
1075
+ }
1076
+ if (R !== S + 2 * P)
1077
+ throw new Error(`${what}: a ring of ${R} isn't the sun and two planets across (${S} + 2 × ${P} = ${S + 2 * P})`);
525
1078
  // Every part where it is with these joints at 0
526
1079
  const v = jointValues({ joints, poses: {} }, {});
527
1080
  for (const j of [lead, follower, ...planetJoints]) v[j.id] = [0];
528
- if (g.output) { const j2 = moving(index(g.output.ring, 'output ring')); if (j2) v[j2.id] = [0]; } // (a range that leaves out 0 would put the ring where the phase isn't reckoned)
529
- const worlds = placeItems({ items, joints }, v), W = (k) => worlds[k];
530
- const O = org(W(idx.sun)), Z = col(W(idx.sun), 2), X0 = col(W(idx.sun), 0);
531
- const sign = (j) => Math.sign(dot(mul(j.parent < 0 ? [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0] : worlds[j.parent], j.a).filter((_, i) => [2, 6, 10].includes(i)), Z));
532
- for (const m of ['carrier', 'ring']) { const c = org(W(idx[m])), z = col(W(idx[m]), 2); if (len(flat(sub(c, O), Z)) > 1e-4 || Math.abs(Math.abs(dot(z, Z)) - 1) > 1e-6) throw new Error(`${what}: the ${m} turns about the sun's axis: centre it there`); }
1081
+ if (g.output) {
1082
+ const j2 = moving(index(g.output.ring, 'output ring'));
1083
+ if (j2) v[j2.id] = [0];
1084
+ } // (a range that leaves out 0 would put the ring where the phase isn't reckoned)
1085
+ const worlds = placeItems({ items, joints }, v),
1086
+ W = (k) => worlds[k];
1087
+ const O = org(W(idx.sun)),
1088
+ Z = col(W(idx.sun), 2),
1089
+ X0 = col(W(idx.sun), 0);
1090
+ const sign = (j) =>
1091
+ Math.sign(
1092
+ dot(
1093
+ mul(j.parent < 0 ? [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0] : worlds[j.parent], j.a).filter((_, i) =>
1094
+ [2, 6, 10].includes(i),
1095
+ ),
1096
+ Z,
1097
+ ),
1098
+ );
1099
+ for (const m of ['carrier', 'ring']) {
1100
+ const c = org(W(idx[m])),
1101
+ z = col(W(idx[m]), 2);
1102
+ if (len(flat(sub(c, O), Z)) > 1e-4 || Math.abs(Math.abs(dot(z, Z)) - 1) > 1e-6)
1103
+ throw new Error(`${what}: the ${m} turns about the sun's axis: centre it there`);
1104
+ }
533
1105
  const gr = ang(flat(col(W(idx.ring), 0), Z), X0, Z) * (dot(col(W(idx.ring), 2), Z) > 0 ? 1 : -1);
534
1106
  // planet k: where it sits (its centre's angle round the sun) and which way its first tooth points
535
- const pl = planets.map((k, i) => { const c = flat(sub(org(W(k)), O), Z); return { id: items[k][0], joint: planetJoints[i], r: len(c), beta: ang(c, X0, Z), gamma: ang(flat(col(W(k), 0), Z), X0, Z), s: sign(planetJoints[i]) }; });
1107
+ const pl = planets.map((k, i) => {
1108
+ const c = flat(sub(org(W(k)), O), Z);
1109
+ return {
1110
+ id: items[k][0],
1111
+ joint: planetJoints[i],
1112
+ r: len(c),
1113
+ beta: ang(c, X0, Z),
1114
+ gamma: ang(flat(col(W(k), 0), Z), X0, Z),
1115
+ s: sign(planetJoints[i]),
1116
+ };
1117
+ });
536
1118
  // One configuration that meshes, everything at its zero: planet 0 in phase with the ring, the sun with planet 0
537
- const b0 = pl[0].beta, pi0 = (R / P) * (gr - b0 * (1 - P / R) + Math.PI / R), sigma0 = (P / S) * (b0 * (1 + S / P) + Math.PI - Math.PI / P - pi0);
1119
+ const b0 = pl[0].beta,
1120
+ pi0 = (R / P) * (gr - b0 * (1 - P / R) + Math.PI / R),
1121
+ sigma0 = (P / S) * (b0 * (1 + S / P) + Math.PI - Math.PI / P - pi0);
538
1122
  // Willis on rotations from the zero (sun σ, carrier κ, ring ρ): σ − κ + (R/S)(ρ − κ) = σ0
539
1123
  const coef = { sun: 1, carrier: -(1 + R / S), ring: R / S };
540
1124
  const sg = { [drive]: sign(lead), [third]: sign(follower) };
541
1125
  // the third's rotation for the driver's: from the relation, with the held one still
542
- const rot = (d) => { const r = { [held[0]]: 0, [drive]: sg[drive] * d }; r[third] = (sigma0 - coef[drive] * r[drive]) / coef[third]; return r; };
1126
+ const rot = (d) => {
1127
+ const r = { [held[0]]: 0, [drive]: sg[drive] * d };
1128
+ r[third] = (sigma0 - coef[drive] * r[drive]) / coef[third];
1129
+ return r;
1130
+ };
543
1131
  // a straight line in the driver's value (f: degrees in, radians out): [ratio, offset in degrees]
544
- const lin = (f) => { const a = f(0), b = f(1), o = a / DEG; return [(b - a) / DEG, ((o + 180) % 360 + 360) % 360 - 180]; }; // (the offset a part-turn: a whole turn is the same place)
545
- const free = (j) => { j.limits = j.dofs[0].slice(0, 2); j.dofs[0] = [-1e6, 1e6, j.dofs[0][2]]; }; // what follows a sun can turn past a turn
1132
+ const lin = (f) => {
1133
+ const a = f(0),
1134
+ b = f(1),
1135
+ o = a / DEG;
1136
+ return [(b - a) / DEG, ((((o + 180) % 360) + 360) % 360) - 180];
1137
+ }; // (the offset a part-turn: a whole turn is the same place)
1138
+ const free = (j) => {
1139
+ j.limits = j.dofs[0].slice(0, 2);
1140
+ j.dofs[0] = [-1e6, 1e6, j.dofs[0][2]];
1141
+ }; // what follows a sun can turn past a turn
546
1142
  const [k3, o3] = lin((d) => sg[third] * rot(d * DEG)[third]);
547
- follower.follow = [lead.id, k3, o3]; free(follower);
548
- const findings = [], f = (level, text, code, between) => findings.push({ level, text, code, ...(between ? { between } : {}) });
1143
+ follower.follow = [lead.id, k3, o3];
1144
+ free(follower);
1145
+ const findings = [],
1146
+ f = (level, text, code, between) => findings.push({ level, text, code, ...(between ? { between } : {}) });
549
1147
  pl.forEach((p, i) => {
550
1148
  // the planet's first tooth from the sun's mesh: π = −(S/P) σ + β (1 + S/P) + π − π/P, β the planet's place
551
- const tooth = (d) => { const r = rot(d * DEG), beta = p.beta + r.carrier; return -(S / P) * r.sun + beta * (1 + S / P) + Math.PI - Math.PI / P; };
1149
+ const tooth = (d) => {
1150
+ const r = rot(d * DEG),
1151
+ beta = p.beta + r.carrier;
1152
+ return -(S / P) * r.sun + beta * (1 + S / P) + Math.PI - Math.PI / P;
1153
+ };
552
1154
  const [kp, op] = lin((d) => p.s * (tooth(d) - p.gamma - rot(d * DEG).carrier));
553
- p.joint.follow = [lead.id, kp, op]; free(p.joint);
1155
+ p.joint.follow = [lead.id, kp, op];
1156
+ free(p.joint);
554
1157
  // and with the ring: in phase with it too, or it can't go there
555
- const ringTooth = (P / R) * tooth(0) + p.beta * (1 - P / R) - Math.PI / R, pitch = (2 * Math.PI) / R;
556
- const miss = (((ringTooth - gr) % pitch) + pitch * 1.5) % pitch - pitch / 2;
1158
+ const ringTooth = (P / R) * tooth(0) + p.beta * (1 - P / R) - Math.PI / R,
1159
+ pitch = (2 * Math.PI) / R;
1160
+ const miss = ((((ringTooth - gr) % pitch) + pitch * 1.5) % pitch) - pitch / 2;
557
1161
  const centre = org(W(planets[i]));
558
- if (Math.abs(miss) > 1e-6) f('fail', `planet ${p.id} can't mesh with the sun and the ring at once where it is (${(p.beta / DEG).toFixed(2)}° round the sun): planets go every ${(360 / planets.length).toFixed(2)}°, and (S + R) / planets must be whole (${S + R} / ${planets.length})`, 'planetary.phase', [O, centre]);
1162
+ if (Math.abs(miss) > 1e-6)
1163
+ f(
1164
+ 'fail',
1165
+ `planet ${p.id} can't mesh with the sun and the ring at once where it is (${(p.beta / DEG).toFixed(2)}° round the sun): planets go every ${(360 / planets.length).toFixed(2)}°, and (S + R) / planets must be whole (${S + R} / ${planets.length})`,
1166
+ 'planetary.phase',
1167
+ [O, centre],
1168
+ );
559
1169
  const m = meshOf(sun, planet, { centre: p.r });
560
1170
  for (const x of m.findings) f(x.level, `sun and ${p.id}: ${x.text}`, x.code, [O, centre]);
561
1171
  if (i === 0) {
562
- for (const x of measured({ ...common, teeth: S }, { ...common, teeth: P }, p.r).findings) f(x.level, `sun and ${p.id}: ${x.text}`, x.code, [O, centre]);
563
- for (const x of measured({ ...common, teeth: P }, { ...common, teeth: R, kind: 'internal' }, p.r).findings) f(x.level, `${p.id} and the ring: ${x.text}`, x.code, [O, centre]);
1172
+ for (const x of measured({ ...common, teeth: S }, { ...common, teeth: P }, p.r).findings)
1173
+ f(x.level, `sun and ${p.id}: ${x.text}`, x.code, [O, centre]);
1174
+ for (const x of measured({ ...common, teeth: P }, { ...common, teeth: R, kind: 'internal' }, p.r).findings)
1175
+ f(x.level, `${p.id} and the ring: ${x.text}`, x.code, [O, centre]);
564
1176
  }
565
1177
  });
566
1178
  const ratioText = `the ${drive} drives the ${third}${held[0] === 'carrier' ? '' : ' and the planets'} (the ${held[0]} held): ${Number(Math.abs(k3).toFixed(4))} turns of the ${third} for each turn of the ${drive}, ${k3 * sg[drive] * sg[third] < 0 ? 'opposite ways' : 'the same way'}`;
567
- out.push({ joint: follower.id, with: lead.id, kind: 'planetary', text: ratioText, findings, between: [O, O], planetary: true, members: [follower.id, ...planetJoints.map((j) => j.id)] });
1179
+ out.push({
1180
+ joint: follower.id,
1181
+ with: lead.id,
1182
+ kind: 'planetary',
1183
+ text: ratioText,
1184
+ findings,
1185
+ between: [O, O],
1186
+ planetary: true,
1187
+ members: [follower.id, ...planetJoints.map((j) => j.id)],
1188
+ });
568
1189
  // A second ring, on the planets' second step: it follows the planets' turning as the first ring would
569
1190
  if (g.output) {
570
- const k2 = index(g.output.ring, 'output ring'), j2 = moving(k2), P2 = num(g.output.planet), R2 = num(g.output.teeth), oc = { ...common };
571
- if (!j2 || j2.type !== 'revolute') throw new Error(`${what}: the output ring ${g.output.ring} turns on a revolute`);
572
- if (j2.follow || j2.meshSpec) throw new Error(`${what}: ${j2.id} follows the planets here: give it no follow or mesh of its own`);
573
- if (R2 - P2 !== R - P) throw new Error(`${what}: the output ring and the planets' second step must differ as the first do: ${R2} - ${P2} isn't ${R} - ${P}, so one centre distance can't serve both`);
1191
+ const k2 = index(g.output.ring, 'output ring'),
1192
+ j2 = moving(k2),
1193
+ P2 = num(g.output.planet),
1194
+ R2 = num(g.output.teeth),
1195
+ oc = { ...common };
1196
+ if (!j2 || j2.type !== 'revolute')
1197
+ throw new Error(`${what}: the output ring ${g.output.ring} turns on a revolute`);
1198
+ if (j2.follow || j2.meshSpec)
1199
+ throw new Error(`${what}: ${j2.id} follows the planets here: give it no follow or mesh of its own`);
1200
+ if (R2 - P2 !== R - P)
1201
+ throw new Error(
1202
+ `${what}: the output ring and the planets' second step must differ as the first do: ${R2} - ${P2} isn't ${R} - ${P}, so one centre distance can't serve both`,
1203
+ );
574
1204
  let p2, r2;
575
- try { p2 = gearModel({ ...oc, teeth: P2 }); r2 = internalModel({ ...oc, teeth: R2 }); } catch (e) { throw new Error(`${what}: ${e.message}`); }
576
- const g2 = ang(flat(col(W(k2), 0), Z), X0, Z), s2 = sign(j2), p0 = pl[0], ps = Math.PI / R2;
577
- const toothAt = (d) => { const r = rot(d * DEG); return -(S / P) * r.sun + (p0.beta + r.carrier) * (1 + S / P) + Math.PI - Math.PI / P; };
578
- const ring2 = (d) => { const r = rot(d * DEG); return (P2 / R2) * toothAt(d) + (p0.beta + r.carrier) * (1 - P2 / R2) - ps - g2; };
1205
+ try {
1206
+ p2 = gearModel({ ...oc, teeth: P2 });
1207
+ r2 = internalModel({ ...oc, teeth: R2 });
1208
+ } catch (e) {
1209
+ throw new Error(`${what}: ${e.message}`);
1210
+ }
1211
+ const g2 = ang(flat(col(W(k2), 0), Z), X0, Z),
1212
+ s2 = sign(j2),
1213
+ p0 = pl[0],
1214
+ ps = Math.PI / R2;
1215
+ const toothAt = (d) => {
1216
+ const r = rot(d * DEG);
1217
+ return -(S / P) * r.sun + (p0.beta + r.carrier) * (1 + S / P) + Math.PI - Math.PI / P;
1218
+ };
1219
+ const ring2 = (d) => {
1220
+ const r = rot(d * DEG);
1221
+ return (P2 / R2) * toothAt(d) + (p0.beta + r.carrier) * (1 - P2 / R2) - ps - g2;
1222
+ };
579
1223
  const [k, o] = lin((d) => s2 * ring2(d));
580
- j2.follow = [lead.id, k, o]; free(j2);
581
- const eff = compoundEfficiency({ planet: P, planet2: P2, ring: R, ring2: R2 }), fails = [], ff = (level, text, code) => fails.push({ level, text, code, between: [O, O] });
582
- for (const x of meshOf(p2, r2, { centre: pl[0].r }).findings) ff(x.level, `${pl[0].id} and the output ring: ${x.text}`, x.code);
1224
+ j2.follow = [lead.id, k, o];
1225
+ free(j2);
1226
+ const eff = compoundEfficiency({ planet: P, planet2: P2, ring: R, ring2: R2 }),
1227
+ fails = [],
1228
+ ff = (level, text, code) => fails.push({ level, text, code, between: [O, O] });
1229
+ for (const x of meshOf(p2, r2, { centre: pl[0].r }).findings)
1230
+ ff(x.level, `${pl[0].id} and the output ring: ${x.text}`, x.code);
583
1231
  // Each planet's second step in phase with the output ring. A planet meshes the sun as well a whole tooth of its
584
1232
  // first step on (2π/P), and that turns its second step too: the first of those turns that puts it in phase with
585
1233
  // the ring is the one it takes (none, where every planet is in phase as it stands, as chapter 11's are)
586
1234
  pl.forEach((p, i) => {
587
- const pitch2 = (2 * Math.PI) / R2, missAt = (m) => { const t2 = (P2 / R2) * ((-(S / P) * sigma0 + p.beta * (1 + S / P) + Math.PI - Math.PI / P + (2 * Math.PI * m) / P)) + p.beta * (1 - P2 / R2) - ps; return (((t2 - (P2 / R2) * ((-(S / P) * sigma0 + p0.beta * (1 + S / P) + Math.PI - Math.PI / P)) - p0.beta * (1 - P2 / R2) + ps) % pitch2) + pitch2 * 1.5) % pitch2 - pitch2 / 2; };
1235
+ const pitch2 = (2 * Math.PI) / R2,
1236
+ missAt = (m) => {
1237
+ const t2 =
1238
+ (P2 / R2) * (-(S / P) * sigma0 + p.beta * (1 + S / P) + Math.PI - Math.PI / P + (2 * Math.PI * m) / P) +
1239
+ p.beta * (1 - P2 / R2) -
1240
+ ps;
1241
+ return (
1242
+ ((((t2 -
1243
+ (P2 / R2) * (-(S / P) * sigma0 + p0.beta * (1 + S / P) + Math.PI - Math.PI / P) -
1244
+ p0.beta * (1 - P2 / R2) +
1245
+ ps) %
1246
+ pitch2) +
1247
+ pitch2 * 1.5) %
1248
+ pitch2) -
1249
+ pitch2 / 2
1250
+ );
1251
+ };
588
1252
  const m = i === 0 ? 0 : Array.from({ length: P }, (_, k) => k).find((k) => Math.abs(missAt(k)) <= 1e-6);
589
- if (m == null) ff('fail', `planet ${p.id} can't mesh with the output ring where it is, whichever tooth of its first step meets the sun: every tooth count a multiple of the planets puts them all in phase`, 'planetary.phase');
590
- else if (m) p.joint.follow = [p.joint.follow[0], p.joint.follow[1], (((p.joint.follow[2] + (p.s * 360 * m) / P + 180) % 360) + 360) % 360 - 180];
1253
+ if (m == null)
1254
+ ff(
1255
+ 'fail',
1256
+ `planet ${p.id} can't mesh with the output ring where it is, whichever tooth of its first step meets the sun: every tooth count a multiple of the planets puts them all in phase`,
1257
+ 'planetary.phase',
1258
+ );
1259
+ else if (m)
1260
+ p.joint.follow = [
1261
+ p.joint.follow[0],
1262
+ p.joint.follow[1],
1263
+ ((((p.joint.follow[2] + (p.s * 360 * m) / P + 180) % 360) + 360) % 360) - 180,
1264
+ ];
1265
+ });
1266
+ out.push({
1267
+ joint: j2.id,
1268
+ with: lead.id,
1269
+ kind: 'planetary',
1270
+ efficiency: eff,
1271
+ text: `the second ring turns ${Number(Math.abs(k).toFixed(5))} of the ${drive}'s turn, ${k * s2 * sg[drive] < 0 ? 'the other way' : 'the same way'} (${Number((1 / Math.abs(k)).toFixed(2))}:1, about ${Math.round(eff * 100)}% efficient, an estimate)`,
1272
+ findings: fails,
1273
+ between: [O, O],
1274
+ planetary: true,
591
1275
  });
592
- out.push({ joint: j2.id, with: lead.id, kind: 'planetary', efficiency: eff, text: `the second ring turns ${Number(Math.abs(k).toFixed(5))} of the ${drive}'s turn, ${k * s2 * sg[drive] < 0 ? 'the other way' : 'the same way'} (${Number((1 / Math.abs(k)).toFixed(2))}:1, about ${Math.round(eff * 100)}% efficient, an estimate)`, findings: fails, between: [O, O], planetary: true });
593
1276
  }
594
1277
  });
595
1278
  return out;
@@ -599,37 +1282,85 @@ function planetaries(list, joints, items, num) {
599
1282
  // whose axes meet at the shaft angle, each gear drawn as @rulecad/gears draws one (back end at z = 0, apex up z). The
600
1283
  // cones must share their apex. The ratio is the surface speeds' where the pitch cones touch; the phase puts a tooth
601
1284
  // of one against a space of the other along that line.
602
- function bevelDrive(j, lead, spec, teeth, common, joints, items, num) {
603
- const what = `joint ${j.id}: mesh`, DEG = Math.PI / 180;
604
- const col = (W, k) => [W[k], W[4 + k], W[8 + k]], org = (W) => [W[3], W[7], W[11]];
605
- const dot = (a, b) => a[0] * b[0] + a[1] * b[1] + a[2] * b[2], sub = (a, b) => [a[0] - b[0], a[1] - b[1], a[2] - b[2]], add = (a, b) => a.map((x, i) => x + b[i]), times = (a, k) => a.map((x) => x * k);
606
- const crossP = (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]], len = (v) => Math.hypot(...v), unit = (v) => times(v, 1 / len(v));
1285
+ function bevelDrive(j, lead, spec, teeth, common, joints, items) {
1286
+ const what = `joint ${j.id}: mesh`,
1287
+ DEG = Math.PI / 180;
1288
+ const col = (W, k) => [W[k], W[4 + k], W[8 + k]],
1289
+ org = (W) => [W[3], W[7], W[11]];
1290
+ const dot = (a, b) => a[0] * b[0] + a[1] * b[1] + a[2] * b[2],
1291
+ sub = (a, b) => [a[0] - b[0], a[1] - b[1], a[2] - b[2]],
1292
+ add = (a, b) => a.map((x, i) => x + b[i]),
1293
+ times = (a, k) => a.map((x) => x * k);
1294
+ const crossP = (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]],
1295
+ len = (v) => Math.hypot(...v),
1296
+ unit = (v) => times(v, 1 / len(v));
607
1297
  const ang = (v, x0, z) => Math.atan2(dot(crossP(x0, v), z), dot(x0, v));
608
- const v = jointValues({ joints, poses: {} }, {}); v[lead.id] = [0]; v[j.id] = [0];
609
- const worlds = placeItems({ items, joints }, v), W1 = worlds[lead.child], W2 = worlds[j.child];
610
- const O1 = org(W1), Z1 = col(W1, 2), X1 = col(W1, 0), O2 = org(W2), Z2 = col(W2, 2), X2 = col(W2, 0);
1298
+ const v = jointValues({ joints, poses: {} }, {});
1299
+ v[lead.id] = [0];
1300
+ v[j.id] = [0];
1301
+ const worlds = placeItems({ items, joints }, v),
1302
+ W1 = worlds[lead.child],
1303
+ W2 = worlds[j.child];
1304
+ const O1 = org(W1),
1305
+ Z1 = col(W1, 2),
1306
+ X1 = col(W1, 0),
1307
+ O2 = org(W2),
1308
+ Z2 = col(W2, 2),
1309
+ X2 = col(W2, 0);
611
1310
  const shaft = Math.acos(Math.max(-1, Math.min(1, dot(Z1, Z2)))) / DEG;
612
1311
  let g1, g2;
613
- try { g1 = bevelModel({ ...common, teeth: teeth[0], mate: teeth[1], shaftAngle: shaft }); g2 = bevelModel({ ...common, teeth: teeth[1], mate: teeth[0], shaftAngle: shaft }); } catch (e) { throw new Error(`${what}: ${e.message}`); }
1312
+ try {
1313
+ g1 = bevelModel({ ...common, teeth: teeth[0], mate: teeth[1], shaftAngle: shaft });
1314
+ g2 = bevelModel({ ...common, teeth: teeth[1], mate: teeth[0], shaftAngle: shaft });
1315
+ } catch (e) {
1316
+ throw new Error(`${what}: ${e.message}`);
1317
+ }
614
1318
  // each cone's apex: along its axis, its cone distance × cos δ from its back end
615
- const A1 = add(O1, times(Z1, g1.coneDistance * Math.cos(g1.pitchAngle * DEG))), A2 = add(O2, times(Z2, g2.coneDistance * Math.cos(g2.pitchAngle * DEG)));
1319
+ const A1 = add(O1, times(Z1, g1.coneDistance * Math.cos(g1.pitchAngle * DEG))),
1320
+ A2 = add(O2, times(Z2, g2.coneDistance * Math.cos(g2.pitchAngle * DEG)));
616
1321
  const findings = [];
617
1322
  const apart = len(sub(A1, A2));
618
- if (apart > 0.01) findings.push({ level: 'fail', text: `the cones' apexes are ${Number(apart.toFixed(3))} mm apart: bevel gears mesh only when their cones meet at one point (move one along its axis)`, code: 'mesh.bevel' });
1323
+ if (apart > 0.01)
1324
+ findings.push({
1325
+ level: 'fail',
1326
+ text: `the cones' apexes are ${Number(apart.toFixed(3))} mm apart: bevel gears mesh only when their cones meet at one point (move one along its axis)`,
1327
+ code: 'mesh.bevel',
1328
+ });
619
1329
  // where the pitch cones touch: from the apex, δ1 from the first's axis toward the second's (both pointing away)
620
- const out1 = times(Z1, -1), out2 = times(Z2, -1), across = unit(sub(out2, times(out1, dot(out1, out2))));
621
- const g = add(times(out1, Math.cos(g1.pitchAngle * DEG)), times(across, Math.sin(g1.pitchAngle * DEG))), P = add(A1, times(g, g1.coneDistance));
622
- const radial = (Z, X) => { const r = sub(g, times(Z, dot(g, Z))); return ang(r, X, Z); };
623
- const b1 = radial(Z1, X1), b2 = radial(Z2, X2);
1330
+ const out1 = times(Z1, -1),
1331
+ out2 = times(Z2, -1),
1332
+ across = unit(sub(out2, times(out1, dot(out1, out2))));
1333
+ const g = add(times(out1, Math.cos(g1.pitchAngle * DEG)), times(across, Math.sin(g1.pitchAngle * DEG))),
1334
+ P = add(A1, times(g, g1.coneDistance));
1335
+ const radial = (Z, X) => {
1336
+ const r = sub(g, times(Z, dot(g, Z)));
1337
+ return ang(r, X, Z);
1338
+ };
1339
+ const b1 = radial(Z1, X1),
1340
+ b2 = radial(Z2, X2);
624
1341
  // the second turns so the surface speeds match where they touch: ω2 = ω1 (Z1 × P)·(Z2 × P) / |Z2 × P|², P from the apex
625
- const p = sub(P, A1), r = dot(crossP(Z1, p), crossP(Z2, p)) / dot(crossP(Z2, p), crossP(Z2, p));
626
- const sgn = (jt, Z) => Math.sign(dot(col(mul(jt.parent < 0 ? [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0] : worlds[jt.parent], jt.a), 2), Z));
627
- const s1 = sgn(lead, Z1), s2 = sgn(j, Z2), z2 = teeth[1];
1342
+ const p = sub(P, A1),
1343
+ r = dot(crossP(Z1, p), crossP(Z2, p)) / dot(crossP(Z2, p), crossP(Z2, p));
1344
+ const sgn = (jt, Z) =>
1345
+ Math.sign(dot(col(mul(jt.parent < 0 ? [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0] : worlds[jt.parent], jt.a), 2), Z));
1346
+ const s1 = sgn(lead, Z1),
1347
+ s2 = sgn(j, Z2),
1348
+ z2 = teeth[1];
628
1349
  const phi = b2 - Math.PI / z2 - r * b1;
629
1350
  j.follow = [lead.id, s2 * r * s1, (s2 * phi) / DEG];
630
- const m = bevelMesh({ ...common, teeth: teeth[0], shaftAngle: shaft }, { ...common, teeth: teeth[1], shaftAngle: shaft });
1351
+ const m = bevelMesh(
1352
+ { ...common, teeth: teeth[0], shaftAngle: shaft },
1353
+ { ...common, teeth: teeth[1], shaftAngle: shaft },
1354
+ );
631
1355
  findings.push(...m.findings);
632
- return { joint: j.id, with: lead.id, kind: 'bevel', findings, between: [O1, O2], text: `bevel gears at ${Number(shaft.toFixed(2))}°, ${Number((teeth[0] / teeth[1]).toFixed(4))} turns of the second for each of the first (cones of ${Number(g1.pitchAngle.toFixed(2))}° and ${Number(g2.pitchAngle.toFixed(2))}°)` };
1356
+ return {
1357
+ joint: j.id,
1358
+ with: lead.id,
1359
+ kind: 'bevel',
1360
+ findings,
1361
+ between: [O1, O2],
1362
+ text: `bevel gears at ${Number(shaft.toFixed(2))}°, ${Number((teeth[0] / teeth[1]).toFixed(4))} turns of the second for each of the first (cones of ${Number(g1.pitchAngle.toFixed(2))}° and ${Number(g2.pitchAngle.toFixed(2))}°)`,
1363
+ };
633
1364
  }
634
1365
 
635
1366
  // A worm and its wheel: "mesh": { "with": <the worm's joint>, "module", "teeth": [starts, wheel's teeth], "worm": {
@@ -637,36 +1368,103 @@ function bevelDrive(j, lead, spec, teeth, common, joints, items, num) {
637
1368
  // rack along the worm's axis, moving a lead a turn: the wheel follows it as a pinion does a rack, its helix's turn at
638
1369
  // that plane taken into account. The worm is drawn as @rulecad/gears draws it (axis up its z, from z = 0).
639
1370
  function wormDrive(j, lead, spec, teeth, common, joints, items, num) {
640
- const what = `joint ${j.id}: mesh`, DEG = Math.PI / 180;
641
- const col = (W, k) => [W[k], W[4 + k], W[8 + k]], org = (W) => [W[3], W[7], W[11]];
642
- const dot = (a, b) => a[0] * b[0] + a[1] * b[1] + a[2] * b[2], sub = (a, b) => [a[0] - b[0], a[1] - b[1], a[2] - b[2]];
643
- const crossP = (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]], len = (v) => Math.hypot(...v);
1371
+ const what = `joint ${j.id}: mesh`,
1372
+ DEG = Math.PI / 180;
1373
+ const col = (W, k) => [W[k], W[4 + k], W[8 + k]],
1374
+ org = (W) => [W[3], W[7], W[11]];
1375
+ const dot = (a, b) => a[0] * b[0] + a[1] * b[1] + a[2] * b[2],
1376
+ sub = (a, b) => [a[0] - b[0], a[1] - b[1], a[2] - b[2]];
1377
+ const crossP = (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]],
1378
+ len = (v) => Math.hypot(...v);
644
1379
  const ang = (v, x0, z) => Math.atan2(dot(crossP(x0, v), z), dot(x0, v));
645
1380
  const ws = spec.worm === true ? {} : spec.worm;
646
1381
  let w, wheel;
647
1382
  try {
648
- w = wormModel({ ...common, starts: teeth[0], ...(ws.diameter != null ? { diameter: num(ws.diameter) } : {}), ...(ws.hand ? { hand: ws.hand } : {}) });
1383
+ w = wormModel({
1384
+ ...common,
1385
+ starts: teeth[0],
1386
+ ...(ws.diameter != null ? { diameter: num(ws.diameter) } : {}),
1387
+ ...(ws.hand ? { hand: ws.hand } : {}),
1388
+ });
649
1389
  wheel = gearModel({ ...common, teeth: teeth[1], helix: w.leadAngle, hand: w.hand });
650
- } catch (e) { throw new Error(`${what}: ${e.message}`); }
651
- const v = jointValues({ joints, poses: {} }, {}); v[lead.id] = [0]; v[j.id] = [0];
652
- const worlds = placeItems({ items, joints }, v), Ww = worlds[lead.child], W2 = worlds[j.child];
653
- const Ow = org(Ww), U = col(Ww, 2), Xw = col(Ww, 0), O2 = org(W2), Z2 = col(W2, 2), X2 = col(W2, 0);
1390
+ } catch (e) {
1391
+ throw new Error(`${what}: ${e.message}`);
1392
+ }
1393
+ const v = jointValues({ joints, poses: {} }, {});
1394
+ v[lead.id] = [0];
1395
+ v[j.id] = [0];
1396
+ const worlds = placeItems({ items, joints }, v),
1397
+ Ww = worlds[lead.child],
1398
+ W2 = worlds[j.child];
1399
+ const Ow = org(Ww),
1400
+ U = col(Ww, 2),
1401
+ Xw = col(Ww, 0),
1402
+ O2 = org(W2),
1403
+ Z2 = col(W2, 2),
1404
+ X2 = col(W2, 0);
654
1405
  if (Math.abs(dot(U, Z2)) > 1e-6) throw new Error(`${what}: a worm's axis and its wheel's cross at right angles`);
655
1406
  // the line between the axes: across both (the worm's along U, the wheel's along Z2)
656
- const rel = sub(O2, Ow), at = dot(rel, U), toWheel = sub(sub(rel, U.map((x) => x * at)), Z2.map((x) => x * dot(rel, Z2))), dist = len(toWheel), Y = toWheel.map((x) => x / dist), Zr = crossP(U, Y);
657
- const sense = w.hand === 'left' ? -1 : 1, sw = Math.sign(dot(col(mul(lead.parent < 0 ? [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0] : worlds[lead.parent], lead.a), 2), U));
658
- const s2 = Math.sign(dot(Z2, Zr)), tw = ang(Y, Xw, U), g2 = ang(X2, U, Zr) * 1, r2 = wheel.pitch / 2;
1407
+ const rel = sub(O2, Ow),
1408
+ at = dot(rel, U),
1409
+ toWheel = sub(
1410
+ sub(
1411
+ rel,
1412
+ U.map((x) => x * at),
1413
+ ),
1414
+ Z2.map((x) => x * dot(rel, Z2)),
1415
+ ),
1416
+ dist = len(toWheel),
1417
+ Y = toWheel.map((x) => x / dist),
1418
+ Zr = crossP(U, Y);
1419
+ const sense = w.hand === 'left' ? -1 : 1,
1420
+ sw = Math.sign(
1421
+ dot(col(mul(lead.parent < 0 ? [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0] : worlds[lead.parent], lead.a), 2), U),
1422
+ );
1423
+ const s2 = Math.sign(dot(Z2, Zr)),
1424
+ tw = ang(Y, Xw, U),
1425
+ g2 = ang(X2, U, Zr) * 1,
1426
+ r2 = wheel.pitch / 2;
659
1427
  // the wheel's helix: its tooth 0 at the worm's plane is turned by k z there
660
- const zMid = dot(sub(Ow, O2), Z2), k = (sense * Math.tan(w.leadAngle * DEG)) / r2;
661
- const phr = rackPhase(wheel, at), L = w.lead;
1428
+ const zMid = dot(sub(Ow, O2), Z2),
1429
+ k = (sense * Math.tan(w.leadAngle * DEG)) / r2;
1430
+ const phr = rackPhase(wheel, at),
1431
+ L = w.lead;
662
1432
  // space centres of the thread, at the wheel, sit at z0 = sense L (tw − θw) / 2π along the worm; the wheel turns as on a rack
663
- const theta = (dw) => { const z0 = (sense * L * (tw - sw * dw * DEG)) / (2 * Math.PI); return s2 * ((z0 - phr) / r2 - g2) - k * zMid; };
664
- const a0 = theta(0), a1 = theta(1);
1433
+ const theta = (dw) => {
1434
+ const z0 = (sense * L * (tw - sw * dw * DEG)) / (2 * Math.PI);
1435
+ return s2 * ((z0 - phr) / r2 - g2) - k * zMid;
1436
+ };
1437
+ const a0 = theta(0),
1438
+ a1 = theta(1);
665
1439
  j.follow = [lead.id, (a1 - a0) / DEG, a0 / DEG];
666
- const m = wormMesh({ ...common, starts: teeth[0], ...(ws.diameter != null ? { diameter: num(ws.diameter) } : {}), ...(ws.hand ? { hand: ws.hand } : {}) }, { teeth: teeth[1] });
1440
+ const m = wormMesh(
1441
+ {
1442
+ ...common,
1443
+ starts: teeth[0],
1444
+ ...(ws.diameter != null ? { diameter: num(ws.diameter) } : {}),
1445
+ ...(ws.hand ? { hand: ws.hand } : {}),
1446
+ },
1447
+ { teeth: teeth[1] },
1448
+ );
667
1449
  const c = meshOf(wheel, rackModel({ ...common, teeth: 4 }), { centre: dist - w.pitch / 2 });
668
- const findings = [...m.findings, ...c.findings.filter((x) => x.code === 'mesh.centre').map((x) => ({ ...x, text: x.text.replace("centre to the rack's pitch line", "the wheel's centre to the worm's pitch cylinder") }))];
669
- return { joint: j.id, with: lead.id, kind: 'worm', worm: m, findings, between: [Ow.map((x, i) => x + U[i] * at), O2], text: `a worm of ${teeth[0]} start${teeth[0] > 1 ? 's' : ''}, ${Number((teeth[1] / teeth[0]).toFixed(3))} turns of the worm for one of the wheel` };
1450
+ const findings = [
1451
+ ...m.findings,
1452
+ ...c.findings
1453
+ .filter((x) => x.code === 'mesh.centre')
1454
+ .map((x) => ({
1455
+ ...x,
1456
+ text: x.text.replace("centre to the rack's pitch line", "the wheel's centre to the worm's pitch cylinder"),
1457
+ })),
1458
+ ];
1459
+ return {
1460
+ joint: j.id,
1461
+ with: lead.id,
1462
+ kind: 'worm',
1463
+ worm: m,
1464
+ findings,
1465
+ between: [Ow.map((x, i) => x + U[i] * at), O2],
1466
+ text: `a worm of ${teeth[0]} start${teeth[0] > 1 ? 's' : ''}, ${Number((teeth[1] / teeth[0]).toFixed(3))} turns of the worm for one of the wheel`,
1467
+ };
670
1468
  }
671
1469
 
672
1470
  // Gears that mesh: "mesh": { "with": <the driving joint>, "module", "teeth": [its, this one's], "shift"?, "ring"? } on
@@ -674,85 +1472,252 @@ function wormDrive(j, lead, spec, teeth, common, joints, items, num) {
674
1472
  // teeth, and the offset that puts a tooth in a gap, read from where the two gears are with their joints at 0. Each
675
1473
  // gear is drawn as @rulecad/gears draws it (its axis up its own z, its first tooth on +x; a rack along its x, teeth up
676
1474
  // +y, its first space at x = 0), and its joint turns it about its own axis. The centre distance is checked here, the
677
- // rest of the meshing by --sweep.
1475
+ // rest of the meshing by --sweep. Each spur, internal and rack mesh also keeps its gears' items and tip circles (a rack's
1476
+ // tip line) in faces, for checkAssembly to find their teeth in the drawn parts and measure how much of the faces meet.
678
1477
  function gearMeshes(joints, items, num) {
679
- const out = [], list = (x) => (x == null ? [] : [].concat(x));
680
- const col = (W, k) => [W[k], W[4 + k], W[8 + k]], org = (W) => [W[3], W[7], W[11]];
681
- const dot = (a, b) => a[0] * b[0] + a[1] * b[1] + a[2] * b[2], sub = (a, b) => [a[0] - b[0], a[1] - b[1], a[2] - b[2]];
1478
+ const out = [],
1479
+ list = (x) => (x == null ? [] : [].concat(x));
1480
+ const col = (W, k) => [W[k], W[4 + k], W[8 + k]],
1481
+ org = (W) => [W[3], W[7], W[11]];
1482
+ const dot = (a, b) => a[0] * b[0] + a[1] * b[1] + a[2] * b[2],
1483
+ sub = (a, b) => [a[0] - b[0], a[1] - b[1], a[2] - b[2]];
682
1484
  const crossP = (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]];
683
- const along = (v, axis) => sub(v, axis.map((x) => x * dot(v, axis))), len = (v) => Math.hypot(...v);
1485
+ const along = (v, axis) =>
1486
+ sub(
1487
+ v,
1488
+ axis.map((x) => x * dot(v, axis)),
1489
+ ),
1490
+ len = (v) => Math.hypot(...v);
684
1491
  const angleIn = (v, x0, z) => Math.atan2(dot(crossP(x0, v), z), dot(x0, v)) / (Math.PI / 180); // v's angle from x0 about z, degrees
685
1492
  // Is an item held still relative to another: every joint between it and the world fixed (or no joint at all)?
686
1493
  const byChild = new Map(joints.map((j) => [j.child, j]));
687
- const still = (i) => { for (let k = i, n = 0; k >= 0 && n < 99; n++) { const j = byChild.get(k); if (!j) return true; if (j.type !== 'fixed') return false; k = j.parent; } return true; };
1494
+ const still = (i) => {
1495
+ for (let k = i, n = 0; k >= 0 && n < 99; n++) {
1496
+ const j = byChild.get(k);
1497
+ if (!j) return true;
1498
+ if (j.type !== 'fixed') return false;
1499
+ k = j.parent;
1500
+ }
1501
+ return true;
1502
+ };
688
1503
  for (const j of joints) {
689
1504
  if (!j.meshSpec) continue;
690
- const spec = j.meshSpec, what = `joint ${j.id}: mesh`;
1505
+ const spec = j.meshSpec,
1506
+ what = `joint ${j.id}: mesh`;
691
1507
  delete j.meshSpec;
692
1508
  if (j.follow) throw new Error(`${what}: a meshed joint follows its mate already: give mesh or follow, not both`);
693
1509
  const lead = joints.find((x) => x.id === spec.with);
694
- if (!lead) throw new Error(`${what}: "with" names the driving joint (${joints.filter((x) => x !== j).map((x) => x.id).join(', ')}; got ${JSON.stringify(spec.with)})`);
695
- if (lead.type !== 'revolute') throw new Error(`${what}: ${lead.id} is a ${lead.type}; the driver is a gear turning on a revolute`);
696
- if (j.type !== 'revolute' && j.type !== 'prismatic') throw new Error(`${what}: a gear turns on a revolute, a rack slides on a prismatic (this is a ${j.type})`);
697
- const kind = spec.bevel ? 'bevel' : spec.worm ? 'worm' : j.type === 'prismatic' ? 'rack' : spec.ring ? 'internal' : 'external';
698
- if (!(lead.parent === j.parent || (still(lead.parent) && still(j.parent)))) throw new Error(`${what}: ${lead.id} and ${j.id} turn on parts that move apart (a planet on a carrier): a mesh needs both on one part, or both on parts held still`);
699
- const teeth = list(spec.teeth).map(num), shift = list(spec.shift ?? [0, 0]).map(num);
700
- if (teeth.length !== 2) throw new Error(`${what}: teeth is [the driver's, this one's] (got ${JSON.stringify(spec.teeth)})`);
701
- const common = { module: num(spec.module), ...(spec.pressureAngle != null ? { pressureAngle: num(spec.pressureAngle) } : {}), ...(spec.backlash != null ? { backlash: num(spec.backlash) } : {}) };
702
- if (kind === 'worm') { out.push(wormDrive(j, lead, spec, teeth, common, joints, items, num)); continue; }
703
- if (kind === 'bevel') { out.push(bevelDrive(j, lead, spec, teeth, common, joints, items, num)); continue; }
1510
+ if (!lead)
1511
+ throw new Error(
1512
+ `${what}: "with" names the driving joint (${joints
1513
+ .filter((x) => x !== j)
1514
+ .map((x) => x.id)
1515
+ .join(', ')}; got ${JSON.stringify(spec.with)})`,
1516
+ );
1517
+ if (lead.type !== 'revolute')
1518
+ throw new Error(`${what}: ${lead.id} is a ${lead.type}; the driver is a gear turning on a revolute`);
1519
+ if (j.type !== 'revolute' && j.type !== 'prismatic')
1520
+ throw new Error(`${what}: a gear turns on a revolute, a rack slides on a prismatic (this is a ${j.type})`);
1521
+ const kind = spec.bevel
1522
+ ? 'bevel'
1523
+ : spec.worm
1524
+ ? 'worm'
1525
+ : j.type === 'prismatic'
1526
+ ? 'rack'
1527
+ : spec.ring
1528
+ ? 'internal'
1529
+ : 'external';
1530
+ if (!(lead.parent === j.parent || (still(lead.parent) && still(j.parent))))
1531
+ throw new Error(
1532
+ `${what}: ${lead.id} and ${j.id} turn on parts that move apart (a planet on a carrier): a mesh needs both on one part, or both on parts held still`,
1533
+ );
1534
+ const teeth = list(spec.teeth).map(num),
1535
+ shift = list(spec.shift ?? [0, 0]).map(num);
1536
+ if (teeth.length !== 2)
1537
+ throw new Error(`${what}: teeth is [the driver's, this one's] (got ${JSON.stringify(spec.teeth)})`);
1538
+ const common = {
1539
+ module: num(spec.module),
1540
+ ...(spec.pressureAngle != null ? { pressureAngle: num(spec.pressureAngle) } : {}),
1541
+ ...(spec.backlash != null ? { backlash: num(spec.backlash) } : {}),
1542
+ };
1543
+ if (kind === 'worm') {
1544
+ out.push(wormDrive(j, lead, spec, teeth, common, joints, items, num));
1545
+ continue;
1546
+ }
1547
+ if (kind === 'bevel') {
1548
+ out.push(bevelDrive(j, lead, spec, teeth, common, joints, items));
1549
+ continue;
1550
+ }
704
1551
  let A, B;
705
1552
  try {
706
1553
  A = gearModel({ ...common, teeth: teeth[0], shift: shift[0] });
707
- B = kind === 'rack' ? rackModel({ ...common, teeth: teeth[1] }) : (kind === 'internal' ? internalModel : gearModel)({ ...common, teeth: teeth[1], shift: shift[1] ?? 0 });
708
- } catch (e) { throw new Error(`${what}: ${e.message}`); }
1554
+ B =
1555
+ kind === 'rack'
1556
+ ? rackModel({ ...common, teeth: teeth[1] })
1557
+ : (kind === 'internal' ? internalModel : gearModel)({ ...common, teeth: teeth[1], shift: shift[1] ?? 0 });
1558
+ } catch (e) {
1559
+ throw new Error(`${what}: ${e.message}`);
1560
+ }
709
1561
  // Where the two gears are with their own joints at 0 (everything else as it stands by default)
710
- const v = jointValues({ joints: joints.map((x) => (x.meshSpec ? { ...x, meshSpec: undefined } : x)), poses: {} }, {});
711
- v[lead.id] = [0]; v[j.id] = [0];
712
- const worlds = placeItems({ items, joints }, v), W1 = worlds[lead.child], W2 = worlds[j.child];
713
- const axisOf = (jt) => { const P = mul(jt.parent < 0 ? [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0] : worlds[jt.parent], jt.a); return { at: org(P), dir: col(P, 2) }; };
714
- const O1 = org(W1), X1 = col(W1, 0), Z1 = col(W1, 2), ax1 = axisOf(lead);
1562
+ const v = jointValues(
1563
+ { joints: joints.map((x) => (x.meshSpec ? { ...x, meshSpec: undefined } : x)), poses: {} },
1564
+ {},
1565
+ );
1566
+ v[lead.id] = [0];
1567
+ v[j.id] = [0];
1568
+ const worlds = placeItems({ items, joints }, v),
1569
+ W1 = worlds[lead.child],
1570
+ W2 = worlds[j.child];
1571
+ const axisOf = (jt) => {
1572
+ const P = mul(jt.parent < 0 ? [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0] : worlds[jt.parent], jt.a);
1573
+ return { at: org(P), dir: col(P, 2) };
1574
+ };
1575
+ const O1 = org(W1),
1576
+ X1 = col(W1, 0),
1577
+ Z1 = col(W1, 2),
1578
+ ax1 = axisOf(lead);
715
1579
  // the driver turns about its own centre and axis, or its teeth wander
716
- if (Math.abs(Math.abs(dot(ax1.dir, Z1)) - 1) > 1e-6 || len(along(sub(O1, ax1.at), ax1.dir)) > 1e-4) throw new Error(`${what}: ${lead.id} doesn't turn its gear about the gear's own centre and axis: anchor the gear's joint at its centre, along its axis`);
1580
+ if (Math.abs(Math.abs(dot(ax1.dir, Z1)) - 1) > 1e-6 || len(along(sub(O1, ax1.at), ax1.dir)) > 1e-4)
1581
+ throw new Error(
1582
+ `${what}: ${lead.id} doesn't turn its gear about the gear's own centre and axis: anchor the gear's joint at its centre, along its axis`,
1583
+ );
717
1584
  const result = { joint: j.id, with: lead.id, kind, findings: [], between: null };
718
1585
  if (kind === 'rack') {
719
- const R0 = org(W2), U = col(W2, 0), Y = col(W2, 1), Zr = col(W2, 2), ax2 = axisOf(j);
1586
+ const R0 = org(W2),
1587
+ U = col(W2, 0),
1588
+ Y = col(W2, 1),
1589
+ Zr = col(W2, 2),
1590
+ ax2 = axisOf(j);
720
1591
  const sTravel = Math.sign(dot(ax2.dir, U));
721
- if (Math.abs(Math.abs(dot(ax2.dir, U)) - 1) > 1e-6) throw new Error(`${what}: ${j.id} doesn't slide the rack along its length (the rack's x)`);
722
- if (Math.abs(Math.abs(dot(Z1, Zr)) - 1) > 1e-6) throw new Error(`${what}: the pinion's axis isn't across the rack (along the rack's z)`);
723
- const s1 = Math.sign(dot(Z1, Zr)), rel = sub(O1, R0), at = dot(rel, U), height = dot(rel, Y);
724
- const k = (Math.PI * A.pitch) / 360, g1 = angleIn(along(X1, Zr), U, Zr);
1592
+ if (Math.abs(Math.abs(dot(ax2.dir, U)) - 1) > 1e-6)
1593
+ throw new Error(`${what}: ${j.id} doesn't slide the rack along its length (the rack's x)`);
1594
+ if (Math.abs(Math.abs(dot(Z1, Zr)) - 1) > 1e-6)
1595
+ throw new Error(`${what}: the pinion's axis isn't across the rack (along the rack's z)`);
1596
+ const s1 = Math.sign(dot(Z1, Zr)),
1597
+ rel = sub(O1, R0),
1598
+ at = dot(rel, U),
1599
+ height = dot(rel, Y);
1600
+ const k = (Math.PI * A.pitch) / 360,
1601
+ g1 = angleIn(along(X1, Zr), U, Zr);
725
1602
  j.follow = [lead.id, sTravel * s1 * k, sTravel * (k * g1 + rackPhase(A, at))];
726
1603
  const m = meshOf(A, B, { centre: height });
727
- result.findings = [...m.findings, ...measured({ ...common, teeth: teeth[0], shift: shift[0] }, { ...common, teeth: teeth[1], kind: 'rack' }, height).findings]; result.between = [O1, [R0[0] + at * U[0], R0[1] + at * U[1], R0[2] + at * U[2]]]; result.text = m.text;
1604
+ result.findings = [
1605
+ ...m.findings,
1606
+ ...measured(
1607
+ { ...common, teeth: teeth[0], shift: shift[0] },
1608
+ { ...common, teeth: teeth[1], kind: 'rack' },
1609
+ height,
1610
+ ).findings,
1611
+ ];
1612
+ result.between = [O1, [R0[0] + at * U[0], R0[1] + at * U[1], R0[2] + at * U[2]]];
1613
+ result.text = m.text;
1614
+ result.faces = {
1615
+ module: A.module,
1616
+ a: { item: lead.child, tip: A.tip / 2 },
1617
+ b: { item: j.child, tipLine: B.tipLine },
1618
+ };
728
1619
  } else {
729
- const O2 = org(W2), X2 = col(W2, 0), Z2 = col(W2, 2), ax2 = axisOf(j);
730
- if (Math.abs(Math.abs(dot(ax2.dir, Z2)) - 1) > 1e-6 || len(along(sub(O2, ax2.at), ax2.dir)) > 1e-4) throw new Error(`${what}: ${j.id} doesn't turn its gear about the gear's own centre and axis: anchor the gear's joint at its centre, along its axis`);
731
- if (Math.abs(Math.abs(dot(Z1, Z2)) - 1) > 1e-6) throw new Error(`${what}: ${lead.id} and ${j.id} turn about axes that aren't parallel (spur gears need parallel axes)`);
732
- const s = Math.sign(dot(Z1, Z2)), d = along(sub(O2, O1), Z1), beta = angleIn(d, X1, Z1), g2 = angleIn(along(X2, Z1), X1, Z1);
1620
+ const O2 = org(W2),
1621
+ X2 = col(W2, 0),
1622
+ Z2 = col(W2, 2),
1623
+ ax2 = axisOf(j);
1624
+ if (Math.abs(Math.abs(dot(ax2.dir, Z2)) - 1) > 1e-6 || len(along(sub(O2, ax2.at), ax2.dir)) > 1e-4)
1625
+ throw new Error(
1626
+ `${what}: ${j.id} doesn't turn its gear about the gear's own centre and axis: anchor the gear's joint at its centre, along its axis`,
1627
+ );
1628
+ if (Math.abs(Math.abs(dot(Z1, Z2)) - 1) > 1e-6)
1629
+ throw new Error(
1630
+ `${what}: ${lead.id} and ${j.id} turn about axes that aren't parallel (spur gears need parallel axes)`,
1631
+ );
1632
+ const s = Math.sign(dot(Z1, Z2)),
1633
+ d = along(sub(O2, O1), Z1),
1634
+ beta = angleIn(d, X1, Z1),
1635
+ g2 = angleIn(along(X2, Z1), X1, Z1);
733
1636
  const m = meshOf(A, B, { centre: len(d) });
734
- m.findings.push(...measured({ ...common, teeth: teeth[0], shift: shift[0] }, { ...common, teeth: teeth[1], shift: shift[1] ?? 0, kind }, len(d)).findings);
1637
+ m.findings.push(
1638
+ ...measured(
1639
+ { ...common, teeth: teeth[0], shift: shift[0] },
1640
+ { ...common, teeth: teeth[1], shift: shift[1] ?? 0, kind },
1641
+ len(d),
1642
+ ).findings,
1643
+ );
735
1644
  // b's angle in the driver's frame is ratio × a's + phase; its joint measures about its own z (the other way when flipped)
736
1645
  j.follow = [lead.id, s * m.ratio, s * (phase(A, B, beta) - g2)];
737
- result.findings = m.findings; result.between = [O1, O2]; result.text = m.text;
1646
+ result.findings = m.findings;
1647
+ result.between = [O1, O2];
1648
+ result.text = m.text;
1649
+ result.faces = {
1650
+ module: A.module,
1651
+ a: { item: lead.child, tip: A.tip / 2 },
1652
+ b: { item: j.child, tip: B.tip / 2 },
1653
+ };
738
1654
  }
739
1655
  out.push(result);
740
1656
  }
741
1657
  return out;
742
1658
  }
743
1659
 
1660
+ /**
1661
+ * How much of two meshed gears' faces meet along an axis (the driver's). Each gear's teeth are found in its drawn
1662
+ * triangles as the corners on its tip circle, within a quarter of a module (a rack's on its tip line, y = tipLine in its
1663
+ * frame), and their stretch along the axis measured: the two stretches should share most of the narrower face. A
1664
+ * gear's frame is its origin and axes in the world (its own axis up Z; a rack along X, teeth up Y). The share of the
1665
+ * narrower face passes from 80 %, warns from 50 % and fails below; a gear with no corners found has no stretch (null).
1666
+ * @param {{ module: number, along: { O: number[], Z: number[] }, a: FaceGear, b: FaceGear }} o
1667
+ * @returns {{ a: number[] | null, b: number[] | null, overlap: number, narrower: number, share: number, level: 'pass' | 'warn' | 'fail' }}
1668
+ * @typedef {{ triangles: number[][][], frame: { O: number[], X: number[], Y: number[] }, tip?: number, tipLine?: number }} FaceGear
1669
+ */
1670
+ export function meshFaces({ module, along, a, b }) {
1671
+ const dot = (u, v) => u[0] * v[0] + u[1] * v[1] + u[2] * v[2],
1672
+ tol = module / 4;
1673
+ const span = (gear) => {
1674
+ const F = gear.frame;
1675
+ let lo = Infinity,
1676
+ hi = -Infinity;
1677
+ for (const t of gear.triangles)
1678
+ for (const v of t) {
1679
+ const d = [v[0] - F.O[0], v[1] - F.O[1], v[2] - F.O[2]];
1680
+ const off = gear.tipLine != null ? dot(d, F.Y) - gear.tipLine : Math.hypot(dot(d, F.X), dot(d, F.Y)) - gear.tip;
1681
+ if (Math.abs(off) > tol) continue;
1682
+ const at = dot([v[0] - along.O[0], v[1] - along.O[1], v[2] - along.O[2]], along.Z);
1683
+ lo = Math.min(lo, at);
1684
+ hi = Math.max(hi, at);
1685
+ }
1686
+ return hi >= lo ? [lo, hi] : null;
1687
+ };
1688
+ const sa = span(a),
1689
+ sb = span(b);
1690
+ if (!sa || !sb) return { a: sa, b: sb, overlap: 0, narrower: 0, share: 0, level: 'fail' };
1691
+ const narrower = Math.min(sa[1] - sa[0], sb[1] - sb[0]),
1692
+ shared = Math.max(0, Math.min(sa[1], sb[1]) - Math.max(sa[0], sb[0])),
1693
+ share = narrower > 0 ? shared / narrower : 0;
1694
+ return {
1695
+ a: sa,
1696
+ b: sb,
1697
+ overlap: shared,
1698
+ narrower,
1699
+ share,
1700
+ level: share >= 0.8 - 1e-9 ? 'pass' : share >= 0.5 - 1e-9 ? 'warn' : 'fail',
1701
+ };
1702
+ }
1703
+
744
1704
  // Where each item's anchors are in a pose: [{ id: 'keyboard@pivot', item, at: [x, y, z] }]
745
1705
  // Where an address is in the world, at these joint values: { id (its item), at, frame }, or null where it is not an
746
1706
  // address on a beam (x1.top@120, x1.a.1). A beam's address it does not have is refused by name.
747
1707
  export function addressAt(s, n, values = s.jointValues) {
748
- const id = String(n).split('.')[0], it = s.items.find((x) => x.id === id);
1708
+ const id = String(n).split('.')[0],
1709
+ it = s.items.find((x) => x.id === id);
749
1710
  if (!it?.beam || !String(n).includes('.') || !s.motion?.address) return null;
750
- const r = s.motion.address(n), W = mul(placeItems(s.motion, values)[r.item], r.frame);
1711
+ const r = s.motion.address(n),
1712
+ W = mul(placeItems(s.motion, values)[r.item], r.frame);
751
1713
  return { id, at: [W[3], W[7], W[11]], frame: W };
752
1714
  }
753
1715
  export function anchorsAt(s, values = s.jointValues) {
754
1716
  const worlds = placeItems(s.motion, values);
755
- return (s.motion.marks || []).map((m) => { const w = mul(worlds[m.item], m.frame); return { id: `${m.id}@${m.name}`, item: m.id, at: [w[3], w[7], w[11]] }; });
1717
+ return (s.motion.marks || []).map((m) => {
1718
+ const w = mul(worlds[m.item], m.frame);
1719
+ return { id: `${m.id}@${m.name}`, item: m.id, at: [w[3], w[7], w[11]] };
1720
+ });
756
1721
  }
757
1722
 
758
1723
  // keyCentres(layout): each key's centre, from lib/layout.mjs (kept under this name for older callers)
@@ -770,37 +1735,60 @@ export function overlap(ga, gb) {
770
1735
  // JSCAD's answer (no Manifold, or a shape Manifold couldn't read): only if fit says they really run into each other
771
1736
  // (their surfaces cross, one is inside the other, or they share volume beside a face plane they share: slower, so
772
1737
  // only here)
773
- if (!solid || solid.stats.fallbacks > fell) { const faces = (g) => jscad.geometries.geom3.toPolygons(g).map((q) => q.vertices); if (!overlapAt(faces(ga), faces(gb))) return 0; }
1738
+ if (!solid || solid.stats.fallbacks > fell) {
1739
+ const faces = (g) => jscad.geometries.geom3.toPolygons(g).map((q) => q.vertices);
1740
+ if (!overlapAt(faces(ga), faces(gb))) return 0;
1741
+ }
774
1742
  return v;
775
1743
  }
776
1744
  // How overlaps are measured: whether the surfaces cross, exactly (fit), and then how much, with Manifold where it's
777
1745
  // installed. JSCAD's intersection misreads faces that come near without touching: two gears 0.07 mm apart (their
778
1746
  // backlash) read as 2.7 mm³ into each other at one angle in twenty, and a planet 0.4 mm over a case as 1.3 mm³.
779
1747
  // Manifold is exact; a shape it can't read as a closed solid falls back to JSCAD's for that pair.
780
- let solid = null, tried = false;
1748
+ let solid = null,
1749
+ tried = false;
781
1750
  async function measurer() {
782
- if (tried) return; tried = true;
783
- try { solid = await booleans('manifold'); } catch { solid = null; } // (without manifold-3d, JSCAD's, as before)
1751
+ if (tried) return;
1752
+ tried = true;
1753
+ try {
1754
+ solid = await booleans('manifold');
1755
+ } catch {
1756
+ solid = null;
1757
+ } // (without manifold-3d, JSCAD's, as before)
784
1758
  }
785
1759
 
786
1760
  // Overlaps between placed parts, remembered across runs (.cache/overlaps.json): a part is its build (the build cache's
787
1761
  // hash: everything it's made from) and where it's placed, so after an edit only the pairs it touches are measured again
788
1762
  const OVERLAPS = paths.cache('overlaps.json');
789
- let remembered = null, fresh = 0;
1763
+ let remembered = null,
1764
+ fresh = 0;
790
1765
  function pairOverlap(pa, pb) {
791
1766
  const solidOf = (p) => p.collide ?? p.geometry; // (a beam by its envelope: lib/beams.mjs)
792
1767
  if (!pa.hash || !pb.hash) return overlap(solidOf(pa), solidOf(pb));
793
- remembered ||= (() => { try { return JSON.parse(host.readText(OVERLAPS)); } catch { return {}; } })();
794
- const at = (p) => `${p.hash}@${Array.from(p.m || []).map((x) => Math.round(x * 1e6) / 1e6).join(',')}`;
1768
+ remembered ||= (() => {
1769
+ const kept = readCacheJson(OVERLAPS); // (one cut short or spoiled: nothing remembered)
1770
+ return kept && typeof kept === 'object' && !Array.isArray(kept) ? kept : {};
1771
+ })();
1772
+ const at = (p) =>
1773
+ `${p.hash}@${Array.from(p.m || [])
1774
+ .map((x) => Math.round(x * 1e6) / 1e6)
1775
+ .join(',')}`;
795
1776
  // (the words in front change whenever the measure does, so an answer remembered from before is measured again: flush
796
1777
  // overlaps, which fit once read as touching and were remembered as 0, came with #371)
797
- const [x, y] = [at(pa), at(pb)].sort(), k = crypto.createHash('sha1').update(`flush+crossing+tracks+${solid ? 'manifold' : 'jscad'}|${x}|${y}`).digest('hex');
798
- if (!(k in remembered)) { remembered[k] = overlap(solidOf(pa), solidOf(pb)); fresh++; }
1778
+ const [x, y] = [at(pa), at(pb)].sort(),
1779
+ k = crypto
1780
+ .createHash('sha1')
1781
+ .update(`flush+crossing+tracks+${solid ? 'manifold' : 'jscad'}|${x}|${y}`)
1782
+ .digest('hex');
1783
+ if (!(k in remembered)) {
1784
+ remembered[k] = overlap(solidOf(pa), solidOf(pb));
1785
+ fresh++;
1786
+ }
799
1787
  return remembered[k];
800
1788
  }
801
1789
  function saveOverlaps() {
802
1790
  if (!fresh) return;
803
- try { host.writeText(OVERLAPS, JSON.stringify(remembered)); fresh = 0; } catch {} // only slower without it
1791
+ if (writeCacheFile(OVERLAPS, JSON.stringify(remembered))) fresh = 0; // (one that can't be written is only slower)
804
1792
  }
805
1793
 
806
1794
  // A screw and what it is threaded into (its part, its nut, its insert) share space by design: fasten's hardware says which
@@ -808,81 +1796,182 @@ const threaded = (a, b) => !!(a.allow?.includes(b.leaf) || b.allow?.includes(a.l
808
1796
 
809
1797
  // checkAssembly(built) -> findings, as @rulecad/printcheck: { level, text, card? } (card: a short line for the mirror)
810
1798
  // What a project prints in, for the motors' heat and press-fit checks
811
- const materialOf = (project) => { try { return readJson(path.join(paths.project(project), 'project.json')).material; } catch { return null; } };
1799
+ const materialOf = (project) => {
1800
+ try {
1801
+ return readJson(path.join(paths.project(project), 'project.json')).material;
1802
+ } catch {
1803
+ return null;
1804
+ }
1805
+ };
812
1806
 
813
1807
  // What's printed and how much it weighs, so "design small" is seen on every change
814
1808
  function massFinding(s, f) {
815
1809
  if (!s.parts.some((p) => p.role === 'reference') && !s.motion?.joints.length) return; // a machine, not a keyboard plate
816
- const parts = printedParts(s); if (!parts.length) return;
817
- const sorted = [...parts].sort((a, b) => b.grams - a.grams), total = sorted.reduce((t, p) => t + p.grams, 0);
818
- f('info', `${Number(total.toFixed(1))} g printed in ${sorted.length} parts; heaviest ${sorted.slice(0, 3).map((p) => `${p.id} ${p.grams} g`).join(', ')}`, null, { code: 'mass.parts', values: { grams: total, parts: Object.fromEntries(sorted.map((p) => [p.id, p.grams])) } });
1810
+ const parts = printedParts(s);
1811
+ if (!parts.length) return;
1812
+ const sorted = [...parts].sort((a, b) => b.grams - a.grams),
1813
+ total = sorted.reduce((t, p) => t + p.grams, 0);
1814
+ f(
1815
+ 'info',
1816
+ `${Number(total.toFixed(1))} g printed in ${sorted.length} parts; heaviest ${sorted
1817
+ .slice(0, 3)
1818
+ .map((p) => `${p.id} ${p.grams} g`)
1819
+ .join(', ')}`,
1820
+ null,
1821
+ { code: 'mass.parts', values: { grams: total, parts: Object.fromEntries(sorted.map((p) => [p.id, p.grams])) } },
1822
+ );
819
1823
  }
820
1824
 
821
1825
  export function checkAssembly(s) {
822
1826
  // the screws found in this pose (at(pose) leaves them to be found again): the fasten and slot nut checks read the same
823
- if (!s.fastened && s.a.fasten?.length && fastening) s = { ...s, fastened: fastening.fastenOf(s, placeItems(s.motion, s.jointValues)) };
824
- const out = [], f = (level, text, card, extra) => out.push({ level, text, ...(card && { card }), ...extra }), mm = (n) => `${Number(n.toFixed(3))}`;
1827
+ if (!s.fastened && s.a.fasten?.length && fastening)
1828
+ s = { ...s, fastened: fastening.fastenOf(s, placeItems(s.motion, s.jointValues)) };
1829
+ const out = [],
1830
+ f = (level, text, card, extra) => out.push({ level, text, ...(card && { card }), ...extra }),
1831
+ mm = (n) => `${Number(n.toFixed(3))}`;
825
1832
  // Versions: every pin, from this assembly and its components, against every copy of that object
826
1833
  const pins = new Map();
827
1834
  for (const r of s.requires) pins.set(`${r.object} ${r.range}`, r);
828
1835
  for (const { object, range } of pins.values()) {
829
1836
  const copies = s.objects.filter((o) => o.objName === object);
830
- if (!copies.length) { f('fail', `requires ${object} ${range}, but nothing uses it`, null, { code: 'requires.unused', refs: { object, range } }); continue; }
1837
+ if (!copies.length) {
1838
+ f('fail', `requires ${object} ${range}, but nothing uses it`, null, {
1839
+ code: 'requires.unused',
1840
+ refs: { object, range },
1841
+ });
1842
+ continue;
1843
+ }
831
1844
  const bad = copies.filter((o) => !satisfies(o.version, range));
832
- f(bad.length ? 'fail' : 'pass', bad.length ? `${object} ${bad[0].version} doesn't meet ${range} (${bad.map((o) => o.id).join(', ')})`
833
- : `${object} ${copies[0].version} meets ${range}${copies.length > 1 ? ` (${copies.length} copies)` : ''}`, null, { code: 'requires.version', refs: { object, range, items: bad.map((o) => o.id) } });
1845
+ f(
1846
+ bad.length ? 'fail' : 'pass',
1847
+ bad.length
1848
+ ? `${object} ${bad[0].version} doesn't meet ${range} (${bad.map((o) => o.id).join(', ')})`
1849
+ : `${object} ${copies[0].version} meets ${range}${copies.length > 1 ? ` (${copies.length} copies)` : ''}`,
1850
+ null,
1851
+ { code: 'requires.version', refs: { object, range, items: bad.map((o) => o.id) } },
1852
+ );
834
1853
  }
835
1854
  // Overlaps between object instances, inside components too. Bounding boxes first: most pairs can't touch.
836
1855
  const named = (p, n) => p.name === n || p.leaf === n || p.item === n || p.name.startsWith(`${n}.`);
837
- const allowed = (a, b) => threaded(a, b) || s.fits.some((x) => x.min != null && x.num(x.min) < 0 && ((named(a, x.a) && named(b, x.b)) || (named(a, x.b) && named(b, x.a))));
838
- const box = new Map(), bx = (p) => box.get(p) || (box.set(p, bounds(p.triangles)), box.get(p));
839
- const touch = (a, b) => [0, 1, 2].every((k) => bx(a).lo[k] <= bx(b).hi[k] + 1e-6 && bx(b).lo[k] <= bx(a).hi[k] + 1e-6);
1856
+ const allowed = (a, b) =>
1857
+ threaded(a, b) ||
1858
+ s.fits.some(
1859
+ (x) =>
1860
+ x.min != null && x.num(x.min) < 0 && ((named(a, x.a) && named(b, x.b)) || (named(a, x.b) && named(b, x.a))),
1861
+ );
1862
+ const box = new Map(),
1863
+ bx = (p) => box.get(p) || (box.set(p, bounds(p.triangles)), box.get(p));
1864
+ const touch = (a, b) =>
1865
+ [0, 1, 2].every((k) => bx(a).lo[k] <= bx(b).hi[k] + 1e-6 && bx(b).lo[k] <= bx(a).hi[k] + 1e-6);
840
1866
  const clashes = [];
841
- for (let i = 0; i < s.parts.length; i++) for (let j = i + 1; j < s.parts.length; j++) {
842
- const pa = s.parts[i], pb = s.parts[j];
843
- if (pa.leaf === pb.leaf || !touch(pa, pb) || allowed(pa, pb)) continue;
844
- const v = pairOverlap(pa, pb);
845
- if (v > 0.01) clashes.push({ text: `${pa.name} and ${pb.name} overlap by ${mm(v)} mm³`, a: pa.name, b: pb.name, volume: v });
846
- }
847
- if (clashes.length) f('fail', clashes.slice(0, 5).map((c) => c.text).join('; ') + (clashes.length > 5 ? `; and ${clashes.length - 5} more` : ''), `${clashes.length} overlaps`,
848
- { code: 'overlap', values: { count: clashes.length }, refs: { overlaps: clashes.map(({ a, b, volume }) => ({ a, b, volume })) } });
849
- else f('pass', `no parts overlap (${new Set(s.parts.map((p) => p.leaf)).size} object instances)`, 'No parts overlap', { code: 'overlap', values: { count: 0 } });
1867
+ for (let i = 0; i < s.parts.length; i++)
1868
+ for (let j = i + 1; j < s.parts.length; j++) {
1869
+ const pa = s.parts[i],
1870
+ pb = s.parts[j];
1871
+ if (pa.leaf === pb.leaf || !touch(pa, pb) || allowed(pa, pb)) continue;
1872
+ const v = pairOverlap(pa, pb);
1873
+ if (v > 0.01)
1874
+ clashes.push({ text: `${pa.name} and ${pb.name} overlap by ${mm(v)} mm³`, a: pa.name, b: pb.name, volume: v });
1875
+ }
1876
+ if (clashes.length)
1877
+ f(
1878
+ 'fail',
1879
+ clashes
1880
+ .slice(0, 5)
1881
+ .map((c) => c.text)
1882
+ .join('; ') + (clashes.length > 5 ? `; and ${clashes.length - 5} more` : ''),
1883
+ `${clashes.length} overlaps`,
1884
+ {
1885
+ code: 'overlap',
1886
+ values: { count: clashes.length },
1887
+ refs: { overlaps: clashes.map(({ a, b, volume }) => ({ a, b, volume })) },
1888
+ },
1889
+ );
1890
+ else
1891
+ f('pass', `no parts overlap (${new Set(s.parts.map((p) => p.leaf)).size} object instances)`, 'No parts overlap', {
1892
+ code: 'overlap',
1893
+ values: { count: 0 },
1894
+ });
850
1895
  // Fits: the closest gap between two named things, against a range. Copies of one fit are reported together, worst first.
851
1896
  // A fit names parts (keyboard, key-0-0.cap), or the faces of an item near one of its anchors (keyboard@pivot, within
852
1897
  // "within" mm, 10 by default): the pocket round a pivot, not the whole case
853
- const marks = anchorsAt(s), within = (x) => (x.within != null ? x.num(x.within) : 10);
1898
+ const marks = anchorsAt(s),
1899
+ within = (x) => (x.within != null ? x.num(x.within) : 10);
854
1900
  // A beam's address in a fit (x1.top@120): the faces near that point, as near an anchor
855
- const addressMark = (n) => { const r = addressAt(s, n); return r && { id: n, item: r.id, at: r.at }; };
1901
+ const addressMark = (n) => {
1902
+ const r = addressAt(s, n);
1903
+ return r && { id: n, item: r.id, at: r.at };
1904
+ };
856
1905
  const near = (p, mark, r) => ({ ...p, polygons: p.polygons.filter((f) => distanceToFace(mark.at, f) <= r) });
857
1906
  const pickIn = (n, x) => {
858
1907
  if (Array.isArray(n)) return n.flatMap((m) => pickIn(m, x));
859
- if (!n.includes('@')) { const ps = s.parts.filter((p) => named(p, n)); if (ps.length) return ps; } // (else a beam's end or face: x1.a, x1.top)
1908
+ if (!n.includes('@')) {
1909
+ const ps = s.parts.filter((p) => named(p, n));
1910
+ if (ps.length) return ps;
1911
+ } // (else a beam's end or face: x1.a, x1.top)
860
1912
  const mark = marks.find((m) => m.id === n) ?? addressMark(n);
861
1913
  if (!mark) return [];
862
- return s.parts.filter((p) => named(p, mark.item)).map((p) => near(p, mark, within(x))).filter((p) => p.polygons.length);
1914
+ return s.parts
1915
+ .filter((p) => named(p, mark.item))
1916
+ .map((p) => near(p, mark, within(x)))
1917
+ .filter((p) => p.polygons.length);
863
1918
  };
864
1919
  const pick = (n) => pickIn(n, {});
865
1920
  const groups = new Map();
866
1921
  for (const x of s.fits) {
867
1922
  if (x.poses && !x.poses.includes(s.pose)) continue; // a fit for some poses only: the folded screen over the keys
868
- if (x.holes) { holesFit(x); continue; }
1923
+ if (x.holes) {
1924
+ holesFit(x);
1925
+ continue;
1926
+ }
869
1927
  if (x.silent) continue; // lets a pair overlap, and has nothing to report
870
- if (x.engage != null) { engageFit(x); continue; }
871
- if (x.seat != null) { seatFit(x, s, f, { placeItems, jointValues, mul, seatSize }); continue; }
1928
+ if (x.engage != null) {
1929
+ engageFit(x);
1930
+ continue;
1931
+ }
1932
+ if (x.seat != null) {
1933
+ seatFit(x, s, f, { placeItems, jointValues, seatSize });
1934
+ continue;
1935
+ }
872
1936
  if (x.pin && pinning) pinFit(x); // (and its gap, as any fit's)
873
1937
  if (x.magnet && pinning) magnetFit(x);
874
- if (x.shaft != null) { shaftFit(x, s, f, { placeItems, jointValues, mul, materialName: materialOf(s.project), holeComp: printerRules(s).hole_comp ?? 0.1 }); continue; }
875
- const A = pickIn(x.a, x), key = x.note || `${x.a} / ${x.b}`;
876
- const lo = x.min != null ? x.num(x.min) : -Infinity, hi = x.max != null ? x.num(x.max) : Infinity;
1938
+ if (x.shaft != null) {
1939
+ shaftFit(x, s, f, {
1940
+ placeItems,
1941
+ jointValues,
1942
+ materialName: materialOf(s.project),
1943
+ holeComp: printerRules(s).hole_comp ?? 0.1,
1944
+ });
1945
+ continue;
1946
+ }
1947
+ const A = pickIn(x.a, x),
1948
+ key = x.note || `${x.a} / ${x.b}`;
1949
+ const lo = x.min != null ? x.num(x.min) : -Infinity,
1950
+ hi = x.max != null ? x.num(x.max) : Infinity;
877
1951
  const reach = Math.max(2, ...[lo, hi].filter(Number.isFinite)) + 1; // look past the range, so a gap near it is measured
878
1952
  let B = pickIn(x.b, x);
879
- if (Array.isArray(x.b) && A.length) { // against many others: only those within reach
880
- const lo3 = [0, 1, 2].map((k) => Math.min(...A.map((p) => bx(p).lo[k]))), hi3 = [0, 1, 2].map((k) => Math.max(...A.map((p) => bx(p).hi[k])));
1953
+ if (Array.isArray(x.b) && A.length) {
1954
+ // against many others: only those within reach
1955
+ const lo3 = [0, 1, 2].map((k) => Math.min(...A.map((p) => bx(p).lo[k]))),
1956
+ hi3 = [0, 1, 2].map((k) => Math.max(...A.map((p) => bx(p).hi[k])));
881
1957
  B = B.filter((p) => [0, 1, 2].every((k) => bx(p).lo[k] <= hi3[k] + reach && lo3[k] <= bx(p).hi[k] + reach));
882
1958
  }
883
- if (!A.length || (!B.length && !Array.isArray(x.b))) { f('fail', `fit ${x.a} / ${x.b}: no such ${A.length ? x.b : x.a}`, null, { code: 'fit.missing', refs: { a: x.a, b: x.b, missing: A.length ? x.b : x.a } }); continue; }
1959
+ if (!A.length || (!B.length && !Array.isArray(x.b))) {
1960
+ f('fail', `fit ${x.a} / ${x.b}: no such ${A.length ? x.b : x.a}`, null, {
1961
+ code: 'fit.missing',
1962
+ refs: { a: x.a, b: x.b, missing: A.length ? x.b : x.a },
1963
+ });
1964
+ continue;
1965
+ }
884
1966
  const vol = A.reduce((t, pa) => t + B.reduce((u, pb) => u + (touch(pa, pb) ? pairOverlap(pa, pb) : 0), 0), 0);
885
- const near = !B.length || vol > 0.01 ? null : closestAt(A.flatMap((p) => p.polygons), B.flatMap((p) => p.polygons), reach);
1967
+ const near =
1968
+ !B.length || vol > 0.01
1969
+ ? null
1970
+ : closestAt(
1971
+ A.flatMap((p) => p.polygons),
1972
+ B.flatMap((p) => p.polygons),
1973
+ reach,
1974
+ );
886
1975
  const gap = !B.length ? Infinity : vol > 0.01 ? -vol : near.gap; // negative: overlap, mm³
887
1976
  const ok = vol > 0.01 ? lo < 0 : gap >= lo && gap <= hi;
888
1977
  if (!groups.has(key)) groups.set(key, { x, lo, hi, results: [] });
@@ -891,124 +1980,356 @@ export function checkAssembly(s) {
891
1980
  // The anchor nearest a point, if one is within 20 mm: where to look
892
1981
  const nearest = (pt) => {
893
1982
  if (!pt || !marks.length) return {};
894
- const m = marks.map((k) => ({ k, d: Math.hypot(k.at[0] - pt[0], k.at[1] - pt[1], k.at[2] - pt[2]) })).sort((a, b) => a.d - b.d)[0];
1983
+ const m = marks
1984
+ .map((k) => ({ k, d: Math.hypot(k.at[0] - pt[0], k.at[1] - pt[1], k.at[2] - pt[2]) }))
1985
+ .sort((a, b) => a.d - b.d)[0];
895
1986
  return m.d <= 20 ? { near: m.k.id, distance: Number(m.d.toFixed(2)) } : {};
896
1987
  };
897
1988
  for (const [key, { x, lo, hi, results }] of groups) {
898
1989
  const worst = results.reduce((w, r) => (!r.ok && w.ok ? r : r.ok === w.ok && r.gap < w.gap ? r : w), results[0]);
899
- const say = (g) => (g < 0 ? `press fit, ${mm(-g)} mm³ overlap` : g === Infinity ? 'not near each other' : `closest gap ${mm(g)} mm`);
1990
+ const say = (g) =>
1991
+ g < 0 ? `press fit, ${mm(-g)} mm³ overlap` : g === Infinity ? 'not near each other' : `closest gap ${mm(g)} mm`;
900
1992
  const n = results.length > 1 ? ` (${results.filter((r) => r.ok).length} of ${results.length} in range)` : '';
901
1993
  const label = (x.label || x.a).replace(/ \(.*\)$/, '');
902
1994
  const where = nearest(worst.at);
903
- f(worst.ok ? 'pass' : 'warn', `${key}: ${say(worst.gap)}${n}${worst.ok ? '' : `, wanted ${lo === -Infinity ? '' : `${mm(lo)} `}to ${hi === Infinity ? 'any' : mm(hi)} mm (${results.filter((r) => !r.ok).map((r) => r.id).join(', ')})${where.near ? `, ${where.distance} mm from ${where.near}` : ''}`}`,
1995
+ f(
1996
+ worst.ok ? 'pass' : 'warn',
1997
+ `${key}: ${say(worst.gap)}${n}${
1998
+ worst.ok
1999
+ ? ''
2000
+ : `, wanted ${lo === -Infinity ? '' : `${mm(lo)} `}to ${hi === Infinity ? 'any' : mm(hi)} mm (${results
2001
+ .filter((r) => !r.ok)
2002
+ .map((r) => r.id)
2003
+ .join(', ')})${where.near ? `, ${where.distance} mm from ${where.near}` : ''}`
2004
+ }`,
904
2005
  `${label}: ${worst.gap < 0 ? `press fit ${mm(-worst.gap)} mm³` : worst.gap === Infinity ? 'apart' : `gap ${Number(worst.gap.toFixed(2))} mm`}${worst.ok ? '' : ' (out of range)'}`,
905
- { code: 'fit', values: { ...(worst.gap < 0 ? { overlap: -worst.gap } : { gap: worst.gap }), min: lo, max: hi, inRange: results.filter((r) => r.ok).length, copies: results.length },
906
- refs: { a: x.a, b: x.b, label: x.label, ...(s.pose ? { pose: s.pose } : {}), outOfRange: results.filter((r) => !r.ok).map((r) => r.id), ...where }, ...(worst.at ? { at: { lo: worst.at, hi: worst.at } } : {}) });
2006
+ {
2007
+ code: 'fit',
2008
+ values: {
2009
+ ...(worst.gap < 0 ? { overlap: -worst.gap } : { gap: worst.gap }),
2010
+ min: lo,
2011
+ max: hi,
2012
+ inRange: results.filter((r) => r.ok).length,
2013
+ copies: results.length,
2014
+ },
2015
+ refs: {
2016
+ a: x.a,
2017
+ b: x.b,
2018
+ label: x.label,
2019
+ ...(s.pose ? { pose: s.pose } : {}),
2020
+ outOfRange: results.filter((r) => !r.ok).map((r) => r.id),
2021
+ ...where,
2022
+ },
2023
+ ...(worst.at ? { at: { lo: worst.at, hi: worst.at } } : {}),
2024
+ },
2025
+ );
907
2026
  }
908
2027
  // Engage fits: a part slid onto a shaft, a pin or a peg goes onto it, not just against its end. Along the axis of the
909
2028
  // joint between them, each part's material near the axis (within radius, 10 mm) spans a stretch; how far the two
910
2029
  // stretches overlap is how far one is on the other. An arm resting on a shaft's end touches it face to face, as a
911
2030
  // seated one does, and nothing overlaps either way: only this tells them apart.
912
2031
  function engageFit(x) {
913
- const top = (n) => String(n).split(/[.@]/)[0], ids = s.motion?.items.map((i) => i[0]) || [], a = top(x.a), b = top(x.b), label = x.note || `${x.a} onto ${x.b}`;
914
- const j = (s.motion?.joints || []).find((jt) => { const pair = [ids[jt.child], jt.parent < 0 ? null : ids[jt.parent]]; return pair.includes(a) && pair.includes(b); });
915
- if (!j) return f('fail', `${label}: no joint between ${a} and ${b} to measure along (engage measures along the joint that holds one on the other)`, null, { code: 'fit.engage', refs: { a: x.a, b: x.b } });
916
- const worlds = placeItems(s.motion, s.jointValues), P = mul(j.parent < 0 ? [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0] : worlds[j.parent], j.a);
917
- const O = [P[3], P[7], P[11]], Z = [P[2], P[6], P[10]], r = x.radius != null ? x.num(x.radius) : 10, need = x.num(x.engage);
2032
+ const top = (n) => String(n).split(/[.@]/)[0],
2033
+ ids = s.motion?.items.map((i) => i[0]) || [],
2034
+ a = top(x.a),
2035
+ b = top(x.b),
2036
+ label = x.note || `${x.a} onto ${x.b}`;
2037
+ const j = (s.motion?.joints || []).find((jt) => {
2038
+ const pair = [ids[jt.child], jt.parent < 0 ? null : ids[jt.parent]];
2039
+ return pair.includes(a) && pair.includes(b);
2040
+ });
2041
+ if (!j)
2042
+ return f(
2043
+ 'fail',
2044
+ `${label}: no joint between ${a} and ${b} to measure along (engage measures along the joint that holds one on the other)`,
2045
+ null,
2046
+ { code: 'fit.engage', refs: { a: x.a, b: x.b } },
2047
+ );
2048
+ const worlds = placeItems(s.motion, s.jointValues),
2049
+ P = mul(j.parent < 0 ? [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0] : worlds[j.parent], j.a);
2050
+ const O = [P[3], P[7], P[11]],
2051
+ Z = [P[2], P[6], P[10]],
2052
+ r = x.radius != null ? x.num(x.radius) : 10,
2053
+ need = x.num(x.engage);
918
2054
  const span = (parts) => {
919
- let lo = Infinity, hi = -Infinity;
920
- for (const p of parts) for (const t of p.triangles) for (const v of t) {
921
- const d = [v[0] - O[0], v[1] - O[1], v[2] - O[2]], along = d[0] * Z[0] + d[1] * Z[1] + d[2] * Z[2];
922
- if (Math.hypot(d[0] - along * Z[0], d[1] - along * Z[1], d[2] - along * Z[2]) <= r) { lo = Math.min(lo, along); hi = Math.max(hi, along); }
923
- }
2055
+ let lo = Infinity,
2056
+ hi = -Infinity;
2057
+ for (const p of parts)
2058
+ for (const t of p.triangles)
2059
+ for (const v of t) {
2060
+ const d = [v[0] - O[0], v[1] - O[1], v[2] - O[2]],
2061
+ along = d[0] * Z[0] + d[1] * Z[1] + d[2] * Z[2];
2062
+ if (Math.hypot(d[0] - along * Z[0], d[1] - along * Z[1], d[2] - along * Z[2]) <= r) {
2063
+ lo = Math.min(lo, along);
2064
+ hi = Math.max(hi, along);
2065
+ }
2066
+ }
924
2067
  return [lo, hi];
925
2068
  };
926
- const [la, ha] = span(pickIn(x.a, x)), [lb, hb] = span(pickIn(x.b, x)), on = Math.max(0, Math.min(ha, hb) - Math.max(la, lb));
2069
+ const [la, ha] = span(pickIn(x.a, x)),
2070
+ [lb, hb] = span(pickIn(x.b, x)),
2071
+ on = Math.max(0, Math.min(ha, hb) - Math.max(la, lb));
927
2072
  const ok = on >= need - 1e-3; // (flush is on: a hair under, in the floating point, is not short)
928
- f(ok ? 'pass' : 'fail', `${label}: ${on > 1e-3 ? `${mm(on)} mm on` : `not on at all (${Math.max(la, lb) - Math.min(ha, hb) < 1e-3 ? 'end to end' : 'apart'})`} along their joint${ok ? '' : `, where it should go ${mm(need)} mm on: its anchor is on the wrong face, or the shaft too short`}`, ok ? null : `${a}: not on ${b}`, { code: 'fit.engage', values: { engaged: on, need }, refs: { a: x.a, b: x.b, joint: j.id } });
2073
+ f(
2074
+ ok ? 'pass' : 'fail',
2075
+ `${label}: ${on > 1e-3 ? `${mm(on)} mm on` : `not on at all (${Math.max(la, lb) - Math.min(ha, hb) < 1e-3 ? 'end to end' : 'apart'})`} along their joint${ok ? '' : `, where it should go ${mm(need)} mm on: its anchor is on the wrong face, or the shaft too short`}`,
2076
+ ok ? null : `${a}: not on ${b}`,
2077
+ { code: 'fit.engage', values: { engaged: on, need }, refs: { a: x.a, b: x.b, joint: j.id } },
2078
+ );
2079
+ }
2080
+
2081
+ // A mesh's faces: the centre distance is said across the axes, so a gear anchored at the wrong height (the wrong face,
2082
+ // a missing spacer, the wrong step of a compound gear) would mesh with nothing and still pass (meshFaces, below).
2083
+ // Spur, internal and rack meshes; worms, bevels and planetaries are placed by their own checks.
2084
+ function faceOverlap(g) {
2085
+ const ids = s.motion.items.map((i) => i[0]),
2086
+ worlds = placeItems(s.motion, s.jointValues);
2087
+ const gear = (x) => {
2088
+ const W = worlds[x.item];
2089
+ return {
2090
+ ...x,
2091
+ triangles: s.parts.filter((p) => named(p, ids[x.item])).flatMap((p) => p.triangles),
2092
+ frame: { O: [W[3], W[7], W[11]], X: [W[0], W[4], W[8]], Y: [W[1], W[5], W[9]], Z: [W[2], W[6], W[10]] },
2093
+ };
2094
+ };
2095
+ const A = gear(g.faces.a),
2096
+ r = meshFaces({ module: g.faces.module, a: A, b: gear(g.faces.b), along: A.frame }),
2097
+ [a, b] = [g.faces.a, g.faces.b].map((x) => ids[x.item]),
2098
+ label = g.with === a && g.joint === b ? `${a} and ${b}` : `${g.with} and ${g.joint} (${a} and ${b})`,
2099
+ extra = {
2100
+ code: 'mesh.face',
2101
+ at: g.between[0],
2102
+ between: g.between,
2103
+ refs: { joints: [g.with, g.joint], items: [a, b] },
2104
+ };
2105
+ if (!r.a || !r.b) {
2106
+ const lost = r.a ? b : a;
2107
+ return f(
2108
+ 'warn',
2109
+ `${label}: no teeth found on ${lost}'s ${g.faces.b.tipLine != null && lost === b ? 'tip line' : 'tip circle'} as the mesh describes it, so how far the faces overlap is unchecked: draw it with the module, teeth and shift its mesh gives`,
2110
+ `${g.joint}: face`,
2111
+ extra,
2112
+ );
2113
+ }
2114
+ f(
2115
+ r.level,
2116
+ `${label}: faces overlap ${mm(r.overlap)} of ${mm(r.narrower)} mm${r.level === 'pass' ? '' : ` (${Math.round(r.share * 100)} % of the narrower face; ${a}'s teeth from ${mm(r.a[0])} to ${mm(r.a[1])} mm along ${g.with}'s axis, ${b}'s from ${mm(r.b[0])} to ${mm(r.b[1])}): ${r.level === 'fail' ? 'too little of the teeth meet to drive' : 'the shared part of the faces carries all the load'}, so move one along its axis (its anchor's height, a spacer) until the faces line up`}`,
2117
+ r.level === 'pass' ? null : `${g.joint}: face`,
2118
+ { ...extra, values: { overlap: r.overlap, narrower: r.narrower } },
2119
+ );
929
2120
  }
930
2121
 
931
2122
  // Pin fits: the pins a fit names, their holes found in the parts and held to the pins' models (lib/pins.mjs)
932
- function pinFit(x) { try { pinning.pinFit(x, s, f); } catch (e) { f('fail', `${x.note || `${x.a} to ${x.b}`}: ${e.message}`, null, { code: 'fit.pin', refs: { a: x.a, b: x.b, pin: x.fastener } }); } }
2123
+ function pinFit(x) {
2124
+ try {
2125
+ pinning.pinFit(x, s, f);
2126
+ } catch (e) {
2127
+ f('fail', `${x.note || `${x.a} to ${x.b}`}: ${e.message}`, null, {
2128
+ code: 'fit.pin',
2129
+ refs: { a: x.a, b: x.b, pin: x.fastener },
2130
+ });
2131
+ }
2132
+ }
933
2133
  // Magnet fits: the magnets a fit names, their pockets found in the parts and held to the magnet's seat (lib/magnets.mjs)
934
- function magnetFit(x) { try { pinning.magnetFit(x, s, f); } catch (e) { f('fail', `${x.note || `${x.a} to ${x.b}`}: ${e.message}`, null, { code: 'fit.magnet', refs: { a: x.a, b: x.b, magnet: x.fastener } }); } }
2134
+ function magnetFit(x) {
2135
+ try {
2136
+ pinning.magnetFit(x, s, f);
2137
+ } catch (e) {
2138
+ f('fail', `${x.note || `${x.a} to ${x.b}`}: ${e.message}`, null, {
2139
+ code: 'fit.magnet',
2140
+ refs: { a: x.a, b: x.b, magnet: x.fastener },
2141
+ });
2142
+ }
2143
+ }
935
2144
  // Holes fits: each mounting hole's screw path, clear into a hole, with material round it
936
2145
  function holesFit(x) {
937
- const A = pick(x.a), B = pick(x.b), label = x.label || `${x.a} into ${x.b}`;
2146
+ const A = pick(x.a),
2147
+ B = pick(x.b),
2148
+ label = x.label || `${x.a} into ${x.b}`;
938
2149
  const board = A.length && s.objects.find((o) => o.id === A[0].leaf)?.built;
939
- if (!board?.circuit) return f('fail', `${label}: ${x.a} isn't a circuit board, so it has no mounting holes to follow`);
2150
+ if (!board?.circuit)
2151
+ return f('fail', `${label}: ${x.a} isn't a circuit board, so it has no mounting holes to follow`);
940
2152
  if (!B.length) return f('fail', `${label}: no such ${x.b}`);
941
2153
  const holes = board.circuit.filter((e) => e.type === 'pcb_hole' && !e.pcb_component_id);
942
2154
  if (!holes.length) return f('fail', `${label}: ${x.a} has no mounting holes`);
943
- const depth = x.num(x.depth), down = x.direction === 'up' ? 1 : -1, faces = B.flatMap((p) => p.triangles);
944
- const base = down < 0 ? 0 : board.values.thickness ?? 0, at = (h, dx, dy, t) => jscad.maths.vec3.transform([0, 0, 0], [h.x + dx, h.y + dy, base + down * t], A[0].m);
945
- const steps = 8, misses = [];
2155
+ const depth = x.num(x.depth),
2156
+ down = x.direction === 'up' ? 1 : -1,
2157
+ faces = B.flatMap((p) => p.triangles);
2158
+ const base = down < 0 ? 0 : (board.values.thickness ?? 0),
2159
+ at = (h, dx, dy, t) => jscad.maths.vec3.transform([0, 0, 0], [h.x + dx, h.y + dy, base + down * t], A[0].m);
2160
+ const steps = 8,
2161
+ misses = [];
946
2162
  for (const h of holes) {
947
- const ring = x.ring != null ? x.num(x.ring) : h.hole_diameter, where = `hole at ${mm(h.x)}, ${mm(h.y)} mm`;
948
- const blocked = Array.from({ length: steps }, (_, i) => (depth * (i + 0.5)) / steps).find((t) => inside(at(h, 0, 0, t), faces));
949
- if (blocked != null) { misses.push(`${where}: solid ${mm(blocked)} mm along the screw's path`); continue; }
950
- const round = Array.from({ length: steps }, (_, i) => (2 * Math.PI * i) / steps).filter((a) => !inside(at(h, ring * Math.cos(a), ring * Math.sin(a), depth / 2), faces));
951
- if (round.length) misses.push(`${where}: no material ${mm(ring)} mm from the screw on ${round.length} of ${steps} sides`);
2163
+ const ring = x.ring != null ? x.num(x.ring) : h.hole_diameter,
2164
+ where = `hole at ${mm(h.x)}, ${mm(h.y)} mm`;
2165
+ const blocked = Array.from({ length: steps }, (_, i) => (depth * (i + 0.5)) / steps).find((t) =>
2166
+ inside(at(h, 0, 0, t), faces),
2167
+ );
2168
+ if (blocked != null) {
2169
+ misses.push(`${where}: solid ${mm(blocked)} mm along the screw's path`);
2170
+ continue;
2171
+ }
2172
+ const round = Array.from({ length: steps }, (_, i) => (2 * Math.PI * i) / steps).filter(
2173
+ (a) => !inside(at(h, ring * Math.cos(a), ring * Math.sin(a), depth / 2), faces),
2174
+ );
2175
+ if (round.length)
2176
+ misses.push(`${where}: no material ${mm(ring)} mm from the screw on ${round.length} of ${steps} sides`);
952
2177
  }
953
- f(misses.length ? 'fail' : 'pass', misses.length ? `${label}: ${misses.join('; ')}` : `${label}: ${holes.length} of ${holes.length} holes clear for ${mm(depth)} mm, with material around each`,
2178
+ f(
2179
+ misses.length ? 'fail' : 'pass',
2180
+ misses.length
2181
+ ? `${label}: ${misses.join('; ')}`
2182
+ : `${label}: ${holes.length} of ${holes.length} holes clear for ${mm(depth)} mm, with material around each`,
954
2183
  `${label}: ${misses.length ? `${misses.length} of ${holes.length} miss` : `${holes.length} of ${holes.length} line up`}`,
955
- { code: 'fit.holes', values: { holes: holes.length, missed: misses.length }, refs: { a: x.a, b: x.b, misses } });
2184
+ { code: 'fit.holes', values: { holes: holes.length, missed: misses.length }, refs: { a: x.a, b: x.b, misses } },
2185
+ );
956
2186
  }
957
2187
  // Joints: every value in its range (a ball's tip within its cone), and every loop closed
958
2188
  if (s.motion?.joints.length) {
959
2189
  const outside = [];
960
2190
  for (const j of s.motion.joints) {
961
2191
  const v = s.jointValues[j.id];
962
- j.dofs.forEach(([lo, hi], i) => { if (v[i] < lo - 1e-9 || v[i] > hi + 1e-9) outside.push(`${j.id} ${mm(v[i])} (${mm(lo)} to ${mm(hi)})`); });
963
- if (j.cone != null) { const tip = Math.acos(Math.min(1, jointMatrix(j, v)[10])) / (Math.PI / 180); if (tip > j.cone + 1e-9) outside.push(`${j.id} tips ${mm(tip)}° (cone ${mm(j.cone)}°)`); }
2192
+ j.dofs.forEach(([lo, hi], i) => {
2193
+ if (v[i] < lo - 1e-9 || v[i] > hi + 1e-9) outside.push(`${j.id} ${mm(v[i])} (${mm(lo)} to ${mm(hi)})`);
2194
+ });
2195
+ if (j.cone != null) {
2196
+ const tip = Math.acos(Math.min(1, jointMatrix(j, v)[10])) / (Math.PI / 180);
2197
+ if (tip > j.cone + 1e-9) outside.push(`${j.id} tips ${mm(tip)}° (cone ${mm(j.cone)}°)`);
2198
+ }
964
2199
  }
965
- if (outside.length) f('fail', `joints out of range: ${outside.join(', ')}`, `${outside.length} joints out of range`, { code: 'joint.range', refs: { joints: outside } });
966
- for (const l of loopGaps(s)) f(l.ok ? 'pass' : 'fail', `${l.label}: ${l.ok ? 'closed' : 'apart'} (${mm(l.gap)} mm, axes ${mm(l.angle)}° apart)`, `${l.label}: ${l.ok ? 'closed' : 'apart'}`, { code: 'loop', values: { gap: l.gap, angle: l.angle }, refs: { label: l.label } });
2200
+ if (outside.length)
2201
+ f('fail', `joints out of range: ${outside.join(', ')}`, `${outside.length} joints out of range`, {
2202
+ code: 'joint.range',
2203
+ refs: { joints: outside },
2204
+ });
2205
+ for (const l of loopGaps(s))
2206
+ f(
2207
+ l.ok ? 'pass' : 'fail',
2208
+ `${l.label}: ${l.ok ? 'closed' : 'apart'} (${mm(l.gap)} mm, axes ${mm(l.angle)}° apart)`,
2209
+ `${l.label}: ${l.ok ? 'closed' : 'apart'}`,
2210
+ { code: 'loop', values: { gap: l.gap, angle: l.angle }, refs: { label: l.label } },
2211
+ );
967
2212
  // Held by something: in a mechanism, every part but the first either turns or slides on a joint, or is fastened,
968
2213
  // through a chain of fits with "fastens", to the first. A part only placed somewhere stays there in the model and
969
2214
  // nowhere else: a ring gear resting on its case turns with the planets; a pawl resting on its post walks off it.
970
2215
  if (s.motion.joints.some((j) => j.type !== 'fixed')) {
971
- const ids = s.motion.items.map((x) => x[0]), top = (n) => String(n).split(/[.@]/)[0];
2216
+ const ids = s.motion.items.map((x) => x[0]),
2217
+ top = (n) => String(n).split(/[.@]/)[0];
972
2218
  // (a beam placed by its ends is the frame, held where it is drawn: what is screwed to it is held by it)
973
- const held = new Set([ids[0], ...s.motion.joints.filter((j) => !j.at).map((j) => ids[j.child]), ...s.items.filter((it) => it.beam && it.from != null).map((it) => it.id)]), links = s.fits.filter((x) => x.fastens).map((x) => [top(x.a), top(x.b)]);
2219
+ const held = new Set([
2220
+ ids[0],
2221
+ ...s.motion.joints.filter((j) => !j.at).map((j) => ids[j.child]),
2222
+ ...s.items.filter((it) => it.beam && it.from != null).map((it) => it.id),
2223
+ ]),
2224
+ links = s.fits.filter((x) => x.fastens).map((x) => [top(x.a), top(x.b)]);
974
2225
  // (a fitting at a beam's end, an end cap pressed into it or a foot screwed into its bore, is held by that beam)
975
- for (const it of s.a.items || []) { const m = typeof it.at === 'string' && (it.fitting || it.bought) ? /^([\w-]+)\.[ab]$/.exec(it.at.trim()) : null; if (m && s.items.some((x) => x.id === m[1] && x.beam)) links.push([it.id, m[1]]); }
976
- for (let grew = true; grew;) { grew = false; for (const [a, b] of links) { if (held.has(a) && !held.has(b)) { held.add(b); grew = true; } if (held.has(b) && !held.has(a)) { held.add(a); grew = true; } } }
2226
+ for (const it of s.a.items || []) {
2227
+ const m = typeof it.at === 'string' && (it.fitting || it.bought) ? /^([\w-]+)\.[ab]$/.exec(it.at.trim()) : null;
2228
+ if (m && s.items.some((x) => x.id === m[1] && x.beam)) links.push([it.id, m[1]]);
2229
+ }
2230
+ for (let grew = true; grew;) {
2231
+ grew = false;
2232
+ for (const [a, b] of links) {
2233
+ if (held.has(a) && !held.has(b)) {
2234
+ held.add(b);
2235
+ grew = true;
2236
+ }
2237
+ if (held.has(b) && !held.has(a)) {
2238
+ held.add(a);
2239
+ grew = true;
2240
+ }
2241
+ }
2242
+ }
977
2243
  const placed = new Set(s.objects.filter((o) => !o.unplaced && o.role !== 'reference').map((o) => top(o.id)));
978
2244
  const loose = ids.filter((id) => !held.has(id) && placed.has(id));
979
- if (loose.length) f('warn', `${loose.join(', ')} ${loose.length > 1 ? 'are' : 'is'} placed, but nothing holds ${loose.length > 1 ? 'them' : 'it'}: give ${loose.length > 1 ? 'each' : 'it'} a joint, or fasten it to what it sits on (pins, screws, a press) and say so with a fit that "fastens"`, `${loose.length} loose`, { code: 'assembly.loose', refs: { items: loose } });
980
- else f('pass', `every part turns or slides on a joint, or is fastened to the ${ids[0]}`, null, { code: 'assembly.held' });
2245
+ if (loose.length)
2246
+ f(
2247
+ 'warn',
2248
+ `${loose.join(', ')} ${loose.length > 1 ? 'are' : 'is'} placed, but nothing holds ${loose.length > 1 ? 'them' : 'it'}: give ${loose.length > 1 ? 'each' : 'it'} a joint, or fasten it to what it sits on (pins, screws, a press) and say so with a fit that "fastens"`,
2249
+ `${loose.length} loose`,
2250
+ { code: 'assembly.loose', refs: { items: loose } },
2251
+ );
2252
+ else
2253
+ f('pass', `every part turns or slides on a joint, or is fastened to the ${ids[0]}`, null, {
2254
+ code: 'assembly.held',
2255
+ });
981
2256
  // A fit that fastens holds two items as one, but only a joint or an anchor moves them: one fastened to a part a
982
2257
  // joint moves, and placed where it stands, stays behind in every pose and is left out of what that joint carries
983
2258
  // (one also fastened to what stays, as a servo to its stand with its arm fastened to the horn, is held there)
984
- const moving = s.motion.joints.filter((j) => !j.at && j.type !== 'fixed'), across = (a, b) => moving.find((jj) => beyond(s.motion, jj, ids.indexOf(a)) !== beyond(s.motion, jj, ids.indexOf(b)));
985
- const still = new Set([ids[0], ...s.motion.joints.filter((j) => !j.at).map((j) => ids[j.child]), ...s.items.filter((it) => it.beam && it.from != null).map((it) => it.id)]), same = links.filter(([a, b]) => ids.includes(a) && ids.includes(b) && !across(a, b));
986
- for (let grew = true; grew;) { grew = false; for (const [a, b] of same) { if (still.has(a) && !still.has(b)) { still.add(b); grew = true; } if (still.has(b) && !still.has(a)) { still.add(a); grew = true; } } }
2259
+ const moving = s.motion.joints.filter((j) => !j.at && j.type !== 'fixed'),
2260
+ across = (a, b) =>
2261
+ moving.find((jj) => beyond(s.motion, jj, ids.indexOf(a)) !== beyond(s.motion, jj, ids.indexOf(b)));
2262
+ const still = new Set([
2263
+ ids[0],
2264
+ ...s.motion.joints.filter((j) => !j.at).map((j) => ids[j.child]),
2265
+ ...s.items.filter((it) => it.beam && it.from != null).map((it) => it.id),
2266
+ ]),
2267
+ same = links.filter(([a, b]) => ids.includes(a) && ids.includes(b) && !across(a, b));
2268
+ for (let grew = true; grew;) {
2269
+ grew = false;
2270
+ for (const [a, b] of same) {
2271
+ if (still.has(a) && !still.has(b)) {
2272
+ still.add(b);
2273
+ grew = true;
2274
+ }
2275
+ if (still.has(b) && !still.has(a)) {
2276
+ still.add(a);
2277
+ grew = true;
2278
+ }
2279
+ }
2280
+ }
987
2281
  for (const x of s.fits.filter((q) => q.fastens)) {
988
- const [a, b] = [top(x.a), top(x.b)], ia = ids.indexOf(a), ib = ids.indexOf(b);
2282
+ const [a, b] = [top(x.a), top(x.b)],
2283
+ ia = ids.indexOf(a),
2284
+ ib = ids.indexOf(b);
989
2285
  if (ia < 0 || ib < 0) continue;
990
2286
  const j = across(a, b);
991
2287
  if (!j || (still.has(a) && still.has(b))) continue;
992
2288
  const [mover, left] = beyond(s.motion, j, ia) ? [a, b] : [b, a];
993
- f('warn', `${left} is fastened to ${mover} (a fit that fastens), but only ${mover} moves on ${j.id}: ${left} is placed where it stands, so it stays there in every pose and its mass is left out of what ${j.id} carries (joint.moment). Place ${left} on ${mover} by an anchor or an address ("at": "${mover}.<anchor>")`,
994
- `${left}: left behind by ${j.id}`, { code: 'assembly.fastened', refs: { items: [left, mover], joint: j.id } });
2289
+ f(
2290
+ 'warn',
2291
+ `${left} is fastened to ${mover} (a fit that fastens), but only ${mover} moves on ${j.id}: ${left} is placed where it stands, so it stays there in every pose and its mass is left out of what ${j.id} carries (joint.moment). Place ${left} on ${mover} by an anchor or an address ("at": "${mover}.<anchor>")`,
2292
+ `${left}: left behind by ${j.id}`,
2293
+ { code: 'assembly.fastened', refs: { items: [left, mover], joint: j.id } },
2294
+ );
995
2295
  }
996
2296
  }
997
2297
  // Gears: each mesh's centre distance and contact ratio, said between the two axes (the rest by --sweep)
998
2298
  for (const g of s.motion.meshes || []) {
999
- f('info', g.planetary ? g.text : `${g.with} drives ${g.joint}: ${g.text}`, null, { code: 'mesh.ratio', refs: { joints: [g.with, g.joint] } });
2299
+ f('info', g.planetary ? g.text : `${g.with} drives ${g.joint}: ${g.text}`, null, {
2300
+ code: 'mesh.ratio',
2301
+ refs: { joints: [g.with, g.joint] },
2302
+ });
2303
+ if (g.faces) faceOverlap(g);
1000
2304
  for (const x of g.findings) {
1001
- const between = x.between || g.between, mid = between[0].map((v, k) => (v + between[1][k]) / 2);
1002
- f(x.level, g.planetary ? x.text : `${g.with} and ${g.joint}: ${x.text}`, x.level === 'pass' ? null : `${g.joint}: ${x.code.split('.')[1]}`, { code: x.code, at: mid, between, ...(x.values ? { values: x.values } : {}), refs: { joints: [g.with, g.joint] } });
2305
+ const between = x.between || g.between,
2306
+ mid = between[0].map((v, k) => (v + between[1][k]) / 2);
2307
+ f(
2308
+ x.level,
2309
+ g.planetary ? x.text : `${g.with} and ${g.joint}: ${x.text}`,
2310
+ x.level === 'pass' ? null : `${g.joint}: ${x.code.split('.')[1]}`,
2311
+ {
2312
+ code: x.code,
2313
+ at: mid,
2314
+ between,
2315
+ ...(x.values ? { values: x.values } : {}),
2316
+ refs: { joints: [g.with, g.joint] },
2317
+ },
2318
+ );
1003
2319
  }
1004
2320
  }
1005
2321
  }
1006
2322
  if (s.a.fasten?.length && fastening) fastening.fastenChecks(s, f, { placeItems });
1007
2323
  // A holes fit and a fit that fastens the same two items: one fasten says both, and knows the screw
1008
- if (fastening) for (const g of fastening.fastenFromFits(s)) {
1009
- f('info', `${g.label} and the fit that fastens ${g.pair[0]} to ${g.pair[1]} are one screwed joint: a fasten says both and knows the screw (its holes, length, thread engaged, the seat under its head and the key that turns it). In place of the two, add to "fasten": ${JSON.stringify(g.fasten)}${g.screw ? '' : ' (with the screw it takes: no thread was found in the fits or the holes)'}, or run cad add fasten ${s.project}/${s.name} --from-fits`,
1010
- null, { code: 'fasten.suggest', refs: { fits: [g.holes, g.fastens], items: g.pair, paste: g.fasten } });
1011
- }
2324
+ if (fastening)
2325
+ for (const g of fastening.fastenFromFits(s)) {
2326
+ f(
2327
+ 'info',
2328
+ `${g.label} and the fit that fastens ${g.pair[0]} to ${g.pair[1]} are one screwed joint: a fasten says both and knows the screw (its holes, length, thread engaged, the seat under its head and the key that turns it). In place of the two, add to "fasten": ${JSON.stringify(g.fasten)}${g.screw ? '' : ' (with the screw it takes: no thread was found in the fits or the holes)'}, or run cad add fasten ${s.project}/${s.name} --from-fits`,
2329
+ null,
2330
+ { code: 'fasten.suggest', refs: { fits: [g.holes, g.fastens], items: g.pair, paste: g.fasten } },
2331
+ );
2332
+ }
1012
2333
  boughtFindings(s, f);
1013
2334
  beamFindings(s, f);
1014
2335
  fittingFindings(s, f);
@@ -1016,7 +2337,20 @@ export function checkAssembly(s) {
1016
2337
  serviceFindings(s, f);
1017
2338
  beltLoads(s, { placeItems, jointValues, mul }); // (a belt's carriage pushed at its acceleration: a load on its joint, before the motor's checks read the loads)
1018
2339
  guideFindings(s, f);
1019
- if (s.generated) { const m = s.generated, [what, ...more] = frameText(m); f('info', `generated: ${what}; ${more.map((x) => x.trim()).join('; ')}`, null, { code: 'frame.generated', values: { inside: m.inside, outside: m.outside, lengths: m.lengths.map(({ length, count }) => ({ length, count })) }, refs: { kind: m.kind, profile: m.profile, join: m.join.kind, arrangement: m.arrangement, by: m.by } }); }
2340
+ if (s.generated) {
2341
+ const m = s.generated,
2342
+ [what, ...more] = frameText(m);
2343
+ f('info', `generated: ${what}; ${more.map((x) => x.trim()).join('; ')}`, null, {
2344
+ code: 'frame.generated',
2345
+ values: {
2346
+ inside: m.inside,
2347
+ outside: m.outside,
2348
+ envelope: m.envelope?.size ?? null,
2349
+ lengths: m.lengths.map(({ length, count }) => ({ length, count })),
2350
+ },
2351
+ refs: { kind: m.kind, profile: m.profile, join: m.join.kind, arrangement: m.arrangement, by: m.by },
2352
+ });
2353
+ }
1020
2354
  joinChecks(s, f);
1021
2355
  slotNutChecks(s, f);
1022
2356
  frameSquareChecks(s, f);
@@ -1027,32 +2361,53 @@ export function checkAssembly(s) {
1027
2361
  motorChecks(s, f, { placeItems, jointValues, mul }, materialOf(s.project));
1028
2362
  powerChecks(s, f);
1029
2363
  loadChecks(s, f, { placeItems, jointValues, mul });
1030
- frameChecks(s, f, { placeItems, jointValues, mul });
2364
+ // (join.drop after the frame's checks: a beam's drop is taken from the frame's own solve where it has one)
2365
+ const solved = frameChecks(s, f, { placeItems, jointValues, mul });
2366
+ joinDropChecks(s, f, solved);
2367
+ // (each printed foot judged at the load the frame's solve puts on it, #378)
2368
+ footFindings(s, f, solved);
1031
2369
  sizeChecks(s, f, { placeItems, jointValues, mul });
1032
2370
  gripChecks(s, f);
1033
- gaitChecks(s, f, { jointValues, placeItems, sweepOne: (v) => clashesOf(s.at(v), named) });
2371
+ gaitChecks(s, f, { jointValues, sweepOne: (v) => clashesOf(s.at(v), named) });
1034
2372
  taskChecks(s, f);
1035
2373
  orderChecks(s, f, { frame: frameBuild });
1036
2374
  // Plates print everything: no references
1037
2375
  if (s.a.kind === 'plate') {
1038
2376
  const refs = s.objects.filter((o) => o.role === 'reference' && !o.unplaced); // an unplaced item only lends its numbers
1039
- if (refs.length) f('fail', `a plate can't print references: ${refs.map((o) => o.id).join(', ')}`, null, { code: 'plate.reference', refs: { items: refs.map((o) => o.id) } });
2377
+ if (refs.length)
2378
+ f('fail', `a plate can't print references: ${refs.map((o) => o.id).join(', ')}`, null, {
2379
+ code: 'plate.reference',
2380
+ refs: { items: refs.map((o) => o.id) },
2381
+ });
1040
2382
  }
1041
- // Rules that are only estimates, anywhere in the assembly or its components
1042
- const est = new Set();
1043
- for (const o of s.objects) for (const e of o.built.entries) if (e.kind === 'estimate' && (e.used || !e.name.includes('.'))) est.add(e.name);
1044
- for (const n of s.seen) { const [u, k] = n.split('.'); if (loadRuleSet(u).rules[k]?.kind === 'estimate') est.add(n); }
1045
- if (est.size) f('warn', `uses estimates, not measurements: ${[...est].join(', ')}. Measure each and settle it with cad measured ${s.project}/${s.name} <name>=<value>`, `Estimate: ${[...est].join(', ')}`, { code: 'rules.estimate', refs: { rules: [...est] } });
2383
+ // Rules that are only estimates, anywhere in the assembly or its components, and seats drawn to an estimated fit
2384
+ // (said the same way by an object's own check: estimates.mjs estimatesFinding)
2385
+ const est = estimatesFinding(
2386
+ s.objects.map((o) => o.built),
2387
+ {
2388
+ ref: `${s.project}/${s.name}`,
2389
+ seen: s.seen,
2390
+ kindOf: (n) => {
2391
+ const [u, k] = n.split('.');
2392
+ return loadRuleSet(u).rules[k]?.kind;
2393
+ },
2394
+ assembly: true,
2395
+ },
2396
+ );
2397
+ if (est) f(est.level, est.text, est.short, { code: est.code, refs: est.refs });
1046
2398
  saveOverlaps();
1047
2399
  return out;
1048
2400
  }
1049
2401
 
1050
2402
  // Each loop at the assembly's pose: how far apart its two anchors are (mm), and their axes (degrees, either way round)
1051
2403
  export function loopGaps(s) {
1052
- const worlds = placeItems(s.motion, s.jointValues), I = [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0];
2404
+ const worlds = placeItems(s.motion, s.jointValues),
2405
+ I = [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0];
1053
2406
  return s.motion.loops.map((l) => {
1054
- const A = mul(l.a.item < 0 ? I : worlds[l.a.item], l.a.frame), B = mul(l.b.item < 0 ? I : worlds[l.b.item], l.b.frame);
1055
- const gap = Math.hypot(A[3] - B[3], A[7] - B[7], A[11] - B[11]), dot = Math.abs(A[2] * B[2] + A[6] * B[6] + A[10] * B[10]);
2407
+ const A = mul(l.a.item < 0 ? I : worlds[l.a.item], l.a.frame),
2408
+ B = mul(l.b.item < 0 ? I : worlds[l.b.item], l.b.frame);
2409
+ const gap = Math.hypot(A[3] - B[3], A[7] - B[7], A[11] - B[11]),
2410
+ dot = Math.abs(A[2] * B[2] + A[6] * B[6] + A[10] * B[10]);
1056
2411
  const angle = Math.acos(Math.min(1, dot)) / (Math.PI / 180);
1057
2412
  return { label: l.label, gap, angle, ok: gap <= l.tolerance && angle <= 0.05 };
1058
2413
  });
@@ -1060,14 +2415,29 @@ export function loopGaps(s) {
1060
2415
 
1061
2416
  // Pairs of parts that overlap, as checkAssembly finds them (fits with a negative min allowed): [[a, b, mm³]]
1062
2417
  function clashesOf(s, named) {
1063
- const allowed = (a, b) => threaded(a, b) || s.fits.some((x) => x.min != null && x.num(x.min) < 0 && ((named(a, x.a) && named(b, x.b)) || (named(a, x.b) && named(b, x.a))));
1064
- const boxes = s.parts.map((p) => bounds(p.triangles)), out = [];
1065
- for (let i = 0; i < s.parts.length; i++) for (let j = i + 1; j < s.parts.length; j++) {
1066
- const pa = s.parts[i], pb = s.parts[j], A = boxes[i], B = boxes[j];
1067
- if (pa.leaf === pb.leaf || ![0, 1, 2].every((k) => A.lo[k] <= B.hi[k] + 1e-6 && B.lo[k] <= A.hi[k] + 1e-6) || allowed(pa, pb)) continue;
1068
- const v = pairOverlap(pa, pb);
1069
- if (v > 0.01) out.push([pa.name, pb.name, v]);
1070
- }
2418
+ const allowed = (a, b) =>
2419
+ threaded(a, b) ||
2420
+ s.fits.some(
2421
+ (x) =>
2422
+ x.min != null && x.num(x.min) < 0 && ((named(a, x.a) && named(b, x.b)) || (named(a, x.b) && named(b, x.a))),
2423
+ );
2424
+ const boxes = s.parts.map((p) => bounds(p.triangles)),
2425
+ out = [];
2426
+ for (let i = 0; i < s.parts.length; i++)
2427
+ for (let j = i + 1; j < s.parts.length; j++) {
2428
+ const pa = s.parts[i],
2429
+ pb = s.parts[j],
2430
+ A = boxes[i],
2431
+ B = boxes[j];
2432
+ if (
2433
+ pa.leaf === pb.leaf ||
2434
+ ![0, 1, 2].every((k) => A.lo[k] <= B.hi[k] + 1e-6 && B.lo[k] <= A.hi[k] + 1e-6) ||
2435
+ allowed(pa, pb)
2436
+ )
2437
+ continue;
2438
+ const v = pairOverlap(pa, pb);
2439
+ if (v > 0.01) out.push([pa.name, pb.name, v]);
2440
+ }
1071
2441
  return out;
1072
2442
  }
1073
2443
  const isNamed = (p, n) => p.name === n || p.leaf === n || p.item === n || p.name.startsWith(`${n}.`);
@@ -1075,32 +2445,76 @@ const isNamed = (p, n) => p.name === n || p.leaf === n || p.item === n || p.name
1075
2445
  // sweep(s, { joint, steps }) -> findings: each free joint (or the one named) moved through its range, the others held
1076
2446
  // at the assembly's pose, looking for parts that collide and loops that come apart on the way
1077
2447
  export function sweep(s, { joint, steps = 24, progress } = {}) {
1078
- const out = [], f = (level, text, card, extra) => out.push({ level, text, ...(card && { card }), ...extra }), mm = (n) => `${Number(n.toFixed(2))}`;
2448
+ const out = [],
2449
+ f = (level, text, card, extra) => out.push({ level, text, ...(card && { card }), ...extra }),
2450
+ mm = (n) => `${Number(n.toFixed(2))}`;
1079
2451
  const free = s.motion.joints.filter((j) => !j.follow && j.dofs.length && (!joint || j.id === joint));
1080
- if (joint && !free.length) throw new Error(`no joint "${joint}" to sweep (${s.motion.joints.filter((j) => !j.follow && j.dofs.length).map((j) => j.id).join(', ') || 'none'})`);
2452
+ if (joint && !free.length)
2453
+ throw new Error(
2454
+ `no joint "${joint}" to sweep (${
2455
+ s.motion.joints
2456
+ .filter((j) => !j.follow && j.dofs.length)
2457
+ .map((j) => j.id)
2458
+ .join(', ') || 'none'
2459
+ })`,
2460
+ );
1081
2461
  const base = s.jointValues;
1082
- for (const j of free) j.dofs.forEach(([lo, hi], d) => {
1083
- const unit = DOFS[j.type][d] === 'angle' ? '°' : ' mm', name = `${j.id}${j.dofs.length > 1 ? ` ${'xyz'[d] && j.type === 'ball' ? 'xyz'[d] : DOFS[j.type][d]}` : ''}`;
1084
- const bad = []; // [value, what]
1085
- // a door with its latch shut: also tried just off shut, finer than a step, so a hit within the first degree is seen
1086
- const held = (s.panels ?? []).find((p) => p.latch && p.joint === j.id && DOFS[j.type][d] === 'angle'), probe = held ? Math.min(PANEL_CHECK.latch_probe.value, (hi - lo) / steps) : 0;
1087
- const values = [...Array(steps + 1).keys()].map((i) => lo + ((hi - lo) * i) / steps);
1088
- if (probe > 0 && probe < (hi - lo) / steps) values.splice(1, 0, lo + probe);
1089
- for (const [i, v] of values.entries()) {
1090
- const set = { ...base, [j.id]: base[j.id].map((x, k) => (k === d ? v : x)) };
1091
- const t = s.at(Object.fromEntries(Object.entries(set).filter(([id]) => !s.motion.joints.find((x) => x.id === id).follow)));
1092
- const what = [...clashesOf(t, isNamed).map(([a, b]) => `${a} hits ${b}`), ...loopGaps(t).filter((l) => !l.ok).map((l) => `${l.label} apart by ${mm(l.gap)} mm`)];
1093
- if (what.length) bad.push([v, what]);
1094
- progress?.({ stage: 'sweep', joint: j.id, step: Math.min(i, steps), steps });
1095
- }
1096
- const ranges = []; // runs of steps in a row that collide
1097
- for (const [v, what] of bad) { const r = ranges[ranges.length - 1]; if (r && Math.abs(v - r.to - (hi - lo) / steps) < 1e-9) { r.to = v; r.what = [...new Set([...r.what, ...what])]; } else ranges.push({ from: v, to: v, what }); }
1098
- const span = `${mm(lo)} to ${mm(hi)}${unit}`, note = held ? ` (${held.latch} shut over ${held.id}: also tried ${mm(probe)}${unit} off shut)` : '';
1099
- if (!ranges.length) f('pass', `sweep ${name}, ${span} in ${steps} steps${note}: nothing collides`, `${name}: clear ${span}`, { code: 'sweep', values: { from: lo, to: hi, steps, ...(held ? { probe } : {}) }, refs: { joint: name, collisions: [], ...(held ? { latch: held.latch } : {}) } });
1100
- else f('fail', `sweep ${name}, ${span} in ${steps} steps${note}: ${ranges.map((r) => `${r.from === r.to ? `at ${mm(r.from)}` : `${mm(r.from)} to ${mm(r.to)}`}${unit.trim()}: ${r.what.slice(0, 3).join('; ')}${r.what.length > 3 ? `; and ${r.what.length - 3} more` : ''}`).join(' | ')}`,
1101
- `${name}: collides ${ranges.map((r) => (r.from === r.to ? mm(r.from) : `${mm(r.from)}-${mm(r.to)}`)).join(', ')}${unit.trim()}`,
1102
- { code: 'sweep', values: { from: lo, to: hi, steps, ...(held ? { probe } : {}) }, refs: { joint: name, ...(held ? { latch: held.latch } : {}), collisions: ranges.map((r) => ({ from: r.from, to: r.to, what: r.what })) } });
1103
- });
2462
+ for (const j of free)
2463
+ j.dofs.forEach(([lo, hi], d) => {
2464
+ const unit = DOFS[j.type][d] === 'angle' ? '°' : ' mm',
2465
+ name = `${j.id}${j.dofs.length > 1 ? ` ${'xyz'[d] && j.type === 'ball' ? 'xyz'[d] : DOFS[j.type][d]}` : ''}`;
2466
+ const bad = []; // [value, what]
2467
+ // a door with its latch shut: also tried just off shut, finer than a step, so a hit within the first degree is seen
2468
+ const held = (s.panels ?? []).find((p) => p.latch && p.joint === j.id && DOFS[j.type][d] === 'angle'),
2469
+ probe = held ? Math.min(PANEL_CHECK.latch_probe.value, (hi - lo) / steps) : 0;
2470
+ const values = [...Array(steps + 1).keys()].map((i) => lo + ((hi - lo) * i) / steps);
2471
+ if (probe > 0 && probe < (hi - lo) / steps) values.splice(1, 0, lo + probe);
2472
+ for (const [i, v] of values.entries()) {
2473
+ const set = { ...base, [j.id]: base[j.id].map((x, k) => (k === d ? v : x)) };
2474
+ const t = s.at(
2475
+ Object.fromEntries(Object.entries(set).filter(([id]) => !s.motion.joints.find((x) => x.id === id).follow)),
2476
+ );
2477
+ const what = [
2478
+ ...clashesOf(t, isNamed).map(([a, b]) => `${a} hits ${b}`),
2479
+ ...loopGaps(t)
2480
+ .filter((l) => !l.ok)
2481
+ .map((l) => `${l.label} apart by ${mm(l.gap)} mm`),
2482
+ ];
2483
+ if (what.length) bad.push([v, what]);
2484
+ progress?.({ stage: 'sweep', joint: j.id, step: Math.min(i, steps), steps });
2485
+ }
2486
+ const ranges = []; // runs of steps in a row that collide
2487
+ for (const [v, what] of bad) {
2488
+ const r = ranges[ranges.length - 1];
2489
+ if (r && Math.abs(v - r.to - (hi - lo) / steps) < 1e-9) {
2490
+ r.to = v;
2491
+ r.what = [...new Set([...r.what, ...what])];
2492
+ } else ranges.push({ from: v, to: v, what });
2493
+ }
2494
+ const span = `${mm(lo)} to ${mm(hi)}${unit}`,
2495
+ note = held ? ` (${held.latch} shut over ${held.id}: also tried ${mm(probe)}${unit} off shut)` : '';
2496
+ if (!ranges.length)
2497
+ f('pass', `sweep ${name}, ${span} in ${steps} steps${note}: nothing collides`, `${name}: clear ${span}`, {
2498
+ code: 'sweep',
2499
+ values: { from: lo, to: hi, steps, ...(held ? { probe } : {}) },
2500
+ refs: { joint: name, collisions: [], ...(held ? { latch: held.latch } : {}) },
2501
+ });
2502
+ else
2503
+ f(
2504
+ 'fail',
2505
+ `sweep ${name}, ${span} in ${steps} steps${note}: ${ranges.map((r) => `${r.from === r.to ? `at ${mm(r.from)}` : `${mm(r.from)} to ${mm(r.to)}`}${unit.trim()}: ${r.what.slice(0, 3).join('; ')}${r.what.length > 3 ? `; and ${r.what.length - 3} more` : ''}`).join(' | ')}`,
2506
+ `${name}: collides ${ranges.map((r) => (r.from === r.to ? mm(r.from) : `${mm(r.from)}-${mm(r.to)}`)).join(', ')}${unit.trim()}`,
2507
+ {
2508
+ code: 'sweep',
2509
+ values: { from: lo, to: hi, steps, ...(held ? { probe } : {}) },
2510
+ refs: {
2511
+ joint: name,
2512
+ ...(held ? { latch: held.latch } : {}),
2513
+ collisions: ranges.map((r) => ({ from: r.from, to: r.to, what: r.what })),
2514
+ },
2515
+ },
2516
+ );
2517
+ });
1104
2518
  saveOverlaps();
1105
2519
  return out;
1106
2520
  }
@@ -1108,11 +2522,20 @@ export function sweep(s, { joint, steps = 24, progress } = {}) {
1108
2522
  // shapes(parts) -> { shapes: [{ part, polygons, triangles }], place: [[shape index, 12 numbers], …] }
1109
2523
  // Each distinct shape once, then where each copy goes: a 3 × 4 transform by rows (x' = a·x + b·y + c·z + d, …).
1110
2524
  export function shapes(parts) {
1111
- const index = new Map(), list = [], place = [];
2525
+ const index = new Map(),
2526
+ list = [],
2527
+ place = [];
1112
2528
  for (const p of parts) {
1113
- if (!index.has(p.shape)) { index.set(p.shape, list.length); list.push({ part: p, polygons: p.local, triangles: p.localTriangles }); }
1114
- const m = p.m, r = (x) => Number(x.toFixed(6)); // JSCAD's mat4 is column-major
1115
- place.push([index.get(p.shape), ...[m[0], m[4], m[8], m[12], m[1], m[5], m[9], m[13], m[2], m[6], m[10], m[14]].map(r)]);
2529
+ if (!index.has(p.shape)) {
2530
+ index.set(p.shape, list.length);
2531
+ list.push({ part: p, polygons: p.local, triangles: p.localTriangles });
2532
+ }
2533
+ const m = p.m,
2534
+ r = (x) => Number(x.toFixed(6)); // JSCAD's mat4 is column-major
2535
+ place.push([
2536
+ index.get(p.shape),
2537
+ ...[m[0], m[4], m[8], m[12], m[1], m[5], m[9], m[13], m[2], m[6], m[10], m[14]].map(r),
2538
+ ]);
1116
2539
  }
1117
2540
  return { shapes: list, place };
1118
2541
  }
@@ -1121,21 +2544,46 @@ export function shapes(parts) {
1121
2544
  export function motionData(s) {
1122
2545
  const mo = s.motion;
1123
2546
  if (!mo.joints.length) return {};
1124
- const r = (x) => Number(x.toFixed(6)), names = mo.items.map((x) => x[0]);
1125
- const named = (p, n) => p.name === n || p.leaf === n || p.item === n || p.name.startsWith(`${n}.`), allow = [];
2547
+ const r = (x) => Number(x.toFixed(6)),
2548
+ names = mo.items.map((x) => x[0]);
2549
+ const named = (p, n) => p.name === n || p.leaf === n || p.item === n || p.name.startsWith(`${n}.`),
2550
+ allow = [];
1126
2551
  const loose = s.fits.filter((x) => x.min != null && x.num(x.min) < 0);
1127
- s.parts.forEach((pa, i) => s.parts.forEach((pb, j) => {
1128
- if (j > i && pa.item !== pb.item && (threaded(pa, pb) || loose.some((x) => (named(pa, x.a) && named(pb, x.b)) || (named(pa, x.b) && named(pb, x.a))))) allow.push([i, j]);
1129
- }));
1130
- return { motion: {
1131
- items: mo.items.map(([n, ...m]) => [n, ...m.map(r)]),
1132
- joints: mo.joints.map(({ id, type, parent, child, a, b, dofs, label, follow, path, cone, step }) => ({ id, type, parent, child, a: a.map(r), b: b.map(r), dofs: dofs.map((d) => d.map(r)),
1133
- ...(label ? { label } : {}), ...(follow ? { follow } : {}), ...(path ? { path: path.map((p) => p.map(r)) } : {}), ...(cone != null ? { cone } : {}), ...(step ? { step } : {}) })),
1134
- poses: mo.poses, ...(s.pose ? { pose: s.pose } : {}),
1135
- part: s.parts.map((p) => names.indexOf(p.moves ?? p.item)), // (a screw moves with the item it sits in)
1136
- ...(allow.length ? { allow } : {}),
1137
- ...(s.gait ? { sequence: gaitSequence(s) ?? undefined } : {}),
1138
- } };
2552
+ s.parts.forEach((pa, i) =>
2553
+ s.parts.forEach((pb, j) => {
2554
+ if (
2555
+ j > i &&
2556
+ pa.item !== pb.item &&
2557
+ (threaded(pa, pb) ||
2558
+ loose.some((x) => (named(pa, x.a) && named(pb, x.b)) || (named(pa, x.b) && named(pb, x.a))))
2559
+ )
2560
+ allow.push([i, j]);
2561
+ }),
2562
+ );
2563
+ return {
2564
+ motion: {
2565
+ items: mo.items.map(([n, ...m]) => [n, ...m.map(r)]),
2566
+ joints: mo.joints.map(({ id, type, parent, child, a, b, dofs, label, follow, path, cone, step }) => ({
2567
+ id,
2568
+ type,
2569
+ parent,
2570
+ child,
2571
+ a: a.map(r),
2572
+ b: b.map(r),
2573
+ dofs: dofs.map((d) => d.map(r)),
2574
+ ...(label ? { label } : {}),
2575
+ ...(follow ? { follow } : {}),
2576
+ ...(path ? { path: path.map((p) => p.map(r)) } : {}),
2577
+ ...(cone != null ? { cone } : {}),
2578
+ ...(step ? { step } : {}),
2579
+ })),
2580
+ poses: mo.poses,
2581
+ ...(s.pose ? { pose: s.pose } : {}),
2582
+ part: s.parts.map((p) => names.indexOf(p.moves ?? p.item)), // (a screw moves with the item it sits in)
2583
+ ...(allow.length ? { allow } : {}),
2584
+ ...(s.gait ? { sequence: gaitSequence(s) ?? undefined } : {}),
2585
+ },
2586
+ };
1139
2587
  }
1140
2588
 
1141
2589
  // ---------- links ----------