@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/order.mjs CHANGED
@@ -9,7 +9,7 @@ import crypto from 'node:crypto';
9
9
  import path from 'node:path';
10
10
  import fs from 'node:fs';
11
11
  import { placeItems, jointValues, mul } from '@rulecad/model-link';
12
- import { host } from './host.mjs';
12
+ import { host, cached } from './host.mjs';
13
13
  import { paths } from './workspace.mjs';
14
14
  import { motorScrews } from './motors.mjs';
15
15
  import jscad from '@jscad/modeling';
@@ -17,11 +17,21 @@ const { geom3 } = jscad.geometries;
17
17
 
18
18
  const top = (n) => String(n).split(/[.@]/)[0];
19
19
  const round = (v) => v.map((x) => (Math.abs(x) < 1e-9 ? 0 : +x.toFixed(6)));
20
- const SIDES = [[0, 0, 1], [0, 0, -1], [1, 0, 0], [-1, 0, 0], [0, 1, 0], [0, -1, 0]];
20
+ const SIDES = [
21
+ [0, 0, 1],
22
+ [0, 0, -1],
23
+ [1, 0, 0],
24
+ [-1, 0, 0],
25
+ [0, 1, 0],
26
+ [0, -1, 0],
27
+ ];
21
28
  const dot = (a, b) => a[0] * b[0] + a[1] * b[1] + a[2] * b[2];
22
29
  const fan = (poly) => poly.slice(1, -1).map((_, i) => [poly[0], poly[i + 1], poly[i + 2]]);
23
30
  function basis(d) {
24
- const a = Math.abs(d[0]) < 0.9 ? [1, 0, 0] : [0, 1, 0], u = [d[1] * a[2] - d[2] * a[1], d[2] * a[0] - d[0] * a[2], d[0] * a[1] - d[1] * a[0]], l = Math.hypot(...u), n = u.map((x) => x / l);
31
+ const a = Math.abs(d[0]) < 0.9 ? [1, 0, 0] : [0, 1, 0],
32
+ u = [d[1] * a[2] - d[2] * a[1], d[2] * a[0] - d[0] * a[2], d[0] * a[1] - d[1] * a[0]],
33
+ l = Math.hypot(...u),
34
+ n = u.map((x) => x / l);
25
35
  return [n, [d[1] * n[2] - d[2] * n[1], d[2] * n[0] - d[0] * n[2], d[0] * n[1] - d[1] * n[0]]];
26
36
  }
27
37
 
@@ -29,35 +39,64 @@ function basis(d) {
29
39
  // (a fitting whose tongue or pegs stand in a beam's slot, an end cap's in its end, is taken without them, as the overlap
30
40
  // check takes it: they slide out along the slot or the beam, and would otherwise hold it to its beam from every side)
31
41
  function groups(s) {
32
- const by = new Map(), beams = new Set(s.objects.filter((o) => o.beam).map((o) => o.id));
42
+ const by = new Map(),
43
+ beams = new Set(s.objects.filter((o) => o.beam).map((o) => o.id));
33
44
  s.parts.forEach((p, order) => {
34
45
  if (!by.has(p.item)) by.set(p.item, { id: p.item, order, parts: [], tris: [] });
35
- const g = by.get(p.item); g.parts.push(p);
36
- for (const t of p.collide && !beams.has(p.item) ? geom3.toPolygons(p.collide).map((q) => q.vertices) : p.triangles) g.tris.push(...fan(t));
46
+ const g = by.get(p.item);
47
+ g.parts.push(p);
48
+ for (const t of p.collide && !beams.has(p.item) ? geom3.toPolygons(p.collide).map((q) => q.vertices) : p.triangles)
49
+ g.tris.push(...fan(t));
37
50
  });
38
51
  const objs = new Map(s.objects.map((o) => [o.id, o]));
39
- for (const g of by.values()) { const o = objs.get(g.id); g.object = o?.objName ?? null; g.bought = o?.bought ?? null; g.motor = !!o?.motor; }
52
+ for (const g of by.values()) {
53
+ const o = objs.get(g.id);
54
+ g.object = o?.objName ?? null;
55
+ g.bought = o?.bought ?? null;
56
+ g.motor = !!o?.motor;
57
+ }
40
58
  return [...by.values()];
41
59
  }
42
60
 
43
61
  // A part seen along a direction: for each cell of a grid across it, the nearest and furthest of it along the direction
44
62
  function raster(g, d, h) {
45
- const [u, v] = basis(d), cells = new Map();
46
- let uLo = Infinity, uHi = -Infinity, vLo = Infinity, vHi = -Infinity, sLo = Infinity, sHi = -Infinity;
63
+ const [u, v] = basis(d),
64
+ cells = new Map();
65
+ let uLo = Infinity,
66
+ uHi = -Infinity,
67
+ vLo = Infinity,
68
+ vHi = -Infinity,
69
+ sLo = Infinity,
70
+ sHi = -Infinity;
47
71
  const k = (i, j) => (i + 1048576) * 2097152 + (j + 1048576);
48
72
  for (const t of g.tris) {
49
73
  const P = t.map((p) => [dot(p, u), dot(p, v), dot(p, d)]);
50
- const lo = [Math.min(P[0][0], P[1][0], P[2][0]), Math.min(P[0][1], P[1][1], P[2][1])], hi = [Math.max(P[0][0], P[1][0], P[2][0]), Math.max(P[0][1], P[1][1], P[2][1])];
51
- uLo = Math.min(uLo, lo[0]); uHi = Math.max(uHi, hi[0]); vLo = Math.min(vLo, lo[1]); vHi = Math.max(vHi, hi[1]); sLo = Math.min(sLo, P[0][2], P[1][2], P[2][2]); sHi = Math.max(sHi, P[0][2], P[1][2], P[2][2]);
74
+ const lo = [Math.min(P[0][0], P[1][0], P[2][0]), Math.min(P[0][1], P[1][1], P[2][1])],
75
+ hi = [Math.max(P[0][0], P[1][0], P[2][0]), Math.max(P[0][1], P[1][1], P[2][1])];
76
+ uLo = Math.min(uLo, lo[0]);
77
+ uHi = Math.max(uHi, hi[0]);
78
+ vLo = Math.min(vLo, lo[1]);
79
+ vHi = Math.max(vHi, hi[1]);
80
+ sLo = Math.min(sLo, P[0][2], P[1][2], P[2][2]);
81
+ sHi = Math.max(sHi, P[0][2], P[1][2], P[2][2]);
52
82
  const det = (P[1][1] - P[2][1]) * (P[0][0] - P[2][0]) + (P[2][0] - P[1][0]) * (P[0][1] - P[2][1]);
53
83
  if (Math.abs(det) < 1e-9) continue; // a face seen edge-on covers no cell: the faces either side of it do
54
- for (let i = Math.floor(lo[0] / h); i <= Math.floor(hi[0] / h); i++) for (let j = Math.floor(lo[1] / h); j <= Math.floor(hi[1] / h); j++) {
55
- const x = (i + 0.5) * h, y = (j + 0.5) * h, a = ((P[1][1] - P[2][1]) * (x - P[2][0]) + (P[2][0] - P[1][0]) * (y - P[2][1])) / det, b = ((P[2][1] - P[0][1]) * (x - P[2][0]) + (P[0][0] - P[2][0]) * (y - P[2][1])) / det, c = 1 - a - b;
56
- if (a < -1e-9 || b < -1e-9 || c < -1e-9) continue; // (exact: a slack in these fractions grows with the triangle)
57
- const z = a * P[0][2] + b * P[1][2] + c * P[2][2];
58
- const key = k(i, j), now = cells.get(key);
59
- if (now) { if (z < now[0]) now[0] = z; if (z > now[1]) now[1] = z; } else cells.set(key, [z, z]);
60
- }
84
+ for (let i = Math.floor(lo[0] / h); i <= Math.floor(hi[0] / h); i++)
85
+ for (let j = Math.floor(lo[1] / h); j <= Math.floor(hi[1] / h); j++) {
86
+ const x = (i + 0.5) * h,
87
+ y = (j + 0.5) * h,
88
+ a = ((P[1][1] - P[2][1]) * (x - P[2][0]) + (P[2][0] - P[1][0]) * (y - P[2][1])) / det,
89
+ b = ((P[2][1] - P[0][1]) * (x - P[2][0]) + (P[0][0] - P[2][0]) * (y - P[2][1])) / det,
90
+ c = 1 - a - b;
91
+ if (a < -1e-9 || b < -1e-9 || c < -1e-9) continue; // (exact: a slack in these fractions grows with the triangle)
92
+ const z = a * P[0][2] + b * P[1][2] + c * P[2][2];
93
+ const key = k(i, j),
94
+ now = cells.get(key);
95
+ if (now) {
96
+ if (z < now[0]) now[0] = z;
97
+ if (z > now[1]) now[1] = z;
98
+ } else cells.set(key, [z, z]);
99
+ }
61
100
  }
62
101
  return { cells, uLo, uHi, vLo, vHi, sLo, sHi, key: k };
63
102
  }
@@ -65,30 +104,53 @@ function raster(g, d, h) {
65
104
  // Blocked when, in a cell they share, the other has something further along than this part's rearmost: this part, moved
66
105
  // on, runs into it. Parts meet at their edges, so this part is thinned by a cell; a thing narrower than that keeps its cells.
67
106
  function blockers(p, q, d, h, rasterOf) {
68
- const A = rasterOf(p, d), B = rasterOf(q, d);
107
+ const A = rasterOf(p, d),
108
+ B = rasterOf(q, d);
69
109
  if (A.uHi < B.uLo || B.uHi < A.uLo || A.vHi < B.vLo || B.vHi < A.vLo || B.sHi <= A.sLo + 0.2) return false;
70
110
  const inner = [...A.cells].filter(([key]) => {
71
- const j = key % 2097152, i = (key - j) / 2097152;
72
- return [[1, 0], [-1, 0], [0, 1], [0, -1]].every(([a, b]) => A.cells.has((i + a) * 2097152 + (j + b)));
111
+ const j = key % 2097152,
112
+ i = (key - j) / 2097152;
113
+ return [
114
+ [1, 0],
115
+ [-1, 0],
116
+ [0, 1],
117
+ [0, -1],
118
+ ].every(([a, b]) => A.cells.has((i + a) * 2097152 + (j + b)));
73
119
  });
74
- for (const [key, a] of inner.length ? inner : [...A.cells]) { const b = B.cells.get(key); if (b && b[1] > a[0] + 0.2) return true; }
120
+ for (const [key, a] of inner.length ? inner : [...A.cells]) {
121
+ const b = B.cells.get(key);
122
+ if (b && b[1] > a[0] + 0.2) return true;
123
+ }
75
124
  return false;
76
125
  }
77
126
 
78
127
  // A pair meant to overlap (a press fit) tells nothing about what stands in whose way
79
128
  const names = (x) => [x].flat().map(top);
80
129
  // (items printed together in place come off the bed together: nothing takes them apart from each other)
81
- const together = (s, a, b) => Array.isArray(s.a?.printInPlace) && s.a.printInPlace.includes(a.id) && s.a.printInPlace.includes(b.id);
82
- const allowedPair = (s, a, b) => together(s, a, b) || s.fits.some((x) => x.min != null && x.num(x.min) < 0 && ((names(x.a).includes(a.id) && names(x.b).includes(b.id)) || (names(x.a).includes(b.id) && names(x.b).includes(a.id))));
130
+ const together = (s, a, b) =>
131
+ Array.isArray(s.a?.printInPlace) && s.a.printInPlace.includes(a.id) && s.a.printInPlace.includes(b.id);
132
+ const allowedPair = (s, a, b) =>
133
+ together(s, a, b) ||
134
+ s.fits.some(
135
+ (x) =>
136
+ x.min != null &&
137
+ x.num(x.min) < 0 &&
138
+ ((names(x.a).includes(a.id) && names(x.b).includes(b.id)) ||
139
+ (names(x.a).includes(b.id) && names(x.b).includes(a.id))),
140
+ );
83
141
 
84
142
  function hitsAlong(origin, dir, tris) {
85
143
  for (const t of tris) {
86
- const e1 = [t[1][0] - t[0][0], t[1][1] - t[0][1], t[1][2] - t[0][2]], e2 = [t[2][0] - t[0][0], t[2][1] - t[0][1], t[2][2] - t[0][2]];
87
- const p = [dir[1] * e2[2] - dir[2] * e2[1], dir[2] * e2[0] - dir[0] * e2[2], dir[0] * e2[1] - dir[1] * e2[0]], det = dot(e1, p);
144
+ const e1 = [t[1][0] - t[0][0], t[1][1] - t[0][1], t[1][2] - t[0][2]],
145
+ e2 = [t[2][0] - t[0][0], t[2][1] - t[0][1], t[2][2] - t[0][2]];
146
+ const p = [dir[1] * e2[2] - dir[2] * e2[1], dir[2] * e2[0] - dir[0] * e2[2], dir[0] * e2[1] - dir[1] * e2[0]],
147
+ det = dot(e1, p);
88
148
  if (Math.abs(det) < 1e-12) continue;
89
- const s = [origin[0] - t[0][0], origin[1] - t[0][1], origin[2] - t[0][2]], u = dot(s, p) / det;
149
+ const s = [origin[0] - t[0][0], origin[1] - t[0][1], origin[2] - t[0][2]],
150
+ u = dot(s, p) / det;
90
151
  if (u < 0 || u > 1) continue;
91
- const q = [s[1] * e1[2] - s[2] * e1[1], s[2] * e1[0] - s[0] * e1[2], s[0] * e1[1] - s[1] * e1[0]], v = dot(dir, q) / det;
152
+ const q = [s[1] * e1[2] - s[2] * e1[1], s[2] * e1[0] - s[0] * e1[2], s[0] * e1[1] - s[1] * e1[0]],
153
+ v = dot(dir, q) / det;
92
154
  if (v < 0 || u + v > 1) continue;
93
155
  if (dot(e2, q) / det > 0.05) return true;
94
156
  }
@@ -102,161 +164,461 @@ function hitsAlong(origin, dir, tris) {
102
164
  * covers: each part that stands over a screw, which has to go on after the parts the screw joins
103
165
  */
104
166
  export function assemblyOrder(s) {
105
- const all = groups(s).filter((g) => g.bought || g.motor || g.parts.some((p) => p.role === 'part' || p.role == null) || s.fits.some((x) => [x.a, x.b].flat().some((n) => top(n) === g.id)));
167
+ const all = groups(s).filter(
168
+ (g) =>
169
+ g.bought ||
170
+ g.motor ||
171
+ g.parts.some((p) => p.role === 'part' || p.role == null) ||
172
+ s.fits.some((x) => [x.a, x.b].flat().some((n) => top(n) === g.id)),
173
+ );
106
174
  if (!all.length) return { steps: [], stuck: null };
107
- const by = new Map(all.map((g) => [g.id, g])), ids = all.map((g) => g.id), joints = s.motion.joints, items = s.motion.items.map((x) => x[0]);
175
+ const by = new Map(all.map((g) => [g.id, g])),
176
+ ids = all.map((g) => g.id),
177
+ joints = s.motion.joints,
178
+ items = s.motion.items.map((x) => x[0]);
108
179
  const bearing = (id) => by.get(id)?.bought?.part === 'bearing';
109
180
  // Items printed together in place (the assembly's printInPlace) come off the bed as one: one step, never taken apart
110
181
  const printSet = new Set(Array.isArray(s.a?.printInPlace) ? s.a.printInPlace.filter((id) => by.has(id)) : []);
111
182
  // How far each part is from the base along joints and fastenings: nearer goes first
112
- const links = new Map(ids.map((id) => [id, new Set()])), tie = (a, b) => { if (links.has(a) && links.has(b) && a !== b) { links.get(a).add(b); links.get(b).add(a); } };
183
+ const links = new Map(ids.map((id) => [id, new Set()])),
184
+ tie = (a, b) => {
185
+ if (links.has(a) && links.has(b) && a !== b) {
186
+ links.get(a).add(b);
187
+ links.get(b).add(a);
188
+ }
189
+ };
113
190
  const fastening = s.fits.filter((x) => x.fastens || x.seat != null || x.shaft != null || x.engage != null);
114
191
  for (const x of fastening) for (const a of [x.a].flat()) for (const b of [x.b].flat()) tie(top(a), top(b));
115
192
  for (const j of joints) if (j.parent >= 0) tie(items[j.parent], items[j.child]);
116
- const base = items.find((id) => by.has(id)) ?? ids[0], level = new Map([[base, 0]]);
117
- for (let queue = [base]; queue.length;) { const id = queue.shift(); for (const o of links.get(id)) if (!level.has(o)) { level.set(o, level.get(id) + 1); queue.push(o); } }
193
+ const base = items.find((id) => by.has(id)) ?? ids[0],
194
+ level = new Map([[base, 0]]);
195
+ for (let queue = [base]; queue.length;) {
196
+ const id = queue.shift();
197
+ for (const o of links.get(id))
198
+ if (!level.has(o)) {
199
+ level.set(o, level.get(id) + 1);
200
+ queue.push(o);
201
+ }
202
+ }
118
203
  const lv = (id) => level.get(id) ?? 1e6;
119
- const rank = (id) => [lv(id), by.get(id).order], earlier = (a, b) => { const [x, y] = [rank(a), rank(b)]; return x[0] - y[0] || x[1] - y[1]; };
204
+ const rank = (id) => [lv(id), by.get(id).order],
205
+ earlier = (a, b) => {
206
+ const [x, y] = [rank(a), rank(b)];
207
+ return x[0] - y[0] || x[1] - y[1];
208
+ };
120
209
  // Constraints: [u, v, why]: u before v
121
- const before = new Map(ids.map((id) => [id, new Map()])), add = (u, v, why) => { if (by.has(u) && by.has(v) && u !== v) before.get(u).set(v, why); };
122
- for (const j of joints) if (j.parent >= 0) add(items[j.parent], items[j.child], `${items[j.child]} turns on ${items[j.parent]}`);
123
- for (const x of fastening) for (const A of [x.a].flat()) for (const B of [x.b].flat()) {
124
- const a = top(A), b = top(B), [u, v] = earlier(a, b) <= 0 ? [a, b] : [b, a];
125
- if (x.seat != null && (bearing(a) || bearing(b))) { const [h, r] = bearing(a) ? [b, a] : [a, b]; add(h, r, `${r} is pressed into ${h}`); continue; }
126
- if ((x.shaft != null || x.engage != null) && (bearing(a) || bearing(b))) { const [r, shaft] = bearing(a) ? [a, b] : [b, a]; add(r, shaft, `${r} goes in before ${shaft}`); continue; }
127
- // (a part placed on another, as a fitting at a beam's address is, goes on after it: its joint says so, and a fastening
128
- // between the two does not turn that round, however far each is from the base)
129
- if (x.fastens && !before.get(v)?.has(u)) add(u, v, x.note || `${v} fastens to ${u}`);
130
- }
210
+ const before = new Map(ids.map((id) => [id, new Map()])),
211
+ add = (u, v, why) => {
212
+ if (by.has(u) && by.has(v) && u !== v) before.get(u).set(v, why);
213
+ };
214
+ for (const j of joints)
215
+ if (j.parent >= 0) add(items[j.parent], items[j.child], `${items[j.child]} turns on ${items[j.parent]}`);
216
+ for (const x of fastening)
217
+ for (const A of [x.a].flat())
218
+ for (const B of [x.b].flat()) {
219
+ const a = top(A),
220
+ b = top(B),
221
+ [u, v] = earlier(a, b) <= 0 ? [a, b] : [b, a];
222
+ if (x.seat != null && (bearing(a) || bearing(b))) {
223
+ const [h, r] = bearing(a) ? [b, a] : [a, b];
224
+ add(h, r, `${r} is pressed into ${h}`);
225
+ continue;
226
+ }
227
+ if ((x.shaft != null || x.engage != null) && (bearing(a) || bearing(b))) {
228
+ const [r, shaft] = bearing(a) ? [a, b] : [b, a];
229
+ add(r, shaft, `${r} goes in before ${shaft}`);
230
+ continue;
231
+ }
232
+ // (a part placed on another, as a fitting at a beam's address is, goes on after it: its joint says so, and a fastening
233
+ // between the two does not turn that round, however far each is from the base)
234
+ if (x.fastens && !before.get(v)?.has(u)) add(u, v, x.note || `${v} fastens to ${u}`);
235
+ }
131
236
  // Screws: what stands on the tool's line goes on after the screw, and if it must already be there, nothing can
132
- const worlds = placeItems(s.motion, s.jointValues), marks = s.motion.marks, reaches = (u, v, seen = new Set()) => { if (u === v) return true; if (seen.has(u)) return false; seen.add(u); return [...before.get(u).keys()].some((w) => reaches(w, v, seen)); };
133
- const R = 1.5, bad = [], covers = []; // (covers: what stands over a screw, kept so another order of the same parts, a frame's build, can be held to it)
237
+ const worlds = placeItems(s.motion, s.jointValues),
238
+ marks = s.motion.marks,
239
+ reaches = (u, v, seen = new Set()) => {
240
+ if (u === v) return true;
241
+ if (seen.has(u)) return false;
242
+ seen.add(u);
243
+ return [...before.get(u).keys()].some((w) => reaches(w, v, seen));
244
+ };
245
+ const R = 1.5,
246
+ bad = [],
247
+ covers = []; // (covers: what stands over a screw, kept so another order of the same parts, a frame's build, can be held to it)
134
248
  for (const x of s.fits.filter((f) => f.access)) {
135
- const [id, name] = String(x.access).split('.'), m = marks.find((k) => k.id === id && k.name === name) ?? (s.items.find((i) => i.id === id)?.beam ? s.motion.address(String(x.access), 'access') : null); // (a beam's address: x1.top@120)
136
- if (!m) throw new Error(`fit ${x.note || `${x.a} / ${x.b}`}: access: no anchor "${x.access}" (give <item>.<anchor>${items.includes(id) ? `; ${id} has ${marks.filter((k) => k.id === id).map((k) => k.name).join(', ') || 'none'}` : ''})`);
137
- const W = mul(worlds[m.item], m.frame), O = [W[3], W[7], W[11]], D = [W[2], W[6], W[10]], [u, v] = basis(D), starts = [[0, 0], [R, 0], [-R, 0], [0, R], [0, -R]].map(([a, b]) => O.map((c, k) => c + a * u[k] + b * v[k]));
138
- const screwed = [top(x.a), top(x.b)].filter((t) => by.has(t)), later = [...screwed].sort(earlier).at(-1);
249
+ const [id, name] = String(x.access).split('.'),
250
+ m =
251
+ marks.find((k) => k.id === id && k.name === name) ??
252
+ (s.items.find((i) => i.id === id)?.beam ? s.motion.address(String(x.access), 'access') : null); // (a beam's address: x1.top@120)
253
+ if (!m)
254
+ throw new Error(
255
+ `fit ${x.note || `${x.a} / ${x.b}`}: access: no anchor "${x.access}" (give <item>.<anchor>${
256
+ items.includes(id)
257
+ ? `; ${id} has ${
258
+ marks
259
+ .filter((k) => k.id === id)
260
+ .map((k) => k.name)
261
+ .join(', ') || 'none'
262
+ }`
263
+ : ''
264
+ })`,
265
+ );
266
+ const W = mul(worlds[m.item], m.frame),
267
+ O = [W[3], W[7], W[11]],
268
+ D = [W[2], W[6], W[10]],
269
+ [u, v] = basis(D),
270
+ starts = [
271
+ [0, 0],
272
+ [R, 0],
273
+ [-R, 0],
274
+ [0, R],
275
+ [0, -R],
276
+ ].map(([a, b]) => O.map((c, k) => c + a * u[k] + b * v[k]));
277
+ const screwed = [top(x.a), top(x.b)].filter((t) => by.has(t)),
278
+ later = [...screwed].sort(earlier).at(-1);
139
279
  for (const q of all) {
140
280
  if (screwed.includes(q.id) || !starts.some((p) => hitsAlong(p, D, q.tris))) continue;
141
281
  if (later && reaches(q.id, later)) bad.push({ fit: x, wall: q.id, at: O, later });
142
- else if (later) { add(later, q.id, `${q.id} covers the screw of ${x.note || later}`); covers.push({ fit: x.note || `${x.a} to ${x.b}`, screwed, wall: q.id }); }
282
+ else if (later) {
283
+ add(later, q.id, `${q.id} covers the screw of ${x.note || later}`);
284
+ covers.push({ fit: x.note || `${x.a} to ${x.b}`, screwed, wall: q.id });
285
+ }
143
286
  }
144
287
  }
145
288
  // A fasten's screws (lib/fasten.mjs): what stands over a head goes on after the parts the screw joins. A part that
146
289
  // must be there first (it comes before them, it is one of them, or it is no step at all) closes the way, unless a
147
290
  // ball-end key reaches the head tilted
148
- for (const rel of s.fastened?.relations ?? []) for (const sc of rel.screws) {
149
- const acc = sc.access; if (!acc?.blockers?.length) continue;
150
- const screwed = [...rel.through, rel.into].map(top).filter((t) => by.has(t)), later = [...screwed].sort(earlier).at(-1), walls = [...new Set(acc.blockers.map((b) => b.item))];
151
- const first = walls.filter((q) => !by.has(q) || screwed.includes(q) || (later && reaches(q, later)));
152
- if (first.length) { if (acc.tilt == null) bad.push({ fit: { note: rel.label }, wall: first[0], at: acc.top, later, fasten: rel.index, screw: sc.index, member: screwed.includes(first[0]), fixed: !by.has(first[0]) }); continue; }
153
- for (const q of walls) { add(later, q, `${q} covers the screws of ${rel.label}`); covers.push({ fasten: rel.index, fit: rel.label, screwed, wall: q }); }
154
- }
291
+ for (const rel of s.fastened?.relations ?? [])
292
+ for (const sc of rel.screws) {
293
+ const acc = sc.access;
294
+ if (!acc?.blockers?.length) continue;
295
+ const screwed = [...rel.through, rel.into].map(top).filter((t) => by.has(t)),
296
+ later = [...screwed].sort(earlier).at(-1),
297
+ walls = [...new Set(acc.blockers.map((b) => b.item))];
298
+ const first = walls.filter((q) => !by.has(q) || screwed.includes(q) || (later && reaches(q, later)));
299
+ if (first.length) {
300
+ if (acc.tilt == null)
301
+ bad.push({
302
+ fit: { note: rel.label },
303
+ wall: first[0],
304
+ at: acc.top,
305
+ later,
306
+ fasten: rel.index,
307
+ screw: sc.index,
308
+ member: screwed.includes(first[0]),
309
+ fixed: !by.has(first[0]),
310
+ });
311
+ continue;
312
+ }
313
+ for (const q of walls) {
314
+ add(later, q, `${q} covers the screws of ${rel.label}`);
315
+ covers.push({ fasten: rel.index, fit: rel.label, screwed, wall: q });
316
+ }
317
+ }
155
318
  // (the middle of a part's box, by a loop: spreading a big part's hundreds of thousands of corners into Math.min runs out of stack)
156
- const box = (g) => { const lo = [Infinity, Infinity, Infinity], hi = [-Infinity, -Infinity, -Infinity]; for (const t of g.tris) for (const x of t) for (let k = 0; k < 3; k++) { if (x[k] < lo[k]) lo[k] = x[k]; if (x[k] > hi[k]) hi[k] = x[k]; } return [0, 1, 2].map((k) => (lo[k] + hi[k]) / 2); };
319
+ const box = (g) => {
320
+ const lo = [Infinity, Infinity, Infinity],
321
+ hi = [-Infinity, -Infinity, -Infinity];
322
+ for (const t of g.tris)
323
+ for (const x of t)
324
+ for (let k = 0; k < 3; k++) {
325
+ if (x[k] < lo[k]) lo[k] = x[k];
326
+ if (x[k] > hi[k]) hi[k] = x[k];
327
+ }
328
+ return [0, 1, 2].map((k) => (lo[k] + hi[k]) / 2);
329
+ };
157
330
  if (bad.length) {
158
- const b = bad[0], label = b.fit.note || `${b.fit.a} to ${b.fit.b}`, why = b.member ? 'it is one of the parts the screw joins' : b.fixed ? 'it is in place before anything is fitted' : `goes on first (${[...before.get(b.wall)].slice(0, 1).map(([, w]) => w)})`;
159
- return { steps: [], stuck: { item: b.later, screw: label, wall: b.wall, at: b.at, ...(b.fasten != null ? { fasten: b.fasten, screws: bad.filter((x) => x.fasten === b.fasten).map((x) => x.screw) } : {}),
160
- text: `the screw of "${label}" can't be reached in any order: ${b.wall} stands over it${b.member || b.fixed ? `, and ${why}` : ` and ${why}`}` } };
331
+ const b = bad[0],
332
+ label = b.fit.note || `${b.fit.a} to ${b.fit.b}`,
333
+ why = b.member
334
+ ? 'it is one of the parts the screw joins'
335
+ : b.fixed
336
+ ? 'it is in place before anything is fitted'
337
+ : `goes on first (${[...before.get(b.wall)].slice(0, 1).map(([, w]) => w)})`;
338
+ return {
339
+ steps: [],
340
+ stuck: {
341
+ item: b.later,
342
+ screw: label,
343
+ wall: b.wall,
344
+ at: b.at,
345
+ ...(b.fasten != null
346
+ ? { fasten: b.fasten, screws: bad.filter((x) => x.fasten === b.fasten).map((x) => x.screw) }
347
+ : {}),
348
+ text: `the screw of "${label}" can't be reached in any order: ${b.wall} stands over it${b.member || b.fixed ? `, and ${why}` : ` and ${why}`}`,
349
+ },
350
+ };
161
351
  }
162
352
  let span = 1;
163
- for (const g of all) for (const t of g.tris) for (const p of t) for (const c of p) span = Math.max(span, Math.abs(c) * 2);
164
- const h = Math.max(0.4, Math.min(1.5, span / 300)), memo = new Map(), rasterOf = (g, d) => { const key = `${g.id}|${d.join(',')}`; if (!memo.has(key)) memo.set(key, raster(g, d, h)); return memo.get(key); };
165
- const free = (p, rest, d) => { for (const q of rest) if (q !== p && !allowedPair(s, p, q) && blockers(p, q, d, h, rasterOf)) return false; return true; };
166
- const dirsFor = (p) => { // along its own axes first: a part on a joint goes on along that joint, then from above, then round the sides
353
+ for (const g of all)
354
+ for (const t of g.tris) for (const p of t) for (const c of p) span = Math.max(span, Math.abs(c) * 2);
355
+ const h = Math.max(0.4, Math.min(1.5, span / 300)),
356
+ memo = new Map(),
357
+ rasterOf = (g, d) => {
358
+ const key = `${g.id}|${d.join(',')}`;
359
+ if (!memo.has(key)) memo.set(key, raster(g, d, h));
360
+ return memo.get(key);
361
+ };
362
+ const free = (p, rest, d) => {
363
+ for (const q of rest) if (q !== p && !allowedPair(s, p, q) && blockers(p, q, d, h, rasterOf)) return false;
364
+ return true;
365
+ };
366
+ const dirsFor = (p) => {
367
+ // along its own axes first: a part on a joint goes on along that joint, then from above, then round the sides
167
368
  const own = [];
168
- for (const j of joints) if (items[j.child] === p.id) { const P = j.parent < 0 ? j.a : mul(worlds[j.parent], j.a); own.push([P[2], P[6], P[10]]); }
169
- for (const m of marks) if (m.id === p.id) { const W = mul(worlds[m.item], m.frame); own.push([W[2], W[6], W[10]]); }
369
+ for (const j of joints)
370
+ if (items[j.child] === p.id) {
371
+ const P = j.parent < 0 ? j.a : mul(worlds[j.parent], j.a);
372
+ own.push([P[2], P[6], P[10]]);
373
+ }
374
+ for (const m of marks)
375
+ if (m.id === p.id) {
376
+ const W = mul(worlds[m.item], m.frame);
377
+ own.push([W[2], W[6], W[10]]);
378
+ }
170
379
  const list = [...own.flatMap((a) => [round(a), round(a.map((x) => -x))]), ...SIDES];
171
380
  return [...new Map(list.map((d) => [d.map((x) => x.toFixed(3)).join(','), d])).values()];
172
381
  };
173
382
  // What stays together if a part can't leave alone: its joint parent and all that hangs from it (planets on their carrier)
174
- const below = (a) => { const out = new Set([a]); for (let grew = true; grew;) { grew = false; for (const j of joints) if (j.parent >= 0 && out.has(items[j.parent]) && by.has(items[j.child]) && !out.has(items[j.child])) { out.add(items[j.child]); grew = true; } } return out; };
175
- const parentOf = (id) => { const j = joints.find((x) => items[x.child] === id); return j && j.parent >= 0 ? items[j.parent] : null; };
383
+ const below = (a) => {
384
+ const out = new Set([a]);
385
+ for (let grew = true; grew;) {
386
+ grew = false;
387
+ for (const j of joints)
388
+ if (j.parent >= 0 && out.has(items[j.parent]) && by.has(items[j.child]) && !out.has(items[j.child])) {
389
+ out.add(items[j.child]);
390
+ grew = true;
391
+ }
392
+ }
393
+ return out;
394
+ };
395
+ const parentOf = (id) => {
396
+ const j = joints.find((x) => items[x.child] === id);
397
+ return j && j.parent >= 0 ? items[j.parent] : null;
398
+ };
176
399
  // Take a set of parts apart, the last-attached first: [{ p, d }] or [{ group, d, sub }] (a set that leaves as one, then apart)
177
400
  function takeApart(start) {
178
401
  let rest = [...start].sort((a, b) => earlier(b.id, a.id));
179
- const off = [], waits = (p, set) => [...before.get(p.id).keys()].some((v) => set.some((q) => q.id === v));
402
+ const off = [],
403
+ waits = (p, set) => [...before.get(p.id).keys()].some((v) => set.some((q) => q.id === v));
180
404
  while (rest.length) {
181
405
  let pick = null;
182
406
  for (const p of rest) {
183
- if (printSet.has(p.id) && printSet.size > 1) { // (the whole print, or nothing of it)
184
- const group = [...printSet].map((id) => rest.find((q) => q.id === id)).filter(Boolean), others = rest.filter((q) => !printSet.has(q.id));
407
+ if (printSet.has(p.id) && printSet.size > 1) {
408
+ // (the whole print, or nothing of it)
409
+ const group = [...printSet].map((id) => rest.find((q) => q.id === id)).filter(Boolean),
410
+ others = rest.filter((q) => !printSet.has(q.id));
185
411
  if (group.some((q) => waits(q, others))) continue;
186
- if (!others.length) { pick = { group, d: [0, 0, 1], sub: { off: [] }, print: true }; break; }
187
- const d = dirsFor(p).find((x) => group.every((q) => others.every((o) => allowedPair(s, q, o) || !blockers(q, o, x, h, rasterOf))));
188
- if (d) { pick = { group, d, sub: { off: [] }, print: true }; break; }
412
+ if (!others.length) {
413
+ pick = { group, d: [0, 0, 1], sub: { off: [] }, print: true };
414
+ break;
415
+ }
416
+ const d = dirsFor(p).find((x) =>
417
+ group.every((q) => others.every((o) => allowedPair(s, q, o) || !blockers(q, o, x, h, rasterOf))),
418
+ );
419
+ if (d) {
420
+ pick = { group, d, sub: { off: [] }, print: true };
421
+ break;
422
+ }
189
423
  continue;
190
424
  }
191
425
  if (waits(p, rest)) continue;
192
- if (rest.length === 1) { pick = { p, d: [0, 0, 1] }; break; }
426
+ if (rest.length === 1) {
427
+ pick = { p, d: [0, 0, 1] };
428
+ break;
429
+ }
193
430
  const d = dirsFor(p).find((x) => free(p, rest, x));
194
- if (d) { pick = { p, d }; break; }
195
- }
196
- if (!pick) for (const p of rest) { // nothing leaves alone: try what's joined to it, as one
197
- for (let a = parentOf(p.id); a && a !== base && rest.some((q) => q.id === a) && !pick; a = parentOf(a)) {
198
- const names = below(a), group = rest.filter((q) => names.has(q.id)), others = rest.filter((q) => !names.has(q.id));
199
- if (group.length < 2 || !others.length || group.length === rest.length || group.some((q) => waits(q, others))) continue;
200
- const d = dirsFor(by.get(a)).find((x) => group.every((q) => others.every((o) => allowedPair(s, q, o) || !blockers(q, o, x, h, rasterOf))));
201
- if (d) { const sub = takeApart(group); if (sub.stuck) return sub; pick = { group, d, sub }; }
431
+ if (d) {
432
+ pick = { p, d };
433
+ break;
202
434
  }
203
- if (pick) break;
204
435
  }
436
+ if (!pick)
437
+ for (const p of rest) {
438
+ // nothing leaves alone: try what's joined to it, as one
439
+ for (let a = parentOf(p.id); a && a !== base && rest.some((q) => q.id === a) && !pick; a = parentOf(a)) {
440
+ const names = below(a),
441
+ group = rest.filter((q) => names.has(q.id)),
442
+ others = rest.filter((q) => !names.has(q.id));
443
+ if (
444
+ group.length < 2 ||
445
+ !others.length ||
446
+ group.length === rest.length ||
447
+ group.some((q) => waits(q, others))
448
+ )
449
+ continue;
450
+ const d = dirsFor(by.get(a)).find((x) =>
451
+ group.every((q) => others.every((o) => allowedPair(s, q, o) || !blockers(q, o, x, h, rasterOf))),
452
+ );
453
+ if (d) {
454
+ const sub = takeApart(group);
455
+ if (sub.stuck) return sub;
456
+ pick = { group, d, sub };
457
+ }
458
+ }
459
+ if (pick) break;
460
+ }
205
461
  if (!pick) {
206
462
  const stuckBy = rest.filter((p) => !waits(p, rest))[0] ?? rest[0];
207
- const holders = [...new Set(SIDES.flatMap((d) => rest.filter((q) => q !== stuckBy && !allowedPair(s, stuckBy, q) && blockers(stuckBy, q, d, h, rasterOf)).map((q) => q.id)))];
463
+ const holders = [
464
+ ...new Set(
465
+ SIDES.flatMap((d) =>
466
+ rest
467
+ .filter((q) => q !== stuckBy && !allowedPair(s, stuckBy, q) && blockers(stuckBy, q, d, h, rasterOf))
468
+ .map((q) => q.id),
469
+ ),
470
+ ),
471
+ ];
208
472
  const ringed = rest.filter((p) => waits(p, rest)).map((p) => p.id);
209
- return { stuck: { item: stuckBy.id, wall: holders[0] ?? null, holders, at: box(stuckBy), text: holders.length ? `${stuckBy.id} can't be reached in any order: ${holders.join(' and ')} ${holders.length > 1 ? 'hold' : 'holds'} it in from every side` : `${ringed.join(', ')} each have to go on before the next, in a ring` } };
473
+ return {
474
+ stuck: {
475
+ item: stuckBy.id,
476
+ wall: holders[0] ?? null,
477
+ holders,
478
+ at: box(stuckBy),
479
+ text: holders.length
480
+ ? `${stuckBy.id} can't be reached in any order: ${holders.join(' and ')} ${holders.length > 1 ? 'hold' : 'holds'} it in from every side`
481
+ : `${ringed.join(', ')} each have to go on before the next, in a ring`,
482
+ },
483
+ };
210
484
  }
211
- off.push(pick); const gone = pick.group ?? [pick.p]; rest = rest.filter((g) => !gone.includes(g));
485
+ off.push(pick);
486
+ const gone = pick.group ?? [pick.p];
487
+ rest = rest.filter((g) => !gone.includes(g));
212
488
  }
213
489
  return { off };
214
490
  }
215
491
  const apart = takeApart(all);
216
492
  if (apart.stuck) return { steps: [], stuck: apart.stuck };
217
493
  // Put together: last off is first on, a set built up on its own and then fitted as one
218
- const seq = [], lay = (off) => { for (const x of [...off].reverse()) { if (x.group) { lay(x.sub.off); seq.push({ group: x.group, d: x.d, ...(x.print ? { print: true } : {}) }); } else seq.push(x); } };
494
+ const seq = [],
495
+ lay = (off) => {
496
+ for (const x of [...off].reverse()) {
497
+ if (x.group) {
498
+ lay(x.sub.off);
499
+ seq.push({ group: x.group, d: x.d, ...(x.print ? { print: true } : {}) });
500
+ } else seq.push(x);
501
+ }
502
+ };
219
503
  lay(apart.off);
220
- const at = new Map(), steps = [];
504
+ const at = new Map(),
505
+ steps = [];
221
506
  // a motor's mounting screws, on the fit that fastens it (motorScrews): counted, with the tool that turns them
222
- const motorFits = new Map(motorScrews(s, { placeItems, jointValues }).map((m) => [m.fit, { fastener: m.name, count: m.count, ...(m.tool ? { key: m.tool } : {}) }]));
223
- seq.forEach((x, i) => { for (const g of x.group ?? [x.p]) at.set(g.id, i); });
507
+ const motorFits = new Map(
508
+ motorScrews(s, { placeItems, jointValues }).map((m) => [
509
+ m.fit,
510
+ { fastener: m.name, count: m.count, ...(m.tool ? { key: m.tool } : {}) },
511
+ ]),
512
+ );
513
+ seq.forEach((x, i) => {
514
+ for (const g of x.group ?? [x.p]) at.set(g.id, i);
515
+ });
224
516
  for (const [i, x] of seq.entries()) {
225
- if (x.group) { steps.push({ items: x.group.map((g) => g.id), object: null, dir: round(x.d), fasteners: [], together: true, ...(x.print ? { printed: true } : {}) }); continue; }
226
- const { p, d } = x, list = [...new Set(s.fits.filter((f) => [...names(f.a), ...names(f.b)].includes(p.id) && (f.fastens || f.seat != null || f.fastener) && [...names(f.a), ...names(f.b)].every((n) => (at.get(n) ?? 0) <= i)))];
227
- steps.push({ items: [p.id], object: p.object, dir: round(d), fasteners: list.map((f) => ({ fit: f.note || f.label || `${f.a} to ${f.b}`, ...(f.fastener ? { fastener: f.fastener } : {}), ...(f.count != null ? { count: f.num(f.count) } : {}), ...(f.key ? { key: f.key } : {}), ...(f.tighten ? { tighten: f.tighten } : {}), ...(!f.fastener ? motorFits.get(f) : {}) })) });
517
+ if (x.group) {
518
+ steps.push({
519
+ items: x.group.map((g) => g.id),
520
+ object: null,
521
+ dir: round(x.d),
522
+ fasteners: [],
523
+ together: true,
524
+ ...(x.print ? { printed: true } : {}),
525
+ });
526
+ continue;
527
+ }
528
+ const { p, d } = x,
529
+ list = [
530
+ ...new Set(
531
+ s.fits.filter(
532
+ (f) =>
533
+ [...names(f.a), ...names(f.b)].includes(p.id) &&
534
+ (f.fastens || f.seat != null || f.fastener) &&
535
+ [...names(f.a), ...names(f.b)].every((n) => (at.get(n) ?? 0) <= i),
536
+ ),
537
+ ),
538
+ ];
539
+ steps.push({
540
+ items: [p.id],
541
+ object: p.object,
542
+ dir: round(d),
543
+ fasteners: list.map((f) => ({
544
+ fit: f.note || f.label || `${f.a} to ${f.b}`,
545
+ ...(f.fastener ? { fastener: f.fastener } : {}),
546
+ ...(f.count != null ? { count: f.num(f.count) } : {}),
547
+ ...(f.key ? { key: f.key } : {}),
548
+ ...(f.tighten ? { tighten: f.tighten } : {}),
549
+ ...(!f.fastener ? motorFits.get(f) : {}),
550
+ })),
551
+ });
228
552
  }
229
553
  // Copies of one thing fitted the same way, one after another, are one step
230
554
  const merged = [];
231
555
  for (const st of steps) {
232
556
  const last = merged.at(-1);
233
- if (last && st.object && !st.together && last.object === st.object && last.dir.join() === st.dir.join() && JSON.stringify(last.fasteners.map((f) => f.fit)) === JSON.stringify(st.fasteners.map((f) => f.fit))) last.items.push(...st.items);
234
- else merged.push({ items: [...st.items], object: st.object, dir: st.dir, fasteners: st.fasteners, ...(st.together ? { together: true } : {}), ...(st.printed ? { printed: true } : {}) });
557
+ if (
558
+ last &&
559
+ st.object &&
560
+ !st.together &&
561
+ last.object === st.object &&
562
+ last.dir.join() === st.dir.join() &&
563
+ JSON.stringify(last.fasteners.map((f) => f.fit)) === JSON.stringify(st.fasteners.map((f) => f.fit))
564
+ )
565
+ last.items.push(...st.items);
566
+ else
567
+ merged.push({
568
+ items: [...st.items],
569
+ object: st.object,
570
+ dir: st.dir,
571
+ fasteners: st.fasteners,
572
+ ...(st.together ? { together: true } : {}),
573
+ ...(st.printed ? { printed: true } : {}),
574
+ });
235
575
  }
236
- merged.forEach((st, i) => { st.n = i + 1; st.text = `${st.items.join(', ')}${st.object && !st.items.includes(st.object) ? ` (${st.object})` : ''}${st.printed ? `, printed together in place (one print)${i ? ', go on as one' : ', first'}` : st.together ? ' go on as one' : i ? ` goes on${st.items.length > 1 ? ', one by one' : ''}` : ' first'}${st.fasteners.length ? `: ${st.fasteners.map(fastenerText).join('; ')}` : ''}`; });
576
+ merged.forEach((st, i) => {
577
+ st.n = i + 1;
578
+ st.text = `${st.items.join(', ')}${st.object && !st.items.includes(st.object) ? ` (${st.object})` : ''}${st.printed ? `, printed together in place (one print)${i ? ', go on as one' : ', first'}` : st.together ? ' go on as one' : i ? ` goes on${st.items.length > 1 ? ', one by one' : ''}` : ' first'}${st.fasteners.length ? `: ${st.fasteners.map(fastenerText).join('; ')}` : ''}`;
579
+ });
237
580
  return { steps: merged, stuck: null, covers };
238
581
  }
239
582
 
240
583
  /** One fastening of a step as the order and the build page say it: the fit, its screws by count and name, the key and how tight. */
241
- export const fastenerText = (f) => `${f.fit}${f.fastener ? ` (${f.count != null ? `${f.count} × ` : ''}${f.fastener})` : ''}${f.key ? ` with ${/^[aeiou8]/i.test(f.key) ? 'an' : 'a'} ${f.key}` : ''}${f.tighten ? `, ${f.tighten.hand ? `to ${f.tighten.torque} N m and no further (a printed bolt, turned by hand, not tightened)` : f.tighten.given ? `to ${f.tighten.torque} N m` : f.tighten.load ? `to ${f.tighten.torque} N m (what the joint's load leaves the thread)` : f.tighten.thread ? `to ${f.tighten.torque} N m at most (half what the thread strips at)` : `to ${f.tighten.torque} N m at most (what the seat takes)`}` : ''}`;
584
+ export const fastenerText = (f) =>
585
+ `${f.fit}${f.fastener ? ` (${f.count != null ? `${f.count} × ` : ''}${f.fastener})` : ''}${f.key ? ` with ${/^[aeiou8]/i.test(f.key) ? 'an' : 'a'} ${f.key}` : ''}${f.tighten ? `, ${f.tighten.hand ? `to ${f.tighten.torque} N m and no further (a printed bolt, turned by hand, not tightened)` : f.tighten.given ? `to ${f.tighten.torque} N m` : f.tighten.load ? `to ${f.tighten.torque} N m (what the joint's load leaves the thread)` : f.tighten.thread ? `to ${f.tighten.torque} N m at most (half what the thread strips at)` : `to ${f.tighten.torque} N m at most (half what the seat takes)`}` : ''}`;
242
586
 
243
587
  // Cached by what the parts are and where they are, with everything else that changes the answer (a motor's screw
244
588
  // names the tool its step gives)
245
589
  function orderFile(s) {
246
- const key = crypto.createHash('sha256').update(JSON.stringify([9, s.a?.printInPlace ?? null, (s.a?.items || []).filter((x) => x.motor).map((x) => [x.id, x.motor.screw ?? null]), s.parts.map((p) => [p.item, p.hash ?? p.shape, Array.from(p.m ?? []).map((x) => +x.toFixed(4))]), s.fits.map(({ num, ...x }) => x), s.motion.joints.map((j) => [j.id, j.child, j.parent])])).digest('hex');
590
+ const key = crypto
591
+ .createHash('sha256')
592
+ .update(
593
+ JSON.stringify([
594
+ 9,
595
+ s.a?.printInPlace ?? null,
596
+ (s.a?.items || []).filter((x) => x.motor).map((x) => [x.id, x.motor.screw ?? null]),
597
+ s.parts.map((p) => [p.item, p.hash ?? p.shape, Array.from(p.m ?? []).map((x) => +x.toFixed(4))]),
598
+ s.fits.map(({ num, ...x }) => x),
599
+ s.motion.joints.map((j) => [j.id, j.child, j.parent]),
600
+ ]),
601
+ )
602
+ .digest('hex');
247
603
  return paths.cache('order', `${key}.json`);
248
604
  }
249
605
  export function orderOf(s) {
250
606
  if (s.orderSteps) return s.orderSteps;
251
607
  const file = orderFile(s);
252
- if (!process.env.CAD_NO_CACHE && host.exists(file)) return (s.orderSteps = JSON.parse(host.readText(file)));
608
+ if (!process.env.CAD_NO_CACHE && cached(file)) return (s.orderSteps = JSON.parse(host.readText(file)));
253
609
  const r = assemblyOrder(s);
254
- try { fs.mkdirSync(path.dirname(file), { recursive: true }); host.writeText(file, JSON.stringify(r)); } catch {} // (only slower without it)
610
+ try {
611
+ fs.mkdirSync(path.dirname(file), { recursive: true });
612
+ host.writeText(file, JSON.stringify(r));
613
+ } catch {
614
+ // (a cache that can't be written is only slower)
615
+ }
255
616
  return (s.orderSteps = r);
256
617
  }
257
618
 
258
619
  // Whether an assembly is something that goes together with fastenings: anything else has no steps to find
259
- export const isBuilt = (s) => s.a.kind !== 'plate' && s.fits.some((x) => x.fastens || x.seat != null || x.shaft != null || x.access);
620
+ export const isBuilt = (s) =>
621
+ s.a.kind !== 'plate' && s.fits.some((x) => x.fastens || x.seat != null || x.shaft != null || x.access);
260
622
 
261
623
  /**
262
624
  * assembly.order, in the assembly's findings shape. With a frame's build (frameBuild, for an assembly with joins) the
@@ -266,22 +628,67 @@ export const isBuilt = (s) => s.a.kind !== 'plate' && s.fits.some((x) => x.faste
266
628
  export function orderChecks(s, f, { frame = null } = {}) {
267
629
  if (!isBuilt(s) || (s.pose != null && s.pose !== s.motion.pose)) return;
268
630
  const r = orderOf(s);
269
- if (r.stuck) return f('fail', r.stuck.text, `${r.stuck.item}: can't be reached`, { code: 'assembly.order', at: r.stuck.at, refs: { item: r.stuck.item, ...(r.stuck.wall ? { wall: r.stuck.wall } : {}), ...(r.stuck.screw ? { screw: r.stuck.screw } : {}), ...(r.stuck.holders ? { holders: r.stuck.holders } : {}) } });
631
+ if (r.stuck)
632
+ return f('fail', r.stuck.text, `${r.stuck.item}: can't be reached`, {
633
+ code: 'assembly.order',
634
+ at: r.stuck.at,
635
+ refs: {
636
+ item: r.stuck.item,
637
+ ...(r.stuck.wall ? { wall: r.stuck.wall } : {}),
638
+ ...(r.stuck.screw ? { screw: r.stuck.screw } : {}),
639
+ ...(r.stuck.holders ? { holders: r.stuck.holders } : {}),
640
+ },
641
+ });
270
642
  const b = frame && s.joins?.length ? frame(s) : null;
271
- if (b?.stuck) return f('fail', `no build from bars to a square frame: ${b.stuck.text}`, `${b.stuck.item}: no build`, { code: 'assembly.order', refs: { item: b.stuck.item, ...(b.stuck.place ? { place: b.stuck.place } : {}), ...(b.stuck.joins ? { joins: b.stuck.joins } : {}) } });
272
- const n = b ? b.steps.length : r.steps.length, first = b ? b.steps.find((st) => st.now?.length)?.now[0] : r.steps[0]?.items[0];
273
- f('pass', `goes together in ${n} step${n === 1 ? '' : 's'}${b ? ' from bars to a square frame (cad order)' : ''}, ${first} first, nothing trapped`, null, { code: 'assembly.order', values: { steps: n }, refs: { first } });
643
+ if (b?.stuck)
644
+ return f('fail', `no build from bars to a square frame: ${b.stuck.text}`, `${b.stuck.item}: no build`, {
645
+ code: 'assembly.order',
646
+ refs: {
647
+ item: b.stuck.item,
648
+ ...(b.stuck.place ? { place: b.stuck.place } : {}),
649
+ ...(b.stuck.joins ? { joins: b.stuck.joins } : {}),
650
+ },
651
+ });
652
+ const n = b ? b.steps.length : r.steps.length,
653
+ first = b ? b.steps.find((st) => st.now?.length)?.now[0] : r.steps[0]?.items[0];
654
+ f(
655
+ 'pass',
656
+ `goes together in ${n} step${n === 1 ? '' : 's'}${b ? ' from bars to a square frame (cad order)' : ''}, ${first} first, nothing trapped`,
657
+ null,
658
+ { code: 'assembly.order', values: { steps: n }, refs: { first } },
659
+ );
274
660
  }
275
661
 
276
662
  /** Each step's picture: what's there, and the new part held off along the way it goes on. @returns {object[][]} parts lists, for preview() */
277
663
  export function stepPictures(s, r) {
278
664
  let off = 40;
279
- for (const p of s.parts) for (const t of p.triangles) for (const v of t) off = Math.max(off, Math.abs(v[0]), Math.abs(v[1]), Math.abs(v[2]));
665
+ for (const p of s.parts)
666
+ for (const t of p.triangles) for (const v of t) off = Math.max(off, Math.abs(v[0]), Math.abs(v[1]), Math.abs(v[2]));
280
667
  off *= 0.5;
281
668
  return r.steps.map((st, i) => {
282
- const shown = new Set(r.steps.slice(0, i + 1).flatMap((x) => x.items)), now = new Set(st.items);
283
- return s.parts.filter((p) => shown.has(p.item)).map((p) => (now.has(p.item) ? { ...p, role: 'part', triangles: p.triangles.map((t) => t.map((v) => v.map((c, k) => c + st.dir[k] * off))) } : { ...p, role: 'reference' }));
669
+ const shown = new Set(r.steps.slice(0, i + 1).flatMap((x) => x.items)),
670
+ now = new Set(st.items);
671
+ return s.parts
672
+ .filter((p) => shown.has(p.item))
673
+ .map((p) =>
674
+ now.has(p.item)
675
+ ? {
676
+ ...p,
677
+ role: 'part',
678
+ triangles: p.triangles.map((t) => t.map((v) => v.map((c, k) => c + st.dir[k] * off))),
679
+ }
680
+ : { ...p, role: 'reference' },
681
+ );
284
682
  });
285
683
  }
286
684
 
287
- export const orderText = (ref, r) => (r.stuck ? `${ref}: ${r.stuck.text}` : [`${ref}: how it goes together`, ...r.steps.flatMap((st) => [...(st.load || []).map((t) => ` first, ${t}`), ` ${String(st.n).padStart(2)}. ${st.text}`])].join('\n'));
685
+ export const orderText = (ref, r) =>
686
+ r.stuck
687
+ ? `${ref}: ${r.stuck.text}`
688
+ : [
689
+ `${ref}: how it goes together`,
690
+ ...r.steps.flatMap((st) => [
691
+ ...(st.load || []).map((t) => ` first, ${t}`),
692
+ ` ${String(st.n).padStart(2)}. ${st.text}`,
693
+ ]),
694
+ ].join('\n');