@rulecad/cad 0.8.0 → 0.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (83) hide show
  1. package/AGENTS.md +24 -10
  2. package/CHANGELOG.md +404 -0
  3. package/EXAMPLES.md +40 -38
  4. package/README.md +193 -67
  5. package/TUTORIAL.md +2 -2
  6. package/bin/cad.mjs +2250 -512
  7. package/lib/animate.mjs +173 -49
  8. package/lib/assembly.mjs +1847 -434
  9. package/lib/beams.mjs +256 -52
  10. package/lib/belts.mjs +66 -15
  11. package/lib/board-work.mjs +12 -0
  12. package/lib/bought.mjs +309 -53
  13. package/lib/buildpage.mjs +179 -29
  14. package/lib/carried.mjs +201 -0
  15. package/lib/clone.mjs +194 -42
  16. package/lib/design.mjs +649 -121
  17. package/lib/drive.mjs +187 -63
  18. package/lib/edit.mjs +899 -191
  19. package/lib/errors.mjs +16 -3
  20. package/lib/explain.mjs +62 -13
  21. package/lib/fasten.mjs +2702 -507
  22. package/lib/fittings.mjs +715 -121
  23. package/lib/fixings.mjs +21 -9
  24. package/lib/framebuild.mjs +790 -175
  25. package/lib/framecheck.mjs +1901 -368
  26. package/lib/framegen.mjs +100 -22
  27. package/lib/frameheat.mjs +225 -42
  28. package/lib/frameprint.mjs +513 -108
  29. package/lib/frames.mjs +81 -17
  30. package/lib/framesize.mjs +792 -120
  31. package/lib/frametip.mjs +235 -0
  32. package/lib/gait.mjs +135 -23
  33. package/lib/grip.mjs +62 -13
  34. package/lib/guides.mjs +1403 -230
  35. package/lib/host.mjs +123 -21
  36. package/lib/inplace.mjs +171 -36
  37. package/lib/jigs.mjs +360 -78
  38. package/lib/joins.mjs +697 -118
  39. package/lib/jsonedit.mjs +88 -26
  40. package/lib/kept.mjs +84 -0
  41. package/lib/kit.mjs +438 -68
  42. package/lib/layout.mjs +2 -1
  43. package/lib/links.mjs +149 -42
  44. package/lib/list.mjs +326 -64
  45. package/lib/live-guard.mjs +68 -0
  46. package/lib/live-shape.mjs +96 -24
  47. package/lib/live.mjs +189 -59
  48. package/lib/loads.mjs +579 -130
  49. package/lib/machine.mjs +372 -74
  50. package/lib/magnets.mjs +162 -44
  51. package/lib/measured.mjs +417 -94
  52. package/lib/mesh.mjs +526 -119
  53. package/lib/meshcmd.mjs +215 -60
  54. package/lib/motors.mjs +1021 -213
  55. package/lib/motorsvg.mjs +114 -32
  56. package/lib/names.mjs +3 -1
  57. package/lib/optimise.mjs +978 -283
  58. package/lib/order.mjs +519 -112
  59. package/lib/panels.mjs +482 -94
  60. package/lib/parts.mjs +78 -23
  61. package/lib/pins.mjs +163 -44
  62. package/lib/plates.mjs +223 -35
  63. package/lib/player.mjs +37 -9
  64. package/lib/power.mjs +64 -13
  65. package/lib/preview.mjs +83 -16
  66. package/lib/profilemeasure.mjs +572 -129
  67. package/lib/rules.mjs +15 -5
  68. package/lib/sandbox-hooks.mjs +77 -19
  69. package/lib/sandbox-run.mjs +117 -18
  70. package/lib/sandbox.mjs +509 -60
  71. package/lib/schema.mjs +42 -11
  72. package/lib/seats.mjs +227 -49
  73. package/lib/services.mjs +261 -52
  74. package/lib/sheet.mjs +851 -178
  75. package/lib/slotnuts.mjs +213 -34
  76. package/lib/targets/gist.mjs +4 -1
  77. package/lib/targets.mjs +22 -4
  78. package/lib/task.mjs +376 -79
  79. package/lib/versions.mjs +111 -28
  80. package/lib/wires.mjs +228 -45
  81. package/lib/workspace.mjs +197 -12
  82. package/package.json +19 -19
  83. package/schemas/assembly.schema.json +2 -2
package/lib/machine.mjs CHANGED
@@ -2,27 +2,78 @@
2
2
  // the task. cad plot plans a drawing on it, checks it against the task, and shows the result before anything moves.
3
3
  import fs from 'node:fs';
4
4
  import path from 'node:path';
5
- import { svgToStrokes, orderStrokes, planToolpath, stepBlocks, estimate, sheetFrame, fk, gaitBlocks } from '@rulecad/robots';
5
+ import {
6
+ svgToStrokes,
7
+ orderStrokes,
8
+ planToolpath,
9
+ stepBlocks,
10
+ estimate,
11
+ sheetFrame,
12
+ fk,
13
+ gaitBlocks,
14
+ } from '@rulecad/robots';
6
15
  import { gaitSequence } from './gait.mjs';
7
16
  import { trainFrom, workingSpeed } from './motors.mjs';
8
17
  import { chainOf, accuracyOf, sample, jacobianError } from './task.mjs';
9
18
  import { paths } from './workspace.mjs';
10
19
 
11
- const num = Number.isFinite, r6 = (x) => +Number(x).toFixed(6), n3 = (x, d = 2) => String(Number(x.toFixed(d)));
20
+ const num = Number.isFinite,
21
+ r6 = (x) => +Number(x).toFixed(6),
22
+ n3 = (x, d = 2) => String(Number(x.toFixed(d)));
12
23
 
13
24
  // One driven joint as an axis: its motor, the steps it takes a degree (or mm) through its train, and the fastest it steps
14
25
  function axisOf(s, id) {
15
- const motion = s.motion, t = trainFrom(motion, id), d = motion.drives.find((x) => x.joint === t.root), j = motion.joints.find((x) => x.id === id), spec = new Map((s.a.joints || []).map((x) => [x.id, x])).get(id) ?? {};
16
- if (!d?.model.stepAngle) throw new Error(`${s.project}/${s.name}: joint ${id} has no stepper driving it, and a step file needs one`);
17
- const micro = d.spec.microsteps ?? 16, per = (360 / d.model.stepAngle) * micro, stepsPerUnit = j.type === 'prismatic' ? (per * t.ratio) / t.slide / 360 : (per * t.ratio) / 360;
18
- const rpm = workingSpeed(d.model, d.spec, d.supply), maxRate = (rpm / 60) * per, home = spec.home;
19
- const homing = home ? { endstop: home.endstop, direction: home.direction ?? -1, rate: Math.round(maxRate / 8), back: Math.round(stepsPerUnit * 3) } : null;
20
- return { name: id, joint: id, motor: d.id, model: d.model.name, driver: d.spec.driver ?? null, stepAngle: d.model.stepAngle, microsteps: micro, ratio: r6(t.ratio), stepsPerUnit: r6(stepsPerUnit), unit: j.type === 'prismatic' ? 'mm' : 'deg', limits: (j.limits ?? j.dofs[0].slice(0, 2)).map(r6), maxRate: Math.round(maxRate), homing,
21
- _why: { stepAngle: `${d.model.name}.step_angle`, microsteps: d.spec.microsteps != null ? `the motor item's "microsteps" (resolution only, not accuracy)` : 'the default, 1/16 (resolution only, not accuracy)', ratio: t.stages.length ? `the train from ${t.root} to ${id}` : 'direct', maxRate: `${n3(rpm, 1)} rpm, ${d.spec.speed != null ? 'the motor item\'s speed' : `the working speed of a ${d.model.name}`}` } };
26
+ const motion = s.motion,
27
+ t = trainFrom(motion, id),
28
+ d = motion.drives.find((x) => x.joint === t.root),
29
+ j = motion.joints.find((x) => x.id === id),
30
+ spec = new Map((s.a.joints || []).map((x) => [x.id, x])).get(id) ?? {};
31
+ if (!d?.model.stepAngle)
32
+ throw new Error(`${s.project}/${s.name}: joint ${id} has no stepper driving it, and a step file needs one`);
33
+ const micro = d.spec.microsteps ?? 16,
34
+ per = (360 / d.model.stepAngle) * micro,
35
+ stepsPerUnit = j.type === 'prismatic' ? (per * t.ratio) / t.slide / 360 : (per * t.ratio) / 360;
36
+ const rpm = workingSpeed(d.model, d.spec, d.supply),
37
+ maxRate = (rpm / 60) * per,
38
+ home = spec.home;
39
+ const homing = home
40
+ ? {
41
+ endstop: home.endstop,
42
+ direction: home.direction ?? -1,
43
+ rate: Math.round(maxRate / 8),
44
+ back: Math.round(stepsPerUnit * 3),
45
+ }
46
+ : null;
47
+ return {
48
+ name: id,
49
+ joint: id,
50
+ motor: d.id,
51
+ model: d.model.name,
52
+ driver: d.spec.driver ?? null,
53
+ stepAngle: d.model.stepAngle,
54
+ microsteps: micro,
55
+ ratio: r6(t.ratio),
56
+ stepsPerUnit: r6(stepsPerUnit),
57
+ unit: j.type === 'prismatic' ? 'mm' : 'deg',
58
+ limits: (j.limits ?? j.dofs[0].slice(0, 2)).map(r6),
59
+ maxRate: Math.round(maxRate),
60
+ homing,
61
+ _why: {
62
+ stepAngle: `${d.model.name}.step_angle`,
63
+ microsteps:
64
+ d.spec.microsteps != null
65
+ ? `the motor item's "microsteps" (resolution only, not accuracy)`
66
+ : 'the default, 1/16 (resolution only, not accuracy)',
67
+ ratio: t.stages.length ? `the train from ${t.root} to ${id}` : 'direct',
68
+ maxRate: `${n3(rpm, 1)} rpm, ${d.spec.speed != null ? "the motor item's speed" : `the working speed of a ${d.model.name}`}`,
69
+ },
70
+ };
22
71
  }
23
72
 
24
73
  /** The slots of a CNC shield each motor is wired to, by motor item: from a wire "<motor>.<anchor>" to "<item>.X" (X, Y, Z or A). */
25
- export function shieldSlots(a) { return slotsOf(a, CONTROLLERS['cnc-shield-v3']); }
74
+ export function shieldSlots(a) {
75
+ return slotsOf(a, CONTROLLERS['cnc-shield-v3']);
76
+ }
26
77
  /** The step and direction slots of the streamer (arm.ino on a CNC Shield V3), in its axis order: axis 0 on X, 1 on Y, 2 on Z. */
27
78
  export const STREAMER_SLOTS = ['X', 'Y', 'Z'];
28
79
 
@@ -30,8 +81,22 @@ export const STREAMER_SLOTS = ['X', 'Y', 'Z'];
30
81
  * scripts/firmware.mjs name it), its step and direction slots in its axis order, the anchor a wire ends on for each, and
31
82
  * how a finding names them. The Mega's slots S0 to S7 are its pins for axes 0 to 7 (arduino-mega-2560's rules). */
32
83
  export const CONTROLLERS = {
33
- 'cnc-shield-v3': { board: 'uno', title: 'an Uno under a CNC Shield V3', of: "the shield's", any: "a shield's slot", slots: STREAMER_SLOTS, wired: /^[^.]+\.([XYZA])$/ },
34
- 'arduino-mega-2560': { board: 'mega', title: 'a Mega 2560', of: "the Mega's", any: "a slot of the Mega", slots: ['S0', 'S1', 'S2', 'S3', 'S4', 'S5', 'S6', 'S7'], wired: /^[^.]+\.(S[0-7])$/ },
84
+ 'cnc-shield-v3': {
85
+ board: 'uno',
86
+ title: 'an Uno under a CNC Shield V3',
87
+ of: "the shield's",
88
+ any: "a shield's slot",
89
+ slots: STREAMER_SLOTS,
90
+ wired: /^[^.]+\.([XYZA])$/,
91
+ },
92
+ 'arduino-mega-2560': {
93
+ board: 'mega',
94
+ title: 'a Mega 2560',
95
+ of: "the Mega's",
96
+ any: 'a slot of the Mega',
97
+ slots: ['S0', 'S1', 'S2', 'S3', 'S4', 'S5', 'S6', 'S7'],
98
+ wired: /^[^.]+\.(S[0-7])$/,
99
+ },
35
100
  };
36
101
 
37
102
  /** The machine's controller: the bought board in its assembly that the streamer runs on, or the Uno under a CNC shield where
@@ -39,7 +104,10 @@ export const CONTROLLERS = {
39
104
  * @param {object} a the assembly's JSON @returns {{ set: string, item: string | null, board: string, title: string, of: string, any: string, slots: string[], wired: RegExp }} */
40
105
  export function controllerOf(a) {
41
106
  const found = (a.items || []).filter((it) => typeof it.bought === 'string' && CONTROLLERS[it.bought]);
42
- if (new Set(found.map((it) => it.bought)).size > 1) throw new Error(`items ${found.map((it) => `${it.id} (${it.bought})`).join(', ')}: a machine streams through one controller, ${Object.keys(CONTROLLERS).join(' or ')}`);
107
+ if (new Set(found.map((it) => it.bought)).size > 1)
108
+ throw new Error(
109
+ `items ${found.map((it) => `${it.id} (${it.bought})`).join(', ')}: a machine streams through one controller, ${Object.keys(CONTROLLERS).join(' or ')}`,
110
+ );
43
111
  const set = found[0]?.bought ?? 'cnc-shield-v3';
44
112
  return { set, item: found[0]?.id ?? null, ...CONTROLLERS[set] };
45
113
  }
@@ -49,12 +117,25 @@ export function controllerOf(a) {
49
117
  * ends on (an external driver's breakout: the motor's wire to it, its STEP and DIR on to the controller).
50
118
  * @param {object} a the assembly's JSON @param {{ wired: RegExp }} c a controller (CONTROLLERS) */
51
119
  export function slotsOf(a, c) {
52
- const out = {}, motors = new Set((a.items || []).filter((it) => it.motor).map((it) => it.id)), top = (x) => String(x).split('.')[0];
53
- const driverOf = Object.fromEntries((a.items || []).filter((it) => it.motor?.driver).map((it) => [it.motor.driver, it.id]));
54
- for (const w of a.wires || []) for (const [m, o] of [[top(w.from), top(w.to)], [top(w.to), top(w.from)]]) if (motors.has(m) && !motors.has(o) && !(o in driverOf)) driverOf[o] = m;
120
+ const out = {},
121
+ motors = new Set((a.items || []).filter((it) => it.motor).map((it) => it.id)),
122
+ top = (x) => String(x).split('.')[0];
123
+ const driverOf = Object.fromEntries(
124
+ (a.items || []).filter((it) => it.motor?.driver).map((it) => [it.motor.driver, it.id]),
125
+ );
126
+ for (const w of a.wires || [])
127
+ for (const [m, o] of [
128
+ [top(w.from), top(w.to)],
129
+ [top(w.to), top(w.from)],
130
+ ])
131
+ if (motors.has(m) && !motors.has(o) && !(o in driverOf)) driverOf[o] = m;
55
132
  for (const w of a.wires || []) {
56
- for (const [from, to] of [[String(w.from), String(w.to)], [String(w.to), String(w.from)]]) {
57
- const m = c.wired.exec(to), id = from.split('.')[0];
133
+ for (const [from, to] of [
134
+ [String(w.from), String(w.to)],
135
+ [String(w.to), String(w.from)],
136
+ ]) {
137
+ const m = c.wired.exec(to),
138
+ id = from.split('.')[0];
58
139
  if (m && from.includes('.')) out[driverOf[id] ?? id] = m[1];
59
140
  }
60
141
  }
@@ -66,23 +147,70 @@ export function slotsOf(a, c) {
66
147
  export function machineOf(s) {
67
148
  if (!s.task && s.gait) return gaitMachineOf(s);
68
149
  if (!s.task) throw new Error(`${s.project}/${s.name} has no "task" and no "gait": a machine says what it is for`);
69
- const c = chainOf(s), motion = s.motion;
150
+ const c = chainOf(s),
151
+ motion = s.motion;
70
152
  const axes = c.names.map((id) => axisOf(s, id));
71
- const kinematics = c.names.length === 2 && motion.joints.filter((j) => c.names.includes(j.id)).every((j) => j.type === 'revolute') ? 'scara' : motion.joints.filter((j) => c.names.includes(j.id)).every((j) => j.type === 'prismatic') ? 'cartesian' : 'serial';
153
+ const kinematics =
154
+ c.names.length === 2 && motion.joints.filter((j) => c.names.includes(j.id)).every((j) => j.type === 'revolute')
155
+ ? 'scara'
156
+ : motion.joints.filter((j) => c.names.includes(j.id)).every((j) => j.type === 'prismatic')
157
+ ? 'cartesian'
158
+ : 'serial';
72
159
  const pen = s.a.task.pen ?? null;
73
- return { format: 'rulecad.machine/1', name: `${s.project}/${s.name}`, kinematics, tool: s.task.tool, elbow: sample(s).elbow, axes, controller: controllerSummary(controllerOf(s.a)), task: { sheet: s.a.task.sheet ?? null, region: s.a.task.region ?? null, volume: s.a.task.volume ?? null, speed: s.task.speed, accuracy: s.task.accuracy, accel: s.task.accel ?? 500, ...(s.task.blockTime ? { blockTime: s.task.blockTime } : {}) }, ...(pen ? { pen } : {}) };
160
+ return {
161
+ format: 'rulecad.machine/1',
162
+ name: `${s.project}/${s.name}`,
163
+ kinematics,
164
+ tool: s.task.tool,
165
+ elbow: sample(s).elbow,
166
+ axes,
167
+ controller: controllerSummary(controllerOf(s.a)),
168
+ task: {
169
+ sheet: s.a.task.sheet ?? null,
170
+ region: s.a.task.region ?? null,
171
+ volume: s.a.task.volume ?? null,
172
+ speed: s.task.speed,
173
+ accuracy: s.task.accuracy,
174
+ accel: s.task.accel ?? 500,
175
+ ...(s.task.blockTime ? { blockTime: s.task.blockTime } : {}),
176
+ },
177
+ ...(pen ? { pen } : {}),
178
+ };
74
179
  }
75
180
 
76
181
  // The controller as the machine description carries it: its build, and the bought item it is
77
182
  const controllerSummary = (c) => ({ board: c.board, set: c.set, item: c.item, slots: c.slots });
78
183
 
79
184
  function gaitMachineOf(s) {
80
- const seq = gaitSequence(s), c = controllerOf(s.a), slots = slotsOf(s.a, c);
81
- let axes = seq.names.map((id) => { const a = axisOf(s, id); return { ...a, ...(slots[a.motor] ? { slot: slots[a.motor] } : {}) }; });
82
- if (axes.every((a) => c.slots.includes(a.slot))) axes = [...axes].sort((a, b) => c.slots.indexOf(a.slot) - c.slots.indexOf(b.slot));
83
- const g = s.gait, pattern = typeof s.a.gait.pattern === 'string' ? s.a.gait.pattern : `duty ${s.a.gait.pattern?.duty}`;
84
- return { format: 'rulecad.machine/1', name: `${s.project}/${s.name}`, kinematics: 'legged', tool: null, axes, task: null, controller: controllerSummary(c),
85
- gait: { legs: g.legs.map((l) => l.name), pattern, period: g.period, stride: g.stride, lift: g.lift, height: g.height, frames: seq.q.length } };
185
+ const seq = gaitSequence(s),
186
+ c = controllerOf(s.a),
187
+ slots = slotsOf(s.a, c);
188
+ let axes = seq.names.map((id) => {
189
+ const a = axisOf(s, id);
190
+ return { ...a, ...(slots[a.motor] ? { slot: slots[a.motor] } : {}) };
191
+ });
192
+ if (axes.every((a) => c.slots.includes(a.slot)))
193
+ axes = [...axes].sort((a, b) => c.slots.indexOf(a.slot) - c.slots.indexOf(b.slot));
194
+ const g = s.gait,
195
+ pattern = typeof s.a.gait.pattern === 'string' ? s.a.gait.pattern : `duty ${s.a.gait.pattern?.duty}`;
196
+ return {
197
+ format: 'rulecad.machine/1',
198
+ name: `${s.project}/${s.name}`,
199
+ kinematics: 'legged',
200
+ tool: null,
201
+ axes,
202
+ task: null,
203
+ controller: controllerSummary(c),
204
+ gait: {
205
+ legs: g.legs.map((l) => l.name),
206
+ pattern,
207
+ period: g.period,
208
+ stride: g.stride,
209
+ lift: g.lift,
210
+ height: g.height,
211
+ frames: seq.q.length,
212
+ },
213
+ };
86
214
  }
87
215
 
88
216
  /**
@@ -94,47 +222,111 @@ function gaitMachineOf(s) {
94
222
  */
95
223
  export function plotGait(s, { cycles = 3, period, from } = {}) {
96
224
  if (!s.gait) throw new Error(`${s.project}/${s.name} has no "gait" to play`);
97
- const m = machineOf(s), seq = gaitSequence(s), names = m.axes.map((a) => a.name), cols = names.map((n) => seq.names.indexOf(n));
225
+ const m = machineOf(s),
226
+ seq = gaitSequence(s),
227
+ names = m.axes.map((a) => a.name),
228
+ cols = names.map((n) => seq.names.indexOf(n));
98
229
  const ordered = { period: seq.period, names, q: seq.q.map((r) => cols.map((i) => r[i])) };
99
- const poses = s.motion.poses || {}, poseName = from ?? s.motion.pose ?? null;
100
- if (from != null && !poses[from]) throw new Error(`--pose ${from}: no such pose (poses: ${Object.keys(poses).join(', ') || 'none'})`);
101
- const pose = poseName ? poses[poseName] : null, findings = [];
230
+ const poses = s.motion.poses || {},
231
+ poseName = from ?? s.motion.pose ?? null;
232
+ if (from != null && !poses[from])
233
+ throw new Error(`--pose ${from}: no such pose (poses: ${Object.keys(poses).join(', ') || 'none'})`);
234
+ const pose = poseName ? poses[poseName] : null,
235
+ findings = [];
102
236
  const start = pose && names.every((n) => num(pose[n])) ? names.map((n) => pose[n]) : null;
103
- if (poseName && !start) findings.push({ level: 'info', text: `the pose "${poseName}" does not set ${names.filter((n) => !num(pose?.[n])).join(', ')}, so the file starts and ends at the cycle's first frame`, code: 'gait.from', values: {} });
104
- const r = gaitBlocks(ordered, { axes: m.axes.map((a) => ({ name: a.name, stepsPerUnit: a.stepsPerUnit, maxRate: a.maxRate, unit: a.unit })), cycles, ...(period != null ? { period } : {}), ...(start ? { from: start } : {}) });
237
+ if (poseName && !start)
238
+ findings.push({
239
+ level: 'info',
240
+ text: `the pose "${poseName}" does not set ${names.filter((n) => !num(pose?.[n])).join(', ')}, so the file starts and ends at the cycle's first frame`,
241
+ code: 'gait.from',
242
+ values: {},
243
+ });
244
+ const r = gaitBlocks(ordered, {
245
+ axes: m.axes.map((a) => ({ name: a.name, stepsPerUnit: a.stepsPerUnit, maxRate: a.maxRate, unit: a.unit })),
246
+ cycles,
247
+ ...(period != null ? { period } : {}),
248
+ ...(start ? { from: start } : {}),
249
+ });
105
250
  findings.push(...r.findings);
106
251
  // the streamer: as many axes as the controller has slots, axis k on its slot k (the shield's X, Y, Z; the Mega's S0 to S7)
107
- const c = CONTROLLERS[m.controller.set], slots = c.slots;
108
- if (names.length > slots.length) findings.push({ level: 'warn', text: `${names.length} axes, and the streamer steps ${slots.length} on ${c.title}: the file is written, and send.mjs refuses it${c.board === 'uno' ? ' (an arduino-mega-2560 in the assembly streams up to 8)' : ''}`, code: 'stream.axes', values: { axes: names.length, streamer: slots.length } });
109
- else for (const [k, a] of m.axes.entries()) {
110
- if (!a.slot) findings.push({ level: 'info', text: `${a.name}'s motor ${a.motor} has no wire to ${c.any}: the streamer steps it as axis ${k}, on ${slots[k]}`, code: 'stream.wiring', refs: { item: a.motor } });
111
- else if (a.slot !== slots[k]) findings.push({ level: 'fail', text: `${a.name}'s motor ${a.motor} is wired to ${c.of} ${a.slot}, and the streamer steps axis ${k} on ${slots[k]}`, code: 'stream.wiring', refs: { item: a.motor } });
112
- }
252
+ const c = CONTROLLERS[m.controller.set],
253
+ slots = c.slots;
254
+ if (names.length > slots.length)
255
+ findings.push({
256
+ level: 'warn',
257
+ text: `${names.length} axes, and the streamer steps ${slots.length} on ${c.title}: the file is written, and send.mjs refuses it${c.board === 'uno' ? ' (an arduino-mega-2560 in the assembly streams up to 8)' : ''}`,
258
+ code: 'stream.axes',
259
+ values: { axes: names.length, streamer: slots.length },
260
+ });
261
+ else
262
+ for (const [k, a] of m.axes.entries()) {
263
+ if (!a.slot)
264
+ findings.push({
265
+ level: 'info',
266
+ text: `${a.name}'s motor ${a.motor} has no wire to ${c.any}: the streamer steps it as axis ${k}, on ${slots[k]}`,
267
+ code: 'stream.wiring',
268
+ refs: { item: a.motor },
269
+ });
270
+ else if (a.slot !== slots[k])
271
+ findings.push({
272
+ level: 'fail',
273
+ text: `${a.name}'s motor ${a.motor} is wired to ${c.of} ${a.slot}, and the streamer steps axis ${k} on ${slots[k]}`,
274
+ code: 'stream.wiring',
275
+ refs: { item: a.motor },
276
+ });
277
+ }
113
278
  const n = r.blocks.length;
114
- findings.push({ level: 'info', text: `${cycles} cycle${cycles === 1 ? '' : 's'} of the gait (${m.gait.pattern}) in ${n} blocks, ${n3(r.time, 1)} s${start ? `, from the pose "${poseName}" and back to it` : ''}`, code: 'plot.time', values: { time: r.time, cycles, blocks: n } });
279
+ findings.push({
280
+ level: 'info',
281
+ text: `${cycles} cycle${cycles === 1 ? '' : 's'} of the gait (${m.gait.pattern}) in ${n} blocks, ${n3(r.time, 1)} s${start ? `, from the pose "${poseName}" and back to it` : ''}`,
282
+ code: 'plot.time',
283
+ values: { time: r.time, cycles, blocks: n },
284
+ });
115
285
  const steps = { ...r, machine: m.name, drawing: 'gait', ...(start ? { pose: poseName } : {}) };
116
286
  return { ok: findings.every((x) => x.level !== 'fail'), findings, steps, machine: m, time: { time: r.time } };
117
287
  }
118
288
 
119
289
  // A picture of a gait's step file: each axis's position through the run, from its blocks, with the gait's frames as dots
120
290
  export function gaitPicture(result) {
121
- const f = result.steps, W = 720, H = 160, pad = 40, colours = ['#135', '#c33', '#383', '#a60'];
291
+ const f = result.steps,
292
+ W = 720,
293
+ H = 160,
294
+ pad = 40,
295
+ colours = ['#135', '#c33', '#383', '#a60'];
122
296
  const series = f.axes.map(() => []);
123
- let t = 0, pos = [...f.start];
297
+ let t = 0,
298
+ pos = [...f.start];
124
299
  series.forEach((p, k) => p.push([0, pos[k] / f.axes[k].stepsPerUnit]));
125
- for (const b of f.blocks) { t += b.time; pos = pos.map((x, k) => x + b.steps[k]); series.forEach((p, k) => p.push([t, pos[k] / f.axes[k].stepsPerUnit, b.kind])); }
126
- const panels = series.map((p, k) => {
127
- const lo = Math.min(...p.map((x) => x[1])), hi = Math.max(...p.map((x) => x[1])), y = (v) => H - 20 - ((v - lo) / (hi - lo || 1)) * (H - 40), x = (s) => pad + (s / (t || 1)) * (W - 2 * pad);
128
- const line = p.map(([s, v]) => `${n3(x(s))},${n3(y(v))}`).join(' '), dots = p.filter((q) => q[2] === 'gait').map(([s, v]) => `<circle cx="${n3(x(s))}" cy="${n3(y(v))}" r="1.6" fill="${colours[k % 4]}"/>`).join('');
129
- return `<g transform="translate(0 ${k * H})"><text x="${pad}" y="14" font-size="12" font-family="sans-serif">${f.axes[k].name}: ${n3(lo, 0)} to ${n3(hi, 0)} ${f.axes[k].unit} (the motor's shaft)</text><polyline points="${line}" fill="none" stroke="${colours[k % 4]}" stroke-width="1"/>${dots}</g>`;
130
- }).join('');
300
+ for (const b of f.blocks) {
301
+ t += b.time;
302
+ pos = pos.map((x, k) => x + b.steps[k]);
303
+ series.forEach((p, k) => p.push([t, pos[k] / f.axes[k].stepsPerUnit, b.kind]));
304
+ }
305
+ const panels = series
306
+ .map((p, k) => {
307
+ const lo = Math.min(...p.map((x) => x[1])),
308
+ hi = Math.max(...p.map((x) => x[1])),
309
+ y = (v) => H - 20 - ((v - lo) / (hi - lo || 1)) * (H - 40),
310
+ x = (s) => pad + (s / (t || 1)) * (W - 2 * pad);
311
+ const line = p.map(([s, v]) => `${n3(x(s))},${n3(y(v))}`).join(' '),
312
+ dots = p
313
+ .filter((q) => q[2] === 'gait')
314
+ .map(([s, v]) => `<circle cx="${n3(x(s))}" cy="${n3(y(v))}" r="1.6" fill="${colours[k % 4]}"/>`)
315
+ .join('');
316
+ return `<g transform="translate(0 ${k * H})"><text x="${pad}" y="14" font-size="12" font-family="sans-serif">${f.axes[k].name}: ${n3(lo, 0)} to ${n3(hi, 0)} ${f.axes[k].unit} (the motor's shaft)</text><polyline points="${line}" fill="none" stroke="${colours[k % 4]}" stroke-width="1"/>${dots}</g>`;
317
+ })
318
+ .join('');
131
319
  return `<svg xmlns="http://www.w3.org/2000/svg" width="${W}" height="${H * series.length + 24}" viewBox="0 0 ${W} ${H * series.length + 24}"><rect width="100%" height="100%" fill="#fff"/>${panels}<text x="${pad}" y="${H * series.length + 16}" font-size="12" font-family="sans-serif">${n3(t, 1)} s: ${f.cycles} cycles, ${n3(f.cycleTime, 2)} s each against the gait's ${f.period} s; dots are the gait's frames</text></svg>\n`;
132
320
  }
133
321
 
134
322
  export function writeGait(s, result) {
135
- const dir = paths.exports(s.project); fs.mkdirSync(dir, { recursive: true }); const file = path.join(dir, `${s.name}-gait.steps.json`);
323
+ const dir = paths.exports(s.project);
324
+ fs.mkdirSync(dir, { recursive: true });
325
+ const file = path.join(dir, `${s.name}-gait.steps.json`);
136
326
  fs.writeFileSync(file, JSON.stringify(result.steps));
137
- const prev = paths.preview(s.project, `${s.name}-gait.svg`); fs.mkdirSync(path.dirname(prev), { recursive: true }); fs.writeFileSync(prev, gaitPicture(result));
327
+ const prev = paths.preview(s.project, `${s.name}-gait.svg`);
328
+ fs.mkdirSync(path.dirname(prev), { recursive: true });
329
+ fs.writeFileSync(prev, gaitPicture(result));
138
330
  return { file, preview: prev };
139
331
  }
140
332
 
@@ -150,8 +342,15 @@ function fitsSheet(strokes, frame) {
150
342
  }
151
343
 
152
344
  export const CALIBRATION = (w, h) => {
153
- const cx = w / 2, cy = h / 2, side = Math.min(100, Math.min(w, h) - 20), r = Math.min(15, (Math.min(w, h) - side) / 4 + 10);
154
- const at = [[cx, cy], [cx - (side / 2 - r), cy - (side / 2 - r)], [cx + (side / 2 - r), cy + (side / 2 - r)]];
345
+ const cx = w / 2,
346
+ cy = h / 2,
347
+ side = Math.min(100, Math.min(w, h) - 20),
348
+ r = Math.min(15, (Math.min(w, h) - side) / 4 + 10);
349
+ const at = [
350
+ [cx, cy],
351
+ [cx - (side / 2 - r), cy - (side / 2 - r)],
352
+ [cx + (side / 2 - r), cy + (side / 2 - r)],
353
+ ];
155
354
  return `<svg xmlns="http://www.w3.org/2000/svg" width="${w}mm" height="${h}mm" viewBox="0 0 ${w} ${h}"><rect id="square" x="${cx - side / 2}" y="${cy - side / 2}" width="${side}" height="${side}" fill="none" stroke="black"/>${at.map(([x, y], i) => `<circle id="circle-${i + 1}" cx="${x}" cy="${y}" r="${r}" fill="none" stroke="black"/>`).join('')}</svg>`;
156
355
  };
157
356
 
@@ -161,43 +360,142 @@ export const CALIBRATION = (w, h) => {
161
360
  */
162
361
  export function plot(s, svg, { tolerance, name } = {}) {
163
362
  if (!s.task?.sheet) throw new Error(`${s.project}/${s.name}: plot draws on a "sheet", and the task has none`);
164
- const m = machineOf(s), frame = sheetFrame(s.task.sheet), c = chainOf(s), tol = tolerance ?? Math.min(0.1, (s.task.accuracy ?? 0.3) / 3);
165
- const page = svgToStrokes(svg, { tolerance: tol }), findings = [...page.findings], ok = () => findings.every((x) => x.level !== 'fail');
166
- if (!page.strokes.length) return { ok: false, findings: [...findings, { level: 'fail', text: 'the drawing has no strokes', code: 'plot.empty' }] };
363
+ const m = machineOf(s),
364
+ frame = sheetFrame(s.task.sheet),
365
+ c = chainOf(s),
366
+ tol = tolerance ?? Math.min(0.1, (s.task.accuracy ?? 0.3) / 3);
367
+ const page = svgToStrokes(svg, { tolerance: tol }),
368
+ findings = [...page.findings],
369
+ ok = () => findings.every((x) => x.level !== 'fail');
370
+ if (!page.strokes.length)
371
+ return {
372
+ ok: false,
373
+ findings: [...findings, { level: 'fail', text: 'the drawing has no strokes', code: 'plot.empty' }],
374
+ };
167
375
  const off = fitsSheet(page.strokes, frame);
168
- if (off.length) { findings.push({ level: 'fail', text: `stroke ${off[0].stroke} leaves the ${n3(frame.width, 0)} × ${n3(frame.height, 0)} mm sheet by ${n3(off[0].by)} mm${off.length > 1 ? `, and ${off.length - 1} more` : ''}: the drawing is larger than the sheet`, code: 'plot.sheet', refs: { stroke: off[0].stroke }, values: { by: off[0].by, count: off.length } }); return { ok: false, findings }; }
169
- const ordered = orderStrokes(page, {}), plan = planToolpath(c, ordered, { tolerance: tol, elbow: m.elbow, sheet: s.task.sheet });
376
+ if (off.length) {
377
+ findings.push({
378
+ level: 'fail',
379
+ text: `stroke ${off[0].stroke} leaves the ${n3(frame.width, 0)} × ${n3(frame.height, 0)} mm sheet by ${n3(off[0].by)} mm${off.length > 1 ? `, and ${off.length - 1} more` : ''}: the drawing is larger than the sheet`,
380
+ code: 'plot.sheet',
381
+ refs: { stroke: off[0].stroke },
382
+ values: { by: off[0].by, count: off.length },
383
+ });
384
+ return { ok: false, findings };
385
+ }
386
+ const ordered = orderStrokes(page, {}),
387
+ plan = planToolpath(c, ordered, { tolerance: tol, elbow: m.elbow, sheet: s.task.sheet });
170
388
  findings.push(...plan.findings);
171
389
  if (!plan.ok) return { ok: false, findings, plan };
172
- const speed = s.task.speed ?? 50, accel = m.task.accel, axes = m.axes.map((a) => ({ name: a.name, stepsPerUnit: a.stepsPerUnit, maxRate: a.maxRate }));
173
- const steps = stepBlocks(plan, { axes, speed, accel, travelSpeed: speed * 2, ...(m.task.blockTime ? { minBlockTime: m.task.blockTime } : {}) });
390
+ const speed = s.task.speed ?? 50,
391
+ accel = m.task.accel,
392
+ axes = m.axes.map((a) => ({ name: a.name, stepsPerUnit: a.stepsPerUnit, maxRate: a.maxRate }));
393
+ const steps = stepBlocks(plan, {
394
+ axes,
395
+ speed,
396
+ accel,
397
+ travelSpeed: speed * 2,
398
+ ...(m.task.blockTime ? { minBlockTime: m.task.blockTime } : {}),
399
+ });
174
400
  // The pen-down lines, with what the budget predicts along them
175
- const { list } = s.task.accuracy != null ? accuracyOf(s) : { list: null }, drawn = plan.moves.filter((x) => x.kind === 'draw').map((x) => ({ stroke: x.stroke, name: x.name, points: x.points.map((p) => p.map(r6)), error: list ? x.q.map((q) => +jacobianError(c, q, list, s.task.deflection).toFixed(4)) : null }));
176
- const time = estimate(steps), out = { ...steps, machine: m.name, drawing: name, drawn };
177
- findings.push(...steps.findings, { level: 'info', text: `${ordered.strokes?.length ?? ordered.length} strokes, ${n3(plan.length.draw, 0)} mm drawn, ${n3(plan.length.travel, 0)} mm of travel, ${n3(time.time, 1)} s, with tool speed ${speed} mm/s`, code: 'plot.time', values: { time: time.time, draw: plan.length.draw, travel: plan.length.travel } });
401
+ const { list } = s.task.accuracy != null ? accuracyOf(s) : { list: null },
402
+ drawn = plan.moves
403
+ .filter((x) => x.kind === 'draw')
404
+ .map((x) => ({
405
+ stroke: x.stroke,
406
+ name: x.name,
407
+ points: x.points.map((p) => p.map(r6)),
408
+ error: list ? x.q.map((q) => +jacobianError(c, q, list, s.task.deflection).toFixed(4)) : null,
409
+ }));
410
+ const time = estimate(steps),
411
+ out = { ...steps, machine: m.name, drawing: name, drawn };
412
+ findings.push(...steps.findings, {
413
+ level: 'info',
414
+ text: `${ordered.strokes?.length ?? ordered.length} strokes, ${n3(plan.length.draw, 0)} mm drawn, ${n3(plan.length.travel, 0)} mm of travel, ${n3(time.time, 1)} s, with tool speed ${speed} mm/s`,
415
+ code: 'plot.time',
416
+ values: { time: time.time, draw: plan.length.draw, travel: plan.length.travel },
417
+ });
178
418
  return { ok: ok(), findings, plan, steps: out, machine: m, time };
179
419
  }
180
420
 
181
421
  // An animated SVG: the sheet, the drawing appearing, the arm sweeping over it
182
422
  export function animation(s, result) {
183
- const { c } = sample(s), f = sheetFrame(s.task.sheet), plan = result.plan, moves = plan.moves, toS = (p) => { const d = p.map((x, k) => x - f.at[k]); return [r6(d[0] * f.u[0] + d[1] * f.u[1] + d[2] * f.u[2]), r6(-(d[0] * f.v[0] + d[1] * f.v[1] + d[2] * f.v[2]))]; };
184
- const speed = s.task.speed ?? 50, frames = [];
423
+ const { c } = sample(s),
424
+ f = sheetFrame(s.task.sheet),
425
+ plan = result.plan,
426
+ moves = plan.moves,
427
+ toS = (p) => {
428
+ const d = p.map((x, k) => x - f.at[k]);
429
+ return [r6(d[0] * f.u[0] + d[1] * f.u[1] + d[2] * f.u[2]), r6(-(d[0] * f.v[0] + d[1] * f.v[1] + d[2] * f.v[2]))];
430
+ };
431
+ const speed = s.task.speed ?? 50,
432
+ frames = [];
185
433
  let t = 0;
186
- for (const m of moves) for (let i = 1; i < m.points.length; i++) { const dt = Math.hypot(...m.points[i].map((x, k) => x - m.points[i - 1][k])) / speed; frames.push({ t: t + dt, q: m.q[i], kind: m.kind }); t += dt; }
187
- const every = Math.max(1, Math.floor(frames.length / 240)), keep = frames.filter((_, i) => !(i % every)), last = frames.at(-1) || { t: 1 }, T = last.t || 1;
188
- const arm = (q) => armPoints(c, q).map(toS).map((p) => p.join(',')).join(' ');
189
- const pts = [...moves.flatMap((m) => m.points.map(toS)), ...armPoints(c, moves[0].q[0]).map(toS)], lo = [0, 1].map((k) => Math.min(-f.width / 2 * (k ? f.height / f.width : 1), ...pts.map((p) => p[k]))), hi = [0, 1].map((k) => Math.max((k ? f.height : f.width) / 2, ...pts.map((p) => p[k])));
190
- const m = 10, draw = result.steps.drawn;
191
- const lines = draw.map((d, i) => { const len = d.points.reduce((a, p, j) => (j ? a + Math.hypot(...p.map((x, k) => x - d.points[j - 1][k])) : 0), 0), start = moves.slice(0, moves.findIndex((x) => x.kind === 'draw' && x.stroke === d.stroke)).reduce((a, x) => a + x.points.reduce((b, p, j) => (j ? b + Math.hypot(...p.map((v, k) => v - x.points[j - 1][k])) : 0), 0), 0) / speed; return `<polyline points="${d.points.map(toS).map((p) => p.join(',')).join(' ')}" fill="none" stroke="#135" stroke-width="0.5" stroke-dasharray="${len}" stroke-dashoffset="${len}"><animate attributeName="stroke-dashoffset" from="${len}" to="0" begin="${n3(start, 2)}s" dur="${n3(len / speed, 2)}s" fill="freeze"/></polyline>`; }).join('');
434
+ for (const m of moves)
435
+ for (let i = 1; i < m.points.length; i++) {
436
+ const dt = Math.hypot(...m.points[i].map((x, k) => x - m.points[i - 1][k])) / speed;
437
+ frames.push({ t: t + dt, q: m.q[i], kind: m.kind });
438
+ t += dt;
439
+ }
440
+ const every = Math.max(1, Math.floor(frames.length / 240)),
441
+ keep = frames.filter((_, i) => !(i % every)),
442
+ last = frames.at(-1) || { t: 1 },
443
+ T = last.t || 1;
444
+ const arm = (q) =>
445
+ armPoints(c, q)
446
+ .map(toS)
447
+ .map((p) => p.join(','))
448
+ .join(' ');
449
+ const pts = [...moves.flatMap((m) => m.points.map(toS)), ...armPoints(c, moves[0].q[0]).map(toS)],
450
+ lo = [0, 1].map((k) => Math.min((-f.width / 2) * (k ? f.height / f.width : 1), ...pts.map((p) => p[k]))),
451
+ hi = [0, 1].map((k) => Math.max((k ? f.height : f.width) / 2, ...pts.map((p) => p[k])));
452
+ const m = 10,
453
+ draw = result.steps.drawn;
454
+ const lines = draw
455
+ .map((d) => {
456
+ const len = d.points.reduce((a, p, j) => (j ? a + Math.hypot(...p.map((x, k) => x - d.points[j - 1][k])) : 0), 0),
457
+ start =
458
+ moves
459
+ .slice(
460
+ 0,
461
+ moves.findIndex((x) => x.kind === 'draw' && x.stroke === d.stroke),
462
+ )
463
+ .reduce(
464
+ (a, x) =>
465
+ a +
466
+ x.points.reduce((b, p, j) => (j ? b + Math.hypot(...p.map((v, k) => v - x.points[j - 1][k])) : 0), 0),
467
+ 0,
468
+ ) / speed;
469
+ return `<polyline points="${d.points
470
+ .map(toS)
471
+ .map((p) => p.join(','))
472
+ .join(
473
+ ' ',
474
+ )}" fill="none" stroke="#135" stroke-width="0.5" stroke-dasharray="${len}" stroke-dashoffset="${len}"><animate attributeName="stroke-dashoffset" from="${len}" to="0" begin="${n3(start, 2)}s" dur="${n3(len / speed, 2)}s" fill="freeze"/></polyline>`;
475
+ })
476
+ .join('');
192
477
  const values = keep.map((x) => arm(x.q)).join(';');
193
478
  return `<svg xmlns="http://www.w3.org/2000/svg" viewBox="${lo[0] - m} ${lo[1] - m} ${hi[0] - lo[0] + 2 * m} ${hi[1] - lo[1] + 2 * m}" width="${Math.round((hi[0] - lo[0] + 2 * m) * 3)}" height="${Math.round((hi[1] - lo[1] + 2 * m) * 3)}"><rect x="${-f.width / 2}" y="${-f.height / 2}" width="${f.width}" height="${f.height}" fill="#fff" stroke="#333" stroke-width="0.4"/>${lines}<polyline points="${arm(moves[0].q[0])}" fill="none" stroke="#c33" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><animate attributeName="points" dur="${n3(T, 2)}s" fill="freeze" values="${values}"/></polyline></svg>\n`;
194
479
  }
195
- const armPoints = (c, q) => { const F = fk(c, q); return [...F.frames.map((x) => x.at), F.position]; };
480
+ const armPoints = (c, q) => {
481
+ const F = fk(c, q);
482
+ return [...F.frames.map((x) => x.at), F.position];
483
+ };
196
484
 
197
485
  export function writePlot(s, result, base) {
198
- const dir = paths.exports(s.project); fs.mkdirSync(dir, { recursive: true }); const file = path.join(dir, `${base}.steps.json`);
486
+ const dir = paths.exports(s.project);
487
+ fs.mkdirSync(dir, { recursive: true });
488
+ const file = path.join(dir, `${base}.steps.json`);
199
489
  fs.writeFileSync(file, JSON.stringify(result.steps));
200
- const prev = paths.preview(s.project, `${base}-plot.svg`); fs.mkdirSync(path.dirname(prev), { recursive: true }); fs.writeFileSync(prev, animation(s, result));
490
+ const prev = paths.preview(s.project, `${base}-plot.svg`);
491
+ fs.mkdirSync(path.dirname(prev), { recursive: true });
492
+ fs.writeFileSync(prev, animation(s, result));
201
493
  return { file, preview: prev };
202
494
  }
203
- export function writeMachine(s, m) { const dir = paths.exports(s.project); fs.mkdirSync(dir, { recursive: true }); const file = path.join(dir, `${s.name}.machine.json`); fs.writeFileSync(file, `${JSON.stringify(m, null, 2)}\n`); return file; }
495
+ export function writeMachine(s, m) {
496
+ const dir = paths.exports(s.project);
497
+ fs.mkdirSync(dir, { recursive: true });
498
+ const file = path.join(dir, `${s.name}.machine.json`);
499
+ fs.writeFileSync(file, `${JSON.stringify(m, null, 2)}\n`);
500
+ return file;
501
+ }