@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
@@ -0,0 +1,142 @@
1
+ // v.shapes: @rulecad/shapes as a design gets it, with what its seats were drawn to kept, as v.fixings keeps its holes
2
+ // (lib/fixings.mjs). A seat for a bought part (a shaft's bore, a bearing's pocket, a plain bearing, a pulley's bore) is
3
+ // drawn to a fit, and the fit is only as good as the figure it rests on: a press fit on a shaft is an estimate until
4
+ // someone presses one in. So each call of shaftBore, bearingSeat, plainBearing and pulleyBore says, as a 'seat.drawn'
5
+ // finding, what it was drawn to, the figure it rests on and how far that figure is trusted (its kind), and cad check
6
+ // and the estimate warning (rules.estimate) say it. @rulecad/shapes itself is unchanged: its helpers already return
7
+ // the fit and its kind; this only listens. No files are read here: the sandbox's runner uses it as the build does.
8
+ import { SHAFT_FITS } from '@rulecad/shapes';
9
+
10
+ /** The helpers of @rulecad/shapes that draw a seat for a bought part, and are reported. */
11
+ export const SEAT_HELPERS = ['shaftBore', 'bearingSeat', 'plainBearing', 'pulleyBore'];
12
+
13
+ const n = (x) => String(Number(Number(x).toFixed(4)));
14
+ const TRUST = {
15
+ measured: 'a measured figure',
16
+ spec: "a standard's figure",
17
+ community: 'a community figure',
18
+ estimate: 'an estimate',
19
+ given: 'a figure given by hand',
20
+ default: 'a default',
21
+ derived: 'a figure derived from the printer',
22
+ };
23
+ const trust = (kind) => TRUST[kind] ?? `a ${kind} figure`;
24
+
25
+ // The printer figure a helper read (press, slip, fit, hole_comp), named as a rule where it is the project's printer's
26
+ // (the printer the design was given reads the same as the printer's rule set: x1c.press, with that rule's kind), and
27
+ // otherwise as a figure the design gave, by hand
28
+ function printerFigure(given, printer, key) {
29
+ let value;
30
+ try {
31
+ value = given?.[key];
32
+ } catch {
33
+ value = undefined;
34
+ }
35
+ const rule = printer?.rules?.[key];
36
+ if (typeof value === 'number' && rule && typeof rule.value === 'number' && Math.abs(rule.value - value) < 1e-9)
37
+ return { rule: `${printer.name}.${key}`, kind: typeof rule.kind === 'string' ? rule.kind : 'given', value };
38
+ return { rule: `printer.${key}`, kind: 'given', value };
39
+ }
40
+
41
+ const fitSaid = (fit) => (typeof fit === 'number' ? `a fit of ${n(fit)} mm` : `${fit} fit`);
42
+
43
+ // A bearing's pocket, as a finding: what bearingSeat drew, and the printer's press or slip it rests on
44
+ function pocketFinding(args, r, printer, o) {
45
+ const s = r?.seat;
46
+ if (!s) return null;
47
+ const outer = args[0]?.outer_diameter ?? args[0]?.outer,
48
+ on =
49
+ typeof s.fit === 'number'
50
+ ? { rule: 'fit', says: 'the fit the design gave', kind: 'given', value: s.fit }
51
+ : { ...printerFigure(o.printer, printer, s.fit), says: null },
52
+ comp = printerFigure(o.printer, printer, 'hole_comp');
53
+ return {
54
+ level: 'info',
55
+ code: 'seat.drawn',
56
+ text:
57
+ `a pocket for a bearing ${n(outer)} mm across drawn ${n(s.pocket)} mm (bearingSeat, ${fitSaid(s.fit)}): it ` +
58
+ `rests on ${on.says ?? on.rule} (${n(Math.abs(s.clearance))} mm ${s.clearance < 0 ? 'of press' : 'of slip'} across), ` +
59
+ `${trust(on.kind)}, plus ${comp.rule} ${n(s.comp)} mm across, since a printed hole comes out small`,
60
+ values: { diameter: s.pocket, outer, clearance: s.clearance, comp: s.comp },
61
+ refs: { helper: 'bearingSeat', fit: s.fit, rule: on.rule, kind: on.kind },
62
+ };
63
+ }
64
+
65
+ // What one call drew, as a finding: { level, text, code, values, refs }
66
+ function seatFinding(helper, args, r, printer) {
67
+ const o = (args[1] && typeof args[1] === 'object' ? args[1] : {}) || {};
68
+ if (helper === 'bearingSeat') return pocketFinding(args, r, printer, o);
69
+ // a bore for a shaft: shaftBore's numbers, or plainBearing's and pulleyBore's solid with them on it
70
+ const shaft = helper === 'pulleyBore' ? args[0]?.bore : args[0],
71
+ diameter = helper === 'shaftBore' ? r?.diameter : r?.bore,
72
+ each = helper === 'shaftBore' ? r?.each : r?.clearance,
73
+ fit = r?.fit,
74
+ kind = r?.kind;
75
+ if (typeof diameter !== 'number' || typeof shaft !== 'number' || typeof each !== 'number') return null;
76
+ const comp = +(diameter - shaft - 2 * each).toFixed(4),
77
+ hc = printerFigure(o.printer, printer, 'hole_comp');
78
+ let on;
79
+ if (typeof fit === 'string' && Object.hasOwn(SHAFT_FITS, fit))
80
+ on = { rule: `SHAFT_FITS.${fit}`, says: `@rulecad/shapes' SHAFT_FITS.${fit}` };
81
+ else if (fit === 'run') {
82
+ const f = printerFigure(o.printer, printer, 'fit');
83
+ on = { rule: f.rule, says: `${f.rule}, the printer's fit` };
84
+ } else on = { rule: 'fit', says: 'the fit the design gave' };
85
+ const what = helper === 'shaftBore' ? 'a bore' : helper === 'pulleyBore' ? "a pulley's bore" : 'a plain bearing';
86
+ return {
87
+ level: 'info',
88
+ code: 'seat.drawn',
89
+ text:
90
+ `${what} for a ${n(shaft)} mm shaft drawn ${n(diameter)} mm (${helper}, ${fitSaid(fit)}): it rests on ` +
91
+ `${on.says} (${n(Math.abs(each))} mm ${each < 0 ? 'of press ' : ''}each side), ${trust(kind)}, plus ${hc.rule} ` +
92
+ `${n(comp)} mm across, since a printed hole comes out small`,
93
+ // (said after the count, where it came up again)
94
+ advice:
95
+ kind === 'estimate'
96
+ ? '. Press a shaft into a test print to settle it, and give the fit that works in mm each side (fit: <mm>)'
97
+ : '',
98
+ values: { diameter, shaft, each, comp },
99
+ refs: { helper, fit, rule: on.rule, kind },
100
+ };
101
+ }
102
+
103
+ /**
104
+ * @rulecad/shapes as a design gets it, with what its seat helpers drew kept as findings.
105
+ * @param {Record<string, any>} shapes the module (@rulecad/shapes)
106
+ * @param {{ printer?: { name: string, rules: Record<string, any> } | null }} [context] printer: the project's printer's
107
+ * rule set, so a fit read from it is named as its rule (x1c.press) with that rule's kind
108
+ * @returns {{ shapes: Record<string, any>, found: () => object[], used: () => boolean }} shapes: v.shapes; found: a
109
+ * 'seat.drawn' finding for each seat drawn, each said once (values.count where it came up again); used: whether the
110
+ * design drew any seat
111
+ */
112
+ export function designShapes(shapes, { printer } = {}) {
113
+ const found = new Map();
114
+ let calls = 0;
115
+ const keep = (x) => {
116
+ if (!x) return;
117
+ const k = `${x.code}|${x.text}${x.advice ?? ''}`,
118
+ had = found.get(k);
119
+ if (had) had.values = { ...had.values, count: (had.values.count ?? 1) + 1 };
120
+ else found.set(k, x);
121
+ };
122
+ const out = { ...shapes };
123
+ for (const helper of SEAT_HELPERS) {
124
+ const f = shapes[helper];
125
+ if (typeof f !== 'function') continue;
126
+ out[helper] = (...args) => {
127
+ const r = f(...args);
128
+ calls++;
129
+ keep(seatFinding(helper, args, r, printer));
130
+ return r;
131
+ };
132
+ }
133
+ return {
134
+ shapes: out,
135
+ found: () =>
136
+ [...found.values()].map(({ advice = '', ...x }) => ({
137
+ ...x,
138
+ text: `${x.text}${x.values.count ? ` (${x.values.count} drawn)` : ''}${advice}`,
139
+ })),
140
+ used: () => calls > 0,
141
+ };
142
+ }
package/lib/drive.mjs CHANGED
@@ -8,7 +8,8 @@ import { trainFrom, axisOf } from './motors.mjs';
8
8
 
9
9
  const fmt = (n) => +Number(n).toFixed(3);
10
10
  const esc = (s) => String(s).replace(/[<>&"]/g, (c) => ({ '<': '&lt;', '>': '&gt;', '&': '&amp;', '"': '&quot;' })[c]);
11
- const rowsAt = (W, p) => [0, 1, 2].map((k) => W[4 * k] * p[0] + W[4 * k + 1] * p[1] + W[4 * k + 2] * p[2] + W[4 * k + 3]);
11
+ const rowsAt = (W, p) =>
12
+ [0, 1, 2].map((k) => W[4 * k] * p[0] + W[4 * k + 1] * p[1] + W[4 * k + 2] * p[2] + W[4 * k + 3]);
12
13
  const COLOUR = { still: '#c9ccd1', moves: '#2f6fb3', load: '#e07a1f', bought: '#e9eaec' };
13
14
 
14
15
  /**
@@ -16,10 +17,17 @@ const COLOUR = { still: '#c9ccd1', moves: '#2f6fb3', load: '#e07a1f', bought: '#
16
17
  * levels across the axis to section at, and how far to turn so the slowest part moves a readable amount.
17
18
  */
18
19
  export function drivePlan(s, { turns } = {}) {
19
- const motion = s.motion, d = (motion.drives || []).find((x) => x.joint);
20
- const root = d?.joint ?? motion.joints.find((j) => !j.follow && motion.joints.some((x) => x.follow?.[0] === j.id))?.id;
20
+ const motion = s.motion,
21
+ d = (motion.drives || []).find((x) => x.joint);
22
+ const root =
23
+ d?.joint ?? motion.joints.find((j) => !j.follow && motion.joints.some((x) => x.follow?.[0] === j.id))?.id;
21
24
  if (!root) return null;
22
- const load = (motion.loads || []).find((l) => l.joint)?.joint ?? motion.joints.filter((j) => trainFrom(motion, j.id).root === root && j.id !== root).sort((a, b) => trainFrom(motion, b.id).ratio - trainFrom(motion, a.id).ratio)[0]?.id ?? root;
25
+ const load =
26
+ (motion.loads || []).find((l) => l.joint)?.joint ??
27
+ motion.joints
28
+ .filter((j) => trainFrom(motion, j.id).root === root && j.id !== root)
29
+ .sort((a, b) => trainFrom(motion, b.id).ratio - trainFrom(motion, a.id).ratio)[0]?.id ??
30
+ root;
23
31
  const ratio = Math.abs(trainFrom(motion, load).ratio) || 1;
24
32
  const n = turns ?? Math.min(6, Math.max(1, (ratio * 60) / 360)); // the slowest part through about 60°, in one to six turns
25
33
  return { root, load, motor: d?.id ?? null, ratio, turns: n };
@@ -27,91 +35,190 @@ export function drivePlan(s, { turns } = {}) {
27
35
 
28
36
  export function driveSvg(s, { turns, title = '' } = {}) {
29
37
  const plan = drivePlan(s, { turns });
30
- if (!plan) throw new Error(`${s.name} has nothing driven to animate: give it a "motor" item that "drives" a joint, or gears that follow one`);
31
- const motion = s.motion, rootJ = motion.joints.find((j) => j.id === plan.root);
32
- const v0 = jointValues(motion, motion.pose ?? undefined), W0 = placeItems(motion, v0);
33
- const { O, Z } = axisOf(motion, W0, rootJ, mul), F = axisFrame(O, Z);
38
+ if (!plan)
39
+ throw new Error(
40
+ `${s.name} has nothing driven to animate: give it a "motor" item that "drives" a joint, or gears that follow one`,
41
+ );
42
+ const motion = s.motion,
43
+ rootJ = motion.joints.find((j) => j.id === plan.root);
44
+ const v0 = jointValues(motion, motion.pose ?? undefined),
45
+ W0 = placeItems(motion, v0);
46
+ const { O, Z } = axisOf(motion, W0, rootJ, mul),
47
+ F = axisFrame(O, Z);
34
48
  const indexOf = new Map(s.items.map((it, k) => [it.id, k]));
35
49
  const loadItem = motion.joints.find((j) => j.id === plan.load)?.child;
36
50
  // Every part, in the axis's frame at rest: what's cut, and what it belongs to
37
- const parts = s.parts.map((p) => ({ p, k: indexOf.get(p.item), world: p.triangles.map((t) => t.map(F)) })).filter((x) => x.k != null && x.world.length);
38
- const span = (x) => { let lo = Infinity, hi = -Infinity; for (const t of x.world) for (const q of t) { lo = Math.min(lo, q[2]); hi = Math.max(hi, q[2]); } return [lo, hi]; };
51
+ const parts = s.parts
52
+ .map((p) => ({ p, k: indexOf.get(p.item), world: p.triangles.map((t) => t.map(F)) }))
53
+ .filter((x) => x.k != null && x.world.length);
54
+ const span = (x) => {
55
+ let lo = Infinity,
56
+ hi = -Infinity;
57
+ for (const t of x.world)
58
+ for (const q of t) {
59
+ lo = Math.min(lo, q[2]);
60
+ hi = Math.max(hi, q[2]);
61
+ }
62
+ return [lo, hi];
63
+ };
39
64
  // Where to cut: through each gear's teeth (the height whose section has the most edges, the middle of that run),
40
65
  // rings named in a planetary included, and through the middle of what carries the load
41
- const geared = new Set([...(motion.meshes || []).flatMap((m) => [m.joint, ...(m.members || [])]), ...motion.joints.filter((j) => j.follow).flatMap((j) => [j.id, j.follow[0]])]);
66
+ const geared = new Set([
67
+ ...(motion.meshes || []).flatMap((m) => [m.joint, ...(m.members || [])]),
68
+ ...motion.joints.filter((j) => j.follow).flatMap((j) => [j.id, j.follow[0]]),
69
+ ]);
42
70
  const childOf = new Map(motion.joints.map((j) => [j.id, j.child]));
43
- const ringItems = new Set((s.a.planetary || []).flatMap((g) => [g.ring, g.output?.ring]).filter(Boolean).map((id) => indexOf.get(id)));
71
+ const ringItems = new Set(
72
+ (s.a.planetary || [])
73
+ .flatMap((g) => [g.ring, g.output?.ring])
74
+ .filter(Boolean)
75
+ .map((id) => indexOf.get(id)),
76
+ );
44
77
  const gearItems = new Set([...[...geared].map((id) => childOf.get(id)), ...ringItems].filter((k) => k != null));
45
78
  const teethAt = (x) => {
46
- const [lo, hi] = span(x), n = Math.min(160, Math.max(8, Math.round((hi - lo) / 0.25))), counts = [];
47
- for (let i = 1; i < n; i++) { const z = lo + ((hi - lo) * i) / n; counts.push([z, sliceAt(x.world, z).length]); }
48
- const top = Math.max(...counts.map((c) => c[1])), run = counts.filter((c) => c[1] >= top * 0.9).map((c) => c[0]);
79
+ const [lo, hi] = span(x),
80
+ n = Math.min(160, Math.max(8, Math.round((hi - lo) / 0.25))),
81
+ counts = [];
82
+ for (let i = 1; i < n; i++) {
83
+ const z = lo + ((hi - lo) * i) / n;
84
+ counts.push([z, sliceAt(x.world, z).length]);
85
+ }
86
+ const top = Math.max(...counts.map((c) => c[1])),
87
+ run = counts.filter((c) => c[1] >= top * 0.9).map((c) => c[0]);
49
88
  return run.length ? (run[0] + run.at(-1)) / 2 : (lo + hi) / 2;
50
89
  };
51
90
  const want = [];
52
- for (const k of gearItems) { const own = parts.filter((x) => x.k === k && x.p.role === 'part'); if (own.length) want.push({ z: teethAt({ world: own.flatMap((x) => x.world) }), ring: ringItems.has(k) }); }
53
- if (loadItem != null && !gearItems.has(loadItem)) { const own = parts.filter((x) => x.k === loadItem && x.p.role === 'part'); if (own.length) { const [lo, hi] = span({ world: own.flatMap((x) => x.world) }); want.push({ z: (lo + hi) / 2, ring: false }); } }
91
+ for (const k of gearItems) {
92
+ const own = parts.filter((x) => x.k === k && x.p.role === 'part');
93
+ if (own.length) want.push({ z: teethAt({ world: own.flatMap((x) => x.world) }), ring: ringItems.has(k) });
94
+ }
95
+ if (loadItem != null && !gearItems.has(loadItem)) {
96
+ const own = parts.filter((x) => x.k === loadItem && x.p.role === 'part');
97
+ if (own.length) {
98
+ const [lo, hi] = span({ world: own.flatMap((x) => x.world) });
99
+ want.push({ z: (lo + hi) / 2, ring: false });
100
+ }
101
+ }
54
102
  want.sort((a, b) => b.ring - a.ring || a.z - b.z);
55
103
  const levels = [];
56
104
  for (const { z } of want) if (!levels.some((l) => Math.abs(l - z) < 1.5)) levels.push(z);
57
105
  const picked = levels.slice(0, 3).sort((a, b) => a - b); // rings first, then the rest, three at most
58
106
  // The frames: the root turned through its turns, each item's rigid move in the plane from two points on it
59
- const N = Math.min(240, Math.max(24, Math.round(plan.turns * 40))), base = v0[plan.root]?.[0] ?? 0;
60
- const ks = [...new Set(parts.map((x) => x.k))], moves = new Map(ks.map((k) => [k, []]));
107
+ const N = Math.min(240, Math.max(24, Math.round(plan.turns * 40))),
108
+ base = v0[plan.root]?.[0] ?? 0;
109
+ const ks = [...new Set(parts.map((x) => x.k))],
110
+ moves = new Map(ks.map((k) => [k, []]));
61
111
  for (let f = 0; f <= N; f++) {
62
- const W = f ? placeItems(motion, jointValues(motion, { ...Object.fromEntries(Object.entries(v0).filter(([id]) => !motion.joints.find((j) => j.id === id)?.follow)), [plan.root]: [base + (360 * plan.turns * f) / N] })) : W0;
112
+ const W = f
113
+ ? placeItems(
114
+ motion,
115
+ jointValues(motion, {
116
+ ...Object.fromEntries(Object.entries(v0).filter(([id]) => !motion.joints.find((j) => j.id === id)?.follow)),
117
+ [plan.root]: [base + (360 * plan.turns * f) / N],
118
+ }),
119
+ )
120
+ : W0;
63
121
  for (const k of ks) {
64
- const a = F(rowsAt(W[k], [0, 0, 0])), local = invRows(W0[k]), axisLocal = rotOnly(local, Z), e = perp(axisLocal);
65
- const b = F(rowsAt(W[k], e)), a0 = F(rowsAt(W0[k], [0, 0, 0])), b0 = F(rowsAt(W0[k], e));
122
+ const a = F(rowsAt(W[k], [0, 0, 0])),
123
+ local = invRows(W0[k]),
124
+ axisLocal = rotOnly(local, Z),
125
+ e = perp(axisLocal);
126
+ const b = F(rowsAt(W[k], e)),
127
+ a0 = F(rowsAt(W0[k], [0, 0, 0])),
128
+ b0 = F(rowsAt(W0[k], e));
66
129
  const th = Math.atan2(b[1] - a[1], b[0] - a[0]) - Math.atan2(b0[1] - a0[1], b0[0] - a0[0]);
67
- const list = moves.get(k), prev = list.length ? list.at(-1).th : 0;
68
- let t = th; while (t - prev > Math.PI) t -= 2 * Math.PI; while (t - prev < -Math.PI) t += 2 * Math.PI; // turned on, not back
69
- const c = Math.cos(t), sn = Math.sin(t);
130
+ const list = moves.get(k),
131
+ prev = list.length ? list.at(-1).th : 0;
132
+ let t = th;
133
+ while (t - prev > Math.PI) t -= 2 * Math.PI;
134
+ while (t - prev < -Math.PI) t += 2 * Math.PI; // turned on, not back
135
+ const c = Math.cos(t),
136
+ sn = Math.sin(t);
70
137
  list.push({ th: t, tx: a[0] - (c * a0[0] - sn * a0[1]), ty: a[1] - (sn * a0[0] + c * a0[1]) });
71
138
  }
72
139
  }
73
- const still = (k) => moves.get(k).every((m) => Math.abs(m.th) < 1e-6 && Math.abs(m.tx) < 1e-6 && Math.abs(m.ty) < 1e-6);
140
+ const still = (k) =>
141
+ moves.get(k).every((m) => Math.abs(m.th) < 1e-6 && Math.abs(m.tx) < 1e-6 && Math.abs(m.ty) < 1e-6);
74
142
  // Each panel: the cut through every part that crosses it, at rest; the moving ones animated
75
- const panels = picked.map((z) => {
76
- const cuts = [];
77
- for (const x of parts) {
78
- const outlines = loops(sliceAt(x.world, z)).filter((o) => o.length > 2);
79
- if (outlines.length) cuts.push({ ...x, d: outlines.map((o) => `M${o.map(([u, w]) => `${fmt(u)} ${fmt(w)}`).join('L')}Z`).join('') });
80
- }
81
- const names = [...new Set(cuts.filter((c) => c.p.role === 'part').map((c) => c.p.item))];
82
- return { z, cuts, names };
83
- }).filter((p) => p.cuts.length);
143
+ const panels = picked
144
+ .map((z) => {
145
+ const cuts = [];
146
+ for (const x of parts) {
147
+ const outlines = loops(sliceAt(x.world, z)).filter((o) => o.length > 2);
148
+ if (outlines.length)
149
+ cuts.push({
150
+ ...x,
151
+ d: outlines.map((o) => `M${o.map(([u, w]) => `${fmt(u)} ${fmt(w)}`).join('L')}Z`).join(''),
152
+ });
153
+ }
154
+ const names = [...new Set(cuts.filter((c) => c.p.role === 'part').map((c) => c.p.item))];
155
+ return { z, cuts, names };
156
+ })
157
+ .filter((p) => p.cuts.length);
84
158
  if (!panels.length) throw new Error(`${s.name}: no part crosses the planes through its gears`);
85
159
  // The view: everything every frame reaches, in each panel
86
160
  let r = 0;
87
- for (const pn of panels) for (const c of pn.cuts) for (const t of c.world) for (const q of t) if (Math.abs(q[2] - pn.z) < 50) r = Math.max(r, Math.hypot(q[0], q[1]));
88
- const cell = 2 * r * 1.1, gap = cell * 0.08, cap = cell * 0.16, W = panels.length * cell + (panels.length + 1) * gap, H = cell + cap * 2 + gap;
161
+ for (const pn of panels)
162
+ for (const c of pn.cuts)
163
+ for (const t of c.world)
164
+ for (const q of t) if (Math.abs(q[2] - pn.z) < 50) r = Math.max(r, Math.hypot(q[0], q[1]));
165
+ const cell = 2 * r * 1.1,
166
+ gap = cell * 0.08,
167
+ cap = cell * 0.16,
168
+ W = panels.length * cell + (panels.length + 1) * gap,
169
+ H = cell + cap * 2 + gap;
89
170
  const dur = `${fmt(Math.max(4, Math.min(12, plan.turns * 2)))}s`;
90
171
  const anim = (k) => {
91
172
  const m = moves.get(k);
92
- return { t: `<animateTransform attributeName="transform" type="translate" values="${m.map((x) => `${fmt(x.tx)} ${fmt(x.ty)}`).join(';')}" dur="${dur}" repeatCount="indefinite"/>`,
93
- r: `<animateTransform attributeName="transform" type="rotate" values="${m.map((x) => fmt((x.th * 180) / Math.PI)).join(';')}" dur="${dur}" repeatCount="indefinite"/>` };
173
+ return {
174
+ t: `<animateTransform attributeName="transform" type="translate" values="${m.map((x) => `${fmt(x.tx)} ${fmt(x.ty)}`).join(';')}" dur="${dur}" repeatCount="indefinite"/>`,
175
+ r: `<animateTransform attributeName="transform" type="rotate" values="${m.map((x) => fmt((x.th * 180) / Math.PI)).join(';')}" dur="${dur}" repeatCount="indefinite"/>`,
176
+ };
94
177
  };
95
- const colour = (c) => (c.p.role !== 'part' ? COLOUR.bought : c.k === loadItem ? COLOUR.load : still(c.k) ? COLOUR.still : COLOUR.moves);
96
- const art = panels.map((pn, i) => {
97
- const cx = gap + i * (cell + gap) + cell / 2, cy = cap + gap + cell / 2;
98
- const order = [...pn.cuts].sort((a, b) => (a.p.role !== 'part') - (b.p.role !== 'part') || still(b.k) - still(a.k)); // bought faint at the back, still parts under moving ones
99
- const shapes = order.map((c) => {
100
- const fill = `<path d="${c.d}" fill="${colour(c)}" fill-rule="evenodd" stroke="#1a1a1a" stroke-width="${fmt(cell / 900)}"/>`;
101
- if (still(c.k)) return fill;
102
- const a = anim(c.k);
103
- return `<g>${a.t}<g>${a.r}${fill}</g></g>`;
104
- }).join('');
105
- const size = cap * 0.3, room = Math.floor(cell / (size * 0.55)), text = `at ${fmt(pn.z)} mm: ${pn.names.join(', ')}`;
106
- const label = `<text x="${fmt(cx - cell / 2)}" y="${fmt(cap * 0.75)}" font-size="${fmt(size)}" font-family="system-ui, sans-serif" fill="#333">${esc(text.length > room ? `${text.slice(0, room - 1)}…` : text)}</text>`;
107
- return `${label}<g transform="translate(${fmt(cx)} ${fmt(cy)}) scale(1 -1)">${shapes}</g>`;
108
- }).join('\n');
109
- const times = (n) => (n === 1 ? 'once' : `${fmt(n)} times`), along = `cut across ${plan.root}'s axis`;
110
- const out = plan.ratio !== 1 ? `${along}: ${plan.load} turns ${fmt((360 * plan.turns) / plan.ratio)}° while ${plan.root} turns ${times(plan.turns)} (${fmt(plan.ratio)}:1)` : `${along}: ${plan.root} turned ${times(plan.turns)}`;
111
- const KEY = [['moves', 'moves'], ['load', 'carries the load'], ['still', 'held still'], ['bought', 'bought']];
112
- const ks2 = Math.min(cap * 0.3, (W - 2 * gap) / (KEY.reduce((n, [, t]) => n + t.length * 0.55 + 3.2, 0))), outSize = Math.min(cap * 0.34, (W - 2 * gap) / (out.length * 0.55));
178
+ const colour = (c) =>
179
+ c.p.role !== 'part' ? COLOUR.bought : c.k === loadItem ? COLOUR.load : still(c.k) ? COLOUR.still : COLOUR.moves;
180
+ const art = panels
181
+ .map((pn, i) => {
182
+ const cx = gap + i * (cell + gap) + cell / 2,
183
+ cy = cap + gap + cell / 2;
184
+ const order = [...pn.cuts].sort(
185
+ (a, b) => (a.p.role !== 'part') - (b.p.role !== 'part') || still(b.k) - still(a.k),
186
+ ); // bought faint at the back, still parts under moving ones
187
+ const shapes = order
188
+ .map((c) => {
189
+ const fill = `<path d="${c.d}" fill="${colour(c)}" fill-rule="evenodd" stroke="#1a1a1a" stroke-width="${fmt(cell / 900)}"/>`;
190
+ if (still(c.k)) return fill;
191
+ const a = anim(c.k);
192
+ return `<g>${a.t}<g>${a.r}${fill}</g></g>`;
193
+ })
194
+ .join('');
195
+ const size = cap * 0.3,
196
+ room = Math.floor(cell / (size * 0.55)),
197
+ text = `at ${fmt(pn.z)} mm: ${pn.names.join(', ')}`;
198
+ const label = `<text x="${fmt(cx - cell / 2)}" y="${fmt(cap * 0.75)}" font-size="${fmt(size)}" font-family="system-ui, sans-serif" fill="#333">${esc(text.length > room ? `${text.slice(0, room - 1)}…` : text)}</text>`;
199
+ return `${label}<g transform="translate(${fmt(cx)} ${fmt(cy)}) scale(1 -1)">${shapes}</g>`;
200
+ })
201
+ .join('\n');
202
+ const times = (n) => (n === 1 ? 'once' : `${fmt(n)} times`),
203
+ along = `cut across ${plan.root}'s axis`;
204
+ const out =
205
+ plan.ratio !== 1
206
+ ? `${along}: ${plan.load} turns ${fmt((360 * plan.turns) / plan.ratio)}° while ${plan.root} turns ${times(plan.turns)} (${fmt(plan.ratio)}:1)`
207
+ : `${along}: ${plan.root} turned ${times(plan.turns)}`;
208
+ const KEY = [
209
+ ['moves', 'moves'],
210
+ ['load', 'carries the load'],
211
+ ['still', 'held still'],
212
+ ['bought', 'bought'],
213
+ ];
214
+ const ks2 = Math.min(cap * 0.3, (W - 2 * gap) / KEY.reduce((n, [, t]) => n + t.length * 0.55 + 3.2, 0)),
215
+ outSize = Math.min(cap * 0.34, (W - 2 * gap) / (out.length * 0.55));
113
216
  let kx = gap;
114
- const key = KEY.map(([k, t]) => { const x = kx; kx += ks2 * (t.length * 0.55 + 3.2); return `<rect x="${fmt(x)}" y="${fmt(H - cap * 0.95)}" width="${fmt(ks2 * 1.2)}" height="${fmt(ks2 * 1.2)}" fill="${COLOUR[k]}" stroke="#1a1a1a" stroke-width="${fmt(cell / 900)}"/><text x="${fmt(x + ks2 * 1.6)}" y="${fmt(H - cap * 0.95 + ks2)}" font-size="${fmt(ks2)}" font-family="system-ui, sans-serif" fill="#555">${t}</text>`; }).join('');
217
+ const key = KEY.map(([k, t]) => {
218
+ const x = kx;
219
+ kx += ks2 * (t.length * 0.55 + 3.2);
220
+ return `<rect x="${fmt(x)}" y="${fmt(H - cap * 0.95)}" width="${fmt(ks2 * 1.2)}" height="${fmt(ks2 * 1.2)}" fill="${COLOUR[k]}" stroke="#1a1a1a" stroke-width="${fmt(cell / 900)}"/><text x="${fmt(x + ks2 * 1.6)}" y="${fmt(H - cap * 0.95 + ks2)}" font-size="${fmt(ks2)}" font-family="system-ui, sans-serif" fill="#555">${t}</text>`;
221
+ }).join('');
115
222
  return `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 ${fmt(W)} ${fmt(H)}" width="${Math.min(1400, 480 * panels.length)}">
116
223
  <title>${esc(title || s.a.title || s.name)}</title>
117
224
  <rect width="${fmt(W)}" height="${fmt(H)}" fill="#fff"/>
@@ -123,11 +230,28 @@ ${key}
123
230
  }
124
231
 
125
232
  // Helpers on the flat row-major 4 × 4 matrices placeItems gives
126
- function invRows(W) { // a rigid move's inverse: the turn transposed, the shift turned back
127
- const R = [[W[0], W[1], W[2]], [W[4], W[5], W[6]], [W[8], W[9], W[10]]], t = [W[3], W[7], W[11]];
233
+ function invRows(W) {
234
+ // a rigid move's inverse: the turn transposed, the shift turned back
235
+ const R = [
236
+ [W[0], W[1], W[2]],
237
+ [W[4], W[5], W[6]],
238
+ [W[8], W[9], W[10]],
239
+ ],
240
+ t = [W[3], W[7], W[11]];
128
241
  const o = new Array(16).fill(0);
129
- for (let i = 0; i < 3; i++) { for (let j = 0; j < 3; j++) o[4 * i + j] = R[j][i]; o[4 * i + 3] = -(R[0][i] * t[0] + R[1][i] * t[1] + R[2][i] * t[2]); }
130
- o[15] = 1; return o;
242
+ for (let i = 0; i < 3; i++) {
243
+ for (let j = 0; j < 3; j++) o[4 * i + j] = R[j][i];
244
+ o[4 * i + 3] = -(R[0][i] * t[0] + R[1][i] * t[1] + R[2][i] * t[2]);
245
+ }
246
+ o[15] = 1;
247
+ return o;
131
248
  }
132
249
  const rotOnly = (W, v) => [0, 1, 2].map((k) => W[4 * k] * v[0] + W[4 * k + 1] * v[1] + W[4 * k + 2] * v[2]);
133
- const perp = (z) => { const n = Math.hypot(...z) || 1, u = z.map((c) => c / n), seed = Math.abs(u[0]) < 0.9 ? [1, 0, 0] : [0, 1, 0]; const c = [seed[1] * u[2] - seed[2] * u[1], seed[2] * u[0] - seed[0] * u[2], seed[0] * u[1] - seed[1] * u[0]], m = Math.hypot(...c); return c.map((x) => (x / m) * 10); };
250
+ const perp = (z) => {
251
+ const n = Math.hypot(...z) || 1,
252
+ u = z.map((c) => c / n),
253
+ seed = Math.abs(u[0]) < 0.9 ? [1, 0, 0] : [0, 1, 0];
254
+ const c = [seed[1] * u[2] - seed[2] * u[1], seed[2] * u[0] - seed[0] * u[2], seed[0] * u[1] - seed[1] * u[0]],
255
+ m = Math.hypot(...c);
256
+ return c.map((x) => (x / m) * 10);
257
+ };