@rulecad/cad 0.8.0 → 0.10.0

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