@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/fasten.mjs CHANGED
@@ -10,7 +10,6 @@
10
10
  // workspace's rule sets and the project's printer, as v.fixings is. The screws, nuts, washers and inserts are placed
11
11
  // as reference parts (hardware, below): faint, checked for overlap, and carried into previews and links.
12
12
  import crypto from 'node:crypto';
13
- import path from 'node:path';
14
13
  import { fixingsFor, DEFAULTS, screwGroup, parseName, threads } from '@rulecad/fixings';
15
14
  import { placeItems, jointValues } from '@rulecad/model-link';
16
15
  import { massesOf } from './loads.mjs';
@@ -26,14 +25,20 @@ import { framesContext } from './beams.mjs';
26
25
  import { givenFor } from './frames.mjs';
27
26
 
28
27
  const { mat4, vec3 } = jscad.maths;
29
- const mm = (n) => String(Number(Number(n).toFixed(3))), r3 = (x) => +x.toFixed(3);
28
+ const mm = (n) => String(Number(Number(n).toFixed(3))),
29
+ r3 = (x) => +x.toFixed(3);
30
30
  // (lengths along a screw's stack, said to a hundredth: measured off drawn parts, a micron either way is the drawing's
31
31
  // grid, not the screw, and "1.999 mm under its head and 10.001 mm" reads as a fault)
32
32
  const mm2 = (n) => String(Number(Number(n).toFixed(2)));
33
- const dot = (a, b) => a[0] * b[0] + a[1] * b[1] + a[2] * b[2], add = (a, b, k = 1) => [a[0] + b[0] * k, a[1] + b[1] * k, a[2] + b[2] * k];
33
+ const dot = (a, b) => a[0] * b[0] + a[1] * b[1] + a[2] * b[2],
34
+ add = (a, b, k = 1) => [a[0] + b[0] * k, a[1] + b[1] * k, a[2] + b[2] * k];
34
35
  const cross = (a, b) => [a[1] * b[2] - a[2] * b[1], a[2] * b[0] - a[0] * b[2], a[0] * b[1] - a[1] * b[0]];
35
- const unit = (v) => { const l = Math.hypot(...v); return v.map((c) => c / l); };
36
- const fan = (poly) => (poly.length === 3 ? [poly] : poly.slice(1, -1).map((_, i) => [poly[0], poly[i + 1], poly[i + 2]]));
36
+ const unit = (v) => {
37
+ const l = Math.hypot(...v);
38
+ return v.map((c) => c / l);
39
+ };
40
+ const fan = (poly) =>
41
+ poly.length === 3 ? [poly] : poly.slice(1, -1).map((_, i) => [poly[0], poly[i + 1], poly[i + 2]]);
37
42
  const top = (n) => String(n).split(/[.@]/)[0];
38
43
  const EPS = 1e-4; // mm: under this, two lengths read from a mesh are the same
39
44
  const READ = 1e-3; // mm: a length read off a part cut by a boolean, whose corners are snapped to its grid, wanders by under this (a seat read 0.0002 mm off on a supply's mount); held against a maker's limit, it is within it
@@ -41,19 +46,89 @@ const an = (t) => (/^(?:[aeiou8]|M\d)/i.test(String(t)) ? 'an' : 'a'); // (an M3
41
46
 
42
47
  /** The working figures of the fasten checks that no rule set holds, each with what it rests on. */
43
48
  export const FASTEN = {
44
- align: { value: 0.05, unit: 'mm', rule: 'Holes share an axis when their centres lie this near it: the play of floating point and of a hole drawn in flats, far under any clearance', kind: 'default', source: 'A working figure of @rulecad/cad', checked: '2026-11-15' },
45
- size: { value: 0.06, unit: 'mm', rule: 'A hole as drawn is taken for a thread\'s pilot, tap, insert or clearance hole when its diameter is within this of that figure', kind: 'default', source: 'A working figure of @rulecad/cad: under the least step between two of a thread\'s holes (M2 tap 1.7 mm, pilot 1.9 mm)', checked: '2026-11-15' },
46
- proud: { value: 1, unit: '× diameter', rule: 'A screw\'s tip may stand up to its own diameter past its nut or the far face of what it is threaded through: more is a longer screw than the joint needs, and it catches', kind: 'default', source: 'A working figure of @rulecad/cad: no standard was found for it', checked: '2026-11-15' },
47
- floor: { value: 0.3, unit: 'mm', rule: 'A screw into a slot nut stops at least this far short of the slot\'s floor, so it tightens on its head and does not press on the beam\'s core: the play of a cut length and a nut\'s height, not a standard', kind: 'default', source: 'A working figure of @rulecad/cad', checked: '2026-11-16' },
48
- square: { value: 0.5, unit: '°', rule: 'A screw into a slot is square to the beam\'s face when its axis is within this of the face\'s normal, as a join\'s end is (JOIN_CHECK.square)', kind: 'default', source: 'A working figure of @rulecad/cad', checked: '2026-11-16' },
49
- countersink: { value: 2, unit: '°', rule: 'A countersink drawn in flat faces is taken for the head\'s angle when it is within this of it', kind: 'default', source: 'A working figure of @rulecad/cad', checked: '2026-11-15' },
49
+ align: {
50
+ value: 0.05,
51
+ unit: 'mm',
52
+ rule: 'Holes share an axis when their centres lie this near it: the play of floating point and of a hole drawn in flats, far under any clearance',
53
+ kind: 'default',
54
+ source: 'A working figure of @rulecad/cad',
55
+ checked: '2026-11-15',
56
+ },
57
+ size: {
58
+ value: 0.06,
59
+ unit: 'mm',
60
+ rule: "A hole as drawn is taken for a thread's pilot, tap, insert or clearance hole when its diameter is within this of that figure",
61
+ kind: 'default',
62
+ source:
63
+ "A working figure of @rulecad/cad: under the least step between two of a thread's holes (M2 tap 1.7 mm, pilot 1.9 mm)",
64
+ checked: '2026-11-15',
65
+ },
66
+ proud: {
67
+ value: 1,
68
+ unit: '× diameter',
69
+ rule: "A screw's tip may stand up to its own diameter past its nut or the far face of what it is threaded through: more is a longer screw than the joint needs, and it catches",
70
+ kind: 'default',
71
+ source: 'A working figure of @rulecad/cad: no standard was found for it',
72
+ checked: '2026-11-15',
73
+ },
74
+ floor: {
75
+ value: 0.3,
76
+ unit: 'mm',
77
+ rule: "A screw into a slot nut stops at least this far short of the slot's floor, so it tightens on its head and does not press on the beam's core: the play of a cut length and a nut's height, not a standard",
78
+ kind: 'default',
79
+ source: 'A working figure of @rulecad/cad',
80
+ checked: '2026-11-16',
81
+ },
82
+ square: {
83
+ value: 0.5,
84
+ unit: '°',
85
+ rule: "A screw into a slot is square to the beam's face when its axis is within this of the face's normal, as a join's end is (JOIN_CHECK.square)",
86
+ kind: 'default',
87
+ source: 'A working figure of @rulecad/cad',
88
+ checked: '2026-11-16',
89
+ },
90
+ stack: {
91
+ value: 0.05,
92
+ unit: 'mm',
93
+ rule: 'Two parts a screw holds lie face to face along it when the far face of one is within this of the near face of the next: more is air the screw is lengthened across, and the parts are not clamped',
94
+ kind: 'default',
95
+ source: 'A working figure of @rulecad/cad: the closest gap a fit of parts that touch is given (0 to 0.05 mm)',
96
+ checked: '2026-11-29',
97
+ },
98
+ wall: {
99
+ value: 0.05,
100
+ unit: 'mm',
101
+ rule: "The plastic round a fasten's far hole is taken as the wall its rule asks when it is within this of it: the play of a hole and a boss drawn in flats",
102
+ kind: 'default',
103
+ source: 'A working figure of @rulecad/cad',
104
+ checked: '2026-11-29',
105
+ },
106
+ countersink: {
107
+ value: 2,
108
+ unit: '°',
109
+ rule: "A countersink drawn in flat faces is taken for the head's angle when it is within this of it",
110
+ kind: 'default',
111
+ source: 'A working figure of @rulecad/cad',
112
+ checked: '2026-11-15',
113
+ },
50
114
  };
51
115
 
52
116
  // ---------- a part measured along an axis ----------
53
117
  // Coordinates about an axis: z along it from O, x and y across it
54
118
  function frameOf(O, D) {
55
- const z = unit(D), seed = Math.abs(z[0]) < 0.9 ? [1, 0, 0] : [0, 1, 0], x = unit(cross(seed, z)), y = cross(z, x);
56
- return { x, y, z, to: (p) => { const q = [p[0] - O[0], p[1] - O[1], p[2] - O[2]]; return [dot(q, x), dot(q, y), dot(q, z)]; } };
119
+ const z = unit(D),
120
+ seed = Math.abs(z[0]) < 0.9 ? [1, 0, 0] : [0, 1, 0],
121
+ x = unit(cross(seed, z)),
122
+ y = cross(z, x);
123
+ return {
124
+ x,
125
+ y,
126
+ z,
127
+ to: (p) => {
128
+ const q = [p[0] - O[0], p[1] - O[1], p[2] - O[2]];
129
+ return [dot(q, x), dot(q, y), dot(q, z)];
130
+ },
131
+ };
57
132
  }
58
133
  // A slice across the axis at z, as 2D segments. Each end is worked out from its edge's lower corner, so the two faces
59
134
  // that share an edge give the very same point, and the segments join end to end exactly.
@@ -62,47 +137,93 @@ function slice(tris, z) {
62
137
  for (const t of tris) {
63
138
  const c = [];
64
139
  for (let i = 0; i < 3; i++) {
65
- let a = t[i], b = t[(i + 1) % 3];
140
+ let a = t[i],
141
+ b = t[(i + 1) % 3];
66
142
  if ((a[2] - z) * (b[2] - z) >= 0) continue;
67
143
  if (a[2] > b[2] || (a[2] === b[2] && (a[0] > b[0] || (a[0] === b[0] && a[1] > b[1])))) [a, b] = [b, a];
68
- const u = (z - a[2]) / (b[2] - a[2]); c.push([a[0] + u * (b[0] - a[0]), a[1] + u * (b[1] - a[1])]);
144
+ const u = (z - a[2]) / (b[2] - a[2]);
145
+ c.push([a[0] + u * (b[0] - a[0]), a[1] + u * (b[1] - a[1])]);
69
146
  }
70
147
  if (c.length === 2) segs.push(c);
71
148
  }
72
149
  return segs;
73
150
  }
74
- const toSeg = (p, q) => { // how far the axis (the origin) is from a segment
75
- const ex = q[0] - p[0], ey = q[1] - p[1], l2 = ex * ex + ey * ey, u = l2 ? Math.max(0, Math.min(1, -(p[0] * ex + p[1] * ey) / l2)) : 0;
151
+ const toSeg = (p, q) => {
152
+ // how far the axis (the origin) is from a segment
153
+ const ex = q[0] - p[0],
154
+ ey = q[1] - p[1],
155
+ l2 = ex * ex + ey * ey,
156
+ u = l2 ? Math.max(0, Math.min(1, -(p[0] * ex + p[1] * ey) / l2)) : 0;
76
157
  return Math.hypot(p[0] + u * ex, p[1] + u * ey);
77
158
  };
78
159
  // The circle through a set of points (Kasa's fit: least squares on x² + y² + Dx + Ey + F), or null where they lie in a line
79
160
  function circle(pts) {
80
- let sx = 0, sy = 0, sxx = 0, syy = 0, sxy = 0, sxz = 0, syz = 0, sz = 0; const n = pts.length;
81
- for (const [x, y] of pts) { const z = x * x + y * y; sx += x; sy += y; sxx += x * x; syy += y * y; sxy += x * y; sxz += x * z; syz += y * z; sz += z; }
161
+ let sx = 0,
162
+ sy = 0,
163
+ sxx = 0,
164
+ syy = 0,
165
+ sxy = 0,
166
+ sxz = 0,
167
+ syz = 0,
168
+ sz = 0;
169
+ const n = pts.length;
170
+ for (const [x, y] of pts) {
171
+ const z = x * x + y * y;
172
+ sx += x;
173
+ sy += y;
174
+ sxx += x * x;
175
+ syy += y * y;
176
+ sxy += x * y;
177
+ sxz += x * z;
178
+ syz += y * z;
179
+ sz += z;
180
+ }
82
181
  // [sxx sxy sx; sxy syy sy; sx sy n] [D E F]' = -[sxz syz sz]'
83
- const A = [[sxx, sxy, sx, -sxz], [sxy, syy, sy, -syz], [sx, sy, n, -sz]];
182
+ const A = [
183
+ [sxx, sxy, sx, -sxz],
184
+ [sxy, syy, sy, -syz],
185
+ [sx, sy, n, -sz],
186
+ ];
84
187
  for (let i = 0; i < 3; i++) {
85
- let p = i; for (let k = i + 1; k < 3; k++) if (Math.abs(A[k][i]) > Math.abs(A[p][i])) p = k;
188
+ let p = i;
189
+ for (let k = i + 1; k < 3; k++) if (Math.abs(A[k][i]) > Math.abs(A[p][i])) p = k;
86
190
  if (Math.abs(A[p][i]) < 1e-12) return null;
87
191
  [A[i], A[p]] = [A[p], A[i]];
88
- for (let k = 0; k < 3; k++) if (k !== i) { const f = A[k][i] / A[i][i]; for (let j = i; j < 4; j++) A[k][j] -= f * A[i][j]; }
192
+ for (let k = 0; k < 3; k++)
193
+ if (k !== i) {
194
+ const f = A[k][i] / A[i][i];
195
+ for (let j = i; j < 4; j++) A[k][j] -= f * A[i][j];
196
+ }
89
197
  }
90
- const D = A[0][3] / A[0][0], E = A[1][3] / A[1][1], F = A[2][3] / A[2][2], c = [-D / 2, -E / 2], r2 = c[0] * c[0] + c[1] * c[1] - F;
198
+ const D = A[0][3] / A[0][0],
199
+ E = A[1][3] / A[1][1],
200
+ F = A[2][3] / A[2][2],
201
+ c = [-D / 2, -E / 2],
202
+ r2 = c[0] * c[0] + c[1] * c[1] - F;
91
203
  return r2 > 0 ? { c, r: Math.sqrt(r2) } : null;
92
204
  }
93
205
  // Points as a round: the circle they lie on once the few that do not (a teardrop's roof) are left out, and whether
94
206
  // they go all the way round it
95
207
  function roundOf(pts) {
96
208
  if (pts.length < 3) return null;
97
- let fit = circle(pts); if (!fit) return null;
98
- const off = (f, p) => Math.abs(Math.hypot(p[0] - f.c[0], p[1] - f.c[1]) - f.r), slack = (f) => Math.max(0.02 * f.r, 0.005);
209
+ let fit = circle(pts);
210
+ if (!fit) return null;
211
+ const off = (f, p) => Math.abs(Math.hypot(p[0] - f.c[0], p[1] - f.c[1]) - f.r),
212
+ slack = (f) => Math.max(0.02 * f.r, 0.005);
99
213
  let on = pts.filter((p) => off(fit, p) <= slack(fit));
100
- if (on.length < pts.length && on.length >= 6) { const again = circle(on); if (again) { fit = again; on = pts.filter((p) => off(fit, p) <= slack(fit)); } }
214
+ if (on.length < pts.length && on.length >= 6) {
215
+ const again = circle(on);
216
+ if (again) {
217
+ fit = again;
218
+ on = pts.filter((p) => off(fit, p) <= slack(fit));
219
+ }
220
+ }
101
221
  if (on.length < 3 || on.length < pts.length * 0.7) return null;
102
222
  const worst = Math.max(...on.map((p) => off(fit, p)));
103
223
  if (worst > 0.004 * fit.r + 0.002) return null;
104
224
  const angles = on.map((p) => Math.atan2(p[1] - fit.c[1], p[0] - fit.c[0])).sort((a, b) => a - b);
105
- let gap = angles[0] + 2 * Math.PI - angles.at(-1); for (let i = 1; i < angles.length; i++) gap = Math.max(gap, angles[i] - angles[i - 1]);
225
+ let gap = angles[0] + 2 * Math.PI - angles.at(-1);
226
+ for (let i = 1; i < angles.length; i++) gap = Math.max(gap, angles[i] - angles[i - 1]);
106
227
  if (gap > (on.length <= 8 ? 2.2 : 1.75)) return null; // (a square's corners are 90° apart; a round with a roof has one gap of 90°)
107
228
  return { ...fit, points: on.length, all: on.length === pts.length, corner: on[0] };
108
229
  }
@@ -114,45 +235,104 @@ function measure(all, R) {
114
235
  // ten-thousandths apart (the snap rounds a corner that lies on a grid line's middle either way), which would open a
115
236
  // closed outline. A segment that starts and ends at one point (a sliver face, cut) is no wall: it would count its
116
237
  // point twice
117
- const G = 1e3, key = (p) => `${Math.round(p[0] * G)},${Math.round(p[1] * G)}`, segs = all.filter(([p, q]) => key(p) !== key(q));
118
- let best = -1, free = Infinity;
119
- segs.forEach(([p, q], i) => { const d = toSeg(p, q); if (d < free) { free = d; best = i; } });
238
+ const G = 1e3,
239
+ key = (p) => `${Math.round(p[0] * G)},${Math.round(p[1] * G)}`,
240
+ segs = all.filter(([p, q]) => key(p) !== key(q));
241
+ let best = -1,
242
+ free = Infinity;
243
+ segs.forEach(([p, q], i) => {
244
+ const d = toSeg(p, q);
245
+ if (d < free) {
246
+ free = d;
247
+ best = i;
248
+ }
249
+ });
120
250
  if (best < 0 || free > R) return { free: Infinity, loop: null };
121
251
  const at = new Map();
122
- segs.forEach((s, i) => { for (const p of s) { const k = key(p); if (!at.has(k)) at.set(k, []); at.get(k).push(i); } });
123
- const mine = new Set([best]), todo = [best];
124
- while (todo.length) for (const p of segs[todo.pop()]) for (const j of at.get(key(p))) if (!mine.has(j)) { mine.add(j); todo.push(j); }
125
- const pts = new Map(); let closed = true, inside = false;
252
+ segs.forEach((s, i) => {
253
+ for (const p of s) {
254
+ const k = key(p);
255
+ if (!at.has(k)) at.set(k, []);
256
+ at.get(k).push(i);
257
+ }
258
+ });
259
+ const mine = new Set([best]),
260
+ todo = [best];
261
+ while (todo.length)
262
+ for (const p of segs[todo.pop()])
263
+ for (const j of at.get(key(p)))
264
+ if (!mine.has(j)) {
265
+ mine.add(j);
266
+ todo.push(j);
267
+ }
268
+ const pts = new Map();
269
+ let closed = true,
270
+ inside = false;
126
271
  for (const i of mine) {
127
272
  const [p, q] = segs[i];
128
- for (const e of [p, q]) { const k = key(e); pts.set(k, e); if (at.get(k).filter((j) => mine.has(j)).length !== 2) closed = false; }
273
+ for (const e of [p, q]) {
274
+ const k = key(e);
275
+ pts.set(k, e);
276
+ if (at.get(k).filter((j) => mine.has(j)).length !== 2) closed = false;
277
+ }
129
278
  // (a ray from the axis along +x, its ends read on the grid they are joined on: two faces' ends a hair either side of
130
279
  // the ray at one corner, as a teardrop's point can be, are one point and cross it once)
131
- const py = Math.round(p[1] * G), qy = Math.round(q[1] * G);
132
- if ((py > 0) !== (qy > 0) && p[0] + ((0 - p[1]) / (q[1] - p[1])) * (q[0] - p[0]) > 0) inside = !inside;
280
+ const py = Math.round(p[1] * G),
281
+ qy = Math.round(q[1] * G);
282
+ if (py > 0 !== qy > 0 && p[0] + ((0 - p[1]) / (q[1] - p[1])) * (q[0] - p[0]) > 0) inside = !inside;
133
283
  }
134
284
  // corners only: a point where the outline runs straight on is a seam between two faces, not a corner
135
- const list = !closed ? [] : [...pts].filter(([k, e]) => {
136
- const [p, q] = at.get(k).filter((j) => mine.has(j)).map((j) => (key(segs[j][0]) === k ? segs[j][1] : segs[j][0]));
137
- const ux = e[0] - p[0], uy = e[1] - p[1], vx = q[0] - e[0], vy = q[1] - e[1];
138
- return Math.abs(ux * vy - uy * vx) > 2e-3 * Math.hypot(ux, uy) * Math.hypot(vx, vy); // (0.1°: a seam left by a boolean lies within its snap of the line; a round's corners turn by degrees)
139
- }).map(([, e]) => e), round = closed ? roundOf(list) : null;
140
- let shape = 'other', d = null, flats = null, offset = null, c = null, corner = null;
285
+ const list = !closed
286
+ ? []
287
+ : [...pts]
288
+ .filter(([k, e]) => {
289
+ const [p, q] = at
290
+ .get(k)
291
+ .filter((j) => mine.has(j))
292
+ .map((j) => (key(segs[j][0]) === k ? segs[j][1] : segs[j][0]));
293
+ const ux = e[0] - p[0],
294
+ uy = e[1] - p[1],
295
+ vx = q[0] - e[0],
296
+ vy = q[1] - e[1];
297
+ return Math.abs(ux * vy - uy * vx) > 2e-3 * Math.hypot(ux, uy) * Math.hypot(vx, vy); // (0.1°: a seam left by a boolean lies within its snap of the line; a round's corners turn by degrees)
298
+ })
299
+ .map(([, e]) => e),
300
+ round = closed ? roundOf(list) : null;
301
+ let shape = 'other',
302
+ d = null,
303
+ flats = null,
304
+ offset = null,
305
+ c = null,
306
+ corner = null;
141
307
  if (round) {
142
- c = round.c; d = 2 * round.r; offset = Math.hypot(c[0], c[1]);
143
- let least = Infinity; for (const i of mine) { const [p, q] = segs[i]; least = Math.min(least, toSeg([p[0] - c[0], p[1] - c[1]], [q[0] - c[0], q[1] - c[1]])); }
308
+ c = round.c;
309
+ d = 2 * round.r;
310
+ offset = Math.hypot(c[0], c[1]);
311
+ let least = Infinity;
312
+ for (const i of mine) {
313
+ const [p, q] = segs[i];
314
+ least = Math.min(least, toSeg([p[0] - c[0], p[1] - c[1]], [q[0] - c[0], q[1] - c[1]]));
315
+ }
144
316
  flats = 2 * least;
145
317
  const sides = round.all ? Math.round(Math.PI / Math.acos(Math.min(1, least / round.r))) : 0; // (a regular polygon's flats lie at r cos(π / n))
146
318
  shape = round.all && sides === 6 ? 'hex' : round.all && sides === 4 ? 'square' : 'round';
147
319
  corner = round.corner;
148
320
  }
149
- const [bp, bq] = segs[best], bl = Math.hypot(bq[0] - bp[0], bq[1] - bp[1]), along = bl > 0 ? [(bq[0] - bp[0]) / bl, (bq[1] - bp[1]) / bl] : null; // (the nearest wall's run: a nut's corners point along a slot's walls)
321
+ const [bp, bq] = segs[best],
322
+ bl = Math.hypot(bq[0] - bp[0], bq[1] - bp[1]),
323
+ along = bl > 0 ? [(bq[0] - bp[0]) / bl, (bq[1] - bp[1]) / bl] : null; // (the nearest wall's run: a nut's corners point along a slot's walls)
150
324
  return { free, loop: { closed, inside: closed && inside, shape, d, flats, offset, c, corner, along } };
151
325
  }
152
326
  const same = (a, b) => {
153
327
  if (!a.loop || !b.loop) return !a.loop && !b.loop;
154
328
  const near = (x, y) => (x == null || y == null ? x == y : Math.abs(x - y) < 1e-3); // (a fit through corners snapped to a boolean's grid wanders by less)
155
- return near(a.free, b.free) && a.loop.shape === b.loop.shape && a.loop.inside === b.loop.inside && near(a.loop.d, b.loop.d) && near(a.loop.offset, b.loop.offset);
329
+ return (
330
+ near(a.free, b.free) &&
331
+ a.loop.shape === b.loop.shape &&
332
+ a.loop.inside === b.loop.inside &&
333
+ near(a.loop.d, b.loop.d) &&
334
+ near(a.loop.offset, b.loop.offset)
335
+ );
156
336
  };
157
337
 
158
338
  /**
@@ -165,34 +345,83 @@ const same = (a, b) => {
165
345
  * near: the faces within R, in the axis's own coordinates, for further slices; x, y: the directions across the axis
166
346
  */
167
347
  export function profile(tris, O, D, R) {
168
- const f = frameOf(O, D), near = [], hits = [], cuts = new Set(), flats = new Set();
169
- for (const poly of tris) for (const t of fan(poly)) {
170
- const q = t.map(f.to);
171
- if (Math.min(q[0][0], q[1][0], q[2][0]) > R || Math.max(q[0][0], q[1][0], q[2][0]) < -R || Math.min(q[0][1], q[1][1], q[2][1]) > R || Math.max(q[0][1], q[1][1], q[2][1]) < -R) continue;
172
- near.push(q);
173
- for (const p of q) cuts.add(Math.round(p[2] * 1e6) / 1e6);
174
- if (Math.abs(q[0][2] - q[1][2]) < 1e-6 && Math.abs(q[0][2] - q[2][2]) < 1e-6) flats.add(Math.round(q[0][2] * 1e6) / 1e6); // (a face square to the axis: a seat, a floor)
175
- // where the axis itself goes through this face, and which way the face looks
176
- const [a, b, c] = q, det = (b[0] - a[0]) * (c[1] - a[1]) - (c[0] - a[0]) * (b[1] - a[1]);
177
- if (Math.abs(det) < 1e-12) continue;
178
- const l1 = (b[0] * c[1] - c[0] * b[1]) / det, l2 = (c[0] * a[1] - a[0] * c[1]) / det, l3 = 1 - l1 - l2;
179
- if (l1 >= -1e-9 && l2 >= -1e-9 && l3 >= -1e-9) hits.push([l1 * a[2] + l2 * b[2] + l3 * c[2], Math.sign(det)]);
180
- }
348
+ const f = frameOf(O, D),
349
+ near = [],
350
+ hits = [],
351
+ cuts = new Set(),
352
+ flats = new Set();
353
+ for (const poly of tris)
354
+ for (const t of fan(poly)) {
355
+ const q = t.map(f.to);
356
+ if (
357
+ Math.min(q[0][0], q[1][0], q[2][0]) > R ||
358
+ Math.max(q[0][0], q[1][0], q[2][0]) < -R ||
359
+ Math.min(q[0][1], q[1][1], q[2][1]) > R ||
360
+ Math.max(q[0][1], q[1][1], q[2][1]) < -R
361
+ )
362
+ continue;
363
+ near.push(q);
364
+ for (const p of q) cuts.add(Math.round(p[2] * 1e6) / 1e6);
365
+ if (Math.abs(q[0][2] - q[1][2]) < 1e-6 && Math.abs(q[0][2] - q[2][2]) < 1e-6)
366
+ flats.add(Math.round(q[0][2] * 1e6) / 1e6); // (a face square to the axis: a seat, a floor)
367
+ // where the axis itself goes through this face, and which way the face looks
368
+ const [a, b, c] = q,
369
+ det = (b[0] - a[0]) * (c[1] - a[1]) - (c[0] - a[0]) * (b[1] - a[1]);
370
+ if (Math.abs(det) < 1e-12) continue;
371
+ const l1 = (b[0] * c[1] - c[0] * b[1]) / det,
372
+ l2 = (c[0] * a[1] - a[0] * c[1]) / det,
373
+ l3 = 1 - l1 - l2;
374
+ if (l1 >= -1e-9 && l2 >= -1e-9 && l3 >= -1e-9) hits.push([l1 * a[2] + l2 * b[2] + l3 * c[2], Math.sign(det)]);
375
+ }
181
376
  // The axis is in material between a face it enters by (looking back along it) and one it leaves by. Faces that
182
377
  // meet on the axis (a hole's floor drawn as a fan, a cone's point) are met together, and count once.
183
378
  hits.sort((p, q) => p[0] - q[0]);
184
379
  const walls = [];
185
- for (let i = 0; i < hits.length;) { let j = i, net = 0; while (j < hits.length && hits[j][0] - hits[i][0] < 1e-6) net += hits[j++][1]; if (net) walls.push([hits[i][0], net > 0 ? -1 : 1]); i = j; }
186
- const solidAt = (z) => { let depth = 0; for (const [w, s] of walls) { if (w > z) break; depth += s; } return depth > 0; };
380
+ for (let i = 0; i < hits.length;) {
381
+ let j = i,
382
+ net = 0;
383
+ while (j < hits.length && hits[j][0] - hits[i][0] < 1e-6) net += hits[j++][1];
384
+ if (net) walls.push([hits[i][0], net > 0 ? -1 : 1]);
385
+ i = j;
386
+ }
387
+ const solidAt = (z) => {
388
+ let depth = 0;
389
+ for (const [w, s] of walls) {
390
+ if (w > z) break;
391
+ depth += s;
392
+ }
393
+ return depth > 0;
394
+ };
187
395
  let zs = [...cuts].sort((a, b) => a - b);
188
396
  // (a drawn thread: sampled evenly, and at every face square to the axis, so a counterbore's floor is a step, not a cone)
189
- if (zs.length > 600) { const lo = zs[0], hi = zs.at(-1); zs = [...new Set([...Array.from({ length: 401 }, (_, i) => lo + ((hi - lo) * i) / 400), ...flats])].sort((a, b) => a - b); }
397
+ if (zs.length > 600) {
398
+ const lo = zs[0],
399
+ hi = zs.at(-1);
400
+ zs = [...new Set([...Array.from({ length: 401 }, (_, i) => lo + ((hi - lo) * i) / 400), ...flats])].sort(
401
+ (a, b) => a - b,
402
+ );
403
+ }
190
404
  const segs = [];
191
405
  for (let i = 0; i + 1 < zs.length; i++) {
192
- const z0 = zs[i], z1 = zs[i + 1], len = z1 - z0; if (len < 1e-5) continue;
193
- const e = Math.min(1e-3, len / 4), a = measure(slice(near, z0 + e), R), b = measure(slice(near, z1 - e), R), solid = solidAt((z0 + z1) / 2);
194
- const hole = !solid && !!a.loop?.inside && !!b.loop?.inside, last = segs.at(-1);
195
- if (last && last.solid === solid && Math.abs(last.z1 - z0) < 1e-4 && same(last.a, last.b) && same(a, b) && same(last.b, a)) last.z1 = z1;
406
+ const z0 = zs[i],
407
+ z1 = zs[i + 1],
408
+ len = z1 - z0;
409
+ if (len < 1e-5) continue;
410
+ const e = Math.min(1e-3, len / 4),
411
+ a = measure(slice(near, z0 + e), R),
412
+ b = measure(slice(near, z1 - e), R),
413
+ solid = solidAt((z0 + z1) / 2);
414
+ const hole = !solid && !!a.loop?.inside && !!b.loop?.inside,
415
+ last = segs.at(-1);
416
+ if (
417
+ last &&
418
+ last.solid === solid &&
419
+ Math.abs(last.z1 - z0) < 1e-4 &&
420
+ same(last.a, last.b) &&
421
+ same(a, b) &&
422
+ same(last.b, a)
423
+ )
424
+ last.z1 = z1;
196
425
  else segs.push({ z0, z1, solid, hole, a, b });
197
426
  }
198
427
  return { segs, near, x: f.x, y: f.y };
@@ -203,33 +432,138 @@ export function profile(tris, O, D, R) {
203
432
  const kept = new Map();
204
433
  function partProfile(p, O, D, R) {
205
434
  if (!p.m || !p.localTriangles) return profile(p.triangles, O, D, R);
206
- const inv = mat4.invert(mat4.create(), p.m), o = vec3.transform([0, 0, 0], O, inv), e = vec3.transform([0, 0, 0], add(O, D), inv), d = [e[0] - o[0], e[1] - o[1], e[2] - o[2]];
435
+ const inv = mat4.invert(mat4.create(), p.m),
436
+ o = vec3.transform([0, 0, 0], O, inv),
437
+ e = vec3.transform([0, 0, 0], add(O, D), inv),
438
+ d = [e[0] - o[0], e[1] - o[1], e[2] - o[2]];
207
439
  const key = `${p.hash ?? p.shape}|${[...o, ...d, R].map((x) => Math.round(x * 1e6) / 1e6).join(',')}`;
208
- if (!kept.has(key)) { if (kept.size > 4000) kept.clear(); kept.set(key, profile(p.localTriangles, o, d, R)); }
440
+ if (!kept.has(key)) {
441
+ if (kept.size > 4000) kept.clear();
442
+ kept.set(key, profile(p.localTriangles, o, d, R));
443
+ }
209
444
  return kept.get(key);
210
445
  }
211
446
  // The stretches of several parts as one run along the axis, turned to run the other way where asked
212
447
  function along(parts, O, D, R, flip) {
213
- const segs = parts.flatMap((p) => { const pr = partProfile(p, O, D, R); return pr.segs.map((s) => ({ ...s, part: p, of: pr })); });
448
+ const segs = parts.flatMap((p) => {
449
+ const pr = partProfile(p, O, D, R);
450
+ return pr.segs.map((s) => ({ ...s, part: p, of: pr }));
451
+ });
214
452
  const out = flip ? segs.map((s) => ({ ...s, z0: -s.z1, z1: -s.z0, a: s.b, b: s.a })) : segs;
215
453
  return out.sort((a, b) => a.z0 - b.z0);
216
454
  }
217
- const reach = (segs) => { const on = segs.filter((s) => s.solid || s.hole); return on.length ? [Math.min(...on.map((s) => s.z0)), Math.max(...on.map((s) => s.z1))] : null; };
455
+ const reach = (segs) => {
456
+ const on = segs.filter((s) => s.solid || s.hole);
457
+ return on.length ? [Math.min(...on.map((s) => s.z0)), Math.max(...on.map((s) => s.z1))] : null;
458
+ };
459
+ // fasten.stack: the parts a screw holds, walked along its axis from under the head, each one's far face held to the
460
+ // next one's near face. A gap is air the screw is lengthened across: a part placed wrong, which the length chosen would
461
+ // hide. Where a fit between the two parts gives a range that holds the gap, the gap is meant (a fit that says so), and
462
+ // it is a warning; otherwise a failure. A part's faces are where it has any material within R of the axis, not only
463
+ // round it: a hole's lead-in that breaks out of a thin wall leaves the part's face where it is, not lower.
464
+ // A gap that a beam's own material fills, within R of the axis, from one face to the next, is no air: the screw clamps
465
+ // the beam's lips between the two, as a rail screwed through a slot into a strip of nuts under the lips does.
466
+ // runs: the members in order, each with its stretches along the axis; across(z0, z1): the beam that fills z0 to z1, or null
467
+ function stackSays(runs, R, fits, num, say, across = () => null) {
468
+ if (runs.length < 2) return;
469
+ const faces = runs.map((r) =>
470
+ reach(r.segs.map((g) => (Math.min(g.a.free, g.b.free) < R - 1e-6 ? { ...g, solid: true } : g))),
471
+ );
472
+ const gaps = [],
473
+ bridged = [];
474
+ for (let j = 0; j + 1 < runs.length; j++) {
475
+ const a = runs[j],
476
+ b = runs[j + 1],
477
+ gap = faces[j + 1][0] - faces[j][1];
478
+ if (gap <= FASTEN.stack.value + EPS) continue;
479
+ const beam = across(faces[j][1], faces[j + 1][0]);
480
+ if (beam) bridged.push(`${a.name} and ${b.name} clamp ${beam} between them`);
481
+ else gaps.push({ a, b, gap });
482
+ }
483
+ if (!gaps.length)
484
+ return say(
485
+ 'fasten.stack',
486
+ 'pass',
487
+ `${runs.map((r) => r.name).join(', ')} lie face to face along the screw, nothing between them more than ${mm(FASTEN.stack.value)} mm apart${bridged.length ? ` (${bridged.join('; ')})` : ''}`,
488
+ );
489
+ for (const { a, b, gap } of gaps) {
490
+ const pair = [top(a.name), top(b.name)].sort().join(),
491
+ fit = (fits || []).find((x) => {
492
+ if (x.fastens || x.holes || typeof x.a !== 'string' || typeof x.b !== 'string') return false;
493
+ if ([top(x.a), top(x.b)].sort().join() !== pair) return false;
494
+ try {
495
+ const lo = x.min == null ? 0 : num(x.min),
496
+ hi = x.max == null ? Infinity : num(x.max);
497
+ return gap >= lo - FASTEN.stack.value && gap <= hi + FASTEN.stack.value;
498
+ } catch {
499
+ return false; // (a range that does not read is no declared gap: said by the fit's own check)
500
+ }
501
+ }),
502
+ values = { gap: r3(gap), between: [a.name, b.name] };
503
+ if (fit)
504
+ say(
505
+ 'fasten.stack',
506
+ 'warn',
507
+ `${a.name} and ${b.name} are ${mm2(gap)} mm apart along the screw, as the fit "${fit.note || `${fit.a} and ${fit.b}`}" allows: the screw is lengthened across the gap and holds them apart, not clamped face to face. A spacer in the gap, named in "through", carries the clamp`,
508
+ { ...values, fit: fit.note ?? null },
509
+ );
510
+ else
511
+ say(
512
+ 'fasten.stack',
513
+ 'fail',
514
+ `${a.name} and ${b.name} are ${mm2(gap)} mm apart along the screw: the screw would be lengthened across the air and clamp nothing. Move ${b.name} or ${a.name} so they meet, or name the spacer that fills the gap in "through"`,
515
+ values,
516
+ );
517
+ }
518
+ }
218
519
  // Whether there is material at each of a ring of points round the axis in one slice: counted from the axis outwards,
219
520
  // each wall crossed changes it. `from`: whether the axis itself is in material there
220
521
  function ring(near, z, radius, from, n = 24) {
221
- const segs = slice(near, z); let solid = 0;
522
+ const segs = slice(near, z);
523
+ let solid = 0;
222
524
  for (let k = 0; k < n; k++) {
223
- const a = ((k + 0.37) * 2 * Math.PI) / n, dx = Math.cos(a), dy = Math.sin(a); let inside = from;
224
- for (const [p, q] of segs) {
225
- const ex = q[0] - p[0], ey = q[1] - p[1], den = dx * ey - dy * ex; if (Math.abs(den) < 1e-12) continue;
226
- const t = (p[0] * ey - p[1] * ex) / den, u = (p[0] * dy - p[1] * dx) / den;
227
- if (t > 1e-9 && t < radius && u >= 0 && u < 1) inside = !inside;
228
- }
229
- if (inside) solid++;
525
+ const a = ((k + 0.37) * 2 * Math.PI) / n,
526
+ crossed = crossings(segs, Math.cos(a), Math.sin(a)).filter((t) => t < radius).length;
527
+ if (from !== (crossed % 2 === 1)) solid++;
230
528
  }
231
529
  return solid / n;
232
530
  }
531
+ // How far along a ray from the axis (dx, dy) each wall of a slice is crossed, nearest first
532
+ function crossings(segs, dx, dy) {
533
+ const out = [];
534
+ for (const [p, q] of segs) {
535
+ const ex = q[0] - p[0],
536
+ ey = q[1] - p[1],
537
+ den = dx * ey - dy * ex;
538
+ if (Math.abs(den) < 1e-12) continue;
539
+ const t = (p[0] * ey - p[1] * ex) / den,
540
+ u = (p[0] * dy - p[1] * dx) / den;
541
+ if (t > 1e-9 && u >= 0 && u < 1) out.push(t);
542
+ }
543
+ return out.sort((a, b) => a - b);
544
+ }
545
+ // The plastic round a hole on the axis, side by side: on each of a ring of rays from the axis in one slice, from the
546
+ // hole's wall (the first wall crossed) to the part's outside (the next). A side the slice sees no outside on within
547
+ // `radius` (the part goes on past what was gathered) is at least radius less the hole, and is taken as no thinner than
548
+ // any side seen whole; one with no wall at all is open. Gives the thinnest side: its wall, its angle in the slice, and
549
+ // atLeast where no side's outside was seen (the wall is then more than the figure)
550
+ function thinnest(near, z, radius, n = 48) {
551
+ const segs = slice(near, z);
552
+ let worst = null,
553
+ beyond = null;
554
+ for (let k = 0; k < n; k++) {
555
+ const a = ((k + 0.37) * 2 * Math.PI) / n,
556
+ t = crossings(segs, Math.cos(a), Math.sin(a));
557
+ if (t.length === 1) {
558
+ const w = Math.max(0, radius - t[0]);
559
+ if (!beyond || w < beyond.wall) beyond = { wall: w, angle: a, open: false, atLeast: true };
560
+ continue;
561
+ }
562
+ const wall = t.length ? t[1] - t[0] : 0;
563
+ if (!worst || wall < worst.wall) worst = { wall, angle: a, open: !t.length, atLeast: false };
564
+ }
565
+ return worst ?? beyond;
566
+ }
233
567
 
234
568
  // ---------- the holes of a part, where a relation names a part and not anchors ----------
235
569
  // Round holes found in a part as drawn, along each of its own three axes: walls that stand along the axis, joined
@@ -238,31 +572,82 @@ const found = new Map();
238
572
  export function holesIn(p) {
239
573
  const key = p.hash ?? p.shape;
240
574
  if (found.has(key)) return found.get(key);
241
- const out = [], tris = (p.localTriangles ?? p.triangles).flatMap(fan);
575
+ const out = [],
576
+ tris = (p.localTriangles ?? p.triangles).flatMap(fan);
242
577
  for (let k = 0; k < 3; k++) {
243
578
  const [u, w] = k === 0 ? [1, 2] : k === 1 ? [2, 0] : [0, 1]; // (u × w = k, so a normal's sense carries over)
244
- const id = new Map(), parent = [], pts = [], span = [], face = [];
245
- const find = (i) => { while (parent[i] !== i) { parent[i] = parent[parent[i]]; i = parent[i]; } return i; };
246
- const node = (v) => { const q = `${Math.round(v[u] * 1e4)},${Math.round(v[w] * 1e4)}`; if (!id.has(q)) { id.set(q, pts.length); parent.push(pts.length); pts.push([v[u], v[w]]); span.push([v[k], v[k]]); face.push(null); } const i = id.get(q); span[i][0] = Math.min(span[i][0], v[k]); span[i][1] = Math.max(span[i][1], v[k]); return i; };
579
+ const id = new Map(),
580
+ parent = [],
581
+ pts = [],
582
+ span = [],
583
+ face = [];
584
+ const find = (i) => {
585
+ while (parent[i] !== i) {
586
+ parent[i] = parent[parent[i]];
587
+ i = parent[i];
588
+ }
589
+ return i;
590
+ };
591
+ const node = (v) => {
592
+ const q = `${Math.round(v[u] * 1e4)},${Math.round(v[w] * 1e4)}`;
593
+ if (!id.has(q)) {
594
+ id.set(q, pts.length);
595
+ parent.push(pts.length);
596
+ pts.push([v[u], v[w]]);
597
+ span.push([v[k], v[k]]);
598
+ face.push(null);
599
+ }
600
+ const i = id.get(q);
601
+ span[i][0] = Math.min(span[i][0], v[k]);
602
+ span[i][1] = Math.max(span[i][1], v[k]);
603
+ return i;
604
+ };
247
605
  for (const t of tris) {
248
- const n = cross([t[1][0] - t[0][0], t[1][1] - t[0][1], t[1][2] - t[0][2]], [t[2][0] - t[0][0], t[2][1] - t[0][1], t[2][2] - t[0][2]]), l = Math.hypot(...n);
606
+ const n = cross(
607
+ [t[1][0] - t[0][0], t[1][1] - t[0][1], t[1][2] - t[0][2]],
608
+ [t[2][0] - t[0][0], t[2][1] - t[0][1], t[2][2] - t[0][2]],
609
+ ),
610
+ l = Math.hypot(...n);
249
611
  if (!(l > 1e-12) || Math.abs(n[k]) > 1e-4 * l) continue; // (a wall: it stands along the axis)
250
- const [a, b, c] = t.map(node); parent[find(a)] = find(b); parent[find(c)] = find(b);
612
+ const [a, b, c] = t.map(node);
613
+ parent[find(a)] = find(b);
614
+ parent[find(c)] = find(b);
251
615
  face[a] ||= [n[u] / l, n[w] / l];
252
616
  }
253
617
  const groups = new Map();
254
- pts.forEach((_, i) => { const r = find(i); if (!groups.has(r)) groups.set(r, []); groups.get(r).push(i); });
618
+ pts.forEach((_, i) => {
619
+ const r = find(i);
620
+ if (!groups.has(r)) groups.set(r, []);
621
+ groups.get(r).push(i);
622
+ });
255
623
  for (const g of groups.values()) {
256
624
  if (g.length < 8) continue;
257
- const round = roundOf(g.map((i) => pts[i])); if (!round || round.r < 0.4 || round.r > 20) continue;
258
- const i = g.find((j) => face[j]), inward = face[i][0] * (round.c[0] - pts[i][0]) + face[i][1] * (round.c[1] - pts[i][1]) > 0;
625
+ const round = roundOf(g.map((i) => pts[i]));
626
+ if (!round || round.r < 0.4 || round.r > 20) continue;
627
+ const i = g.find((j) => face[j]),
628
+ inward = face[i][0] * (round.c[0] - pts[i][0]) + face[i][1] * (round.c[1] - pts[i][1]) > 0;
259
629
  if (!inward) continue; // (a boss's outside, not a hole)
260
- const lo = Math.min(...g.map((j) => span[j][0])), hi = Math.max(...g.map((j) => span[j][1]));
630
+ const lo = Math.min(...g.map((j) => span[j][0])),
631
+ hi = Math.max(...g.map((j) => span[j][1]));
261
632
  const twin = out.find((h) => h.k === k && Math.hypot(h.c[0] - round.c[0], h.c[1] - round.c[1]) < 0.02);
262
- if (twin) { twin.d = Math.min(twin.d, 2 * round.r); twin.lo = Math.min(twin.lo, lo); twin.hi = Math.max(twin.hi, hi); } else out.push({ k, c: round.c, d: 2 * round.r, lo, hi });
633
+ if (twin) {
634
+ twin.d = Math.min(twin.d, 2 * round.r);
635
+ twin.lo = Math.min(twin.lo, lo);
636
+ twin.hi = Math.max(twin.hi, hi);
637
+ } else out.push({ k, c: round.c, d: 2 * round.r, lo, hi });
263
638
  }
264
639
  }
265
- const holes = out.map((h) => { const [u, w] = h.k === 0 ? [1, 2] : h.k === 1 ? [2, 0] : [0, 1], at = [0, 0, 0], axis = [0, 0, 0]; at[u] = h.c[0]; at[w] = h.c[1]; at[h.k] = (h.lo + h.hi) / 2; axis[h.k] = 1; return { at, axis, d: h.d }; })
640
+ const holes = out
641
+ .map((h) => {
642
+ const [u, w] = h.k === 0 ? [1, 2] : h.k === 1 ? [2, 0] : [0, 1],
643
+ at = [0, 0, 0],
644
+ axis = [0, 0, 0];
645
+ at[u] = h.c[0];
646
+ at[w] = h.c[1];
647
+ at[h.k] = (h.lo + h.hi) / 2;
648
+ axis[h.k] = 1;
649
+ return { at, axis, d: h.d };
650
+ })
266
651
  .sort((a, b) => a.at[0] - b.at[0] || a.at[1] - b.at[1] || a.at[2] - b.at[2]);
267
652
  found.set(key, holes);
268
653
  return holes;
@@ -273,15 +658,41 @@ export function holesIn(p) {
273
658
  // as the screw model gives it), a socket or a spanner on a hexagon head. radius: the room it needs round the screw's
274
659
  // axis; reach: how far over the head that room is needed (a key's long arm, put in along the axis)
275
660
  function toolFor(model, form, fx) {
276
- let set; try { set = peekRuleSet('hexkey').rules; } catch { return null; }
277
- const sizes = set.sizes.value, at = (s) => { const i = sizes.findIndex((k) => k >= s - 1e-6); return i < 0 ? sizes.length - 1 : i; };
661
+ let set;
662
+ try {
663
+ set = peekRuleSet('hexkey').rules;
664
+ } catch {
665
+ return null;
666
+ }
667
+ const sizes = set.sizes.value,
668
+ at = (s) => {
669
+ const i = sizes.findIndex((k) => k >= s - 1e-6);
670
+ return i < 0 ? sizes.length - 1 : i;
671
+ };
278
672
  if (form === 'hex') {
279
- const flats = fx.figures.hex_head_flats?.value ?? model.headDiameter, i = at(flats);
280
- return { name: `${mm(flats)} mm socket or spanner`, size: flats, radius: flats / Math.cos(Math.PI / 6) / 2 + set.socket_wall.value, reach: set.long_arm.value[i], tilt: 0, rests: ['hexkey.socket_wall', 'hexkey.long_arm'] };
673
+ const flats = fx.figures.hex_head_flats?.value ?? model.headDiameter,
674
+ i = at(flats);
675
+ return {
676
+ name: `${mm(flats)} mm socket or spanner`,
677
+ size: flats,
678
+ radius: flats / Math.cos(Math.PI / 6) / 2 + set.socket_wall.value,
679
+ reach: set.long_arm.value[i],
680
+ tilt: 0,
681
+ rests: ['hexkey.socket_wall', 'hexkey.long_arm'],
682
+ };
281
683
  }
282
- const s = model.key; if (s == null) return null;
283
- const i = at(s), exact = Math.abs(sizes[i] - s) < 1e-6;
284
- return { name: `${mm(s)} mm hex key`, size: s, radius: (exact ? set.corners.value[i] : s / Math.cos(Math.PI / 6)) / 2, reach: set.long_arm.value[i], tilt: set.ball_end_tilt?.value ?? 0, rests: ['hexkey.corners', 'hexkey.long_arm', 'hexkey.ball_end_tilt'] };
684
+ const s = model.key;
685
+ if (s == null) return null;
686
+ const i = at(s),
687
+ exact = Math.abs(sizes[i] - s) < 1e-6;
688
+ return {
689
+ name: `${mm(s)} mm hex key`,
690
+ size: s,
691
+ radius: (exact ? set.corners.value[i] : s / Math.cos(Math.PI / 6)) / 2,
692
+ reach: set.long_arm.value[i],
693
+ tilt: set.ball_end_tilt?.value ?? 0,
694
+ rests: ['hexkey.corners', 'hexkey.long_arm', 'hexkey.ball_end_tilt'],
695
+ };
285
696
  }
286
697
  // What stands in a tool's way: every part with material within its radius of the line from P along U, up to its
287
698
  // reach, each with how far over the head it is first met
@@ -290,27 +701,55 @@ function inTheWay(parts, P, U, radius, reach) {
290
701
  for (const p of parts) {
291
702
  for (const seg of partProfile(p, P, U, radius).segs) {
292
703
  if (seg.z1 <= 1e-3 || seg.z0 >= reach) continue;
293
- if (seg.solid || Math.min(seg.a.free, seg.b.free) < radius - 1e-3) { const z = Math.max(0, seg.z0); if (!out.has(p.item) || out.get(p.item) > z) out.set(p.item, z); break; }
704
+ if (seg.solid || Math.min(seg.a.free, seg.b.free) < radius - 1e-3) {
705
+ const z = Math.max(0, seg.z0);
706
+ if (!out.has(p.item) || out.get(p.item) > z) out.set(p.item, z);
707
+ break;
708
+ }
294
709
  }
295
710
  }
296
711
  return [...out].map(([item, z]) => ({ item, z: r3(z) })).sort((a, b) => a.z - b.z);
297
712
  }
298
713
  // A screw's access: its tool, what stands on the straight line over its head, and the tilt a ball end reaches it at where that is blocked
299
714
  function accessOf(parts, tool, P, U) {
300
- const lift = 0.05, start = add(P, U, lift), blockers = inTheWay(parts, start, U, tool.radius, tool.reach).map((b) => ({ ...b, z: r3(b.z + lift) })); // (from just over the head, so the head's own seat is not met)
715
+ const lift = 0.05,
716
+ start = add(P, U, lift),
717
+ blockers = inTheWay(parts, start, U, tool.radius, tool.reach).map((b) => ({ ...b, z: r3(b.z + lift) })); // (from just over the head, so the head's own seat is not met)
301
718
  let tilt = null;
302
719
  if (blockers.length && tool.tilt > 0) {
303
- const f = frameOf(start, U), t = (tool.tilt * Math.PI) / 180;
304
- for (let k = 0; k < 8 && tilt == null; k++) { const a = (k * Math.PI) / 4, W = unit([0, 1, 2].map((c) => U[c] * Math.cos(t) + (f.x[c] * Math.cos(a) + f.y[c] * Math.sin(a)) * Math.sin(t))); if (!inTheWay(parts, start, W, tool.radius, tool.reach).length) tilt = tool.tilt; }
720
+ const f = frameOf(start, U),
721
+ t = (tool.tilt * Math.PI) / 180;
722
+ for (let k = 0; k < 8 && tilt == null; k++) {
723
+ const a = (k * Math.PI) / 4,
724
+ W = unit(
725
+ [0, 1, 2].map((c) => U[c] * Math.cos(t) + (f.x[c] * Math.cos(a) + f.y[c] * Math.sin(a)) * Math.sin(t)),
726
+ );
727
+ if (!inTheWay(parts, start, W, tool.radius, tool.reach).length) tilt = tool.tilt;
728
+ }
305
729
  }
306
- return { tool: { name: tool.name, size: tool.size, radius: r3(tool.radius), reach: tool.reach, rests: tool.rests }, top: P.map(r3), axis: U.map(r3), blockers, tilt };
730
+ return {
731
+ tool: { name: tool.name, size: tool.size, radius: r3(tool.radius), reach: tool.reach, rests: tool.rests },
732
+ top: P.map(r3),
733
+ axis: U.map(r3),
734
+ blockers,
735
+ tilt,
736
+ };
307
737
  }
308
738
 
309
739
  // ---------- the project's fixings ----------
310
740
  const bound = new Map();
311
741
  export function fixingsOf(project) {
312
742
  const { context, hash } = fixingsContext({ project, dir: paths.project(project) });
313
- if (bound.get(project)?.hash !== hash) bound.set(project, { hash, F: fixingsFor({ ...(Object.keys(context.sets).length ? { sets: context.sets } : {}), ...(context.printer ? { printer: context.printer } : {}) }), material: context.material, printer: context.printer?.name ?? 'x1c' });
743
+ if (bound.get(project)?.hash !== hash)
744
+ bound.set(project, {
745
+ hash,
746
+ F: fixingsFor({
747
+ ...(Object.keys(context.sets).length ? { sets: context.sets } : {}),
748
+ ...(context.printer ? { printer: context.printer } : {}),
749
+ }),
750
+ material: context.material,
751
+ printer: context.printer?.name ?? 'x1c',
752
+ });
314
753
  return bound.get(project);
315
754
  }
316
755
  // A piece of hardware as a part's shape, made once for each name: the light solid of @rulecad/fixings, its faces, a hash.
@@ -319,15 +758,30 @@ const shapes = new Map();
319
758
  function shapeOf(F, kind, m, o) {
320
759
  const key = `${kind}:${typeof m === 'string' ? m : m.name}:${JSON.stringify(o)}`;
321
760
  if (!shapes.has(key)) {
322
- const g = F[kind](m, o), [p] = named({ body: g }, { body: { label: g.model.name } });
323
- shapes.set(key, { geometry: p.geometry, polygons: p.polygons, triangles: p.triangles, model: g.model, hash: `fixing:${crypto.createHash('sha256').update(JSON.stringify([key, p.polygons])).digest('hex').slice(0, 16)}` });
761
+ const g = F[kind](m, o),
762
+ [p] = named({ body: g }, { body: { label: g.model.name } });
763
+ shapes.set(key, {
764
+ geometry: p.geometry,
765
+ polygons: p.polygons,
766
+ triangles: p.triangles,
767
+ model: g.model,
768
+ hash: `fixing:${crypto
769
+ .createHash('sha256')
770
+ .update(JSON.stringify([key, p.polygons]))
771
+ .digest('hex')
772
+ .slice(0, 16)}`,
773
+ });
324
774
  }
325
775
  return shapes.get(key);
326
776
  }
327
777
  // Where a piece of hardware stands in the world: its own z along Z from P, its x towards X where one is given
328
778
  function standing(P, Z, X) {
329
- const z = unit(Z); let x = X && unit(add(X, z, -dot(X, z)));
330
- if (!x || !x.every(Number.isFinite)) { const seed = Math.abs(z[0]) < 0.9 ? [1, 0, 0] : [0, 1, 0]; x = unit(cross(seed, z)); }
779
+ const z = unit(Z);
780
+ let x = X && unit(add(X, z, -dot(X, z)));
781
+ if (!x || !x.every(Number.isFinite)) {
782
+ const seed = Math.abs(z[0]) < 0.9 ? [1, 0, 0] : [0, 1, 0];
783
+ x = unit(cross(seed, z));
784
+ }
331
785
  const y = cross(z, x);
332
786
  return [x[0], x[1], x[2], 0, y[0], y[1], y[2], 0, z[0], z[1], z[2], 0, P[0], P[1], P[2], 1];
333
787
  }
@@ -337,9 +791,17 @@ const NUTS = ['hex', 'square', 'lock'];
337
791
  // A head on a beam's slot (a join's screw, lib/joins.mjs: x.lips is { item, slot, inside }): the slot's opening, its
338
792
  // cavity's width under the lips, and the room there at that width, from the profile's slot family
339
793
  function lipsOf(s, l, fx) {
340
- const b = s.objects.find((o) => o.id === l.item)?.beam, sl = b?.profile.slots[l.slot];
794
+ const b = s.objects.find((o) => o.id === l.item)?.beam,
795
+ sl = b?.profile.slots[l.slot];
341
796
  if (!sl) throw new Error(`fasten: ${l.item} has no slot ${l.slot} for a head to sit in`);
342
- return { slot: l.slot, inside: !!l.inside, opening: sl.opening, cavityWidth: sl.cavityWidth, room: sl.straight > 0 ? sl.straight : sl.cavityDepth - sl.lip, thread: fx.thread };
797
+ return {
798
+ slot: l.slot,
799
+ inside: !!l.inside,
800
+ opening: sl.opening,
801
+ cavityWidth: sl.cavityWidth,
802
+ room: sl.straight > 0 ? sl.straight : sl.cavityDepth - sl.lip,
803
+ thread: fx.thread,
804
+ };
343
805
  }
344
806
  // What a slot's lips take under a head D across, over an opening w: the head's circle less the strip of the opening across
345
807
  // it, A = π D² / 4 - 2 (c √(R² - c²) + R² asin(c / R)) with R = D / 2 and c = w / 2, at the beam alloy's strength (taken
@@ -348,63 +810,281 @@ function lipsOf(s, l, fx) {
348
810
  function lipsTake(F, s, item, fx, D, w) {
349
811
  const name = s.objects.find((o) => o.id === item)?.beam?.material?.name;
350
812
  let mat = null;
351
- try { mat = name ? peekRuleSet(name) : null; } catch { mat = null; }
813
+ try {
814
+ mat = name ? peekRuleSet(name) : null;
815
+ } catch {
816
+ mat = null;
817
+ }
352
818
  if (!mat?.rules?.strength || !mat.rules.modulus) return null;
353
- const R = D / 2, c = Math.min(w / 2, R), area = Math.PI * R * R - 2 * (c * Math.sqrt(R * R - c * c) + R * R * Math.asin(c / R));
819
+ const R = D / 2,
820
+ c = Math.min(w / 2, R),
821
+ area = Math.PI * R * R - 2 * (c * Math.sqrt(R * R - c * c) + R * R * Math.asin(c / R));
354
822
  let limit, full;
355
- try { limit = F.seating(fx, { head: 'button', material: { name, rules: mat.rules }, force: 1 }).limit; full = F.preload(fx, { force: 1 }).full; } catch { return null; }
356
- const K = DEFAULTS.nut_factor.value, force = limit * area, torque = (K * fx.major * force) / 1000, by = torque <= full.torque ? 'lips' : 'screw';
357
- const T = +Math.min(torque, full.torque).toFixed(2);
358
- return { area: +area.toFixed(2), limit, force: +force.toFixed(1), torque: T,
359
- text: by === 'lips' ? `on ${name} (${mm(limit)} MPa) the ${mm(+area.toFixed(1))} mm² either side of the opening takes ${mm(+force.toFixed(0))} N, a tightening of ${mm(T)} N m (the lips' bending not counted: an estimate)`
360
- : `the lips take ${mm(+force.toFixed(0))} N on ${mm(+area.toFixed(1))} mm² of ${name}, more than the screw tightened fully: ${mm(T)} N m, three quarters of its proof load` };
823
+ try {
824
+ limit = F.seating(fx, { head: 'button', material: { name, rules: mat.rules }, force: 1 }).limit;
825
+ full = F.preload(fx, { force: 1 }).full;
826
+ } catch {
827
+ return null;
828
+ }
829
+ const K = DEFAULTS.nut_factor.value,
830
+ force = limit * area,
831
+ torque = (K * fx.major * force) / 1000,
832
+ by = torque <= full.torque ? 'lips' : 'screw';
833
+ const T = +Math.min(torque, full.torque).toFixed(2),
834
+ most = seatMost(fx, force, full.torque);
835
+ return {
836
+ area: +area.toFixed(2),
837
+ limit,
838
+ force: +force.toFixed(1),
839
+ torque: T,
840
+ most,
841
+ text:
842
+ by === 'lips'
843
+ ? `on ${name} (${mm(limit)} MPa) the ${mm(+area.toFixed(1))} mm² either side of the opening takes ${mm(+force.toFixed(0))} N, a tightening of ${mm(T)} N m (the lips' bending not counted: an estimate), so tighten to ${mm(most)} N m at most, ${HALF_THAT}`
844
+ : `the lips take ${mm(+force.toFixed(0))} N on ${mm(+area.toFixed(1))} mm² of ${name}, more than the screw tightened fully: ${mm(T)} N m, three quarters of its proof load${most < hundredthDown(full.torque) ? `; half what the lips take, ${mm(most)} N m, is the most to tighten to (${SCATTER})` : ''}`,
845
+ };
846
+ }
847
+ // The most torque to tighten a screw to on a seat that takes `force` N (issue #582): half what the seat takes
848
+ // (fixings.load_margin, since the clamp a torque gives scatters by a quarter to a third), within a screw tightened
849
+ // fully (three quarters of its proof load, `full` N m), rounded down to the hundredth. The rule screwLoad of
850
+ // @rulecad/fixings keeps under a load, so a joint is tightened alike with a load on it and without
851
+ const hundredthDown = (t) => Math.floor(t * 100 + 1e-9) / 100,
852
+ SCATTER = "fixings.load_margin: a torque's clamp scatters by a quarter to a third",
853
+ HALF_THAT = `half that (${SCATTER})`;
854
+ function seatMost(fx, force, full = Infinity) {
855
+ return hundredthDown(
856
+ Math.min((DEFAULTS.nut_factor.value * fx.major * force) / DEFAULTS.load_margin.value / 1000, full),
857
+ );
361
858
  }
362
859
  // "into" as a slot on a beam (x1.top, x1.top.2, x1.top@120): the beam, the face's slots the screws may go in, the distance
363
860
  // where one is given; null where into is not a beam's face (a part, or a beam's end: a tap there is read from its ops)
364
861
  function slotInto(s, n, what) {
365
- const i = String(n).indexOf('.'), id = i < 0 ? n : n.slice(0, i), rest = i < 0 ? '' : n.slice(i + 1).trim(), o = s.objects.find((x) => x.id === id && x.beam);
862
+ const i = String(n).indexOf('.'),
863
+ id = i < 0 ? n : n.slice(0, i),
864
+ rest = i < 0 ? '' : n.slice(i + 1).trim(),
865
+ o = s.objects.find((x) => x.id === id && x.beam);
366
866
  const m = o && /^(top|bottom|front|back)(?:\.(\d+))?(?:@(.+))?$/.exec(rest);
367
867
  if (!m) return null;
368
- const b = o.beam, all = b.places.filter((p) => p.face === m[1]), places = m[2] ? all.filter((p) => p.index === +m[2]) : all;
369
- if (!places.length) throw new Error(`${what}: ${id}'s ${m[1]} face has ${all.length} slot${all.length === 1 ? '' : 's'}: into names ${all.map((p) => `${id}.${p.name}`).join(' or ') || `another face of ${id}`}`);
868
+ const b = o.beam,
869
+ all = b.places.filter((p) => p.face === m[1]),
870
+ places = m[2] ? all.filter((p) => p.index === +m[2]) : all;
871
+ if (!places.length)
872
+ throw new Error(
873
+ `${what}: ${id}'s ${m[1]} face has ${all.length} slot${all.length === 1 ? '' : 's'}: into names ${all.map((p) => `${id}.${p.name}`).join(' or ') || `another face of ${id}`}`,
874
+ );
370
875
  const open = places.filter((p) => p.slot);
371
- if (!open.length) throw new Error(`${what}: ${id}'s ${rest.split('@')[0]} face is closed: there is no slot there for a nut. Faces of ${b.profile.name} with a slot: ${[...new Set(b.places.filter((p) => p.slot).map((p) => p.face))].join(', ') || 'none'}`);
876
+ if (!open.length)
877
+ throw new Error(
878
+ `${what}: ${id}'s ${rest.split('@')[0]} face is closed: there is no slot there for a nut. Faces of ${b.profile.name} with a slot: ${[...new Set(b.places.filter((p) => p.slot).map((p) => p.face))].join(', ') || 'none'}`,
879
+ );
372
880
  let distance = null;
373
- if (m[3] != null) { try { distance = beamAnchor(b, `${open[0].name}@${m[3]}`).distance; } catch (e) { throw new Error(`${what}: ${String(e.message).replace(/^beamAnchor: /, '')}`); } }
374
- return { item: id, beam: b, face: m[1], places: open.map((p) => ({ ...p, slotModel: b.profile.slots[p.slot] })), distance, address: rest };
881
+ if (m[3] != null) {
882
+ try {
883
+ distance = beamAnchor(b, `${open[0].name}@${m[3]}`).distance;
884
+ } catch (e) {
885
+ throw new Error(`${what}: ${String(e.message).replace(/^beamAnchor: /, '')}`);
886
+ }
887
+ }
888
+ return {
889
+ item: id,
890
+ beam: b,
891
+ face: m[1],
892
+ places: open.map((p) => ({ ...p, slotModel: b.profile.slots[p.slot] })),
893
+ distance,
894
+ address: rest,
895
+ };
375
896
  }
376
897
  // what is under a screw's head in a slot past the part: the lip, or down to where the nut seats under sloped lips
377
- const lipSays = (sl) => (sl.seat > sl.lip + 1e-6 ? `the ${mm2(sl.seat)} mm down to its nut's seat under the slot's sloped ${mm2(sl.lip)} mm lips` : `the slot's ${mm2(sl.lip)} mm lip`);
898
+ const lipSays = (sl) =>
899
+ sl.seat > sl.lip + 1e-6
900
+ ? `the ${mm2(sl.seat)} mm down to its nut's seat under the slot's sloped ${mm2(sl.lip)} mm lips`
901
+ : `the slot's ${mm2(sl.lip)} mm lip`;
902
+ // The world's axis a direction lies nearest, as a side is named: "+x", "-z"
903
+ const sideOf = (v) => {
904
+ const k = [0, 1, 2].reduce((m, i) => (Math.abs(v[i]) > Math.abs(v[m]) ? i : m), 0);
905
+ return `${v[k] < 0 ? '-' : '+'}${'xyz'[k]}`;
906
+ };
907
+ // fasten.wall: the plastic round the far hole, side by side at the middle of its first full-size stretch, where the screw forms or holds
908
+ // its thread in a printed part (a pilot, a tapped or printed thread, a heat-set insert). The thinnest side is held to
909
+ // the insert's least wall (the thread set's insert_wall), or, for a thread in the plastic itself, to the wall a boss
910
+ // fixings.boss_diameter across leaves round the hole as drawn. A thin side splits as the screw goes in or the insert is
911
+ // pressed, and the joint holds less than its engagement says. Said as a warning: the figures are makers' guides
912
+ function wallSays(end, { x, fx, flip, R, intoMat, say }) {
913
+ if (!['pilot', 'tap', 'thread', 'insert'].includes(end.kind) || end.beamTap || end.motor || end.slot) return;
914
+ if (intoMat.cls !== 'plastic' || !end.main?.of?.near || !(end.depth > 0)) return;
915
+ const insert = end.kind === 'insert',
916
+ holeD = insert ? end.d : end.kind === 'thread' ? end.free : end.d;
917
+ let want, rule;
918
+ if (insert) {
919
+ const w = fx.figures.insert_wall?.value;
920
+ if (typeof w !== 'number') return;
921
+ want = w;
922
+ rule = `${fx.set}.insert_wall asks ${mm(w)} mm`;
923
+ } else {
924
+ const k = DEFAULTS.boss_diameter.value,
925
+ outer = k * fx.major;
926
+ want = (outer - holeD) / 2;
927
+ rule = `fixings.boss_diameter asks a boss ${mm(k)} diameters across, ${mm(outer)} mm, so ${mm2(want)} mm round its ${mm2(holeD)} mm hole`;
928
+ }
929
+ // (the middle of the hole's first stretch at its full size, where the thread is: a hole that runs on through a cavity,
930
+ // as a set screw's down through a wall into a bore, has only air round it there)
931
+ const lo = Math.max(end.mouth, end.main.z0 ?? end.mouth),
932
+ hi = Math.min(end.mouth + end.depth, end.main.z1 ?? end.mouth + end.depth),
933
+ z = hi > lo ? (lo + hi) / 2 : end.mouth + end.depth / 2,
934
+ down = z - end.mouth,
935
+ t = thinnest(end.main.of.near, flip ? -z : z, R);
936
+ if (!t) return;
937
+ const pr = end.main.of,
938
+ local = [0, 1, 2].map((c) => pr.x[c] * Math.cos(t.angle) + pr.y[c] * Math.sin(t.angle)),
939
+ m = end.main.part?.m,
940
+ world = m ? [0, 1, 2].map((r) => m[r] * local[0] + m[4 + r] * local[1] + m[8 + r] * local[2]) : local,
941
+ side = sideOf(world),
942
+ what = insert ? "its heat-set insert's hole" : end.kind === 'pilot' ? 'its pilot' : 'its thread',
943
+ values = { wall: r3(t.wall), least: r3(want), side, depth: r3(down) };
944
+ if (t.atLeast || t.wall >= want - FASTEN.wall.value)
945
+ say(
946
+ 'fasten.wall',
947
+ 'pass',
948
+ // (said the same for each screw that passes, so the screws share one finding; the wall measured is in values)
949
+ `${x.into} has at least ${mm2(want)} mm of plastic round ${what} on every side, ${mm2(down)} mm down: ${rule}`,
950
+ values,
951
+ );
952
+ else
953
+ say(
954
+ 'fasten.wall',
955
+ 'warn',
956
+ `${x.into} has ${t.open ? 'no plastic' : `only ${mm2(t.wall)} mm of plastic`} round ${what} on its ${side} side, ${mm2(down)} mm down, where ${rule}: the wall can split as the ${insert ? 'insert is pressed in' : 'screw cuts its thread'}, and the joint holds less than its thread says. Move the hole in from that side, or give ${x.into} more material there`,
957
+ values,
958
+ );
959
+ }
378
960
  // A screw into a slot (into is slotInto's): where its axis meets the face, read in the beam's own frame, held to a slot's
379
961
  // centre line within the play its hole gives it (fasten.slot); then the slot nut under the lips, as the far end: its
380
962
  // thread from its tongue down, the slot's floor under it. null where the screw is not over a slot, said as fasten.slot
381
963
  function slotEnd(s, at, n, { B, O, D, x, fx, cl, clr, say, sc }) {
382
- const pm = B.parts.find((p) => p.m)?.m, item = at.item, part = top(x.through.at(-1));
383
- if (!pm) { say('fasten.slot', 'fail', `${item} is not placed, so its slots are nowhere`); return null; }
384
- const inv = mat4.invert(mat4.create(), pm), Ol = vec3.transform([0, 0, 0], O, inv), El = vec3.transform([0, 0, 0], add(O, D), inv), Dl = unit([El[0] - Ol[0], El[1] - Ol[1], El[2] - Ol[2]]);
385
- const hits = at.places.map((p) => {
386
- const nrm = [p.normal[0], p.normal[1], 0], dn = dot(Dl, nrm);
387
- if (dn > -1e-6) return null; // (pointing out of the face, or along it)
388
- const t = ((p.at[0] - Ol[0]) * nrm[0] + (p.at[1] - Ol[1]) * nrm[1]) / dn, Q = add(Ol, Dl, t);
389
- return { p, t, across: (Q[0] - p.at[0]) * p.along[0] + (Q[1] - p.at[1]) * p.along[1], along: Q[2], angle: (Math.acos(Math.min(1, -dn)) * 180) / Math.PI };
390
- }).filter(Boolean).sort((a, b) => Math.abs(a.across) - Math.abs(b.across));
964
+ const pm = B.parts.find((p) => p.m)?.m,
965
+ item = at.item,
966
+ part = top(x.through.at(-1));
967
+ if (!pm) {
968
+ say('fasten.slot', 'fail', `${item} is not placed, so its slots are nowhere`);
969
+ return null;
970
+ }
971
+ const inv = mat4.invert(mat4.create(), pm),
972
+ Ol = vec3.transform([0, 0, 0], O, inv),
973
+ El = vec3.transform([0, 0, 0], add(O, D), inv),
974
+ Dl = unit([El[0] - Ol[0], El[1] - Ol[1], El[2] - Ol[2]]);
975
+ const hits = at.places
976
+ .map((p) => {
977
+ const nrm = [p.normal[0], p.normal[1], 0],
978
+ dn = dot(Dl, nrm);
979
+ if (dn > -1e-6) return null; // (pointing out of the face, or along it)
980
+ const t = ((p.at[0] - Ol[0]) * nrm[0] + (p.at[1] - Ol[1]) * nrm[1]) / dn,
981
+ Q = add(Ol, Dl, t);
982
+ return {
983
+ p,
984
+ t,
985
+ across: (Q[0] - p.at[0]) * p.along[0] + (Q[1] - p.at[1]) * p.along[1],
986
+ along: Q[2],
987
+ angle: (Math.acos(Math.min(1, -dn)) * 180) / Math.PI,
988
+ };
989
+ })
990
+ .filter(Boolean)
991
+ .sort((a, b) => Math.abs(a.across) - Math.abs(b.across));
391
992
  const face = `${item}'s ${at.face} face`;
392
- if (!hits.length) { say('fasten.slot', 'fail', `the screw does not go into ${face}: its axis points along it or away from it`); return null; }
393
- const h = hits[0], hole = cl.at(-1), d = hole && !hole.lips ? hole.d : clr.normal?.diameter ?? fx.major, play = Math.max(0, (d - fx.major) / 2), off = Math.abs(h.across), L = at.beam.length;
394
- const named = at.beam.places.filter((q) => q.face === h.p.face).length > 1 ? h.p.name : h.p.face, slot = `${item}'s ${named} slot`, values = { distance: r3(off), play: r3(play), along: r3(h.along) };
395
- const pitch = at.places.length > 1 ? Math.hypot(at.places[1].at[0] - at.places[0].at[0], at.places[1].at[1] - at.places[0].at[1]) : null;
396
- const bad = (text, v = values) => { say('fasten.slot', 'fail', text, v); return null; };
397
- if (h.angle > FASTEN.square.value) return bad(`the screw meets ${face} ${mm(+h.angle.toFixed(2))}° from square: a slot nut pulls straight out of its slot, so the screw stands square to the face`, { ...values, angle: +h.angle.toFixed(2) });
398
- if (off > play + 1e-3) return bad(`${part}'s hole is ${mm(off)} mm off the centre line of ${slot}, where its ${mm(d)} mm hole lets ${an(fx.thread)} ${fx.thread} screw move ${mm(play)} mm: the screw meets ${at.face === 'top' || at.face === 'bottom' ? 'the face' : 'the side'} beside the slot, not its nut${pitch ? `. ${item}'s ${at.face} slots are ${mm(pitch)} mm apart` : ''}. Move the hole ${mm(off)} mm, or ${part} is drawn for another profile`);
399
- if (h.along < -1e-3 || h.along > L + 1e-3) return bad(`the screw meets ${face} ${mm(h.along)} mm from its end a, past the beam: it is ${mm(L)} mm long`);
400
- say('fasten.slot', 'pass', `over the centre line of ${slot} (${h.p.slot})${off > 1e-3 ? `, ${mm(off)} mm off it, within the ${mm(play)} mm its ${mm(d)} mm hole gives` : ''}, ${mm(h.along)} mm from ${item}'s end a`, values);
993
+ if (!hits.length) {
994
+ say('fasten.slot', 'fail', `the screw does not go into ${face}: its axis points along it or away from it`);
995
+ return null;
996
+ }
997
+ const h = hits[0],
998
+ hole = cl.at(-1),
999
+ d = hole && !hole.lips ? hole.d : (clr.normal?.diameter ?? fx.major),
1000
+ play = Math.max(0, (d - fx.major) / 2),
1001
+ off = Math.abs(h.across),
1002
+ L = at.beam.length;
1003
+ const named = at.beam.places.filter((q) => q.face === h.p.face).length > 1 ? h.p.name : h.p.face,
1004
+ slot = `${item}'s ${named} slot`,
1005
+ values = { distance: r3(off), play: r3(play), along: r3(h.along) };
1006
+ const pitch =
1007
+ at.places.length > 1
1008
+ ? Math.hypot(at.places[1].at[0] - at.places[0].at[0], at.places[1].at[1] - at.places[0].at[1])
1009
+ : null;
1010
+ const bad = (text, v = values) => {
1011
+ say('fasten.slot', 'fail', text, v);
1012
+ return null;
1013
+ };
1014
+ if (h.angle > FASTEN.square.value)
1015
+ return bad(
1016
+ `the screw meets ${face} ${mm(+h.angle.toFixed(2))}° from square: a slot nut pulls straight out of its slot, so the screw stands square to the face`,
1017
+ { ...values, angle: +h.angle.toFixed(2) },
1018
+ );
1019
+ if (off > play + 1e-3)
1020
+ return bad(
1021
+ `${part}'s hole is ${mm(off)} mm off the centre line of ${slot}, where its ${mm(d)} mm hole lets ${an(fx.thread)} ${fx.thread} screw move ${mm(play)} mm: the screw meets ${at.face === 'top' || at.face === 'bottom' ? 'the face' : 'the side'} beside the slot, not its nut${pitch ? `. ${item}'s ${at.face} slots are ${mm(pitch)} mm apart` : ''}. Move the hole ${mm(off)} mm, or ${part} is drawn for another profile`,
1022
+ );
1023
+ if (h.along < -1e-3 || h.along > L + 1e-3)
1024
+ return bad(`the screw meets ${face} ${mm(h.along)} mm from its end a, past the beam: it is ${mm(L)} mm long`);
1025
+ // the nut is no point: it runs half its length either side of the screw along the slot, and all of it is in the slot
1026
+ const half = (n.length ?? 0) / 2,
1027
+ span = [h.along - half, h.along + half],
1028
+ past = span[0] < -1e-3 ? { end: 'a', by: -span[0] } : span[1] > L + 1e-3 ? { end: 'b', by: span[1] - L } : null;
1029
+ if (past)
1030
+ return bad(
1031
+ `the screw meets ${face} ${mm(h.along)} mm from its end a, and its nut, ${n.name}, is ${mm(n.length)} mm long along the slot: it runs ${mm(+past.by.toFixed(3))} mm past ${item}'s end ${past.end}, out of the slot (the beam is ${mm(L)} mm long). Move ${part}'s hole at least ${mm(+past.by.toFixed(3))} mm in from end ${past.end}`,
1032
+ { ...values, length: n.length, span: span.map(r3), end: past.end, past: r3(past.by) },
1033
+ );
1034
+ say(
1035
+ 'fasten.slot',
1036
+ 'pass',
1037
+ `over the centre line of ${slot} (${h.p.slot})${off > 1e-3 ? `, ${mm(off)} mm off it, within the ${mm(play)} mm its ${mm(d)} mm hole gives` : ''}, ${mm(h.along)} mm from ${item}'s end a`,
1038
+ values,
1039
+ );
401
1040
  // the nut's top seats under the lips, lower where their undersides slope and it is wider than the opening (nutFit's
402
1041
  // slot_nut.seat): its thread, its tongue's with it, starts there
403
- const sm = h.p.slotModel, seat = n.fits?.find((q) => q.code === 'slot_nut.seat')?.values?.seat ?? sm.lip, zFace = h.t, zLip = zFace + seat, alongW = unit([pm[8], pm[9], pm[10]]);
404
- sc.slot = { item, place: h.p.name, named, face: at.face, slot: h.p.slot, distance: r3(h.along), nut: n.name, kind: n.nutKind, entry: n.entry, thread: fx.thread, part };
405
- sc.slotPlay = play; sc.slotSays = slot; // (for the place "into" gives, held over the group: slotPlaced)
406
- return { slot: { item, place: named, face: at.face, slot: h.p.slot, opening: sm.opening, lip: sm.lip, seat: r3(seat), along: alongW, distance: r3(h.along), part }, kind: 'nut', mouth: zFace, depth: sm.cavityDepth, floor: zFace + sm.cavityDepth,
407
- blind: true, far: zFace + sm.cavityDepth, d: fx.major, free: fx.major, nut: { kind: n.nutKind, model: n, z: zLip, seated: true }, zThr: zLip - n.tongueHeight, thread: n.height + n.tongueHeight };
1042
+ const sm = h.p.slotModel,
1043
+ seat = n.fits?.find((q) => q.code === 'slot_nut.seat')?.values?.seat ?? sm.lip,
1044
+ zFace = h.t,
1045
+ zLip = zFace + seat,
1046
+ alongW = unit([pm[8], pm[9], pm[10]]);
1047
+ sc.slot = {
1048
+ item,
1049
+ place: h.p.name,
1050
+ named,
1051
+ face: at.face,
1052
+ slot: h.p.slot,
1053
+ distance: r3(h.along),
1054
+ span: span.map(r3),
1055
+ nut: n.name,
1056
+ kind: n.nutKind,
1057
+ entry: n.entry,
1058
+ thread: fx.thread,
1059
+ part,
1060
+ };
1061
+ sc.slotPlay = play;
1062
+ sc.slotSays = slot; // (for the place "into" gives, held over the group: slotPlaced)
1063
+ return {
1064
+ slot: {
1065
+ item,
1066
+ place: named,
1067
+ face: at.face,
1068
+ slot: h.p.slot,
1069
+ opening: sm.opening,
1070
+ lip: sm.lip,
1071
+ seat: r3(seat),
1072
+ along: alongW,
1073
+ distance: r3(h.along),
1074
+ part,
1075
+ },
1076
+ kind: 'nut',
1077
+ mouth: zFace,
1078
+ depth: sm.cavityDepth,
1079
+ floor: zFace + sm.cavityDepth,
1080
+ blind: true,
1081
+ far: zFace + sm.cavityDepth,
1082
+ d: fx.major,
1083
+ free: fx.major,
1084
+ nut: { kind: n.nutKind, model: n, z: zLip, seated: true },
1085
+ zThr: zLip - n.tongueHeight,
1086
+ thread: n.height + n.tongueHeight,
1087
+ };
408
1088
  }
409
1089
  /**
410
1090
  * Which way a screw goes along its anchor's axis, from the reach of the first part under its head and of the part it
@@ -415,7 +1095,9 @@ function slotEnd(s, at, n, { B, O, D, x, fx, cl, clr, say, sc }) {
415
1095
  * @param {number[]} first @param {number[]} last @returns {boolean} true where the axis is turned
416
1096
  */
417
1097
  export function screwFlips(first, last) {
418
- const mid = (r) => (r[0] + r[1]) / 2, tie = Math.abs(mid(last) - mid(first)) < 1e-3, astride = first[0] < last[0] - 1e-3 && first[1] > last[1] + 1e-3;
1098
+ const mid = (r) => (r[0] + r[1]) / 2,
1099
+ tie = Math.abs(mid(last) - mid(first)) < 1e-3,
1100
+ astride = first[0] < last[0] - 1e-3 && first[1] > last[1] + 1e-3;
419
1101
  return tie && astride ? true : mid(last) < mid(first);
420
1102
  }
421
1103
  // "into" with a distance (x1.top@150) places the fasten's screws as a group: the middle of their spread along the slot is
@@ -423,20 +1105,50 @@ export function screwFlips(first, last) {
423
1105
  function slotPlaced(rel, at, x) {
424
1106
  const on = rel.screws.filter((sc) => sc.slot);
425
1107
  if (!on.length) return;
426
- const along = on.map((sc) => sc.slot.distance), lo = Math.min(...along), hi = Math.max(...along), mid = (lo + hi) / 2, play = Math.min(...on.map((sc) => sc.slotPlay));
427
- const off = Math.abs(mid - at.distance), values = { along: r3(mid), wanted: r3(at.distance), distance: r3(off), play: r3(play) }, slot = on[0].slotSays, part = top(x.through.at(-1));
428
- const where = on.length > 1 ? `the middle of its ${on.length} screws (${mm(lo)} to ${mm(hi)} mm from ${at.item}'s end a) is ${mm(mid)} mm along ${slot}` : `the screw meets ${slot} ${mm(mid)} mm from ${at.item}'s end a`;
429
- const said = off > play + 1e-3
430
- ? { level: 'fail', text: `${where}, and into says ${x.into}, ${mm(at.distance)} mm: ${mm(off)} mm apart, where ${on.length > 1 ? 'their holes give' : 'its hole gives'} ${mm(play)} mm. Move ${part} ${mm(off)} mm along ${at.item}, or give the place it is at`, values }
431
- : { level: 'pass', text: `${where}, where into says ${x.into}${off > 1e-3 ? `, ${mm(off)} mm off it, within the ${mm(play)} mm ${on.length > 1 ? 'their holes give' : 'its hole gives'}` : ''}`, values };
1108
+ const along = on.map((sc) => sc.slot.distance),
1109
+ lo = Math.min(...along),
1110
+ hi = Math.max(...along),
1111
+ mid = (lo + hi) / 2,
1112
+ play = Math.min(...on.map((sc) => sc.slotPlay));
1113
+ const off = Math.abs(mid - at.distance),
1114
+ values = { along: r3(mid), wanted: r3(at.distance), distance: r3(off), play: r3(play) },
1115
+ slot = on[0].slotSays,
1116
+ part = top(x.through.at(-1));
1117
+ const where =
1118
+ on.length > 1
1119
+ ? `the middle of its ${on.length} screws (${mm(lo)} to ${mm(hi)} mm from ${at.item}'s end a) is ${mm(mid)} mm along ${slot}`
1120
+ : `the screw meets ${slot} ${mm(mid)} mm from ${at.item}'s end a`;
1121
+ const said =
1122
+ off > play + 1e-3
1123
+ ? {
1124
+ level: 'fail',
1125
+ text: `${where}, and into says ${x.into}, ${mm(at.distance)} mm: ${mm(off)} mm apart, where ${on.length > 1 ? 'their holes give' : 'its hole gives'} ${mm(play)} mm. Move ${part} ${mm(off)} mm along ${at.item}, or give the place it is at`,
1126
+ values,
1127
+ }
1128
+ : {
1129
+ level: 'pass',
1130
+ text: `${where}, where into says ${x.into}${off > 1e-3 ? `, ${mm(off)} mm off it, within the ${mm(play)} mm ${on.length > 1 ? 'their holes give' : 'its hole gives'}` : ''}`,
1131
+ values,
1132
+ };
432
1133
  for (const sc of on) (sc.found['fasten.slot'] ||= []).push(said);
433
1134
  }
434
1135
  // A slot nut as a part's shape, made once for each: frames' reference solid, in the slot's frame (z out of the face)
435
1136
  const slotShapes = new Map();
436
1137
  function slotNutShape(n) {
437
1138
  if (!slotShapes.has(n.name)) {
438
- const g = slotNut(n, { given: { sets: framesContext().sets } }), [p] = named({ body: g }, { body: { label: n.name } });
439
- slotShapes.set(n.name, { geometry: p.geometry, polygons: p.polygons, triangles: p.triangles, model: { name: n.name, title: n.title, mass: n.mass, kind: n.nutKind, length: null }, hash: `fixing:${crypto.createHash('sha256').update(JSON.stringify([n.name, p.polygons])).digest('hex').slice(0, 16)}` });
1139
+ const g = slotNut(n, { given: { sets: framesContext().sets } }),
1140
+ [p] = named({ body: g }, { body: { label: n.name } });
1141
+ slotShapes.set(n.name, {
1142
+ geometry: p.geometry,
1143
+ polygons: p.polygons,
1144
+ triangles: p.triangles,
1145
+ model: { name: n.name, title: n.title, mass: n.mass, kind: n.nutKind, length: null },
1146
+ hash: `fixing:${crypto
1147
+ .createHash('sha256')
1148
+ .update(JSON.stringify([n.name, p.polygons]))
1149
+ .digest('hex')
1150
+ .slice(0, 16)}`,
1151
+ });
440
1152
  }
441
1153
  return slotShapes.get(n.name);
442
1154
  }
@@ -446,12 +1158,17 @@ function beamTap(s, B, O, D) {
446
1158
  for (const p of B.parts) {
447
1159
  const b = s.objects.find((o) => o.id === p.leaf)?.beam;
448
1160
  if (!b || !p.m) continue;
449
- for (const t of b.ops.filter((x) => x.op === 'tap')) for (const bn of t.bores) {
450
- const bo = b.bores.find((q) => q.name === bn), P = vec3.transform([0, 0, 0], [bo.at[0], bo.at[1], bo.end === 'a' ? 0 : b.length], p.m), e = vec3.transform([0, 0, 0], [bo.at[0], bo.at[1], bo.end === 'a' ? 1 : b.length - 1], p.m);
451
- const Z = unit([e[0] - P[0], e[1] - P[1], e[2] - P[2]]), off = Math.hypot(...cross(add(P, O, -1), D));
452
- const near = Math.abs(dot(add(P, O, -1), D));
453
- if (Math.abs(Math.abs(dot(Z, D)) - 1) < 1e-6 && off <= FASTEN.align.value && (!best || near < best.near)) best = { thread: t.thread, depth: t.depth, bore: bn, length: b.length, near };
454
- }
1161
+ for (const t of b.ops.filter((x) => x.op === 'tap'))
1162
+ for (const bn of t.bores) {
1163
+ const bo = b.bores.find((q) => q.name === bn),
1164
+ P = vec3.transform([0, 0, 0], [bo.at[0], bo.at[1], bo.end === 'a' ? 0 : b.length], p.m),
1165
+ e = vec3.transform([0, 0, 0], [bo.at[0], bo.at[1], bo.end === 'a' ? 1 : b.length - 1], p.m);
1166
+ const Z = unit([e[0] - P[0], e[1] - P[1], e[2] - P[2]]),
1167
+ off = Math.hypot(...cross(add(P, O, -1), D));
1168
+ const near = Math.abs(dot(add(P, O, -1), D));
1169
+ if (Math.abs(Math.abs(dot(Z, D)) - 1) < 1e-6 && off <= FASTEN.align.value && (!best || near < best.near))
1170
+ best = { thread: t.thread, depth: t.depth, bore: bn, length: b.length, near };
1171
+ }
455
1172
  }
456
1173
  if (!best) return null;
457
1174
  const { near, ...out } = best;
@@ -465,9 +1182,13 @@ function printedEnd(s, B, O, D) {
465
1182
  const b = s.objects.find((o) => o.id === p.leaf)?.beam;
466
1183
  if (!b?.printed?.ends || !p.m) continue;
467
1184
  for (const [e, fix] of Object.entries(b.printed.ends)) {
468
- const z = e === 'a' ? 0 : b.length, P = vec3.transform([0, 0, 0], [fix.at[0], fix.at[1], z], p.m), q = vec3.transform([0, 0, 0], [fix.at[0], fix.at[1], e === 'a' ? 1 : b.length - 1], p.m);
469
- const Z = unit([q[0] - P[0], q[1] - P[1], q[2] - P[2]]), off = Math.hypot(...cross(add(P, O, -1), D));
470
- if (Math.abs(Math.abs(dot(Z, D)) - 1) < 1e-6 && off <= FASTEN.align.value) return { end: e, thread: fix.thread, kind: fix.kind };
1185
+ const z = e === 'a' ? 0 : b.length,
1186
+ P = vec3.transform([0, 0, 0], [fix.at[0], fix.at[1], z], p.m),
1187
+ q = vec3.transform([0, 0, 0], [fix.at[0], fix.at[1], e === 'a' ? 1 : b.length - 1], p.m);
1188
+ const Z = unit([q[0] - P[0], q[1] - P[1], q[2] - P[2]]),
1189
+ off = Math.hypot(...cross(add(P, O, -1), D));
1190
+ if (Math.abs(Math.abs(dot(Z, D)) - 1) < 1e-6 && off <= FASTEN.align.value)
1191
+ return { end: e, thread: fix.thread, kind: fix.kind };
471
1192
  }
472
1193
  }
473
1194
  return null;
@@ -486,183 +1207,471 @@ function printedEnd(s, B, O, D) {
486
1207
  export function fastenOf(s, worlds, opts = {}) {
487
1208
  const list = s.a.fasten || [];
488
1209
  if (!list.length) return { relations: [], hardware: [], fits: [] };
489
- const { F, material, printer } = fixingsOf(s.project), parts = s.parts.filter((p) => !p.hardware), ids = s.motion.items.map((x) => x[0]);
1210
+ const { F, material, printer } = fixingsOf(s.project),
1211
+ parts = s.parts.filter((p) => !p.hardware),
1212
+ ids = s.motion.items.map((x) => x[0]);
490
1213
  const isNamed = (p, n) => p.name === n || p.leaf === n || p.item === n || p.name.startsWith(`${n}.`);
491
1214
  const pick = (n) => parts.filter((p) => isNamed(p, n) && p.role !== 'support');
492
- const world = (k, pt) => [0, 1, 2].map((r) => worlds[k][4 * r] * pt[0] + worlds[k][4 * r + 1] * pt[1] + worlds[k][4 * r + 2] * pt[2] + worlds[k][4 * r + 3]);
493
- const turned = (k, v) => [0, 1, 2].map((r) => worlds[k][4 * r] * v[0] + worlds[k][4 * r + 1] * v[1] + worlds[k][4 * r + 2] * v[2]);
1215
+ const world = (k, pt) =>
1216
+ [0, 1, 2].map(
1217
+ (r) =>
1218
+ worlds[k][4 * r] * pt[0] + worlds[k][4 * r + 1] * pt[1] + worlds[k][4 * r + 2] * pt[2] + worlds[k][4 * r + 3],
1219
+ );
1220
+ const turned = (k, v) =>
1221
+ [0, 1, 2].map((r) => worlds[k][4 * r] * v[0] + worlds[k][4 * r + 1] * v[1] + worlds[k][4 * r + 2] * v[2]);
494
1222
  const rowsToMat4 = (r) => [r[0], r[4], r[8], 0, r[1], r[5], r[9], 0, r[2], r[6], r[10], 0, r[3], r[7], r[11], 1];
495
- const relations = [], hardware = [], fits = [];
1223
+ const relations = [],
1224
+ hardware = [],
1225
+ fits = [];
496
1226
 
497
1227
  list.forEach((x, k) => {
498
- const what = `fasten ${k + 1}`, through = x.through || [];
1228
+ const what = `fasten ${k + 1}`,
1229
+ through = x.through || [];
499
1230
  // Refused by name before anything is measured: the screw, the parts, where the screws go
500
1231
  let fx;
501
- try { fx = F.fixingModel(String(x.screw), {}, { anyLength: true }); } catch (e) { throw new Error(`${what}: ${e.message}`); }
502
- if (!['screw', 'thread'].includes(fx.item)) throw new Error(`${what}: "screw" names a screw by its thread and head ("M3 cap", "M4x12 button"): ${x.screw} is ${/^[aeiou]/.test(fx.item) ? 'an' : 'a'} ${fx.item}`);
1232
+ try {
1233
+ fx = F.fixingModel(String(x.screw), {}, { anyLength: true });
1234
+ } catch (e) {
1235
+ throw new Error(`${what}: ${e.message}`);
1236
+ }
1237
+ if (!['screw', 'thread'].includes(fx.item))
1238
+ throw new Error(
1239
+ `${what}: "screw" names a screw by its thread and head ("M3 cap", "M4x12 button"): ${x.screw} is ${/^[aeiou]/.test(fx.item) ? 'an' : 'a'} ${fx.item}`,
1240
+ );
503
1241
  // a printed bolt ("M8x20 hex printed"): refused by name where its thread is finer than the printer prints
504
- if (fx.printed) { try { F.printedBoltModel(fx, { length: fx.length ?? 20, material }); } catch (e) { throw new Error(`${what}: ${e.message.replace(/^printedBoltModel: /, '')}`); } }
1242
+ if (fx.printed) {
1243
+ try {
1244
+ F.printedBoltModel(fx, { length: fx.length ?? 20, material });
1245
+ } catch (e) {
1246
+ throw new Error(`${what}: ${e.message.replace(/^printedBoltModel: /, '')}`);
1247
+ }
1248
+ }
505
1249
  const form = fx.head?.form ?? (fx.made.heads.includes('cap') ? 'cap' : fx.made.heads[0]);
506
- if (!Array.isArray(through)) throw new Error(`${what}: "through" lists the parts the screw passes, in order from under its head (["bracket"])`);
1250
+ if (!Array.isArray(through))
1251
+ throw new Error(
1252
+ `${what}: "through" lists the parts the screw passes, in order from under its head (["bracket"])`,
1253
+ );
507
1254
  if (typeof x.into !== 'string' || !x.into) throw new Error(`${what}: "into" names the part the screw ends in`);
508
1255
  const slotAt = slotInto(s, x.into, what); // (into a slot on a beam: a slot nut under its lips)
509
- const members = [...through, x.into].map((n, j) => { const ps = pick(slotAt && j === through.length ? slotAt.item : n); if (!ps.length) throw new Error(`${what}: no part "${n}" (items: ${ids.join(', ')})`); return { name: n, parts: ps }; });
1256
+ const members = [...through, x.into].map((n, j) => {
1257
+ const ps = pick(slotAt && j === through.length ? slotAt.item : n);
1258
+ if (!ps.length) throw new Error(`${what}: no part "${n}" (items: ${ids.join(', ')})`);
1259
+ return { name: n, parts: ps };
1260
+ });
510
1261
  // A yoke (a screw through one cheek, what lies between, into the other) or a split clamp (across its own slot)
511
1262
  const yoke = through.length > 0 && through[0] === x.into;
512
- if (yoke && x.holes != null) throw new Error(`${what}: a screw that ends in ${x.into}, the part under its head, is placed with "at": an anchor on each screw's axis, pointing from the head into the part`);
513
- if ((x.at == null) === (x.holes == null)) throw new Error(`${what}: give "at" (an anchor for each screw: ["${top(through[0] ?? x.into)}.h1"]) or "holes" (a part whose holes are the screws' places), one of the two`);
514
- if (slotAt && x.nut != null && x.nut !== true && !NUT_KINDS.includes(x.nut)) throw new Error(`${what}: into a slot, "nut" is the slot nut's kind, ${NUT_KINDS.join(', ')}, or true for the strongest made for the slot (got ${JSON.stringify(x.nut)})`);
515
- if (!slotAt && x.nut != null && x.nut !== false && x.nut !== true && !NUTS.includes(x.nut)) throw new Error(`${what}: "nut" is true (a hexagon nut) or ${NUTS.join(', ')} (got ${JSON.stringify(x.nut)})${NUT_KINDS.includes(x.nut) ? `: a ${x.nut} nut goes in a beam's slot, so "into" names the slot (x1.top)` : ''}`);
1263
+ if (yoke && x.holes != null)
1264
+ throw new Error(
1265
+ `${what}: a screw that ends in ${x.into}, the part under its head, is placed with "at": an anchor on each screw's axis, pointing from the head into the part`,
1266
+ );
1267
+ if ((x.at == null) === (x.holes == null))
1268
+ throw new Error(
1269
+ `${what}: give "at" (an anchor for each screw: ["${top(through[0] ?? x.into)}.h1"]) or "holes" (a part whose holes are the screws' places), one of the two`,
1270
+ );
1271
+ if (slotAt && x.nut != null && x.nut !== true && !NUT_KINDS.includes(x.nut))
1272
+ throw new Error(
1273
+ `${what}: into a slot, "nut" is the slot nut's kind, ${NUT_KINDS.join(', ')}, or true for the strongest made for the slot (got ${JSON.stringify(x.nut)})`,
1274
+ );
1275
+ if (!slotAt && x.nut != null && x.nut !== false && x.nut !== true && !NUTS.includes(x.nut))
1276
+ throw new Error(
1277
+ `${what}: "nut" is true (a hexagon nut) or ${NUTS.join(', ')} (got ${JSON.stringify(x.nut)})${NUT_KINDS.includes(x.nut) ? `: a ${x.nut} nut goes in a beam's slot, so "into" names the slot (x1.top)` : ''}`,
1278
+ );
516
1279
  const wantNut = slotAt ? null : x.nut === true ? 'hex' : x.nut || null;
517
- if (form === 'set' && (through.length || wantNut || x.washer)) throw new Error(`${what}: a set screw goes into one part whole: give it "into" alone (no through, nut or washer)`);
518
- if (form !== 'set' && !through.length) throw new Error(`${what}: "through" names what the screw holds down, the part under its head: only a set screw has none`);
1280
+ if (form === 'set' && (through.length || wantNut || x.washer))
1281
+ throw new Error(
1282
+ `${what}: a set screw goes into one part whole: give it "into" alone (no through, nut or washer)`,
1283
+ );
1284
+ if (form !== 'set' && !through.length)
1285
+ throw new Error(
1286
+ `${what}: "through" names what the screw holds down, the part under its head: only a set screw has none`,
1287
+ );
519
1288
  const given = fx.length ?? (x.length != null ? s.num(x.length) : null);
520
- if (fx.length != null && x.length != null && Math.abs(s.num(x.length) - fx.length) > 1e-9) throw new Error(`${what}: ${x.screw} gives the length, and "length" says ${s.num(x.length)}: give it once`);
521
- if (given != null && !(given > 0)) throw new Error(`${what}: "length" is the screw's length, above 0 mm (got ${given})`);
1289
+ if (fx.length != null && x.length != null && Math.abs(s.num(x.length) - fx.length) > 1e-9)
1290
+ throw new Error(`${what}: ${x.screw} gives the length, and "length" says ${s.num(x.length)}: give it once`);
1291
+ if (given != null && !(given > 0))
1292
+ throw new Error(`${what}: "length" is the screw's length, above 0 mm (got ${given})`);
522
1293
  const torque = x.torque != null ? s.num(x.torque) : null;
523
- if (torque != null && !(torque > 0)) throw new Error(`${what}: "torque" is the tightening torque, above 0 N m (got ${torque})`);
524
- let head = null, washer = null;
525
- if (form !== 'set') { const m = F.screwModel(fx, { length: fx.length ?? 10, head: form, anyLength: true }); head = { form, across: m.headDiameter, height: m.headHeight, angle: fx.head?.angle ?? fx.figures.countersunk_angle?.value ?? 90 }; }
526
- if (x.washer) { try { washer = F.washerModel(fx.thread); } catch (e) { throw new Error(`${what}: ${e.message}`); } }
1294
+ if (torque != null && !(torque > 0))
1295
+ throw new Error(`${what}: "torque" is the tightening torque, above 0 N m (got ${torque})`);
1296
+ let head = null,
1297
+ washer = null;
1298
+ if (form !== 'set') {
1299
+ const m = F.screwModel(fx, { length: fx.length ?? 10, head: form, anyLength: true });
1300
+ head = {
1301
+ form,
1302
+ across: m.headDiameter,
1303
+ height: m.headHeight,
1304
+ angle: fx.head?.angle ?? fx.figures.countersunk_angle?.value ?? 90,
1305
+ };
1306
+ }
1307
+ if (x.washer) {
1308
+ try {
1309
+ washer = F.washerModel(fx.thread);
1310
+ } catch (e) {
1311
+ throw new Error(`${what}: ${e.message}`);
1312
+ }
1313
+ }
527
1314
  const nutModel = (kind) => F.nutModel(fx.thread, { kind });
528
- if (wantNut) { try { nutModel(wantNut); } catch (e) { throw new Error(`${what}: ${e.message}`); } }
1315
+ if (wantNut) {
1316
+ try {
1317
+ nutModel(wantNut);
1318
+ } catch (e) {
1319
+ throw new Error(`${what}: ${e.message}`);
1320
+ }
1321
+ }
529
1322
  // the slot nut: the one made for the slot's family and the thread, of the kind asked (the strongest where none is)
530
1323
  let slotNutM = null;
531
1324
  if (slotAt) {
532
- if (form === 'set') throw new Error(`${what}: a set screw goes into one part whole: into a slot, give a screw with a head ("${fx.thread} button")`);
533
- try { slotNutM = nutFor(slotAt.beam.profile, slotAt.places[0].name, fx.thread, { ...(typeof x.nut === 'string' ? { kind: x.nut } : {}), given: givenFor(framesContext(), slotAt.beam.profile.name) }); }
534
- catch (e) { throw new Error(`${what}: ${String(e.message).replace(/^nutFor: /, '')}`); }
1325
+ if (form === 'set')
1326
+ throw new Error(
1327
+ `${what}: a set screw goes into one part whole: into a slot, give a screw with a head ("${fx.thread} button")`,
1328
+ );
1329
+ try {
1330
+ slotNutM = nutFor(slotAt.beam.profile, slotAt.places[0].name, fx.thread, {
1331
+ ...(typeof x.nut === 'string' ? { kind: x.nut } : {}),
1332
+ given: givenFor(framesContext(), slotAt.beam.profile.name),
1333
+ });
1334
+ } catch (e) {
1335
+ throw new Error(`${what}: ${String(e.message).replace(/^nutFor: /, '')}`);
1336
+ }
535
1337
  }
536
1338
  const R = Math.max(head?.across ?? fx.major, washer?.diameter ?? 0, fx.major * 2.2) / 2 + 1.5;
537
1339
 
538
1340
  // A motor item ends the screws in its own tapped mounting holes, which its light solid does not draw; so does a bought
539
1341
  // part whose rule set gives tapped mounting holes (a supply's), held to the reach its maker allows
540
- const boughtMount = (() => { const o = s.objects.find((q) => q.id === top(x.into) && q.bought?.mount?.thread), k2 = o ? ids.indexOf(o.id) : -1; return o && k2 >= 0 ? { id: o.id, item: k2, model: { name: o.bought.set, mount: { thread: o.bought.mount.thread, holes: o.bought.mount.holes, depth: o.bought.mount.reach, reach: true } } } : null; })();
541
- const drive = (s.motion.drives || []).find((d) => d.id === top(x.into)) ?? boughtMount, Wm = drive ? worlds[drive.item] : null;
1342
+ const boughtMount = (() => {
1343
+ const o = s.objects.find((q) => q.id === top(x.into) && q.bought?.mount?.thread),
1344
+ k2 = o ? ids.indexOf(o.id) : -1;
1345
+ return o && k2 >= 0
1346
+ ? {
1347
+ id: o.id,
1348
+ item: k2,
1349
+ model: {
1350
+ name: o.bought.set,
1351
+ mount: {
1352
+ thread: o.bought.mount.thread,
1353
+ holes: o.bought.mount.holes,
1354
+ depth: o.bought.mount.reach,
1355
+ reach: true,
1356
+ },
1357
+ },
1358
+ }
1359
+ : null;
1360
+ })();
1361
+ const drive = (s.motion.drives || []).find((d) => d.id === top(x.into)) ?? boughtMount,
1362
+ Wm = drive ? worlds[drive.item] : null;
542
1363
  const onMount = (O, D) => {
543
1364
  if (!drive?.model.mount?.thread || !drive.model.mount.holes?.length) return null;
544
- const q = [O[0] - Wm[3], O[1] - Wm[7], O[2] - Wm[11]], l = [Wm[0] * q[0] + Wm[4] * q[1] + Wm[8] * q[2], Wm[1] * q[0] + Wm[5] * q[1] + Wm[9] * q[2]];
1365
+ const q = [O[0] - Wm[3], O[1] - Wm[7], O[2] - Wm[11]],
1366
+ l = [Wm[0] * q[0] + Wm[4] * q[1] + Wm[8] * q[2], Wm[1] * q[0] + Wm[5] * q[1] + Wm[9] * q[2]];
545
1367
  if (Math.abs(Math.abs(dot(unit(D), [Wm[2], Wm[6], Wm[10]])) - 1) > 1e-6) return null;
546
1368
  const h = drive.model.mount.holes.find(([hx, hy]) => Math.hypot(l[0] - hx, l[1] - hy) <= FASTEN.align.value);
547
- return h ? { at: h, thread: drive.model.mount.thread, depth: drive.model.mount.depth, model: drive.model.name, reach: !!drive.model.mount.reach } : null;
1369
+ return h
1370
+ ? {
1371
+ at: h,
1372
+ thread: drive.model.mount.thread,
1373
+ depth: drive.model.mount.depth,
1374
+ model: drive.model.name,
1375
+ reach: !!drive.model.mount.reach,
1376
+ }
1377
+ : null;
548
1378
  };
549
1379
 
550
1380
  // The screws' axes: an anchor each, or the holes of a part
551
1381
  const axes = [];
552
- if (x.at) s.motion.fasten[k].forEach((an, i) => {
553
- const fr = an.frame, P = [fr[3], fr[7], fr[11]], Z = [fr[2], fr[6], fr[10]];
554
- axes.push({ name: an.name ?? `screw ${i + 1}`, O: an.item < 0 ? P : world(an.item, P), D: unit(an.item < 0 ? Z : turned(an.item, Z)) });
555
- });
1382
+ if (x.at)
1383
+ s.motion.fasten[k].forEach((an, i) => {
1384
+ const fr = an.frame,
1385
+ P = [fr[3], fr[7], fr[11]],
1386
+ Z = [fr[2], fr[6], fr[10]];
1387
+ axes.push({
1388
+ name: an.name ?? `screw ${i + 1}`,
1389
+ O: an.item < 0 ? P : world(an.item, P),
1390
+ D: unit(an.item < 0 ? Z : turned(an.item, Z)),
1391
+ });
1392
+ });
556
1393
  else {
557
- const ps = pick(x.holes); if (!ps.length) throw new Error(`${what}: "holes" names a part: no part "${x.holes}" (items: ${ids.join(', ')})`);
1394
+ const ps = pick(x.holes);
1395
+ if (!ps.length) throw new Error(`${what}: "holes" names a part: no part "${x.holes}" (items: ${ids.join(', ')})`);
558
1396
  const others = members.filter((m) => !m.parts.some((p) => ps.includes(p)));
559
1397
  for (const p of ps) {
560
1398
  const board = s.objects.find((o) => o.id === p.leaf)?.built?.circuit;
561
- const local = board ? board.filter((e) => e.type === 'pcb_hole' && !e.pcb_component_id).map((h) => ({ at: [h.x, h.y, 0], axis: [0, 0, 1], d: h.hole_diameter }))
562
- : holesIn(p).filter((h) => h.d >= fx.major * 0.6 && h.d <= Math.max((head?.across ?? fx.major * 2) + 1, fx.major * 1.6));
1399
+ const local = board
1400
+ ? board
1401
+ .filter((e) => e.type === 'pcb_hole' && !e.pcb_component_id)
1402
+ .map((h) => ({ at: [h.x, h.y, 0], axis: [0, 0, 1], d: h.hole_diameter }))
1403
+ : holesIn(p).filter(
1404
+ (h) => h.d >= fx.major * 0.6 && h.d <= Math.max((head?.across ?? fx.major * 2) + 1, fx.major * 1.6),
1405
+ );
563
1406
  for (const h of local) {
564
- const O = vec3.transform([0, 0, 0], h.at, p.m), e = vec3.transform([0, 0, 0], add(h.at, h.axis), p.m), D = unit([e[0] - O[0], e[1] - O[1], e[2] - O[2]]);
1407
+ const O = vec3.transform([0, 0, 0], h.at, p.m),
1408
+ e = vec3.transform([0, 0, 0], add(h.at, h.axis), p.m),
1409
+ D = unit([e[0] - O[0], e[1] - O[1], e[2] - O[2]]);
565
1410
  // a hole of this part is a screw's place where its axis goes on to another part of the joint
566
1411
  if (others.length && !others.some((m) => reach(along(m.parts, O, D, R, false)))) continue;
567
1412
  if (drive && !onMount(O, D)) continue; // (into a motor: only its mounting holes, not the hole its boss sits in)
568
- axes.push({ name: `hole at ${mm(h.at[0])}, ${mm(h.at[1])}${Math.abs(h.at[2]) > 1e-6 && !board ? `, ${mm(h.at[2])}` : ''}`, O, D });
1413
+ axes.push({
1414
+ name: `hole at ${mm(h.at[0])}, ${mm(h.at[1])}${Math.abs(h.at[2]) > 1e-6 && !board ? `, ${mm(h.at[2])}` : ''}`,
1415
+ O,
1416
+ D,
1417
+ });
569
1418
  }
570
1419
  }
571
1420
  }
572
1421
  const label = x.note || (through.length ? `${through.join(' and ')} to ${x.into}` : `in ${x.into}`);
573
- const rel = { index: k, what, label, screw: String(x.screw), thread: fx.thread, form, through, into: x.into, screws: [], general: [] };
574
- if (!axes.length) rel.general.push({ code: 'fasten.holes', level: 'fail', text: `no holes found in ${x.holes} that lead on to ${[...through, x.into].filter((n) => n !== x.holes).join(' or ') || 'another part'}: draw them with v.fixings, or place each screw with "at"` });
1422
+ const rel = {
1423
+ index: k,
1424
+ what,
1425
+ label,
1426
+ screw: String(x.screw),
1427
+ thread: fx.thread,
1428
+ form,
1429
+ through,
1430
+ into: x.into,
1431
+ screws: [],
1432
+ general: [],
1433
+ };
1434
+ if (!axes.length)
1435
+ rel.general.push({
1436
+ code: 'fasten.holes',
1437
+ level: 'fail',
1438
+ text: `no holes found in ${x.holes} that lead on to ${[...through, x.into].filter((n) => n !== x.holes).join(' or ') || 'another part'}: draw them with v.fixings, or place each screw with "at"`,
1439
+ });
575
1440
 
576
- const matOf = (m) => { // what a member is made of: the project's plastic for a printed part, its own word for a reference
577
- const p = m.parts[0], bm = s.objects.find((o) => o.id === p.leaf)?.beam;
578
- if (bm) { const E = bm.material?.modulus; return { name: bm.material?.name ?? null, cls: E == null ? 'aluminium' : E < 20000 ? 'plastic' : E < 100000 ? 'aluminium' : 'steel', known: false }; } // (a beam: its alloy, by the class of its modulus)
1441
+ const matOf = (m) => {
1442
+ // what a member is made of: the project's plastic for a printed part, its own word for a reference
1443
+ const p = m.parts[0],
1444
+ bm = s.objects.find((o) => o.id === p.leaf)?.beam;
1445
+ if (bm) {
1446
+ const E = bm.material?.modulus;
1447
+ return {
1448
+ name: bm.material?.name ?? null,
1449
+ cls: E == null ? 'aluminium' : E < 20000 ? 'plastic' : E < 100000 ? 'aluminium' : 'steel',
1450
+ known: false,
1451
+ };
1452
+ } // (a beam: its alloy, by the class of its modulus)
579
1453
  const own = s.objects.find((o) => o.id === p.leaf)?.built?.object?.material;
580
1454
  const name = own ? String(own).trim().toLowerCase().split(/\s/)[0] : p.role === 'reference' ? null : material;
581
1455
  if (!name) return { name: null, cls: null, known: false };
582
- try { const e = F.engagement(fx, { depth: 1, material: name }); return { name, cls: e.class, known: true }; } catch { return { name, cls: p.role === 'reference' ? null : 'plastic', known: false }; }
1456
+ try {
1457
+ const e = F.engagement(fx, { depth: 1, material: name });
1458
+ return { name, cls: e.class, known: true };
1459
+ } catch {
1460
+ return { name, cls: p.role === 'reference' ? null : 'plastic', known: false };
1461
+ }
1462
+ };
1463
+ const drawn = (kind) => {
1464
+ try {
1465
+ return F.holeModel(fx, { kind });
1466
+ } catch {
1467
+ return null;
1468
+ }
583
1469
  };
584
- const drawn = (kind) => { try { return F.holeModel(fx, { kind }); } catch { return null; } };
585
- const clr = { close: drawn('close'), normal: drawn('clearance'), loose: drawn('loose') }, clrOf = clr, sizeTol = FASTEN.size.value;
1470
+ const clr = { close: drawn('close'), normal: drawn('clearance'), loose: drawn('loose') },
1471
+ clrOf = clr,
1472
+ sizeTol = FASTEN.size.value;
586
1473
  // A circuit board's holes are drilled by its fab, not printed: held to the thread's clearance holes as they stand
587
- const drilled = (n) => (typeof fx.figures[n]?.value === 'number' ? { diameter: fx.figures[n].value, nominal: fx.figures[n].value, comp: 0, basis: { rule: `${fx.set}.${n}` } } : null);
588
- const clrDrilled = { close: drilled('clearance_close'), normal: drilled('clearance'), loose: drilled('clearance_loose') };
589
- const isBoard = (m) => m.parts.some((p) => { const o = s.objects.find((q) => q.id === p.leaf); return o?.built?.circuit || o?.bought?.part === 'board'; }); // (a circuit's holes, or a bought board's, are drilled, not printed)
1474
+ const drilled = (n) =>
1475
+ typeof fx.figures[n]?.value === 'number'
1476
+ ? { diameter: fx.figures[n].value, nominal: fx.figures[n].value, comp: 0, basis: { rule: `${fx.set}.${n}` } }
1477
+ : null;
1478
+ const clrDrilled = {
1479
+ close: drilled('clearance_close'),
1480
+ normal: drilled('clearance'),
1481
+ loose: drilled('clearance_loose'),
1482
+ };
1483
+ const isBoard = (m) =>
1484
+ m.parts.some((p) => {
1485
+ const o = s.objects.find((q) => q.id === p.leaf);
1486
+ return o?.built?.circuit || o?.bought?.part === 'board' || o?.role === 'reference';
1487
+ }); // (a circuit's holes, a bought board's, or any reference's, are drilled, not printed: v.fixings draws a
1488
+ // reference's holes with no hole compensation, lib/fixings.mjs)
590
1489
 
591
1490
  axes.forEach((ax, i) => {
592
- const sc = { index: i, name: ax.name, found: {}, hardware: [] }, say = (code, level, text, values) => { (sc.found[code] ||= []).push({ level, text, ...(values ? { values } : {}) }); };
1491
+ const sc = { index: i, name: ax.name, found: {}, hardware: [] },
1492
+ say = (code, level, text, values) => {
1493
+ (sc.found[code] ||= []).push({ level, text, ...(values ? { values } : {}) });
1494
+ };
593
1495
  rel.screws.push(sc);
594
1496
  // Which way the screw goes: from the part under its head towards the part it ends in (a set screw: against its anchor).
595
1497
  // A yoke or a split clamp ends the screw in the part under its head: its first stretch of material from the head is
596
1498
  // that side, the rest the far side, and the anchor's axis says the way (from the head into the part)
597
1499
  const side = (j, segs) => {
598
1500
  if (!yoke || (j !== 0 && j !== members.length - 1)) return segs;
599
- const on = (seg) => seg.solid || seg.hole, i = segs.findIndex(on); let e = i;
1501
+ const on = (seg) => seg.solid || seg.hole,
1502
+ i = segs.findIndex(on);
1503
+ let e = i;
600
1504
  while (e >= 0 && e < segs.length && on(segs[e])) e++;
601
1505
  return i < 0 ? segs : j === 0 ? segs.slice(0, e) : segs.slice(e);
602
1506
  };
603
1507
  // (a beam is open along the axis where a slot, its bore and an access hole meet: it is on the axis where any of it lies within R)
604
- const isBeam = (m) => m.parts.some((p) => s.objects.find((o) => o.id === p.leaf)?.beam), reachOf = (m, segs) => (isBeam(m) ? reach(segs.map((g) => (Math.min(g.a.free, g.b.free) < R - 1e-6 ? { ...g, solid: true } : g))) : reach(segs));
1508
+ const isBeam = (m) => m.parts.some((p) => s.objects.find((o) => o.id === p.leaf)?.beam),
1509
+ reachOf = (m, segs) =>
1510
+ isBeam(m)
1511
+ ? reach(segs.map((g) => (Math.min(g.a.free, g.b.free) < R - 1e-6 ? { ...g, solid: true } : g)))
1512
+ : reach(segs);
605
1513
  const raw = members.map((m, j) => reachOf(m, side(j, along(m.parts, ax.O, ax.D, R, false))));
606
1514
  const missing = members.filter((_, j) => !raw[j]);
607
- sc.at = ax.O; sc.between = [ax.O, ax.O];
608
- if (missing.length) return say('fasten.holes', 'fail', `${missing.map((m) => m.name).join(' and ')} ${missing.length > 1 ? 'are' : 'is'} nowhere on the screw's axis (nothing of ${missing.length > 1 ? 'them' : 'it'} within ${mm(R)} mm of it)${yoke ? `: a screw that ends in ${x.into}, the part under its head, goes through one side of it and into the other, along its anchor's axis` : ': the parts are not where the joint needs them'}`);
609
- const mid = (r) => (r[0] + r[1]) / 2, flip = yoke ? false : members.length > 1 ? screwFlips(raw[0], raw.at(-1)) : true;
610
- const D = flip ? ax.D.map((c) => -c) : ax.D, O = ax.O, at = (z) => add(O, D, z);
1515
+ sc.at = ax.O;
1516
+ sc.between = [ax.O, ax.O];
1517
+ if (missing.length)
1518
+ return say(
1519
+ 'fasten.holes',
1520
+ 'fail',
1521
+ `${missing.map((m) => m.name).join(' and ')} ${missing.length > 1 ? 'are' : 'is'} nowhere on the screw's axis (nothing of ${missing.length > 1 ? 'them' : 'it'} within ${mm(R)} mm of it)${yoke ? `: a screw that ends in ${x.into}, the part under its head, goes through one side of it and into the other, along its anchor's axis` : ': the parts are not where the joint needs them'}`,
1522
+ );
1523
+ const mid = (r) => (r[0] + r[1]) / 2,
1524
+ flip = yoke ? false : members.length > 1 ? screwFlips(raw[0], raw.at(-1)) : true;
1525
+ const D = flip ? ax.D.map((c) => -c) : ax.D,
1526
+ O = ax.O,
1527
+ at = (z) => add(O, D, z);
611
1528
  const runs = members.map((m, j) => ({ ...m, segs: side(j, along(m.parts, O, ax.D, R, flip)) }));
612
1529
  for (const r of runs) r.reach = reachOf(r, r.segs);
613
1530
  const order = runs.slice(1).find((r, j) => mid(r.reach) < mid(runs[j].reach));
614
- if (order) return say('fasten.holes', 'fail', `${order.name} lies before ${runs[runs.indexOf(order) - 1].name} along the screw: "through" lists the parts in order from under the head, and "into" comes last`);
615
- const tol = 1e-3, B = runs.at(-1), A = through.length ? runs[0] : null, headR = head ? head.across / 2 : 0;
1531
+ if (order)
1532
+ return say(
1533
+ 'fasten.holes',
1534
+ 'fail',
1535
+ `${order.name} lies before ${runs[runs.indexOf(order) - 1].name} along the screw: "through" lists the parts in order from under the head, and "into" comes last`,
1536
+ );
1537
+ // (a beam that is not one of the members, whose material within R runs the whole way from one face to the next)
1538
+ const beamAcross = (z0, z1) => {
1539
+ for (const id of new Set(parts.filter((p) => s.objects.find((o) => o.id === p.leaf)?.beam).map((p) => p.item)))
1540
+ if (!members.some((m) => m.parts.some((p) => p.item === id))) {
1541
+ const segs = along(
1542
+ parts.filter((p) => p.item === id),
1543
+ O,
1544
+ ax.D,
1545
+ R,
1546
+ flip,
1547
+ ).filter((g) => g.solid || Math.min(g.a.free, g.b.free) < R - 1e-6);
1548
+ let z = z0 + FASTEN.stack.value;
1549
+ for (const g of segs) if (g.z0 <= z + EPS && g.z1 > z) z = g.z1;
1550
+ if (z >= z1 - FASTEN.stack.value) return id;
1551
+ }
1552
+ return null;
1553
+ };
1554
+ if (!yoke) stackSays(runs, R, s.a.fits, s.num, say, beamAcross);
1555
+ const tol = 1e-3,
1556
+ B = runs.at(-1),
1557
+ A = through.length ? runs[0] : null,
1558
+ headR = head ? head.across / 2 : 0;
616
1559
  const offAxis = (seg) => (seg.a.loop?.offset != null && seg.a.loop.shape === 'round' ? seg.a.loop.offset : null);
617
- const solidSays = (r, seg) => { const o = offAxis(seg); return `the axis meets solid ${r.name} ${mm(seg.z1 - seg.z0)} mm deep${o != null ? `: its nearest hole is ${mm(o)} mm from the axis` : ': no hole lies near'}`; };
618
- let bad = false, worst = 0;
619
- const size = (seg) => (seg.a.loop.shape === 'round' && seg.a.loop.d != null ? Math.min(seg.a.loop.d, seg.b.loop?.d ?? Infinity) : 2 * Math.min(seg.a.free, seg.b.free));
1560
+ const solidSays = (r, seg) => {
1561
+ const o = offAxis(seg);
1562
+ return `the axis meets solid ${r.name} ${mm(seg.z1 - seg.z0)} mm deep${o != null ? `: its nearest hole is ${mm(o)} mm from the axis` : ': no hole lies near'}`;
1563
+ };
1564
+ let bad = false,
1565
+ worst = 0;
1566
+ const size = (seg) =>
1567
+ seg.a.loop.shape === 'round' && seg.a.loop.d != null
1568
+ ? Math.min(seg.a.loop.d, seg.b.loop?.d ?? Infinity)
1569
+ : 2 * Math.min(seg.a.free, seg.b.free);
620
1570
 
621
1571
  // The seat: where the hole first comes in under the head's width
622
- let zSeat = A ? null : B.reach[0], cone = null, flat = true, proud = 0, bore0 = 0;
1572
+ let zSeat = A ? null : B.reach[0],
1573
+ cone = null,
1574
+ flat = true,
1575
+ proud = 0,
1576
+ bore0 = 0;
623
1577
  const lips = x.lips ? lipsOf(s, x.lips, fx) : null;
624
- if (A && lips?.inside) { // a head inside a beam's slot (a blind join): it sits under the lips, the last narrow stretch of the part before the far end
1578
+ if (A && lips?.inside) {
1579
+ // a head inside a beam's slot (a blind join): it sits under the lips, the last narrow stretch of the part before the far end
625
1580
  const narrow = (seg) => !seg.solid && Math.min(seg.a.free, seg.b.free) < headR - tol; // (between the lips: open along the beam, so not a hole)
626
1581
  let n = A.segs.length - 1;
627
1582
  while (n >= 0 && !narrow(A.segs[n])) n--;
628
1583
  while (n > 0 && narrow(A.segs[n - 1])) n--;
629
- if (n >= 0) { bore0 = n; zSeat = A.segs[n].z0; }
630
- else { say('fasten.holes', 'fail', `${A.name}'s slot has no lips on the screw's axis for its head to sit under`); bad = true; }
631
- } else if (A && lips) { // a head on a beam's slot from outside (an end-tap join): it sits on the lips, the first narrow stretch from the head
1584
+ if (n >= 0) {
1585
+ bore0 = n;
1586
+ zSeat = A.segs[n].z0;
1587
+ } else {
1588
+ say('fasten.holes', 'fail', `${A.name}'s slot has no lips on the screw's axis for its head to sit under`);
1589
+ bad = true;
1590
+ }
1591
+ } else if (A && lips) {
1592
+ // a head on a beam's slot from outside (an end-tap join): it sits on the lips, the first narrow stretch from the head
632
1593
  const n = A.segs.findIndex((seg) => !seg.solid && Math.min(seg.a.free, seg.b.free) < headR - tol);
633
- if (n >= 0 && !A.segs.slice(0, n).some((seg) => seg.solid)) { bore0 = n; zSeat = A.segs[n].z0; }
634
- else { say('fasten.holes', 'fail', `${A.name}'s slot has no lips on the screw's axis for its head to sit on`); bad = true; }
1594
+ if (n >= 0 && !A.segs.slice(0, n).some((seg) => seg.solid)) {
1595
+ bore0 = n;
1596
+ zSeat = A.segs[n].z0;
1597
+ } else {
1598
+ say('fasten.holes', 'fail', `${A.name}'s slot has no lips on the screw's axis for its head to sit on`);
1599
+ bad = true;
1600
+ }
635
1601
  } else if (A) {
636
1602
  for (const [n, seg] of A.segs.entries()) {
637
- if (seg.solid) { say('fasten.holes', 'fail', solidSays(A, seg)); bad = true; break; }
1603
+ if (seg.solid) {
1604
+ say('fasten.holes', 'fail', solidSays(A, seg));
1605
+ bad = true;
1606
+ break;
1607
+ }
638
1608
  if (!seg.hole) continue;
639
- const fa = seg.a.free, fb = seg.b.free;
1609
+ const fa = seg.a.free,
1610
+ fb = seg.b.free;
640
1611
  if (fa >= headR - tol && fb >= headR - tol) continue; // (a counterbore: the head goes down it)
641
1612
  bore0 = n;
642
- if (fa >= headR - tol) { zSeat = seg.z0 + ((fa - headR) / (fa - fb)) * (seg.z1 - seg.z0); cone = seg; flat = false; } // (a cone that narrows past the head's width: a countersink)
643
- else if (form === 'countersunk') { // a countersunk head on a hole narrower than itself: it rides high
1613
+ if (fa >= headR - tol) {
1614
+ zSeat = seg.z0 + ((fa - headR) / (fa - fb)) * (seg.z1 - seg.z0);
1615
+ cone = seg;
1616
+ flat = false;
1617
+ } // (a cone that narrows past the head's width: a countersink)
1618
+ else if (form === 'countersunk') {
1619
+ // a countersunk head on a hole narrower than itself: it rides high
644
1620
  const slope = fa > fb + tol ? (fa - fb) / (seg.z1 - seg.z0) : Math.tan(((head.angle / 2) * Math.PI) / 180);
645
1621
  if (fa > fb + tol) cone = seg;
646
- proud = (headR - fa) / slope; zSeat = seg.z0 - proud; flat = false;
1622
+ proud = (headR - fa) / slope;
1623
+ zSeat = seg.z0 - proud;
1624
+ flat = false;
647
1625
  } else zSeat = seg.z0;
648
1626
  break;
649
1627
  }
650
- if (zSeat == null && !bad) { say('fasten.holes', 'fail', `${A.name} has no hole on the screw's axis for its head to sit on`); bad = true; }
1628
+ if (zSeat == null && !bad) {
1629
+ say('fasten.holes', 'fail', `${A.name} has no hole on the screw's axis for its head to sit on`);
1630
+ bad = true;
1631
+ }
651
1632
  }
652
1633
  if (bad) return;
653
- const wt = washer ? washer.thickness : 0, zHead = zSeat - wt;
654
- sc.at = at(zHead); sc.between = [at(zHead), at(zHead + (given ?? fx.major * 3))];
1634
+ const wt = washer ? washer.thickness : 0,
1635
+ zHead = zSeat - wt;
1636
+ sc.at = at(zHead);
1637
+ sc.between = [at(zHead), at(zHead + (given ?? fx.major * 3))];
655
1638
 
656
1639
  // Each part passed through: a hole all the way, wide enough for the thread, on the axis
657
1640
  const cl = [];
658
1641
  for (const [j, r] of runs.slice(0, -1).entries()) {
659
- const segs = r.segs.filter((seg, n) => (j ? true : n >= bore0) && seg !== cone && seg.z1 > zSeat + tol), stop = segs.find((seg) => seg.solid);
660
- if (stop) { say('fasten.holes', 'fail', solidSays(r, stop)); bad = true; continue; }
661
- if (j === 0 && lips) { cl.push({ name: r.name, d: lips.opening, lips }); continue; } // (between a slot's lips: open along the beam)
1642
+ const segs = r.segs.filter((seg, n) => (j ? true : n >= bore0) && seg !== cone && seg.z1 > zSeat + tol),
1643
+ stop = segs.find((seg) => seg.solid);
1644
+ if (stop) {
1645
+ say('fasten.holes', 'fail', solidSays(r, stop));
1646
+ bad = true;
1647
+ continue;
1648
+ }
1649
+ if (j === 0 && lips) {
1650
+ cl.push({ name: r.name, d: lips.opening, lips });
1651
+ continue;
1652
+ } // (between a slot's lips: open along the beam)
662
1653
  const holes = segs.filter((seg) => seg.hole);
663
- if (!holes.length) { say('fasten.holes', 'fail', `${r.name} has no hole on the screw's axis`); bad = true; continue; }
664
- const narrow = holes.reduce((m, seg) => (size(seg) < size(m) ? seg : m), holes[0]), d = size(narrow);
665
- for (const seg of holes) { const o = offAxis(seg); if (o != null && o > worst) worst = o; if (o != null && o > FASTEN.align.value) { say('fasten.holes', 'fail', `${r.name}'s hole is ${mm(o)} mm off the screw's axis: the holes do not line up`, { distance: r3(o) }); bad = true; break; } }
1654
+ if (!holes.length) {
1655
+ say('fasten.holes', 'fail', `${r.name} has no hole on the screw's axis`);
1656
+ bad = true;
1657
+ continue;
1658
+ }
1659
+ const narrow = holes.reduce((m, seg) => (size(seg) < size(m) ? seg : m), holes[0]),
1660
+ d = size(narrow);
1661
+ for (const seg of holes) {
1662
+ const o = offAxis(seg);
1663
+ if (o != null && o > worst) worst = o;
1664
+ if (o != null && o > FASTEN.align.value) {
1665
+ say(
1666
+ 'fasten.holes',
1667
+ 'fail',
1668
+ `${r.name}'s hole is ${mm(o)} mm off the screw's axis: the holes do not line up`,
1669
+ { distance: r3(o) },
1670
+ );
1671
+ bad = true;
1672
+ break;
1673
+ }
1674
+ }
666
1675
  cl.push({ name: r.name, d, free: 2 * Math.min(narrow.a.free, narrow.b.free), board: isBoard(r) });
667
1676
  }
668
1677
  // The far end: the hole in the last part, from its mouth; or, into a slot, the slot nut under its lips
@@ -671,260 +1680,1006 @@ export function fastenOf(s, worlds, opts = {}) {
671
1680
  const mh = !slotAt && (first?.solid || (first?.hole && drive && drive === boughtMount)) ? onMount(O, D) : null; // (a bought part may draw its tapped holes: a rail's carriage)
672
1681
  if (slotAt) end = slotEnd(s, slotAt, slotNutM, { B, O, D, x, fx, cl, clr, say, sc });
673
1682
  else if (mh) {
674
- if (mh.thread !== fx.thread) { say('fasten.end', 'fail', `${x.into}'s mounting holes are ${mh.thread} threads, and the screw is ${fx.thread}: use ${an(mh.thread)} ${mh.thread} screw`); bad = true; }
675
- else end = { mouth: first.z0, d: fx.major, free: fx.major, depth: mh.depth, blind: true, far: first.z0 + mh.depth, pocket: null, main: first, motor: mh };
676
- } else if (first.solid) { const o = offAxis(first); say('fasten.holes', 'fail', `${solidSays(B, first)}${o != null ? ': the holes do not line up' : ''}`, o != null ? { distance: r3(o) } : undefined); bad = true; }
677
- else {
678
- const n0 = B.segs.indexOf(first), mouth = first.z0; let n = n0;
1683
+ if (mh.thread !== fx.thread) {
1684
+ say(
1685
+ 'fasten.end',
1686
+ 'fail',
1687
+ `${x.into}'s mounting holes are ${mh.thread} threads, and the screw is ${fx.thread}: use ${an(mh.thread)} ${mh.thread} screw`,
1688
+ );
1689
+ bad = true;
1690
+ } else
1691
+ end = {
1692
+ mouth: first.z0,
1693
+ d: fx.major,
1694
+ free: fx.major,
1695
+ depth: mh.depth,
1696
+ blind: true,
1697
+ far: first.z0 + mh.depth,
1698
+ pocket: null,
1699
+ main: first,
1700
+ motor: mh,
1701
+ };
1702
+ } else if (first.solid) {
1703
+ const o = offAxis(first);
1704
+ say(
1705
+ 'fasten.holes',
1706
+ 'fail',
1707
+ `${solidSays(B, first)}${o != null ? ': the holes do not line up' : ''}`,
1708
+ o != null ? { distance: r3(o) } : undefined,
1709
+ );
1710
+ bad = true;
1711
+ } else {
1712
+ const n0 = B.segs.indexOf(first),
1713
+ mouth = first.z0;
1714
+ let n = n0;
679
1715
  while (B.segs[n]?.hole && B.segs[n].a.free > B.segs[n].b.free + tol) n++; // (a lead-in at the mouth)
680
- const main = B.segs[n]?.hole ? B.segs[n] : first, d = size(main), free = Math.min(main.a.free, main.b.free);
681
- let stop = main.z1, pocket = null, blind = false, m = B.segs.indexOf(main) + 1;
1716
+ const main = B.segs[n]?.hole ? B.segs[n] : first,
1717
+ d = size(main),
1718
+ free = Math.min(main.a.free, main.b.free);
1719
+ let stop = main.z1,
1720
+ pocket = null,
1721
+ blind = false,
1722
+ m = B.segs.indexOf(main) + 1;
682
1723
  for (; m < B.segs.length; m++) {
683
1724
  const seg = B.segs[m];
684
- if (seg.solid) { blind = true; break; }
685
- if (!seg.hole) { // a slot open to the side across the screw, the hole going on past it: a nut's slot (v.fixings.nutTrap)
686
- if (!pocket && seg.a.free > free + 0.3 && same(seg.a, seg.b) && B.segs.slice(m + 1).some((s) => s.hole)) pocket = seg;
1725
+ if (seg.solid) {
1726
+ blind = true;
1727
+ break;
1728
+ }
1729
+ if (!seg.hole) {
1730
+ // a slot open to the side across the screw, the hole going on past it: a nut's slot (v.fixings.nutTrap)
1731
+ if (!pocket && seg.a.free > free + 0.3 && same(seg.a, seg.b) && B.segs.slice(m + 1).some((s) => s.hole))
1732
+ pocket = seg;
687
1733
  continue;
688
1734
  }
689
- if (Math.min(seg.a.free, seg.b.free) < free - tol) { blind = true; break; } // (it narrows: a hole's point, a step)
1735
+ if (Math.min(seg.a.free, seg.b.free) < free - tol) {
1736
+ blind = true;
1737
+ break;
1738
+ } // (it narrows: a hole's point, a step)
690
1739
  if (seg.a.free > free + 0.3 && same(seg.a, seg.b) && !pocket) pocket = seg; // (it widens to a seat on the far side)
691
1740
  if (!pocket) stop = seg.z1;
692
1741
  }
693
- const o = offAxis(main); if (o != null && o > worst) worst = o;
694
- if (o != null && o > FASTEN.align.value) { say('fasten.holes', 'fail', `${B.name}'s hole is ${mm(o)} mm off the screw's axis: the holes do not line up`, { distance: r3(o) }); bad = true; }
695
- end = { mouth, d, free: 2 * free, depth: (blind ? B.segs[m].z0 : stop) - mouth, blind, far: B.reach[1], pocket, main };
1742
+ const o = offAxis(main);
1743
+ if (o != null && o > worst) worst = o;
1744
+ if (o != null && o > FASTEN.align.value) {
1745
+ say(
1746
+ 'fasten.holes',
1747
+ 'fail',
1748
+ `${B.name}'s hole is ${mm(o)} mm off the screw's axis: the holes do not line up`,
1749
+ { distance: r3(o) },
1750
+ );
1751
+ bad = true;
1752
+ }
1753
+ end = {
1754
+ mouth,
1755
+ d,
1756
+ free: 2 * free,
1757
+ depth: (blind ? B.segs[m].z0 : stop) - mouth,
1758
+ blind,
1759
+ far: B.reach[1],
1760
+ pocket,
1761
+ main,
1762
+ };
696
1763
  }
697
- if (!bad) say('fasten.holes', 'pass', `one axis from under the head ${through.length ? `through ${through.join(', ')} ` : ''}into ${x.into}${worst > 1e-4 ? ` (the holes within ${mm(worst)} mm of it)` : ''}`, { distance: r3(worst) });
1764
+ if (!bad)
1765
+ say(
1766
+ 'fasten.holes',
1767
+ 'pass',
1768
+ `one axis from under the head ${through.length ? `through ${through.join(', ')} ` : ''}into ${x.into}${worst > 1e-4 ? ` (the holes within ${mm(worst)} mm of it)` : ''}`,
1769
+ { distance: r3(worst) },
1770
+ );
698
1771
 
699
1772
  // fasten.clearance: what each hole passed measures, against the thread's clearance hole as drawn on this printer
700
1773
  if (cl.length) {
701
- if (!clr.normal) say('fasten.clearance', 'info', `${fx.thread} has no clearance hole in its rule set (${fx.set}): the holes it passes are not held to one`);
702
- else for (const c of cl) {
703
- if (c.lips) { // a slot's opening: the screw passes between its lips, so it is a slot, not a clearance hole, by design
704
- const values = { opening: c.lips.opening, major: fx.major };
705
- if (c.lips.opening < fx.major) say('fasten.clearance', 'fail', `${c.name}'s slot opens ${mm(c.lips.opening)} mm, narrower than ${an(fx.thread)} ${fx.thread} screw (${mm(fx.major)} mm): it does not pass between the lips`, values);
706
- else say('fasten.clearance', 'pass', `${an(fx.thread)} ${fx.thread} screw passes between the lips of ${c.name}'s slot, ${mm(c.lips.opening)} mm apart (${c.lips.slot}.opening): it slides along the slot until tightened`, values);
707
- continue;
1774
+ if (!clr.normal)
1775
+ say(
1776
+ 'fasten.clearance',
1777
+ 'info',
1778
+ `${fx.thread} has no clearance hole in its rule set (${fx.set}): the holes it passes are not held to one`,
1779
+ );
1780
+ else
1781
+ for (const c of cl) {
1782
+ if (c.lips) {
1783
+ // a slot's opening: the screw passes between its lips, so it is a slot, not a clearance hole, by design
1784
+ const values = { opening: c.lips.opening, major: fx.major };
1785
+ if (c.lips.opening < fx.major)
1786
+ say(
1787
+ 'fasten.clearance',
1788
+ 'fail',
1789
+ `${c.name}'s slot opens ${mm(c.lips.opening)} mm, narrower than ${an(fx.thread)} ${fx.thread} screw (${mm(fx.major)} mm): it does not pass between the lips`,
1790
+ values,
1791
+ );
1792
+ else
1793
+ say(
1794
+ 'fasten.clearance',
1795
+ 'pass',
1796
+ `${an(fx.thread)} ${fx.thread} screw passes between the lips of ${c.name}'s slot, ${mm(c.lips.opening)} mm apart (${c.lips.slot}.opening): it slides along the slot until tightened`,
1797
+ values,
1798
+ );
1799
+ continue;
1800
+ }
1801
+ const clr = c.board && clrDrilled.normal ? clrDrilled : clrOf,
1802
+ as = c.board && clrDrilled.normal ? 'as drilled' : 'as drawn';
1803
+ const lo = (clr.close ?? clr.normal).diameter,
1804
+ hi = (clr.loose ?? clr.normal).diameter,
1805
+ want = clr.normal,
1806
+ basis = `${want.basis.rule} ${mm(want.nominal)} mm${want.comp ? ` and ${printer}.hole_comp ${mm(want.comp)} mm` : ''}`;
1807
+ const values = { diameter: r3(c.d), wanted: want.diameter, least: lo, most: hi };
1808
+ if (c.d < lo - sizeTol)
1809
+ say(
1810
+ 'fasten.clearance',
1811
+ 'fail',
1812
+ `${c.name}'s hole measures ${mm(c.d)} mm where ${an(fx.thread)} ${fx.thread} screw passes through: a clearance hole should be ${mm(want.diameter)} mm ${as} (${basis}), ${mm(lo)} mm at the closest`,
1813
+ values,
1814
+ );
1815
+ else if (c.d > hi + sizeTol)
1816
+ say(
1817
+ 'fasten.clearance',
1818
+ 'warn',
1819
+ `${c.name}'s hole measures ${mm(c.d)} mm, wider than the loosest clearance hole for ${fx.thread}, ${mm(hi)} mm ${as}: the screw does not place the part, and the head has less to sit on (${mm(want.diameter)} mm is the normal hole)`,
1820
+ values,
1821
+ );
1822
+ else
1823
+ say(
1824
+ 'fasten.clearance',
1825
+ 'pass',
1826
+ `${c.name}'s hole measures ${mm(c.d)} mm, ${an(fx.thread)} ${fx.thread} clearance hole ${as} (${Math.abs(c.d - want.diameter) <= sizeTol ? basis : `between the close ${mm(lo)} mm and the loose ${mm(hi)} mm; the normal hole is ${mm(want.diameter)} mm`})`,
1827
+ values,
1828
+ );
708
1829
  }
709
- const clr = c.board && clrDrilled.normal ? clrDrilled : clrOf, as = c.board && clrDrilled.normal ? 'as drilled' : 'as drawn';
710
- const lo = (clr.close ?? clr.normal).diameter, hi = (clr.loose ?? clr.normal).diameter, want = clr.normal, basis = `${want.basis.rule} ${mm(want.nominal)} mm${want.comp ? ` and ${printer}.hole_comp ${mm(want.comp)} mm` : ''}`;
711
- const values = { diameter: r3(c.d), wanted: want.diameter, least: lo, most: hi };
712
- if (c.d < lo - sizeTol) say('fasten.clearance', 'fail', `${c.name}'s hole measures ${mm(c.d)} mm where ${an(fx.thread)} ${fx.thread} screw passes through: a clearance hole should be ${mm(want.diameter)} mm ${as} (${basis}), ${mm(lo)} mm at the closest`, values);
713
- else if (c.d > hi + sizeTol) say('fasten.clearance', 'warn', `${c.name}'s hole measures ${mm(c.d)} mm, wider than the loosest clearance hole for ${fx.thread}, ${mm(hi)} mm ${as}: the screw does not place the part, and the head has less to sit on (${mm(want.diameter)} mm is the normal hole)`, values);
714
- else say('fasten.clearance', 'pass', `${c.name}'s hole measures ${mm(c.d)} mm, ${an(fx.thread)} ${fx.thread} clearance hole ${as} (${Math.abs(c.d - want.diameter) <= sizeTol ? basis : `between the close ${mm(lo)} mm and the loose ${mm(hi)} mm; the normal hole is ${mm(want.diameter)} mm`})`, values);
715
- }
716
1830
  }
717
1831
  if (!end) return;
718
1832
 
719
1833
  // fasten.end: what holds the screw there
720
- const kinds = [['pilot', 'a pilot the screw forms its own thread in'], ['tap', 'a hole to tap'], ['insert', 'a heat-set insert\'s hole']].map(([kind, says]) => ({ kind, says, hole: drawn(kind) })).filter((c) => c.hole);
721
- const isClearance = clr.normal && end.d >= (clr.close ?? clr.normal).diameter - sizeTol && end.d <= (clr.loose ?? clr.normal).diameter + sizeTol;
722
- const options = () => [...kinds.map((c) => `${c.says} (${mm(c.hole.diameter)} mm)`), ...(fx.made.nuts.length ? ['a nut\'s seat on a clearance hole, or a clearance hole with "nut"'] : [])].join(', ');
1834
+ const kinds = [
1835
+ ['pilot', 'a pilot the screw forms its own thread in'],
1836
+ ['tap', 'a hole to tap'],
1837
+ ['insert', "a heat-set insert's hole"],
1838
+ ]
1839
+ .map(([kind, says]) => ({ kind, says, hole: drawn(kind) }))
1840
+ .filter((c) => c.hole);
1841
+ const isClearance =
1842
+ clr.normal &&
1843
+ end.d >= (clr.close ?? clr.normal).diameter - sizeTol &&
1844
+ end.d <= (clr.loose ?? clr.normal).diameter + sizeTol;
1845
+ const options = () =>
1846
+ [
1847
+ ...kinds.map((c) => `${c.says} (${mm(c.hole.diameter)} mm)`),
1848
+ ...(fx.made.nuts.length ? ['a nut\'s seat on a clearance hole, or a clearance hole with "nut"'] : []),
1849
+ ].join(', ');
723
1850
  const endValues = { diameter: r3(end.d), depth: r3(end.depth) };
724
1851
  let seatNut = null;
725
- if (end.pocket && !end.blind) { // a seat drawn on the far side: whose nut is it
726
- const sh = end.pocket.a.loop.shape, across = sh === 'hex' || sh === 'square' ? end.pocket.a.loop.flats : 2 * end.pocket.a.free;
727
- for (const kind of sh === 'square' ? ['square'] : ['hex', 'lock']) { try { const n = nutModel(kind); if (across >= n.flats - 0.05 && across <= n.flats + 1 && (!seatNut || wantNut === kind)) seatNut = { kind, model: n, across }; } catch {} }
1852
+ if (end.pocket && !end.blind) {
1853
+ // a seat drawn on the far side: whose nut is it
1854
+ const sh = end.pocket.a.loop.shape,
1855
+ across = sh === 'hex' || sh === 'square' ? end.pocket.a.loop.flats : 2 * end.pocket.a.free;
1856
+ for (const kind of sh === 'square' ? ['square'] : ['hex', 'lock']) {
1857
+ try {
1858
+ const n = nutModel(kind);
1859
+ if (across >= n.flats - 0.05 && across <= n.flats + 1 && (!seatNut || wantNut === kind))
1860
+ seatNut = { kind, model: n, across };
1861
+ } catch {
1862
+ // (not a nut the fixings know: no nut seat of this kind)
1863
+ }
1864
+ }
728
1865
  }
729
1866
  if (end.slot) {
730
- const n = end.nut.model, warns = n.fits.filter((q) => q.level === 'warn' || q.level === 'fail'), notes = n.fits.filter((q) => q.level === 'info'), where = `${end.slot.item}'s ${end.slot.place} slot`;
731
- if (end.slot.opening < fx.major) say('fasten.clearance', 'fail', `${where} opens ${mm(end.slot.opening)} mm, narrower than ${an(fx.thread)} ${fx.thread} screw (${mm(fx.major)} mm): it does not pass between the lips`, { opening: end.slot.opening, major: fx.major });
732
- else say('fasten.clearance', 'pass', `${an(fx.thread)} ${fx.thread} screw passes between the lips of ${where}, ${mm(end.slot.opening)} mm apart`, { opening: end.slot.opening, major: fx.major });
733
- say('fasten.end', warns.length ? 'warn' : 'pass', `ends in ${an(n.nutKind)} ${n.nutKind} nut under the lips of ${where}: ${n.name}, ${mm(end.thread)} mm of ${n.thread} thread from ${mm(end.zThr - end.mouth)} to ${mm(end.zThr - end.mouth + end.thread)} mm under the face, the slot's floor at ${mm(end.depth)} mm${n.entry === 'end' ? '. It goes in from an open end of the slot (frame.nut)' : '. It goes in through the opening, anywhere along the slot'}${warns.length || notes.length ? `. ${[...warns, ...notes].map((q) => q.text).join('; ')}` : ''}`, { thread: end.thread, floor: end.depth, height: n.height, tongue: n.tongueHeight });
734
- } else if (end.motor) { end.kind = 'tap'; say('fasten.end', 'pass', end.motor.reach ? `ends in ${x.into}'s own ${fx.thread} thread, which its maker allows a screw ${mm(end.depth)} mm into (${end.motor.model}.mount_hole_reach)` : `ends in ${x.into}'s own ${fx.thread} thread, ${mm(end.depth)} mm deep (${end.motor.model}.mount_hole_depth)`, endValues); }
735
- else if (wantNut || seatNut) {
736
- const kind = wantNut ?? seatNut.kind, nm = nutModel(kind);
737
- if (end.blind) say('fasten.end', 'fail', `a nut is given, and ${x.into}'s hole is blind, ${mm(end.depth)} mm deep: a nut holds a screw that comes out of the far side`, endValues);
738
- else if (!isClearance) say('fasten.end', 'fail', `a nut holds this screw, so ${x.into} is passed through: its hole measures ${mm(end.d)} mm, and a clearance hole should be ${mm(clr.normal?.diameter ?? fx.major)} mm as drawn`, endValues);
1867
+ const n = end.nut.model,
1868
+ warns = n.fits.filter((q) => q.level === 'warn' || q.level === 'fail'),
1869
+ notes = n.fits.filter((q) => q.level === 'info'),
1870
+ where = `${end.slot.item}'s ${end.slot.place} slot`;
1871
+ if (end.slot.opening < fx.major)
1872
+ say(
1873
+ 'fasten.clearance',
1874
+ 'fail',
1875
+ `${where} opens ${mm(end.slot.opening)} mm, narrower than ${an(fx.thread)} ${fx.thread} screw (${mm(fx.major)} mm): it does not pass between the lips`,
1876
+ { opening: end.slot.opening, major: fx.major },
1877
+ );
1878
+ else
1879
+ say(
1880
+ 'fasten.clearance',
1881
+ 'pass',
1882
+ `${an(fx.thread)} ${fx.thread} screw passes between the lips of ${where}, ${mm(end.slot.opening)} mm apart`,
1883
+ { opening: end.slot.opening, major: fx.major },
1884
+ );
1885
+ say(
1886
+ 'fasten.end',
1887
+ warns.length ? 'warn' : 'pass',
1888
+ `ends in ${an(n.nutKind)} ${n.nutKind} nut under the lips of ${where}: ${n.name}, ${mm(end.thread)} mm of ${n.thread} thread from ${mm(end.zThr - end.mouth)} to ${mm(end.zThr - end.mouth + end.thread)} mm under the face, the slot's floor at ${mm(end.depth)} mm${n.entry === 'end' ? '. It goes in from an open end of the slot (frame.nut)' : '. It goes in through the opening, anywhere along the slot'}${warns.length || notes.length ? `. ${[...warns, ...notes].map((q) => q.text).join('; ')}` : ''}`,
1889
+ { thread: end.thread, floor: end.depth, height: n.height, tongue: n.tongueHeight },
1890
+ );
1891
+ } else if (end.motor) {
1892
+ end.kind = 'tap';
1893
+ say(
1894
+ 'fasten.end',
1895
+ 'pass',
1896
+ end.motor.reach
1897
+ ? `ends in ${x.into}'s own ${fx.thread} thread, which its maker allows a screw ${mm(end.depth)} mm into (${end.motor.model}.mount_hole_reach)`
1898
+ : `ends in ${x.into}'s own ${fx.thread} thread, ${mm(end.depth)} mm deep (${end.motor.model}.mount_hole_depth)`,
1899
+ endValues,
1900
+ );
1901
+ } else if (wantNut || seatNut) {
1902
+ const kind = wantNut ?? seatNut.kind,
1903
+ nm = nutModel(kind);
1904
+ if (end.blind)
1905
+ say(
1906
+ 'fasten.end',
1907
+ 'fail',
1908
+ `a nut is given, and ${x.into}'s hole is blind, ${mm(end.depth)} mm deep: a nut holds a screw that comes out of the far side`,
1909
+ endValues,
1910
+ );
1911
+ else if (!isClearance)
1912
+ say(
1913
+ 'fasten.end',
1914
+ 'fail',
1915
+ `a nut holds this screw, so ${x.into} is passed through: its hole measures ${mm(end.d)} mm, and a clearance hole should be ${mm(clr.normal?.diameter ?? fx.major)} mm as drawn`,
1916
+ endValues,
1917
+ );
739
1918
  else {
740
1919
  const zNut = end.pocket && seatNut ? end.pocket.z0 : end.far;
741
- end.kind = 'nut'; end.nut = { kind, model: nm, z: zNut, seated: !!(end.pocket && seatNut), corner: end.pocket && seatNut && (end.pocket.a.loop.corner || end.pocket.a.loop.along) ? { seg: end.pocket } : null };
742
- say('fasten.end', 'pass', `ends in ${an(nm.name)} ${nm.name} ${end.nut.seated ? `in its seat in ${x.into}, ${mm(seatNut.across)} mm across the flats for the nut's ${mm(nm.flats)} mm` : `on the far face of ${x.into}`}, past a ${mm(end.d)} mm clearance hole`, { ...endValues, flats: nm.flats });
1920
+ end.kind = 'nut';
1921
+ end.nut = {
1922
+ kind,
1923
+ model: nm,
1924
+ z: zNut,
1925
+ seated: !!(end.pocket && seatNut),
1926
+ corner:
1927
+ end.pocket && seatNut && (end.pocket.a.loop.corner || end.pocket.a.loop.along)
1928
+ ? { seg: end.pocket }
1929
+ : null,
1930
+ };
1931
+ say(
1932
+ 'fasten.end',
1933
+ 'pass',
1934
+ `ends in ${an(nm.name)} ${nm.name} ${end.nut.seated ? `in its seat in ${x.into}, ${mm(seatNut.across)} mm across the flats for the nut's ${mm(nm.flats)} mm` : `on the far face of ${x.into}`}, past a ${mm(end.d)} mm clearance hole`,
1935
+ { ...endValues, flats: nm.flats },
1936
+ );
743
1937
  }
744
1938
  } else {
745
- const bt = beamTap(s, B, O, D), pe = bt ? null : printedEnd(s, B, O, D);
746
- if (pe && pe.thread !== fx.thread) { say('fasten.end', 'fail', `${x.into}'s end ${pe.end} is printed with ${an(pe.thread)} ${pe.thread} ${pe.kind === 'nut' ? 'captive nut' : 'heat-set insert'} in place of a tap, and the screw is ${fx.thread}: use ${an(pe.thread)} ${pe.thread} screw (a printed foot takes it as "thread": "${pe.thread}")`, { thread: pe.thread }); bad = true; return; }
747
- if (bt && bt.thread !== fx.thread) { say('fasten.end', 'fail', `${x.into}'s bore ${bt.bore} is tapped ${bt.thread}, and the screw is ${fx.thread}: use ${an(bt.thread)} ${bt.thread} screw, or tap it ${fx.thread}`); bad = true; return; }
748
- if (bt) { end.kind = 'tap'; end.blind = bt.depth < bt.length - 1e-6; end.depth = Math.min(bt.depth, bt.length); end.beamTap = bt; }
749
- const hit = bt ? null : kinds.filter((c) => Math.abs(end.d - c.hole.diameter) <= sizeTol).sort((p, q) => Math.abs(end.d - p.hole.diameter) - Math.abs(end.d - q.hole.diameter))[0];
1939
+ const bt = beamTap(s, B, O, D),
1940
+ pe = bt ? null : printedEnd(s, B, O, D);
1941
+ if (pe && pe.thread !== fx.thread) {
1942
+ say(
1943
+ 'fasten.end',
1944
+ 'fail',
1945
+ `${x.into}'s end ${pe.end} is printed with ${an(pe.thread)} ${pe.thread} ${pe.kind === 'nut' ? 'captive nut' : 'heat-set insert'} in place of a tap, and the screw is ${fx.thread}: use ${an(pe.thread)} ${pe.thread} screw (a printed foot takes it as "thread": "${pe.thread}")`,
1946
+ { thread: pe.thread },
1947
+ );
1948
+ bad = true;
1949
+ return;
1950
+ }
1951
+ if (bt && bt.thread !== fx.thread) {
1952
+ say(
1953
+ 'fasten.end',
1954
+ 'fail',
1955
+ `${x.into}'s bore ${bt.bore} is tapped ${bt.thread}, and the screw is ${fx.thread}: use ${an(bt.thread)} ${bt.thread} screw, or tap it ${fx.thread}`,
1956
+ );
1957
+ bad = true;
1958
+ return;
1959
+ }
1960
+ if (bt) {
1961
+ end.kind = 'tap';
1962
+ end.blind = bt.depth < bt.length - 1e-6;
1963
+ end.depth = Math.min(bt.depth, bt.length);
1964
+ end.beamTap = bt;
1965
+ }
1966
+ const hit = bt
1967
+ ? null
1968
+ : kinds
1969
+ .filter((c) => Math.abs(end.d - c.hole.diameter) <= sizeTol)
1970
+ .sort((p, q) => Math.abs(end.d - p.hole.diameter) - Math.abs(end.d - q.hole.diameter))[0];
750
1971
  let threaded = null;
751
- if (!hit && end.main.a.loop.shape !== 'round') { try { const t = F.threadModel(fx, { internal: true, length: Math.max(end.depth, fx.pitch * 2) }); if (end.free > fx.major - 2 * fx.pitch && end.free < fx.major + 1) threaded = t; } catch {} }
752
- if (bt) say('fasten.end', 'pass', `ends in ${x.into}'s own ${bt.thread} thread, tapped ${mm(end.depth)} mm into its end bore ${bt.bore} (a machined tap, on its cut-and-drill sheet)`, { ...endValues, depth: r3(end.depth) });
753
- else if (hit && fx.printed && hit.kind === 'pilot') { // (a plastic bolt forms no thread in plastic: a pilot is for a bought thread-forming screw)
754
- say('fasten.end', 'fail', `${x.into}'s hole is ${hit.says} (${mm(end.d)} mm as drawn), and ${fx.name} is a printed bolt: a plastic thread cannot form its own thread in plastic. Print the thread in ${x.into} (v.fixings.hole('${fx.thread}', { kind: 'thread' })), or end it in a nut or a heat-set insert`, endValues); bad = true; return;
1972
+ if (!hit && end.main.a.loop.shape !== 'round') {
1973
+ try {
1974
+ const t = F.threadModel(fx, { internal: true, length: Math.max(end.depth, fx.pitch * 2) });
1975
+ if (end.free > fx.major - 2 * fx.pitch && end.free < fx.major + 1) threaded = t;
1976
+ } catch {
1977
+ // (no thread the fixings know for it: the hole is read as plain)
1978
+ }
1979
+ }
1980
+ if (bt)
1981
+ say(
1982
+ 'fasten.end',
1983
+ 'pass',
1984
+ `ends in ${x.into}'s own ${bt.thread} thread, tapped ${mm(end.depth)} mm into its end bore ${bt.bore} (a machined tap, on its cut-and-drill sheet)`,
1985
+ { ...endValues, depth: r3(end.depth) },
1986
+ );
1987
+ else if (hit && fx.printed && hit.kind === 'pilot') {
1988
+ // (a plastic bolt forms no thread in plastic: a pilot is for a bought thread-forming screw)
1989
+ say(
1990
+ 'fasten.end',
1991
+ 'fail',
1992
+ `${x.into}'s hole is ${hit.says} (${mm(end.d)} mm as drawn), and ${fx.name} is a printed bolt: a plastic thread cannot form its own thread in plastic. Print the thread in ${x.into} (v.fixings.hole('${fx.thread}', { kind: 'thread' })), or end it in a nut or a heat-set insert`,
1993
+ endValues,
1994
+ );
1995
+ bad = true;
1996
+ return;
755
1997
  } else if (hit) {
756
1998
  end.kind = hit.kind;
757
- const basis = hit.hole.basis, trust = basis.kind === 'measured' ? 'measured' : basis.kind === 'spec' ? 'a standard\'s figure' : `${/^[aeiou]/.test(basis.kind) ? 'an' : 'a'} ${basis.kind} figure`;
758
- say('fasten.end', 'pass', `ends in ${x.into}, in ${hit.says}: ${mm(end.d)} mm as drawn (${basis.rule}, ${trust}), ${end.blind ? `${mm(end.depth)} mm deep` : `through its ${mm(end.depth)} mm`}`, endValues);
759
- if (hit.kind === 'insert') { try { end.insert = F.insertModel(fx.thread); } catch { end.insert = null; } }
760
- } else if (threaded) { end.kind = 'thread'; say('fasten.end', 'pass', `ends in ${x.into}, in a thread drawn to print, ${mm(end.free)} mm across its crests, ${end.blind ? `${mm(end.depth)} mm deep` : `through its ${mm(end.depth)} mm`}`, endValues); }
761
- else if (isClearance) say('fasten.end', 'fail', `nothing holds the screw in ${x.into}: its hole measures ${mm(end.d)} mm, a clearance hole. The far end should be ${options()}`, endValues);
762
- else say('fasten.end', 'fail', `${x.into}'s hole measures ${mm(end.d)} mm, which is no hole for ${fx.thread}: the far end should be ${options()}`, endValues);
1999
+ const basis = hit.hole.basis,
2000
+ trust =
2001
+ basis.kind === 'measured'
2002
+ ? 'measured'
2003
+ : basis.kind === 'spec'
2004
+ ? "a standard's figure"
2005
+ : `${/^[aeiou]/.test(basis.kind) ? 'an' : 'a'} ${basis.kind} figure`;
2006
+ say(
2007
+ 'fasten.end',
2008
+ 'pass',
2009
+ `ends in ${x.into}, in ${hit.says}: ${mm(end.d)} mm as drawn (${basis.rule}, ${trust}), ${end.blind ? `${mm(end.depth)} mm deep` : `through its ${mm(end.depth)} mm`}`,
2010
+ endValues,
2011
+ );
2012
+ if (hit.kind === 'insert') {
2013
+ try {
2014
+ end.insert = F.insertModel(fx.thread);
2015
+ } catch {
2016
+ end.insert = null;
2017
+ }
2018
+ }
2019
+ } else if (threaded) {
2020
+ end.kind = 'thread';
2021
+ say(
2022
+ 'fasten.end',
2023
+ 'pass',
2024
+ `ends in ${x.into}, in a thread drawn to print, ${mm(end.free)} mm across its crests, ${end.blind ? `${mm(end.depth)} mm deep` : `through its ${mm(end.depth)} mm`}`,
2025
+ endValues,
2026
+ );
2027
+ } else if (isClearance)
2028
+ say(
2029
+ 'fasten.end',
2030
+ 'fail',
2031
+ `nothing holds the screw in ${x.into}: its hole measures ${mm(end.d)} mm, a clearance hole. The far end should be ${options()}`,
2032
+ endValues,
2033
+ );
2034
+ else
2035
+ say(
2036
+ 'fasten.end',
2037
+ 'fail',
2038
+ `${x.into}'s hole measures ${mm(end.d)} mm, which is no hole for ${fx.thread}: the far end should be ${options()}`,
2039
+ endValues,
2040
+ );
763
2041
  }
764
2042
 
765
2043
  // fasten.length: the length chosen, or the one given held to the stack as measured
766
- const zGrip = end.kind === 'nut' ? end.nut.z : end.mouth, grip = zGrip - zHead, stack = zGrip - zSeat, intoMat = matOf(B), tipRoom = DEFAULTS.tip_room.value;
2044
+ const zGrip = end.kind === 'nut' ? end.nut.z : end.mouth,
2045
+ grip = zGrip - zHead,
2046
+ stack = zGrip - zSeat,
2047
+ intoMat = matOf(B),
2048
+ tipRoom = DEFAULTS.tip_room.value;
767
2049
  sc.grip = r3(grip);
768
- let pick = null, none = null, need = null;
769
- if (end.slot) { // the shortest sold length with a hex nut's height of thread in the slot nut, its tip short of the slot's floor
2050
+ let pick = null,
2051
+ none = null,
2052
+ need = null;
2053
+ if (end.slot) {
2054
+ // the shortest sold length with a hex nut's height of thread in the slot nut, its tip short of the slot's floor
770
2055
  const hexH = fx.figures.nut_height?.value;
771
2056
  need = r3(hexH ? Math.min(end.thread, hexH) : end.thread);
772
- const lo = end.zThr + need - zHead, hi = end.floor - FASTEN.floor.value - zHead;
2057
+ const lo = end.zThr + need - zHead,
2058
+ hi = end.floor - FASTEN.floor.value - zHead;
773
2059
  // (a printed bolt is printed to any whole millimetre: every one from the shortest up is "sold")
774
- const sold = fx.printed ? Array.from({ length: Math.max(0, Math.floor(hi + EPS) - Math.ceil(lo - EPS) + 1) }, (_, i) => Math.ceil(lo - EPS) + i) : fx.figures.lengths?.value || [], L0 = sold.find((l) => l >= lo - EPS && l <= hi + EPS);
775
- end.need = need; end.window = [r3(lo), r3(hi)];
776
- if (L0) pick = { name: F.screwModel(fx, { length: L0, head: form }).name, length: L0, engaged: r3(Math.min(end.thread, zHead + L0 - end.zThr)), spare: r3(end.floor - zHead - L0) };
777
- else if (fx.printed) none = `no whole millimetre from ${mm2(lo)} to ${mm2(hi)} mm is a length for the printed bolt: ${mm2(grip)} mm under its head (${end.slot.part}${washer ? ', the washer' : ''} and ${lipSays(end.slot)}) leaves ${mm2(hi - lo)} mm between ${mm2(need)} mm in the nut and ${mm2(FASTEN.floor.value)} mm kept off the slot's floor. A part of another thickness, or a washer under the head`;
778
- else none = `no ${fx.thread} ${form} screw is sold from ${mm2(lo)} to ${mm2(hi)} mm long, what ${mm2(grip)} mm under its head (${end.slot.part}${washer ? ', the washer' : ''} and ${lipSays(end.slot)}) leaves: ${mm2(need)} mm in the nut and ${mm2(FASTEN.floor.value)} mm kept off the slot's floor (${(sold.filter((l) => l < lo - EPS).at(-1) ?? null) != null ? `${fx.thread}x${sold.filter((l) => l < lo - EPS).at(-1)} engages too little, ` : ''}${sold.find((l) => l > hi + EPS) != null ? `${fx.thread}x${sold.find((l) => l > hi + EPS)} reaches the floor` : 'none is that long'}). A part of another thickness, or a washer under the head`;
779
- } else if (end.motor && form !== 'set') { // the longest sold length that stops short of the motor's thread's end, as motor.mount chooses
780
- const sold = fx.figures.lengths?.value || [], room = end.depth - (end.motor.reach ? 0 : tipRoom), L0 = [...sold].reverse().find((l) => l > grip + EPS && l - grip <= room + (end.motor.reach ? READ : EPS)); // (a maker's reach is the limit itself: no room kept past it, the mesh's grid allowed)
781
- if (L0) pick = { name: F.screwModel(fx, { length: L0, head: form }).name, length: L0, engaged: r3(L0 - grip), spare: r3(room - (L0 - grip)) };
782
- else none = end.motor.reach ? `no ${fx.thread} ${form} screw that is sold goes ${mm2(grip)} mm under its head into ${x.into} and stops within the ${mm2(end.depth)} mm its maker allows` : `no ${fx.thread} ${form} screw that is sold goes ${mm2(grip)} mm under its head into ${x.into} and stops within its ${mm2(end.depth)} mm of thread, ${mm2(tipRoom)} mm kept at its tip`;
2060
+ const sold = fx.printed
2061
+ ? Array.from(
2062
+ { length: Math.max(0, Math.floor(hi + EPS) - Math.ceil(lo - EPS) + 1) },
2063
+ (_, i) => Math.ceil(lo - EPS) + i,
2064
+ )
2065
+ : fx.figures.lengths?.value || [],
2066
+ L0 = sold.find((l) => l >= lo - EPS && l <= hi + EPS);
2067
+ end.need = need;
2068
+ end.window = [r3(lo), r3(hi)];
2069
+ if (L0)
2070
+ pick = {
2071
+ name: F.screwModel(fx, { length: L0, head: form }).name,
2072
+ length: L0,
2073
+ engaged: r3(Math.min(end.thread, zHead + L0 - end.zThr)),
2074
+ spare: r3(end.floor - zHead - L0),
2075
+ };
2076
+ else if (fx.printed)
2077
+ none = `no whole millimetre from ${mm2(lo)} to ${mm2(hi)} mm is a length for the printed bolt: ${mm2(grip)} mm under its head (${end.slot.part}${washer ? ', the washer' : ''} and ${lipSays(end.slot)}) leaves ${mm2(hi - lo)} mm between ${mm2(need)} mm in the nut and ${mm2(FASTEN.floor.value)} mm kept off the slot's floor. A part of another thickness, or a washer under the head`;
2078
+ else
2079
+ none = `no ${fx.thread} ${form} screw is sold from ${mm2(lo)} to ${mm2(hi)} mm long, what ${mm2(grip)} mm under its head (${end.slot.part}${washer ? ', the washer' : ''} and ${lipSays(end.slot)}) leaves: ${mm2(need)} mm in the nut and ${mm2(FASTEN.floor.value)} mm kept off the slot's floor (${(sold.filter((l) => l < lo - EPS).at(-1) ?? null) != null ? `${fx.thread}x${sold.filter((l) => l < lo - EPS).at(-1)} engages too little, ` : ''}${sold.find((l) => l > hi + EPS) != null ? `${fx.thread}x${sold.find((l) => l > hi + EPS)} reaches the floor` : 'none is that long'}). A part of another thickness, or a washer under the head`;
2080
+ } else if (end.motor && form !== 'set') {
2081
+ // the longest sold length that stops short of the motor's thread's end, as motor.mount chooses
2082
+ const sold = fx.figures.lengths?.value || [],
2083
+ room = end.depth - (end.motor.reach ? 0 : tipRoom),
2084
+ L0 = [...sold].reverse().find((l) => l > grip + EPS && l - grip <= room + (end.motor.reach ? READ : EPS)); // (a maker's reach is the limit itself: no room kept past it, the mesh's grid allowed)
2085
+ if (L0)
2086
+ pick = {
2087
+ name: F.screwModel(fx, { length: L0, head: form }).name,
2088
+ length: L0,
2089
+ engaged: r3(L0 - grip),
2090
+ spare: r3(room - (L0 - grip)),
2091
+ };
2092
+ else
2093
+ none = end.motor.reach
2094
+ ? `no ${fx.thread} ${form} screw that is sold goes ${mm2(grip)} mm under its head into ${x.into} and stops within the ${mm2(end.depth)} mm its maker allows`
2095
+ : `no ${fx.thread} ${form} screw that is sold goes ${mm2(grip)} mm under its head into ${x.into} and stops within its ${mm2(end.depth)} mm of thread, ${mm2(tipRoom)} mm kept at its tip`;
783
2096
  need = pick ? pick.engaged : null;
784
2097
  } else if (end.kind && form !== 'set' && stack > 1e-6) {
785
- const into = { kind: end.kind, ...(end.kind === 'nut' ? { nut: end.nut.kind } : end.blind ? (end.kind === 'insert' ? { room: Math.max(end.depth - tipRoom, end.insert?.length ?? 0) } : { depth: end.depth }) : { through: true }), ...(['tap', 'thread'].includes(end.kind) && intoMat.cls ? { material: intoMat.known ? intoMat.name : intoMat.cls } : {}) };
786
- try { pick = F.lengthFor(r3(stack), fx, { into, head: form, ...(washer ? { washer: true } : {}) }); need = pick.need; } catch (e) { none = e.message.replace(/^lengthFor: /, ''); }
2098
+ const into = {
2099
+ kind: end.kind,
2100
+ ...(end.kind === 'nut'
2101
+ ? { nut: end.nut.kind }
2102
+ : end.blind
2103
+ ? end.kind === 'insert'
2104
+ ? { room: Math.max(end.depth - tipRoom, end.insert?.length ?? 0) }
2105
+ : { depth: end.depth }
2106
+ : { through: true }),
2107
+ ...(['tap', 'thread'].includes(end.kind) && intoMat.cls
2108
+ ? { material: intoMat.known ? intoMat.name : intoMat.cls }
2109
+ : {}),
2110
+ };
2111
+ try {
2112
+ pick = F.lengthFor(r3(stack), fx, { into, head: form, ...(washer ? { washer: true } : {}) });
2113
+ need = pick.need;
2114
+ } catch (e) {
2115
+ none = e.message.replace(/^lengthFor: /, '');
2116
+ }
787
2117
  }
788
2118
  // how much thread the far end offers, and how much the rule for it asks
789
- const avail = !end.kind ? 0 : end.slot ? end.thread : end.kind === 'nut' ? end.nut.model.height : end.kind === 'insert' ? Math.min(end.insert?.length ?? end.depth, end.depth) : end.depth;
2119
+ const avail = !end.kind
2120
+ ? 0
2121
+ : end.slot
2122
+ ? end.thread
2123
+ : end.kind === 'nut'
2124
+ ? end.nut.model.height
2125
+ : end.kind === 'insert'
2126
+ ? Math.min(end.insert?.length ?? end.depth, end.depth)
2127
+ : end.depth;
790
2128
  if (need == null && end.kind) {
791
2129
  if (end.kind === 'nut') need = end.nut.model.height;
792
- else if (end.kind === 'insert') need = Math.min(DEFAULTS.insert_engagement.value * fx.major, end.insert?.length ?? Infinity);
2130
+ else if (end.kind === 'insert')
2131
+ need = Math.min(DEFAULTS.insert_engagement.value * fx.major, end.insert?.length ?? Infinity);
793
2132
  else if (end.kind === 'pilot' && fx.figures.pilot_depth) need = fx.figures.pilot_depth.value;
794
- else { try { need = F.engagement(fx, { depth: 1, material: end.kind === 'pilot' ? 'plastic' : intoMat.known ? intoMat.name : intoMat.cls ?? 'plastic' }).need; } catch { need = null; } }
2133
+ else {
2134
+ try {
2135
+ need = F.engagement(fx, {
2136
+ depth: 1,
2137
+ material: end.kind === 'pilot' ? 'plastic' : intoMat.known ? intoMat.name : (intoMat.cls ?? 'plastic'),
2138
+ }).need;
2139
+ } catch {
2140
+ need = null;
2141
+ }
2142
+ }
795
2143
  }
796
- let L = given ?? pick?.length ?? null, sold = true;
2144
+ let L = given ?? pick?.length ?? null,
2145
+ sold = true;
797
2146
  if (form === 'set' && L == null) L = Math.max(1, Math.floor(end.depth));
798
- if (L == null) { const want = grip + (need ?? fx.major), listed = fx.figures.lengths?.value; L = (Array.isArray(listed) && listed.find((l) => l >= want - 1e-9)) || Math.ceil(want); } // (none fits: drawn at the nearest, so the picture still shows the joint)
2147
+ if (L == null) {
2148
+ const want = grip + (need ?? fx.major),
2149
+ listed = fx.figures.lengths?.value;
2150
+ L = (Array.isArray(listed) && listed.find((l) => l >= want - 1e-9)) || Math.ceil(want);
2151
+ } // (none fits: drawn at the nearest, so the picture still shows the joint)
799
2152
  let model;
800
- try { model = F.screwModel(fx, { length: L, head: form }); } catch (e) { sold = false; model = F.screwModel(fx, { length: L, head: form, anyLength: true }); if (given != null) say('fasten.length', 'fail', e.message.replace(/^screw: /, '')); }
801
- const inEnd = L - grip, zTip = zHead + L, inThread = end.slot ? zTip - end.zThr : inEnd; // (a slot nut's thread starts in its tongue, in the opening)
802
- sc.dir = D; sc.engaged = end.kind ? r3(Math.max(0, Math.min(inThread, avail))) : 0; sc.endKind = end.kind ?? null; sc.intoMaterial = intoMat.known ? intoMat.name : null; sc.bear = (washer ? washer.diameter : head?.across ?? fx.major * 2) / 2;
803
- sc.length = L; sc.model = model; sc.between = [at(zHead), at(zTip)]; sc.end = end.kind ?? null;
2153
+ try {
2154
+ model = F.screwModel(fx, { length: L, head: form });
2155
+ } catch (e) {
2156
+ sold = false;
2157
+ model = F.screwModel(fx, { length: L, head: form, anyLength: true });
2158
+ if (given != null) say('fasten.length', 'fail', e.message.replace(/^screw: /, ''));
2159
+ }
2160
+ const inEnd = L - grip,
2161
+ zTip = zHead + L,
2162
+ inThread = end.slot ? zTip - end.zThr : inEnd; // (a slot nut's thread starts in its tongue, in the opening)
2163
+ sc.dir = D;
2164
+ sc.engaged = end.kind ? r3(Math.max(0, Math.min(inThread, avail))) : 0;
2165
+ sc.endKind = end.kind ?? null;
2166
+ sc.intoMaterial = intoMat.known ? intoMat.name : null;
2167
+ sc.bear = (washer ? washer.diameter : (head?.across ?? fx.major * 2)) / 2;
2168
+ sc.length = L;
2169
+ sc.model = model;
2170
+ sc.between = [at(zHead), at(zTip)];
2171
+ sc.end = end.kind ?? null;
804
2172
  // a screw into a thread in plastic (a pilot, a tapped or a printed thread): the most torque to tighten it to keeps its
805
2173
  // preload to the thread's stripping load over fixings.load_margin, as screwLoad does. A stripping load is an estimate
806
2174
  // and a torque's clamp scatters by a quarter to a third, so the seat alone may ask more than the thread takes
807
2175
  let threadMost = null; // { torque, strip }: rounded down to the hundredth, as screwLoad's
808
2176
  if (!fx.printed && ['pilot', 'tap', 'thread'].includes(sc.endKind) && sc.intoMaterial && sc.engaged > 0) {
809
- try { const strip = F.stripping(fx, { depth: sc.engaged, material: sc.intoMaterial }).strip; threadMost = { strip, torque: Math.floor(((DEFAULTS.nut_factor.value * fx.major * strip) / DEFAULTS.load_margin.value / 1000) * 100 + 1e-9) / 100 }; } catch { threadMost = null; }
2177
+ try {
2178
+ const strip = F.stripping(fx, { depth: sc.engaged, material: sc.intoMaterial }).strip;
2179
+ threadMost = {
2180
+ strip,
2181
+ torque:
2182
+ Math.floor(
2183
+ ((DEFAULTS.nut_factor.value * fx.major * strip) / DEFAULTS.load_margin.value / 1000) * 100 + 1e-9,
2184
+ ) / 100,
2185
+ };
2186
+ } catch {
2187
+ threadMost = null;
2188
+ }
810
2189
  }
811
- const threadSays = (t) => (threadMost && threadMost.torque < t ? `; its thread in ${sc.intoMaterial} strips at about ${mm(+threadMost.strip.toFixed(0))} N, an estimate, so tighten to ${mm(threadMost.torque)} N m at most, half that` : ''); // (where the thread holds a screw to less than the seat)
812
- const lenValues = { length: L, grip: r3(grip), into: r3(inEnd) }, under = `${mm2(grip)} mm under its head${washer ? ' (its washer with it)' : ''}`;
2190
+ const threadSays = (t) =>
2191
+ threadMost && threadMost.torque < t
2192
+ ? `; its thread in ${sc.intoMaterial} strips at about ${mm(+threadMost.strip.toFixed(0))} N, an estimate, so tighten to ${mm(threadMost.torque)} N m at most, half that`
2193
+ : ''; // (where the thread holds a screw to less than the seat)
2194
+ const lenValues = { length: L, grip: r3(grip), into: r3(inEnd) },
2195
+ under = `${mm2(grip)} mm under its head${washer ? ' (its washer with it)' : ''}`;
813
2196
  const wouldDo = pick && pick.length !== L ? `${pick.name} would do` : null;
814
2197
  if (given == null) {
815
- if (pick && end.slot) say('fasten.length', 'pass', `${pick.name} chosen, the shortest ${fx.printed ? 'that fits (a printed bolt is printed to any whole millimetre)' : 'sold that fits'}: ${under} (${end.slot.part}${washer ? ', the washer' : ''} and ${lipSays(end.slot)}), ${mm2(pick.engaged)} mm into its nut, its tip ${mm2(zTip - end.mouth)} mm into the slot and ${mm2(pick.spare)} mm short of its floor`, { ...lenValues, floor: r3(pick.spare) });
816
- else if (pick) say('fasten.length', 'pass', `${pick.name} chosen, the ${end.motor ? (end.motor.reach ? 'longest sold that goes no further than its maker allows' : 'longest sold that stops short of the end of the thread') : fx.printed ? 'shortest that fits (a printed bolt is printed to any whole millimetre)' : 'shortest sold that fits'}: ${under} and ${mm2(pick.engaged)} mm into ${x.into}${end.kind === 'nut' ? '\'s nut' : ''}${pick.spare != null ? `, ${mm2(pick.spare)} mm short of bottoming out` : ''}`, lenValues);
2198
+ if (pick && end.slot)
2199
+ say(
2200
+ 'fasten.length',
2201
+ 'pass',
2202
+ `${pick.name} chosen, the shortest ${fx.printed ? 'that fits (a printed bolt is printed to any whole millimetre)' : 'sold that fits'}: ${under} (${end.slot.part}${washer ? ', the washer' : ''} and ${lipSays(end.slot)}), ${mm2(pick.engaged)} mm into its nut, its tip ${mm2(zTip - end.mouth)} mm into the slot and ${mm2(pick.spare)} mm short of its floor`,
2203
+ { ...lenValues, floor: r3(pick.spare) },
2204
+ );
2205
+ else if (pick)
2206
+ say(
2207
+ 'fasten.length',
2208
+ 'pass',
2209
+ `${pick.name} chosen, the ${end.motor ? (end.motor.reach ? 'longest sold that goes no further than its maker allows' : 'longest sold that stops short of the end of the thread') : fx.printed ? 'shortest that fits (a printed bolt is printed to any whole millimetre)' : 'shortest sold that fits'}: ${under} and ${mm2(pick.engaged)} mm into ${x.into}${end.kind === 'nut' ? "'s nut" : ''}${pick.spare != null ? `, ${mm2(pick.spare)} mm short of bottoming out` : ''}`,
2210
+ lenValues,
2211
+ );
817
2212
  else if (none) say('fasten.length', 'fail', `no length chosen: ${none}`, lenValues);
818
- else if (form !== 'set') say('fasten.length', 'info', `no length chosen until the far end is one a screw holds in: ${model.name} is drawn`, lenValues);
819
- } else if (inEnd <= EPS) say('fasten.length', 'fail', `${model.name} does not reach ${x.into}: it is ${mm2(L)} mm long and there is ${under}${wouldDo ? `. ${wouldDo}` : ''}`, lenValues);
820
- else if (end.slot && zTip > end.floor - FASTEN.floor.value + EPS) say('fasten.length', 'fail', `${model.name} reaches the slot's floor: with ${under} its tip goes ${mm2(zTip - end.mouth)} mm into ${end.slot.item}'s ${end.slot.place} slot, whose floor is ${mm2(end.depth)} mm under the face, where ${mm2(FASTEN.floor.value)} mm is kept: it presses on the beam's core and not on its nut${wouldDo ? `. ${wouldDo}` : ''}`, { ...lenValues, floor: r3(end.floor - zTip) });
821
- else if (end.slot) say('fasten.length', sold ? 'pass' : 'info', `${model.name} reaches: ${under}, its tip ${mm2(zTip - end.mouth)} mm into the slot, ${mm2(end.floor - zTip)} mm short of its floor`, lenValues);
822
- else if (end.blind && inEnd > end.depth - (end.kind === 'insert' || end.motor?.reach ? 0 : tipRoom) + (end.motor?.reach ? READ : EPS)) say('fasten.length', 'fail', `${model.name} bottoms out: with ${under} it goes ${mm2(inEnd)} mm into a hole ${mm2(end.depth)} mm deep${end.kind === 'insert' ? '' : `, where ${mm2(tipRoom)} mm is kept at its tip`}, so it tightens on its tip and not on its head${wouldDo ? `. ${wouldDo}` : `. Deepen the hole to ${mm2(inEnd + tipRoom)} mm, or use a shorter screw`}`, { ...lenValues, depth: r3(end.depth) });
2213
+ else if (form !== 'set')
2214
+ say(
2215
+ 'fasten.length',
2216
+ 'info',
2217
+ `no length chosen until the far end is one a screw holds in: ${model.name} is drawn`,
2218
+ lenValues,
2219
+ );
2220
+ } else if (inEnd <= EPS)
2221
+ say(
2222
+ 'fasten.length',
2223
+ 'fail',
2224
+ `${model.name} does not reach ${x.into}: it is ${mm2(L)} mm long and there is ${under}${wouldDo ? `. ${wouldDo}` : ''}`,
2225
+ lenValues,
2226
+ );
2227
+ else if (end.slot && zTip > end.floor - FASTEN.floor.value + EPS)
2228
+ say(
2229
+ 'fasten.length',
2230
+ 'fail',
2231
+ `${model.name} reaches the slot's floor: with ${under} its tip goes ${mm2(zTip - end.mouth)} mm into ${end.slot.item}'s ${end.slot.place} slot, whose floor is ${mm2(end.depth)} mm under the face, where ${mm2(FASTEN.floor.value)} mm is kept: it presses on the beam's core and not on its nut${wouldDo ? `. ${wouldDo}` : ''}`,
2232
+ { ...lenValues, floor: r3(end.floor - zTip) },
2233
+ );
2234
+ else if (end.slot)
2235
+ say(
2236
+ 'fasten.length',
2237
+ sold ? 'pass' : 'info',
2238
+ `${model.name} reaches: ${under}, its tip ${mm2(zTip - end.mouth)} mm into the slot, ${mm2(end.floor - zTip)} mm short of its floor`,
2239
+ lenValues,
2240
+ );
2241
+ else if (
2242
+ end.blind &&
2243
+ inEnd > end.depth - (end.kind === 'insert' || end.motor?.reach ? 0 : tipRoom) + (end.motor?.reach ? READ : EPS)
2244
+ )
2245
+ say(
2246
+ 'fasten.length',
2247
+ 'fail',
2248
+ `${model.name} bottoms out: with ${under} it goes ${mm2(inEnd)} mm into a hole ${mm2(end.depth)} mm deep${end.kind === 'insert' ? '' : `, where ${mm2(tipRoom)} mm is kept at its tip`}, so it tightens on its tip and not on its head${wouldDo ? `. ${wouldDo}` : `. Deepen the hole to ${mm2(inEnd + tipRoom)} mm, or use a shorter screw`}`,
2249
+ { ...lenValues, depth: r3(end.depth) },
2250
+ );
823
2251
  else {
824
- const far = end.kind === 'nut' ? end.nut.z + end.nut.model.height : end.far, out = end.blind ? 0 : zTip - far, most = FASTEN.proud.value * fx.major;
825
- if (out > most + EPS) say('fasten.length', 'warn', `${model.name} stands ${mm2(out)} mm proud of ${end.kind === 'nut' ? 'its nut' : `${x.into}'s far face`}, more than its own diameter${wouldDo ? `: ${wouldDo}` : ''}`, { ...lenValues, proud: r3(out) });
826
- else if (sold) say('fasten.length', 'pass', `${model.name} reaches: ${under}, ${mm2(inEnd)} mm into ${x.into}${end.kind === 'nut' ? '\'s nut' : ''}${end.blind ? `, ${mm2(end.depth - inEnd)} mm short of the hole's end` : out > 1e-6 ? `, its tip ${mm2(out)} mm proud` : ''}`, lenValues);
2252
+ const far = end.kind === 'nut' ? end.nut.z + end.nut.model.height : end.far,
2253
+ out = end.blind ? 0 : zTip - far,
2254
+ most = FASTEN.proud.value * fx.major;
2255
+ if (out > most + EPS)
2256
+ say(
2257
+ 'fasten.length',
2258
+ 'warn',
2259
+ `${model.name} stands ${mm2(out)} mm proud of ${end.kind === 'nut' ? 'its nut' : `${x.into}'s far face`}, more than its own diameter${wouldDo ? `: ${wouldDo}` : ''}`,
2260
+ { ...lenValues, proud: r3(out) },
2261
+ );
2262
+ else if (sold)
2263
+ say(
2264
+ 'fasten.length',
2265
+ 'pass',
2266
+ `${model.name} reaches: ${under}, ${mm2(inEnd)} mm into ${x.into}${end.kind === 'nut' ? "'s nut" : ''}${end.blind ? `, ${mm2(end.depth - inEnd)} mm short of the hole's end` : out > 1e-6 ? `, its tip ${mm2(out)} mm proud` : ''}`,
2267
+ lenValues,
2268
+ );
827
2269
  }
828
2270
 
2271
+ wallSays(end, { x, fx, flip, R, intoMat, say });
2272
+
829
2273
  // fasten.engagement: thread engaged at the far end, against the rule for what it is in
830
- if (end.motor && form !== 'set') { // a bought part's thread: held to its depth, and to the least engagement any metal is given (engagement.steel), as motor.mount is
831
- const e = Math.max(0, Math.min(inEnd, end.depth)), least = r3(F.engagement(fx, { depth: 1, material: 'steel' }).need), turns = +(e / fx.pitch).toFixed(1), values = { engaged: r3(e), depth: end.depth, turns, least };
832
- if (end.motor.reach && e >= Math.min(least, end.depth) - EPS) say('fasten.engagement', 'pass', `${mm(e)} mm into ${x.into}'s own thread, ${mm(turns)} turns: as far as its maker allows (${end.motor.model}.mount_hole_reach, ${mm(end.depth)} mm), its thread rated by its maker`, values);
833
- else if (e >= least - EPS) say('fasten.engagement', 'pass', `${mm(e)} mm of ${x.into}'s own thread, ${mm(turns)} turns of its ${mm(end.depth)} mm: a bought part's thread, held to its depth and to the ${mm(least)} mm engagement.steel gives any metal`, values);
834
- else say('fasten.engagement', 'fail', `${mm(e)} mm of ${x.into}'s own thread, ${mm(turns)} turns of its ${mm(end.depth)} mm: less than the ${mm(least)} mm engagement.steel gives any metal, so the thread strips before the screw holds. A longer screw, or a counterbore to sink its head`, values);
835
- }
836
- else if (end.kind && need != null && form !== 'set') {
2274
+ if (end.motor && form !== 'set') {
2275
+ // a bought part's thread: held to its depth, and to the least engagement any metal is given (engagement.steel), as motor.mount is
2276
+ const e = Math.max(0, Math.min(inEnd, end.depth)),
2277
+ least = r3(F.engagement(fx, { depth: 1, material: 'steel' }).need),
2278
+ turns = +(e / fx.pitch).toFixed(1),
2279
+ values = { engaged: r3(e), depth: end.depth, turns, least };
2280
+ if (end.motor.reach && e >= Math.min(least, end.depth) - EPS)
2281
+ say(
2282
+ 'fasten.engagement',
2283
+ 'pass',
2284
+ `${mm(e)} mm into ${x.into}'s own thread, ${mm(turns)} turns: as far as its maker allows (${end.motor.model}.mount_hole_reach, ${mm(end.depth)} mm), its thread rated by its maker`,
2285
+ values,
2286
+ );
2287
+ else if (e >= least - EPS)
2288
+ say(
2289
+ 'fasten.engagement',
2290
+ 'pass',
2291
+ `${mm(e)} mm of ${x.into}'s own thread, ${mm(turns)} turns of its ${mm(end.depth)} mm: a bought part's thread, held to its depth and to the ${mm(least)} mm engagement.steel gives any metal`,
2292
+ values,
2293
+ );
2294
+ else
2295
+ say(
2296
+ 'fasten.engagement',
2297
+ 'fail',
2298
+ `${mm(e)} mm of ${x.into}'s own thread, ${mm(turns)} turns of its ${mm(end.depth)} mm: less than the ${mm(least)} mm engagement.steel gives any metal, so the thread strips before the screw holds. A longer screw, or a counterbore to sink its head`,
2299
+ values,
2300
+ );
2301
+ } else if (end.kind && need != null && form !== 'set') {
837
2302
  // (held to the micron it is said in: the length was chosen from the stack rounded to the micron)
838
- const engaged = Math.max(0, Math.min(inThread, avail)), ok = r3(engaged) >= need - EPS, values = { engaged: r3(engaged), need: r3(need), turns: +(engaged / fx.pitch).toFixed(1) };
839
- const what2 = end.kind === 'nut' ? `its ${end.nut.model.name}, ${mm(avail)} mm high` : end.kind === 'insert' ? `the insert, ${mm(avail)} mm long` : `${intoMat.name ? `${intoMat.name}${intoMat.cls && intoMat.known ? ` (a${intoMat.cls === 'aluminium' ? 'n' : ''} ${intoMat.cls})` : ''}` : end.kind === 'pilot' ? 'plastic' : x.into}`;
840
- const rule = end.slot ? `${fx.set}.nut_height asks ${mm(need)} mm, a hexagon nut's height of thread` : end.kind === 'nut' ? 'a nut wants its whole height engaged' : end.kind === 'insert' ? `fixings.insert_engagement asks a diameter of thread or the whole insert, ${mm(need)} mm` : end.kind === 'pilot' && fx.figures.pilot_depth ? `${fx.set}.pilot_depth asks ${mm(need)} mm` : `engagement.${end.kind === 'pilot' ? 'plastic' : intoMat.cls ?? 'plastic'} asks ${mm(need / fx.major)} diameters, ${mm(need)} mm`;
841
- if (ok) say('fasten.engagement', 'pass', `${mm(engaged)} mm of thread in ${what2}, ${mm(values.turns)} turns: ${rule}`, values);
2303
+ const engaged = Math.max(0, Math.min(inThread, avail)),
2304
+ ok = r3(engaged) >= need - EPS,
2305
+ values = { engaged: r3(engaged), need: r3(need), turns: +(engaged / fx.pitch).toFixed(1) };
2306
+ const what2 =
2307
+ end.kind === 'nut'
2308
+ ? `its ${end.nut.model.name}, ${mm(avail)} mm high`
2309
+ : end.kind === 'insert'
2310
+ ? `the insert, ${mm(avail)} mm long`
2311
+ : `${intoMat.name ? `${intoMat.name}${intoMat.cls && intoMat.known ? ` (a${intoMat.cls === 'aluminium' ? 'n' : ''} ${intoMat.cls})` : ''}` : end.kind === 'pilot' ? 'plastic' : x.into}`;
2312
+ const rule = end.slot
2313
+ ? `${fx.set}.nut_height asks ${mm(need)} mm, a hexagon nut's height of thread`
2314
+ : end.kind === 'nut'
2315
+ ? 'a nut wants its whole height engaged'
2316
+ : end.kind === 'insert'
2317
+ ? `fixings.insert_engagement asks a diameter of thread or the whole insert, ${mm(need)} mm`
2318
+ : end.kind === 'pilot' && fx.figures.pilot_depth
2319
+ ? `${fx.set}.pilot_depth asks ${mm(need)} mm`
2320
+ : `engagement.${end.kind === 'pilot' ? 'plastic' : (intoMat.cls ?? 'plastic')} asks ${mm(need / fx.major)} diameters, ${mm(need)} mm`;
2321
+ if (ok)
2322
+ say(
2323
+ 'fasten.engagement',
2324
+ 'pass',
2325
+ `${mm(engaged)} mm of thread in ${what2}, ${mm(values.turns)} turns: ${rule}`,
2326
+ values,
2327
+ );
842
2328
  else {
843
- const cure = avail < need - EPS ? (end.kind === 'insert' || end.kind === 'nut' ? `there is only ${mm(avail)} mm of it` : `the hole offers ${mm(avail)} mm: ${end.blind ? `deepen it to ${mm(need + tipRoom)} mm` : `${x.into} wants ${mm(need)} mm of thread on the axis`}`)
844
- : pick && pick.length > L ? `${pick.name} would do` : none ? none : `a screw ${mm(grip + need)} mm or longer would do`;
845
- say('fasten.engagement', 'fail', `${model.name} engages ${mm(engaged)} mm of thread in ${what2}, ${mm(values.turns)} turns, where ${rule}: ${cure}`, values);
2329
+ const cure =
2330
+ avail < need - EPS
2331
+ ? end.kind === 'insert' || end.kind === 'nut'
2332
+ ? `there is only ${mm(avail)} mm of it`
2333
+ : `the hole offers ${mm(avail)} mm: ${end.blind ? `deepen it to ${mm(need + tipRoom)} mm` : `${x.into} wants ${mm(need)} mm of thread on the axis`}`
2334
+ : pick && pick.length > L
2335
+ ? `${pick.name} would do`
2336
+ : none
2337
+ ? none
2338
+ : `a screw ${mm(grip + need)} mm or longer would do`;
2339
+ say(
2340
+ 'fasten.engagement',
2341
+ 'fail',
2342
+ `${model.name} engages ${mm(engaged)} mm of thread in ${what2}, ${mm(values.turns)} turns, where ${rule}: ${cure}`,
2343
+ values,
2344
+ );
846
2345
  }
847
- } else if (end.kind && form !== 'set') say('fasten.engagement', 'info', `nothing says what ${x.into} is made of, so the thread engaged in it is not held to a rule: give its object a "material"`);
2346
+ } else if (end.kind && form !== 'set')
2347
+ say(
2348
+ 'fasten.engagement',
2349
+ 'info',
2350
+ `nothing says what ${x.into} is made of, so the thread engaged in it is not held to a rule: give its object a "material"`,
2351
+ );
848
2352
 
849
2353
  // fasten.seat: a flat seat under the head, as wide as the head and square to the axis, and what it takes
850
- if (A && lips) { // a head on a slot's lips: held where it spans the opening, and, inside the slot, where it fits in the cavity
851
- const across = (washer ? washer.diameter : head.across), values = { across, opening: lips.opening, ...(lips.inside ? { cavity: lips.cavityWidth, room: lips.room, height: head.height } : {}) }, of = `${A.name}'s slot (${lips.slot})`;
852
- if (form === 'countersunk' || across <= lips.opening + 1e-9) say('fasten.seat', 'fail', `the ${form} head, ${mm(across)} mm across, ${form === 'countersunk' ? 'has no cone to sit in on' : 'pulls through'} ${of}, whose lips are ${mm(lips.opening)} mm apart: a head wider than the opening, a button or a cap, holds`, values);
853
- else if (lips.inside && across > lips.cavityWidth + 1e-9) say('fasten.seat', 'fail', `the head, ${mm(across)} mm across, does not go into ${of}, ${mm(lips.cavityWidth)} mm wide under its lips: a smaller head, or a join that puts the head outside the beam`, values);
854
- else if (lips.inside && head.height > lips.room + 1e-9) say('fasten.seat', 'fail', `the head, ${mm(head.height)} mm high, does not fit under the lips of ${of}, which has ${mm(lips.room)} mm at its full width: a lower head (a button)`, values);
2354
+ if (A && lips) {
2355
+ // a head on a slot's lips: held where it spans the opening, and, inside the slot, where it fits in the cavity
2356
+ const across = washer ? washer.diameter : head.across,
2357
+ values = {
2358
+ across,
2359
+ opening: lips.opening,
2360
+ ...(lips.inside ? { cavity: lips.cavityWidth, room: lips.room, height: head.height } : {}),
2361
+ },
2362
+ of = `${A.name}'s slot (${lips.slot})`;
2363
+ if (form === 'countersunk' || across <= lips.opening + 1e-9)
2364
+ say(
2365
+ 'fasten.seat',
2366
+ 'fail',
2367
+ `the ${form} head, ${mm(across)} mm across, ${form === 'countersunk' ? 'has no cone to sit in on' : 'pulls through'} ${of}, whose lips are ${mm(lips.opening)} mm apart: a head wider than the opening, a button or a cap, holds`,
2368
+ values,
2369
+ );
2370
+ else if (lips.inside && across > lips.cavityWidth + 1e-9)
2371
+ say(
2372
+ 'fasten.seat',
2373
+ 'fail',
2374
+ `the head, ${mm(across)} mm across, does not go into ${of}, ${mm(lips.cavityWidth)} mm wide under its lips: a smaller head, or a join that puts the head outside the beam`,
2375
+ values,
2376
+ );
2377
+ else if (lips.inside && head.height > lips.room + 1e-9)
2378
+ say(
2379
+ 'fasten.seat',
2380
+ 'fail',
2381
+ `the head, ${mm(head.height)} mm high, does not fit under the lips of ${of}, which has ${mm(lips.room)} mm at its full width: a lower head (a button)`,
2382
+ values,
2383
+ );
855
2384
  else {
856
2385
  // what the lips take: the head's circle less the strip of the opening across it, against the beam's alloy;
857
2386
  // the tightening is the least of that and a screw tightened fully (three quarters of its proof load)
858
- const bt = lipsTake(F, s, x.lips.item, fx, across, lips.opening), v2 = bt ? { ...values, area: bt.area, limit: bt.limit, force: bt.force, torque: bt.torque } : values;
859
- if (bt) { sc.most = bt.torque; sc.seatForce = bt.force; }
860
- say('fasten.seat', 'pass', `the head, ${mm(across)} mm across, bears on the lips of ${of} ${lips.inside ? `from inside, in its ${mm(lips.cavityWidth)} mm cavity (${mm(head.height)} mm of the ${mm(lips.room)} mm under the lips)` : 'from outside'}, on each side of its ${mm(lips.opening)} mm opening${bt ? `; ${bt.text}${threadSays(bt.torque)}` : ''}`, v2);
2387
+ const bt = lipsTake(F, s, x.lips.item, fx, across, lips.opening),
2388
+ v2 = bt ? { ...values, area: bt.area, limit: bt.limit, force: bt.force, torque: bt.torque } : values;
2389
+ if (bt) {
2390
+ sc.most = bt.most;
2391
+ sc.seatForce = bt.force;
2392
+ }
2393
+ say(
2394
+ 'fasten.seat',
2395
+ 'pass',
2396
+ `the head, ${mm(across)} mm across, bears on the lips of ${of} ${lips.inside ? `from inside, in its ${mm(lips.cavityWidth)} mm cavity (${mm(head.height)} mm of the ${mm(lips.room)} mm under the lips)` : 'from outside'}, on each side of its ${mm(lips.opening)} mm opening${bt ? `; ${bt.text}${threadSays(bt.most)}` : ''}`,
2397
+ v2,
2398
+ );
861
2399
  }
862
2400
  } else if (A) {
863
- const seatPart = A.segs[bore0], near = seatPart.of.near, zLocal = (z) => (flip ? -z : z), bearR = (washer ? washer.diameter : head.across) / 2, boreR = seatPart.a.free, seatMat = matOf(A); // (boreR: the hole's mouth at the seat, a lead-in with it)
2401
+ const seatPart = A.segs[bore0],
2402
+ near = seatPart.of.near,
2403
+ zLocal = (z) => (flip ? -z : z),
2404
+ bearR = (washer ? washer.diameter : head.across) / 2,
2405
+ boreR = seatPart.a.free,
2406
+ seatMat = matOf(A); // (boreR: the hole's mouth at the seat, a lead-in with it)
864
2407
  const e = 0.02;
865
2408
  if (form === 'countersunk') {
866
- if (!cone) say('fasten.seat', 'fail', `a countersunk head sits in a ${mm(head.angle)}° countersink, and ${A.name}'s hole has a square edge: the head stands ${mm(proud)} mm proud on a line of contact. Draw it with v.fixings.countersink`, { proud: r3(proud) });
2409
+ if (!cone)
2410
+ say(
2411
+ 'fasten.seat',
2412
+ 'fail',
2413
+ `a countersunk head sits in a ${mm(head.angle)}° countersink, and ${A.name}'s hole has a square edge: the head stands ${mm(proud)} mm proud on a line of contact. Draw it with v.fixings.countersink`,
2414
+ { proud: r3(proud) },
2415
+ );
867
2416
  else {
868
- const ang = (2 * Math.atan((cone.a.free - cone.b.free) / (cone.z1 - cone.z0)) * 180) / Math.PI, okAngle = Math.abs(ang - head.angle) <= FASTEN.countersink.value;
869
- if (!okAngle) say('fasten.seat', 'fail', `${A.name}'s countersink is ${mm(+ang.toFixed(1))}°, and ${fx.thread}'s countersunk head is ${mm(head.angle)}°: the head bears on a line, not on its cone`, { angle: +ang.toFixed(1), wanted: head.angle });
870
- else if (proud > 0.05) say('fasten.seat', 'warn', `${A.name}'s countersink is ${mm(2 * cone.a.free)} mm across at its mouth, and the head is ${mm(head.across)} mm: the head stands ${mm(proud)} mm proud`, { proud: r3(proud), angle: +ang.toFixed(1) });
871
- else say('fasten.seat', 'pass', `the countersunk head sits in a ${mm(+ang.toFixed(1))}° countersink in ${A.name}, its top ${zSeat - A.reach[0] > 0.01 ? `${mm(zSeat - A.reach[0])} mm under the face` : 'flush with the face'}`, { angle: +ang.toFixed(1), sunk: r3(zSeat - A.reach[0]) });
2417
+ const ang = (2 * Math.atan((cone.a.free - cone.b.free) / (cone.z1 - cone.z0)) * 180) / Math.PI,
2418
+ okAngle = Math.abs(ang - head.angle) <= FASTEN.countersink.value;
2419
+ if (!okAngle)
2420
+ say(
2421
+ 'fasten.seat',
2422
+ 'fail',
2423
+ `${A.name}'s countersink is ${mm(+ang.toFixed(1))}°, and ${fx.thread}'s countersunk head is ${mm(head.angle)}°: the head bears on a line, not on its cone`,
2424
+ { angle: +ang.toFixed(1), wanted: head.angle },
2425
+ );
2426
+ else if (proud > 0.05)
2427
+ say(
2428
+ 'fasten.seat',
2429
+ 'warn',
2430
+ `${A.name}'s countersink is ${mm(2 * cone.a.free)} mm across at its mouth, and the head is ${mm(head.across)} mm: the head stands ${mm(proud)} mm proud`,
2431
+ { proud: r3(proud), angle: +ang.toFixed(1) },
2432
+ );
2433
+ else
2434
+ say(
2435
+ 'fasten.seat',
2436
+ 'pass',
2437
+ `the countersunk head sits in a ${mm(+ang.toFixed(1))}° countersink in ${A.name}, its top ${zSeat - A.reach[0] > 0.01 ? `${mm(zSeat - A.reach[0])} mm under the face` : 'flush with the face'}`,
2438
+ { angle: +ang.toFixed(1), sunk: r3(zSeat - A.reach[0]) },
2439
+ );
872
2440
  }
873
2441
  } else {
874
- const under = Math.min(ring(near, zLocal(zSeat + e), boreR + 0.6 * (bearR - boreR), false), ring(near, zLocal(zSeat + e), bearR - e, false)), over = Math.max(ring(near, zLocal(zSeat - e), boreR + 0.6 * (bearR - boreR), false), ring(near, zLocal(zSeat - e), bearR - e, false));
875
- const whole = under > 1 - 1e-9 && over < 1e-9, values = { under: r3(under), across: 2 * bearR, hole: r3(2 * boreR) };
876
- if (!flat || !whole) say('fasten.seat', 'fail', flat && washer && over > 1e-9 && zSeat - A.reach[0] > 0.01 ? `the washer, ${mm(2 * bearR)} mm across, does not go down ${A.name}'s counterbore to the seat: the counterbore is drawn for the head alone (${mm(head.across)} mm)`
877
- : !flat || over > 1e-9 ? `the ${washer ? 'washer' : 'head'} has no flat seat on ${A.name}: the face under it is not square to the screw (${cone ? 'a cone' : `material stands above the seat on ${Math.round(over * 100)}% of the way round`})` : `the ${washer ? 'washer' : 'head'} overhangs its seat on ${A.name}: there is material under ${Math.round(under * 100)}% of the ring out to its ${mm(2 * bearR)} mm, where a flat seat as wide as the ${washer ? 'washer' : 'head'} is asked`, values);
2442
+ const under = Math.min(
2443
+ ring(near, zLocal(zSeat + e), boreR + 0.6 * (bearR - boreR), false),
2444
+ ring(near, zLocal(zSeat + e), bearR - e, false),
2445
+ ),
2446
+ over = Math.max(
2447
+ ring(near, zLocal(zSeat - e), boreR + 0.6 * (bearR - boreR), false),
2448
+ ring(near, zLocal(zSeat - e), bearR - e, false),
2449
+ );
2450
+ const whole = under > 1 - 1e-9 && over < 1e-9,
2451
+ values = { under: r3(under), across: 2 * bearR, hole: r3(2 * boreR) };
2452
+ if (!flat || !whole)
2453
+ say(
2454
+ 'fasten.seat',
2455
+ 'fail',
2456
+ flat && washer && over > 1e-9 && zSeat - A.reach[0] > 0.01
2457
+ ? `the washer, ${mm(2 * bearR)} mm across, does not go down ${A.name}'s counterbore to the seat: the counterbore is drawn for the head alone (${mm(head.across)} mm)`
2458
+ : !flat || over > 1e-9
2459
+ ? `the ${washer ? 'washer' : 'head'} has no flat seat on ${A.name}: the face under it is not square to the screw (${cone ? 'a cone' : `material stands above the seat on ${Math.round(over * 100)}% of the way round`})`
2460
+ : `the ${washer ? 'washer' : 'head'} overhangs its seat on ${A.name}: there is material under ${Math.round(under * 100)}% of the ring out to its ${mm(2 * bearR)} mm, where a flat seat as wide as the ${washer ? 'washer' : 'head'} is asked`,
2461
+ values,
2462
+ );
878
2463
  else {
879
2464
  // what the seat takes: the ring under the head as drawn, against the strength of what it sits on
880
2465
  let st = null;
881
- if (seatMat.name && seatMat.known) { try { st = F.seating(fx, { head: form, material: seatMat.name, ...(torque != null ? { torque } : fx.printed ? { force: 1 } : {}) }); } catch { st = null; } } // (a printed bolt has no proof load to tighten to: only what the seat takes is read)
882
- const sunk = zSeat - A.reach[0], where = `a flat seat on ${A.name}${sunk > 0.01 ? `, ${mm(sunk)} mm down its counterbore` : ''}, whole out to the ${washer ? 'washer' : 'head'}'s ${mm(2 * bearR)} mm`;
883
- if (!st) say('fasten.seat', 'pass', `${where}${seatMat.name ? ` (no strength is known for ${seatMat.name}, so the pressure under it is not checked)` : ''}`, values);
2466
+ if (seatMat.name && seatMat.known) {
2467
+ try {
2468
+ st = F.seating(fx, {
2469
+ head: form,
2470
+ material: seatMat.name,
2471
+ ...(torque != null ? { torque } : fx.printed ? { force: 1 } : {}),
2472
+ });
2473
+ } catch {
2474
+ st = null;
2475
+ }
2476
+ } // (a printed bolt has no proof load to tighten to: only what the seat takes is read)
2477
+ const sunk = zSeat - A.reach[0],
2478
+ where = `a flat seat on ${A.name}${sunk > 0.01 ? `, ${mm(sunk)} mm down its counterbore` : ''}, whole out to the ${washer ? 'washer' : 'head'}'s ${mm(2 * bearR)} mm`;
2479
+ if (!st)
2480
+ say(
2481
+ 'fasten.seat',
2482
+ 'pass',
2483
+ `${where}${seatMat.name ? ` (no strength is known for ${seatMat.name}, so the pressure under it is not checked)` : ''}`,
2484
+ values,
2485
+ );
884
2486
  else {
885
- const D2 = st.head === 'hex' ? head.across * Math.cos(Math.PI / 6) : head.across, area = (d) => (Math.PI / 4) * (d * d - (2 * boreR) ** 2), bare = area(D2), onWasher = st.washer ? area(st.washer.diameter) : null, mine = washer ? onWasher : bare;
886
- const takes = st.limit * mine, K = DEFAULTS.nut_factor.value, torqueOf = (N) => (K * fx.major * N) / 1000, v2 = { ...values, area: +mine.toFixed(2), limit: st.limit, force: +takes.toFixed(1), ...(fx.printed ? {} : { torque: +torqueOf(takes).toFixed(3) }) }; // (a printed bolt: no tightening torque)
887
- if (!fx.printed) { sc.most = +torqueOf(takes).toFixed(2); sc.seatForce = takes; } // (a printed bolt is done up by hand: no torque to tighten to)
888
- if (torque == null && fx.printed) say('fasten.seat', 'pass', `${where}; on ${st.material} (${mm(st.limit)} MPa) its ${mm(+mine.toFixed(1))} mm² takes ${mm(+takes.toFixed(0))} N. A printed bolt is done up by hand, with no torque to tighten to`, v2);
889
- else if (torque == null) say('fasten.seat', 'pass', `${where}; on ${st.material} (${mm(st.limit)} MPa) its ${mm(+mine.toFixed(1))} mm² takes ${mm(+takes.toFixed(0))} N, a tightening of ${mm(+torqueOf(takes).toFixed(2))} N m${!washer && onWasher && sunk <= 0.01 && !(threadMost && threadMost.torque <= +torqueOf(takes).toFixed(2)) ? `: the ${fx.thread} washer would raise that to ${mm(+(st.limit * onWasher).toFixed(0))} N (${mm(+torqueOf(st.limit * onWasher).toFixed(2))} N m)` : ''}${threadSays(+torqueOf(takes).toFixed(2))}`, v2);
2487
+ // (the head bears on the flat face under it, its bearing diameter dw, where its rule set gives it:
2488
+ // seating says which it took)
2489
+ const outline = st.head === 'hex' ? head.across * Math.cos(Math.PI / 6) : head.across,
2490
+ D2 = st.bearing ?? outline,
2491
+ faceSays =
2492
+ !washer && Math.abs(D2 - outline) > 0.01 ? `, out to the head's ${mm(r3(D2))} mm bearing face,` : '',
2493
+ area = (d) => (Math.PI / 4) * (d * d - (2 * boreR) ** 2),
2494
+ bare = area(D2),
2495
+ onWasher = st.washer ? area(st.washer.diameter) : null,
2496
+ mine = washer ? onWasher : bare;
2497
+ const takes = st.limit * mine,
2498
+ K = DEFAULTS.nut_factor.value,
2499
+ torqueOf = (N) => (K * fx.major * N) / 1000,
2500
+ v2 = {
2501
+ ...values,
2502
+ area: +mine.toFixed(2),
2503
+ limit: st.limit,
2504
+ force: +takes.toFixed(1),
2505
+ ...(fx.printed ? {} : { torque: +torqueOf(takes).toFixed(3) }),
2506
+ }; // (a printed bolt: no tightening torque)
2507
+ // the most to tighten to: half what the seat takes, within a screw tightened fully (seatMost), with a load
2508
+ // on the joint or without
2509
+ const seatSafe = fx.printed ? null : seatMost(fx, takes, F.preload(fx, { force: 1 }).full.torque),
2510
+ takesSays = `takes ${mm(+takes.toFixed(0))} N, a tightening of ${mm(+torqueOf(takes).toFixed(2))} N m`,
2511
+ safeSays =
2512
+ seatSafe == null
2513
+ ? ''
2514
+ : seatSafe < hundredthDown(torqueOf(takes) / DEFAULTS.load_margin.value)
2515
+ ? `, more than the screw tightened fully: tighten to ${mm(seatSafe)} N m at most, three quarters of its proof load`
2516
+ : `, so tighten to ${mm(seatSafe)} N m at most, ${HALF_THAT}`;
2517
+ // a washer, where there is none, would let the screw be tightened further: the most it allows, held to half
2518
+ // what a thread in plastic strips at, where that is more than without it
2519
+ const onIt =
2520
+ !washer && onWasher && sunk <= 0.01 && seatSafe != null
2521
+ ? Math.min(
2522
+ seatMost(fx, st.limit * onWasher, F.preload(fx, { force: 1 }).full.torque),
2523
+ threadMost?.torque ?? Infinity,
2524
+ )
2525
+ : null,
2526
+ washerMost = onIt != null && onIt > Math.min(seatSafe, threadMost?.torque ?? Infinity) ? onIt : null;
2527
+ if (!fx.printed) {
2528
+ sc.most = seatSafe;
2529
+ sc.seatForce = takes;
2530
+ } // (a printed bolt is done up by hand: no torque to tighten to)
2531
+ if (torque == null && fx.printed)
2532
+ say(
2533
+ 'fasten.seat',
2534
+ 'pass',
2535
+ `${where}; on ${st.material} (${mm(st.limit)} MPa) its ${mm(+mine.toFixed(1))} mm²${faceSays} takes ${mm(+takes.toFixed(0))} N. A printed bolt is done up by hand, with no torque to tighten to`,
2536
+ v2,
2537
+ );
2538
+ else if (torque == null)
2539
+ say(
2540
+ 'fasten.seat',
2541
+ 'pass',
2542
+ `${where}; on ${st.material} (${mm(st.limit)} MPa) its ${mm(+mine.toFixed(1))} mm²${faceSays} ${takesSays}${safeSays}${washerMost != null ? `; the ${fx.thread} washer would raise what it takes to ${mm(+(st.limit * onWasher).toFixed(0))} N, so it could be tightened to ${mm(washerMost)} N m` : ''}${threadSays(seatSafe)}`,
2543
+ v2,
2544
+ );
890
2545
  else {
891
- const p = st.force / mine, within = p <= st.limit + 1e-9, pw = onWasher ? st.force / onWasher : null;
2546
+ const p = st.force / mine,
2547
+ within = p <= st.limit + 1e-9,
2548
+ pw = onWasher ? st.force / onWasher : null;
892
2549
  // A printed bolt turned to a torque by hand: the clamp is T = K d F with steel's nut factor, an estimate for a
893
2550
  // plastic thread, and held against what the bolt itself breaks at, since a printed bolt breaks long before a seat gives
894
- const turned = fx.printed ? `turned by hand to ${mm(torque)} N m, it clamps with about ${mm(st.force)} N (T = K d F, fixings.nut_factor ${mm(K)} for steel threads: an estimate for a printed one)` : null;
2551
+ const turned = fx.printed
2552
+ ? `turned by hand to ${mm(torque)} N m, it clamps with about ${mm(st.force)} N (T = K d F, fixings.nut_factor ${mm(K)} for steel threads: an estimate for a printed one)`
2553
+ : null;
895
2554
  if (fx.printed) {
896
- const bolt = F.printedBoltModel(fx, { length: L, head: form, material, nut: boltMate(sc) }), want = DEFAULTS.load_margin.value, ok = st.force * want <= bolt.breaking + 1e-9, safe = Math.floor(torqueOf(bolt.breaking / want) * 100 + 1e-9) / 100; // (down to the hundredth: rounded up, the most named would fail its own check)
897
- say('fasten.torque', ok ? 'pass' : st.force <= bolt.breaking ? 'warn' : 'fail', `${turned}: ${ok ? `${mm(+(bolt.breaking / st.force).toFixed(2))} times under the ${mm(bolt.breaking)} N it breaks at (${bolt.governs})` : `${st.force <= bolt.breaking ? `under the ${mm(bolt.breaking)} N it breaks at (${bolt.governs}), but not ${mm(want)} times (fixings.load_margin)` : `more than the ${mm(bolt.breaking)} N it breaks at (${bolt.governs}): turning it that far breaks it`}. Turn it to ${mm(safe)} N m at most, or snug by hand with no torque given`}`,
898
- { torque, force: st.force, breaking: bolt.breaking, margin: +(bolt.breaking / st.force).toFixed(2), most: safe });
2555
+ const bolt = F.printedBoltModel(fx, { length: L, head: form, material, nut: boltMate(sc) }),
2556
+ want = DEFAULTS.load_margin.value,
2557
+ ok = st.force * want <= bolt.breaking + 1e-9,
2558
+ safe = Math.floor(torqueOf(bolt.breaking / want) * 100 + 1e-9) / 100; // (down to the hundredth: rounded up, the most named would fail its own check)
2559
+ say(
2560
+ 'fasten.torque',
2561
+ ok ? 'pass' : st.force <= bolt.breaking ? 'warn' : 'fail',
2562
+ `${turned}: ${ok ? `${mm(+(bolt.breaking / st.force).toFixed(2))} times under the ${mm(bolt.breaking)} N it breaks at (${bolt.governs})` : `${st.force <= bolt.breaking ? `under the ${mm(bolt.breaking)} N it breaks at (${bolt.governs}), but not ${mm(want)} times (fixings.load_margin)` : `more than the ${mm(bolt.breaking)} N it breaks at (${bolt.governs}): turning it that far breaks it`}. Turn it to ${mm(safe)} N m at most, or snug by hand with no torque given`}`,
2563
+ {
2564
+ torque,
2565
+ force: st.force,
2566
+ breaking: bolt.breaking,
2567
+ margin: +(bolt.breaking / st.force).toFixed(2),
2568
+ most: safe,
2569
+ },
2570
+ );
899
2571
  }
900
- if (within) say('fasten.seat', 'pass', `${where}; ${turned ?? `at ${mm(torque)} N m the screw clamps with ${mm(st.force)} N`}, ${mm(+p.toFixed(1))} MPa under the ${washer ? 'washer' : 'head'} on ${st.material}, whose strength is ${mm(st.limit)} MPa`, { ...v2, pressure: +p.toFixed(1) });
901
- else say('fasten.seat', 'fail', `${turned ?? `at ${mm(torque)} N m the screw clamps with ${mm(st.force)} N`}: ${mm(+p.toFixed(1))} MPa under the ${washer ? 'washer' : 'head'} on ${st.material}, whose strength is ${mm(st.limit)} MPa. ${!washer && pw != null && pw <= st.limit && sunk <= 0.01 && !(threadMost && threadMost.torque < torque) ? `The ${fx.thread} washer, ${mm(st.washer.diameter)} mm across, brings it to ${mm(+pw.toFixed(1))} MPa, within: give "washer": true` : threadMost && threadMost.torque < +torqueOf(takes).toFixed(2) ? `The seat takes ${mm(+takes.toFixed(0))} N (${mm(+torqueOf(takes).toFixed(2))} N m), and its thread in ${sc.intoMaterial} strips at about ${mm(+threadMost.strip.toFixed(0))} N, an estimate: tighten to ${mm(threadMost.torque)} N m at most, half that` : `The seat takes ${mm(+takes.toFixed(0))} N (${mm(+torqueOf(takes).toFixed(2))} N m): ${fx.printed ? 'turn it no further than that' : 'tighten to that'}, or spread the load wider`}`, { ...v2, pressure: +p.toFixed(1), ...(pw != null ? { washer: +pw.toFixed(1) } : {}) });
2572
+ if (within)
2573
+ say(
2574
+ 'fasten.seat',
2575
+ 'pass',
2576
+ `${where}; ${turned ?? `at ${mm(torque)} N m the screw clamps with ${mm(st.force)} N`}, ${mm(+p.toFixed(1))} MPa under the ${washer ? 'washer' : 'head'} on ${st.material}, whose strength is ${mm(st.limit)} MPa`,
2577
+ { ...v2, pressure: +p.toFixed(1) },
2578
+ );
2579
+ else
2580
+ say(
2581
+ 'fasten.seat',
2582
+ 'fail',
2583
+ `${turned ?? `at ${mm(torque)} N m the screw clamps with ${mm(st.force)} N`}: ${mm(+p.toFixed(1))} MPa under the ${washer ? 'washer' : 'head'} on ${st.material}, whose strength is ${mm(st.limit)} MPa. ${!washer && pw != null && pw <= st.limit && sunk <= 0.01 && !(threadMost && threadMost.torque < torque) ? `The ${fx.thread} washer, ${mm(st.washer.diameter)} mm across, brings it to ${mm(+pw.toFixed(1))} MPa, within: give "washer": true` : threadMost && threadMost.torque < seatSafe ? `The seat takes ${mm(+takes.toFixed(0))} N (${mm(+torqueOf(takes).toFixed(2))} N m), and its thread in ${sc.intoMaterial} strips at about ${mm(+threadMost.strip.toFixed(0))} N, an estimate: tighten to ${mm(threadMost.torque)} N m at most, half that` : fx.printed ? `The seat takes ${mm(+takes.toFixed(0))} N (${mm(+torqueOf(takes).toFixed(2))} N m): turn it no further than that, or spread the load wider` : `The seat ${takesSays}${safeSays}, or spread the load wider`}`,
2584
+ { ...v2, pressure: +p.toFixed(1), ...(pw != null ? { washer: +pw.toFixed(1) } : {}) },
2585
+ );
902
2586
  }
903
2587
  }
904
2588
  }
905
2589
  }
906
2590
  }
907
- // the torque to tighten to: the seat's take, held to half what a thread in plastic strips at
908
- if (sc.most != null && threadMost && threadMost.torque < sc.most) { sc.most = threadMost.torque; sc.mostBy = 'thread'; }
2591
+ // the torque to tighten to: half the seat's take, held to half what a thread in plastic strips at
2592
+ if (sc.most != null && threadMost && threadMost.torque < sc.most) {
2593
+ sc.most = threadMost.torque;
2594
+ sc.mostBy = 'thread';
2595
+ }
2596
+ // a torque given for a steel screw into a thread in plastic, with a load on the joint or without: its clamp held
2597
+ // against what the thread is estimated to strip at, fixings.load_margin times over (issue #582)
2598
+ if (torque != null && threadMost) {
2599
+ const K = DEFAULTS.nut_factor.value,
2600
+ want = DEFAULTS.load_margin.value,
2601
+ force = (torque * 1000) / (K * fx.major),
2602
+ strip = threadMost.strip,
2603
+ level = force * want <= strip + 1e-9 ? 'pass' : force <= strip + 1e-9 ? 'warn' : 'fail',
2604
+ of = `the ${mm(+strip.toFixed(0))} N its thread in ${sc.intoMaterial} is estimated to strip at`;
2605
+ say(
2606
+ 'fasten.torque',
2607
+ level,
2608
+ `at ${mm(torque)} N m the screw clamps with about ${mm(+force.toFixed(1))} N (T = K d F, fixings.nut_factor ${mm(K)}, an estimate)${
2609
+ level === 'pass'
2610
+ ? `, ${mm(+(strip / force).toFixed(2))} times under ${of}`
2611
+ : level === 'warn'
2612
+ ? `: more than half ${of}, and a torque's clamp scatters by a quarter to a third (fixings.load_margin), so the thread may strip as it is done up. Tighten to ${mm(threadMost.torque)} N m at most`
2613
+ : `: more than ${of}, so tightening it that far strips the thread. Tighten to ${mm(threadMost.torque)} N m at most`
2614
+ }`,
2615
+ {
2616
+ torque,
2617
+ force: +force.toFixed(1),
2618
+ strip: +strip.toFixed(1),
2619
+ margin: +(strip / force).toFixed(2),
2620
+ most: threadMost.torque,
2621
+ },
2622
+ );
2623
+ }
909
2624
 
910
2625
  // The hardware, each piece where it sits: its own frame, the item it moves with, the way it comes out, what it may overlap
911
- const host = (r) => r.parts[0], up = D.map((c) => -c), piece = (kind, m, o, P, Z, r, lift, allow, X) => sc.hardware.push({ kind, shape: shapeOf(F, kind, m, o), M: standing(P, Z, X), host: host(r), lift, allow });
2626
+ const host = (r) => r.parts[0],
2627
+ up = D.map((c) => -c),
2628
+ piece = (kind, m, o, P, Z, r, lift, allow, X) =>
2629
+ sc.hardware.push({ kind, shape: shapeOf(F, kind, m, o), M: standing(P, Z, X), host: host(r), lift, allow });
912
2630
  // (a printed nut carrier stands in a beam's slot, inside the beam's envelope, which the overlap check measures: the
913
2631
  // screw and nut in it may overlap that beam)
914
- const carrierIn = (() => { const it = (s.a.items || []).find((q) => q.id === top(x.into)); if (it?.fitting?.kind !== 'nut-carrier' || typeof it.at !== 'string') return []; const b = it.at.split('.')[0]; return [...new Set(s.parts.filter((p) => p.item === b && !p.hardware).map((p) => p.leaf))]; })();
2632
+ const carrierIn = (() => {
2633
+ const it = (s.a.items || []).find((q) => q.id === top(x.into));
2634
+ if (it?.fitting?.kind !== 'nut-carrier' || typeof it.at !== 'string') return [];
2635
+ const b = it.at.split('.')[0];
2636
+ return [...new Set(s.parts.filter((p) => p.item === b && !p.hardware).map((p) => p.leaf))];
2637
+ })();
915
2638
  const ends = [...new Set([...B.parts.map((p) => p.leaf), ...carrierIn])];
916
- if (A) piece('screw', fx, { length: L, head: form, anyLength: true }, at(zHead), up, A, up, A.parts.some((p) => s.objects.find((o) => o.id === p.leaf)?.beam) ? [...ends, ...new Set(A.parts.map((p) => p.leaf))] : ends); // (a screw through a beam, or its head in a slot, is inside the beam's envelope, which the overlap check measures)
2639
+ if (A)
2640
+ piece(
2641
+ 'screw',
2642
+ fx,
2643
+ { length: L, head: form, anyLength: true },
2644
+ at(zHead),
2645
+ up,
2646
+ A,
2647
+ up,
2648
+ A.parts.some((p) => s.objects.find((o) => o.id === p.leaf)?.beam)
2649
+ ? [...ends, ...new Set(A.parts.map((p) => p.leaf))]
2650
+ : ends,
2651
+ ); // (a screw through a beam, or its head in a slot, is inside the beam's envelope, which the overlap check measures)
917
2652
  else piece('screw', fx, { length: L, head: form, anyLength: true }, at(zSeat), up, B, up, ends);
918
2653
  if (washer) piece('washer', fx.thread, {}, at(zSeat), up, A, up, []);
919
- if (end.slot) sc.hardware.push({ kind: 'nut', shape: slotNutShape(end.nut.model), M: standing(at(end.mouth), up, end.slot.along), host: host(B), lift: end.slot.along, allow: ends });
2654
+ if (end.slot)
2655
+ sc.hardware.push({
2656
+ kind: 'nut',
2657
+ shape: slotNutShape(end.nut.model),
2658
+ M: standing(at(end.mouth), up, end.slot.along),
2659
+ host: host(B),
2660
+ lift: end.slot.along,
2661
+ allow: ends,
2662
+ });
920
2663
  else if (end.kind === 'nut') {
921
2664
  let X = null;
922
- if (end.nut.corner) { const lp = end.nut.corner.seg.a.loop, pr = end.nut.corner.seg.of, v = lp.corner ? [lp.corner[0] - lp.c[0], lp.corner[1] - lp.c[1]] : lp.along, local = add(pr.x.map((c) => c * v[0]), pr.y, v[1]), pm = end.nut.corner.seg.part.m; X = pm ? [0, 1, 2].map((r) => pm[r] * local[0] + pm[4 + r] * local[1] + pm[8 + r] * local[2]) : local; }
2665
+ if (end.nut.corner) {
2666
+ const lp = end.nut.corner.seg.a.loop,
2667
+ pr = end.nut.corner.seg.of,
2668
+ v = lp.corner ? [lp.corner[0] - lp.c[0], lp.corner[1] - lp.c[1]] : lp.along,
2669
+ local = add(
2670
+ pr.x.map((c) => c * v[0]),
2671
+ pr.y,
2672
+ v[1],
2673
+ ),
2674
+ pm = end.nut.corner.seg.part.m;
2675
+ X = pm ? [0, 1, 2].map((r) => pm[r] * local[0] + pm[4 + r] * local[1] + pm[8 + r] * local[2]) : local;
2676
+ }
923
2677
  piece('nut', fx.thread, { kind: end.nut.kind }, at(end.nut.z), D, B, D, carrierIn, X);
924
2678
  }
925
2679
  if (end.kind === 'insert' && end.insert) piece('insert', fx.thread, {}, at(end.mouth), up, B, up, ends);
926
2680
  // fasten.access: the key's way to the head, along its axis, with every other part in place (said by fastenChecks, with the order)
927
- const tool0 = toolFor(model, form, fx), tool = tool0 && fx.printed ? { ...tool0, name: `${tool0.name} turned by hand` } : tool0; // (a printed bolt takes no wrench's torque)
2681
+ const tool0 = toolFor(model, form, fx),
2682
+ tool = tool0 && fx.printed ? { ...tool0, name: `${tool0.name} turned by hand` } : tool0; // (a printed bolt takes no wrench's torque)
928
2683
  sc.tool = tool?.name ?? null;
929
2684
  if (opts.access && tool) sc.access = accessOf(parts, tool, add(A ? at(zHead) : at(zSeat), up, model.top), up);
930
2685
  });
@@ -932,28 +2687,88 @@ export function fastenOf(s, worlds, opts = {}) {
932
2687
  if (slotAt?.distance != null) slotPlaced(rel, slotAt, x);
933
2688
  // The pieces of this relation, named, and the fits it stands for
934
2689
  const count = { screw: 0, nut: 0, washer: 0, insert: 0 };
935
- for (const sc of rel.screws) for (const h of sc.hardware) {
936
- const id = `fasten-${k + 1}-${h.kind}-${sc.index + 1}`, hostIndex = ids.indexOf(h.host.item), hostWorld = rowsToMat4(worlds[hostIndex]);
937
- count[h.kind]++;
938
- const others = sc.hardware.filter((o) => o !== h).map((o) => `fasten-${k + 1}-${o.kind}-${sc.index + 1}`); // (a screw in its own nut, washer and insert)
939
- const hm = h.shape.model, bolt = h.kind === 'screw' && fx.printed ? F.printedBoltModel(fx, { length: hm.length, head: hm.head, material, nut: boltMate(sc) }) : null; // (a printed bolt: by its name, in plastic)
940
- hardware.push({ id, kind: h.kind, name: bolt ? bolt.name : hm.name, thread: fx.thread, fasten: k, screw: sc.index, grams: bolt ? bolt.grams : hm.mass, label, ...(bolt ? { printed: true } : {}), length: hm.length ?? null, head: h.kind === 'screw' ? hm.head : h.kind === 'nut' ? hm.kind : null, shape: h.shape, host: hostIndex, hostItem: h.host.item, with: h.host.object || h.host.item,
941
- local: mat4.multiply(mat4.create(), mat4.invert(mat4.create(), hostWorld), h.M), lift: vec3.transform([0, 0, 0], h.lift, mat4.invert(mat4.create(), [...hostWorld.slice(0, 12), 0, 0, 0, 1])), allow: [...h.allow, ...others] });
942
- }
2690
+ for (const sc of rel.screws)
2691
+ for (const h of sc.hardware) {
2692
+ const id = `fasten-${k + 1}-${h.kind}-${sc.index + 1}`,
2693
+ hostIndex = ids.indexOf(h.host.item),
2694
+ hostWorld = rowsToMat4(worlds[hostIndex]);
2695
+ count[h.kind]++;
2696
+ const others = sc.hardware.filter((o) => o !== h).map((o) => `fasten-${k + 1}-${o.kind}-${sc.index + 1}`); // (a screw in its own nut, washer and insert)
2697
+ const hm = h.shape.model,
2698
+ bolt =
2699
+ h.kind === 'screw' && fx.printed
2700
+ ? F.printedBoltModel(fx, { length: hm.length, head: hm.head, material, nut: boltMate(sc) })
2701
+ : null; // (a printed bolt: by its name, in plastic)
2702
+ hardware.push({
2703
+ id,
2704
+ kind: h.kind,
2705
+ name: bolt ? bolt.name : hm.name,
2706
+ thread: fx.thread,
2707
+ fasten: k,
2708
+ screw: sc.index,
2709
+ grams: bolt ? bolt.grams : hm.mass,
2710
+ label,
2711
+ ...(bolt ? { printed: true } : {}),
2712
+ length: hm.length ?? null,
2713
+ head: h.kind === 'screw' ? hm.head : h.kind === 'nut' ? hm.kind : null,
2714
+ shape: h.shape,
2715
+ host: hostIndex,
2716
+ hostItem: h.host.item,
2717
+ with: h.host.object || h.host.item,
2718
+ local: mat4.multiply(mat4.create(), mat4.invert(mat4.create(), hostWorld), h.M),
2719
+ lift: vec3.transform([0, 0, 0], h.lift, mat4.invert(mat4.create(), [...hostWorld.slice(0, 12), 0, 0, 0, 1])),
2720
+ allow: [...h.allow, ...others],
2721
+ });
2722
+ }
943
2723
  const names = new Map();
944
2724
  for (const h of hardware.filter((o) => o.fasten === k)) names.set(h.name, (names.get(h.name) ?? 0) + 1);
945
2725
  // the screws' lines carry the key that turns them and how tight: the torque given, or the most the seat under the head
946
2726
  // takes, held to half what a thread in plastic strips at
947
- const keys = [...new Set(rel.screws.map((sc) => sc.tool).filter(Boolean))], most = rel.screws.map((sc) => sc.most).filter((t) => t != null);
948
- const least = most.length ? Math.min(...most) : null, byThread = least != null && rel.screws.some((sc) => sc.most === least && sc.mostBy === 'thread'); // (the least of the seats' and the threads' takes)
949
- const tighten = torque != null ? { torque, given: true, ...(fx.printed ? { hand: true } : {}) } : least != null ? { torque: least, given: false, ...(byThread ? { thread: true } : {}) } : null;
950
- const lines = [...names].map(([fastener, n]) => ({ fastener, count: n, ...(rel.screws.some((sc) => sc.model?.name === fastener) ? { ...(keys.length ? { key: keys.join(' or ') } : {}), ...(tighten ? { tighten } : {}) } : {}) }));
951
- through.forEach((t, j) => fits.push({ a: t, b: slotAt ? slotAt.item : x.into, fastens: true, silent: true, fasten: k, note: x.note || `${t} fastened to ${x.into}`, ...(j === 0 && lines[0] ? lines[0] : {}) }));
952
- if (!through.length && lines[0]) fits.push({ a: x.into, b: x.into, silent: true, fasten: k, note: label, ...lines[0] });
953
- for (const l of lines.slice(1)) fits.push({ a: through[0] ?? x.into, b: slotAt ? slotAt.item : x.into, silent: true, fasten: k, note: x.note || `${through[0] ?? x.into} fastened to ${x.into}`, ...l });
954
- rel.count = count; rel.torque = torque;
2727
+ const keys = [...new Set(rel.screws.map((sc) => sc.tool).filter(Boolean))],
2728
+ most = rel.screws.map((sc) => sc.most).filter((t) => t != null);
2729
+ const least = most.length ? Math.min(...most) : null,
2730
+ byThread = least != null && rel.screws.some((sc) => sc.most === least && sc.mostBy === 'thread'); // (the least of the seats' and the threads' takes)
2731
+ const tighten =
2732
+ torque != null
2733
+ ? { torque, given: true, ...(fx.printed ? { hand: true } : {}) }
2734
+ : least != null
2735
+ ? { torque: least, given: false, ...(byThread ? { thread: true } : {}) }
2736
+ : null;
2737
+ const lines = [...names].map(([fastener, n]) => ({
2738
+ fastener,
2739
+ count: n,
2740
+ ...(rel.screws.some((sc) => sc.model?.name === fastener)
2741
+ ? { ...(keys.length ? { key: keys.join(' or ') } : {}), ...(tighten ? { tighten } : {}) }
2742
+ : {}),
2743
+ }));
2744
+ through.forEach((t, j) =>
2745
+ fits.push({
2746
+ a: t,
2747
+ b: slotAt ? slotAt.item : x.into,
2748
+ fastens: true,
2749
+ silent: true,
2750
+ fasten: k,
2751
+ note: x.note || `${t} fastened to ${x.into}`,
2752
+ ...(j === 0 && lines[0] ? lines[0] : {}),
2753
+ }),
2754
+ );
2755
+ if (!through.length && lines[0])
2756
+ fits.push({ a: x.into, b: x.into, silent: true, fasten: k, note: label, ...lines[0] });
2757
+ for (const l of lines.slice(1))
2758
+ fits.push({
2759
+ a: through[0] ?? x.into,
2760
+ b: slotAt ? slotAt.item : x.into,
2761
+ silent: true,
2762
+ fasten: k,
2763
+ note: x.note || `${through[0] ?? x.into} fastened to ${x.into}`,
2764
+ ...l,
2765
+ });
2766
+ rel.count = count;
2767
+ rel.torque = torque;
955
2768
  rel.load = loadOf(s, worlds, rel, list, { F, fx, ids, material });
956
- if (rel.load?.tighten != null && torque == null) for (const ft of fits.filter((q) => q.fasten === k && q.tighten)) ft.tighten = { torque: rel.load.tighten, given: false, load: true };
2769
+ if (rel.load?.tighten != null && torque == null)
2770
+ for (const ft of fits.filter((q) => q.fasten === k && q.tighten))
2771
+ ft.tighten = { torque: rel.load.tighten, given: false, load: true };
957
2772
  relations.push(rel);
958
2773
  });
959
2774
  return { relations, hardware, fits };
@@ -961,20 +2776,40 @@ export function fastenOf(s, worlds, opts = {}) {
961
2776
 
962
2777
  // ---------- fasten.load: what a joint carries, shared between its screws ----------
963
2778
  const G = 9.80665; // m/s²
964
- const sub3 = (p, q) => [p[0] - q[0], p[1] - q[1], p[2] - q[2]], scale3 = (p, k) => p.map((c) => c * k), rowsAt = (W, p) => [0, 1, 2].map((r) => W[4 * r] * p[0] + W[4 * r + 1] * p[1] + W[4 * r + 2] * p[2] + W[4 * r + 3]);
2779
+ const sub3 = (p, q) => [p[0] - q[0], p[1] - q[1], p[2] - q[2]],
2780
+ scale3 = (p, k) => p.map((c) => c * k),
2781
+ rowsAt = (W, p) => [0, 1, 2].map((r) => W[4 * r] * p[0] + W[4 * r + 1] * p[1] + W[4 * r + 2] * p[2] + W[4 * r + 3]);
965
2782
  // The items a joint holds up: those left with no way to the ground (the first item) once the joint's own links are cut.
966
2783
  // Links are the motion's joints, fits that fasten and the other fasten relations; null where both sides keep a way.
967
2784
  function beyondOf(s, rel, list, ids) {
968
- const idx = (n) => ids.indexOf(top(n)), members = new Set([...rel.through, rel.into].map(idx)), links = [];
2785
+ const idx = (n) => ids.indexOf(top(n)),
2786
+ members = new Set([...rel.through, rel.into].map(idx)),
2787
+ links = [];
969
2788
  for (const j of s.motion.joints || []) links.push([j.parent, j.child]);
970
2789
  for (const x of s.a.fits || []) if (x.fastens) links.push([idx(x.a), idx(x.b)]);
971
- list.forEach((x, k) => { if (k !== rel.index) for (const t of x.through || []) links.push([idx(t), idx(x.into)]); });
972
- const cut = links.filter(([p, q]) => p >= -1 && q >= 0 && !(members.has(p) && members.has(q))), reach = (from) => {
973
- const seen = new Set(from);
974
- for (let grew = true; grew;) { grew = false; for (const [p, q] of cut) { if (seen.has(p) && !seen.has(q)) { seen.add(q); grew = true; } if (seen.has(q) && !seen.has(p)) { seen.add(p); grew = true; } } }
975
- return seen;
976
- };
977
- const ground = reach([-1, 0]), loose = [...members].filter((m) => !ground.has(m));
2790
+ list.forEach((x, k) => {
2791
+ if (k !== rel.index) for (const t of x.through || []) links.push([idx(t), idx(x.into)]);
2792
+ });
2793
+ const cut = links.filter(([p, q]) => p >= -1 && q >= 0 && !(members.has(p) && members.has(q))),
2794
+ reach = (from) => {
2795
+ const seen = new Set(from);
2796
+ for (let grew = true; grew;) {
2797
+ grew = false;
2798
+ for (const [p, q] of cut) {
2799
+ if (seen.has(p) && !seen.has(q)) {
2800
+ seen.add(q);
2801
+ grew = true;
2802
+ }
2803
+ if (seen.has(q) && !seen.has(p)) {
2804
+ seen.add(p);
2805
+ grew = true;
2806
+ }
2807
+ }
2808
+ }
2809
+ return seen;
2810
+ };
2811
+ const ground = reach([-1, 0]),
2812
+ loose = [...members].filter((m) => !ground.has(m));
978
2813
  if (!loose.length || loose.length === members.size) return null;
979
2814
  return reach(loose);
980
2815
  }
@@ -984,42 +2819,149 @@ function beyondOf(s, rel, list, ids) {
984
2819
  * screw against its strength (screwLoad). Null where nothing loads the joint (no "loads", no motor beyond it).
985
2820
  */
986
2821
  function loadOf(s, worlds, rel, list, { F, fx, ids, material }) {
987
- const ok = rel.screws.filter((sc) => sc.dir && sc.at), loads = (s.motion.loads || []).filter((l) => l.mass != null);
2822
+ const ok = rel.screws.filter((sc) => sc.dir && sc.at),
2823
+ loads = (s.motion.loads || []).filter((l) => l.mass != null);
988
2824
  if (!ok.length || ok.length < rel.screws.length) return null;
989
2825
  const beyond = beyondOf(s, rel, list, ids);
990
- const drives = (s.motion.drives || []).filter((d) => beyond?.has(d.item) && d.joint && (() => { const j = s.motion.joints.find((q) => q.id === d.joint); return j && !beyond.has(j.child); })());
2826
+ const drives = (s.motion.drives || []).filter(
2827
+ (d) =>
2828
+ beyond?.has(d.item) &&
2829
+ d.joint &&
2830
+ (() => {
2831
+ const j = s.motion.joints.find((q) => q.id === d.joint);
2832
+ return j && !beyond.has(j.child);
2833
+ })(),
2834
+ );
991
2835
  if (!loads.length && !drives.length) return null;
992
2836
  if (!beyond) return { closed: true };
993
2837
  const u = unit(ok[0].dir);
994
2838
  if (ok.some((sc) => Math.abs(dot(unit(sc.dir), u) - 1) > 1e-6)) return { skew: true };
995
- const headSide = rel.through.some((t) => beyond.has(ids.indexOf(top(t)))), n = headSide ? u.map((c) => -c) : u; // n: the way the held part comes off
996
- const g = s.motion.gravity || [0, 0, -1], gl = Math.hypot(...g), down = g.map((c) => c / gl);
997
- let Fw = [0, 0, 0], Mw = [0, 0, 0], kg = 0;
998
- const hang = (mass, X) => { const f = scale3(down, mass * G); Fw = add(Fw, f); Mw = add(Mw, cross(X, f)); kg += mass; };
2839
+ const headSide = rel.through.some((t) => beyond.has(ids.indexOf(top(t)))),
2840
+ n = headSide ? u.map((c) => -c) : u; // n: the way the held part comes off
2841
+ const g = s.motion.gravity || [0, 0, -1],
2842
+ gl = Math.hypot(...g),
2843
+ down = g.map((c) => c / gl);
2844
+ let Fw = [0, 0, 0],
2845
+ Mw = [0, 0, 0],
2846
+ kg = 0;
2847
+ const hang = (mass, X) => {
2848
+ const f = scale3(down, mass * G);
2849
+ Fw = add(Fw, f);
2850
+ Mw = add(Mw, cross(X, f));
2851
+ kg += mass;
2852
+ };
999
2853
  const masses = massesOf(s, { placeItems, jointValues });
1000
- for (const m of masses) if (beyond.has(m.item)) { const d = (s.motion.drives || []).find((q) => q.item === m.item), mass = m.kg || (d ? d.model.mass ?? 0 : 0); if (mass > 0) hang(mass, rowsAt(worlds[m.item], m.centre)); }
2854
+ for (const m of masses)
2855
+ if (beyond.has(m.item)) {
2856
+ const d = (s.motion.drives || []).find((q) => q.item === m.item),
2857
+ mass = m.kg || (d ? (d.model.mass ?? 0) : 0);
2858
+ if (mass > 0) hang(mass, rowsAt(worlds[m.item], m.centre));
2859
+ }
1001
2860
  const hung = loads.filter((l) => beyond.has(l.item));
1002
2861
  for (const l of hung) hang(l.mass, rowsAt(worlds[l.item], [l.frame[3], l.frame[7], l.frame[11]]));
1003
2862
  // the joint's frame: e1, e2 across it, n along the screws; places about the screws' centroid
1004
- const c = ok.reduce((t, sc) => add(t, sc.at, 1 / ok.length), [0, 0, 0]), seed = Math.abs(n[0]) < 0.9 ? [1, 0, 0] : [0, 1, 0], e1 = unit(cross(seed, n)), e2 = cross(n, e1);
1005
- const places = ok.map((sc) => { const q = sub3(sc.at, c); return [dot(q, e1), dot(q, e2)]; }), local = (v) => [dot(v, e1), dot(v, e2), dot(v, n)];
1006
- const Mc = sub3(Mw, cross(c, Fw)), pivot = Math.min(...ok.map((sc) => sc.bear)); // N mm about the centroid
1007
- const torques = drives.map((d) => { const W = worlds[d.item], T = mountTorque(d), axis = [W[2], W[6], W[10]]; return { id: d.id, torque: T, about: T * dot(axis, n), M: scale3(axis, T * 1000) }; });
2863
+ const c = ok.reduce((t, sc) => add(t, sc.at, 1 / ok.length), [0, 0, 0]),
2864
+ seed = Math.abs(n[0]) < 0.9 ? [1, 0, 0] : [0, 1, 0],
2865
+ e1 = unit(cross(seed, n)),
2866
+ e2 = cross(n, e1);
2867
+ const places = ok.map((sc) => {
2868
+ const q = sub3(sc.at, c);
2869
+ return [dot(q, e1), dot(q, e2)];
2870
+ }),
2871
+ local = (v) => [dot(v, e1), dot(v, e2), dot(v, n)];
2872
+ const Mc = sub3(Mw, cross(c, Fw)),
2873
+ pivot = Math.min(...ok.map((sc) => sc.bear)); // N mm about the centroid
2874
+ const torques = drives.map((d) => {
2875
+ const W = worlds[d.item],
2876
+ T = mountTorque(d),
2877
+ axis = [W[2], W[6], W[10]];
2878
+ return { id: d.id, torque: T, about: T * dot(axis, n), M: scale3(axis, T * 1000) };
2879
+ });
1008
2880
  const Mt = torques.reduce((t, q) => add(t, q.M), [0, 0, 0]);
1009
2881
  // the worst of the motor turning either way; each screw against its strength at its share
1010
- const cases = (torques.length ? [1, -1] : [1]).map((sign) => screwGroup(places, { force: local(Fw), moment: local(add(Mc, Mt, sign)).map((m) => m / 1000), pivot }));
1011
- const screws = ok.map((sc, i) => {
1012
- const pick = cases.map((gp) => gp.screws[i]).reduce((a, b) => (b.tension > a.tension + 1e-9 || (Math.abs(b.tension - a.tension) <= 1e-9 && b.shear > a.shear) ? b : a));
2882
+ const cases = (torques.length ? [1, -1] : [1]).map((sign) =>
2883
+ screwGroup(places, { force: local(Fw), moment: local(add(Mc, Mt, sign)).map((m) => m / 1000), pivot }),
2884
+ );
2885
+ const loadOn = (sc, pick, most = sc.seatForce) => {
1013
2886
  const threaded = ['pilot', 'tap', 'thread'].includes(sc.endKind) && sc.intoMaterial && sc.engaged > 0;
1014
- const r = fx.printed ? printedLoad(F, fx, sc, pick, material) : F.screwLoad(fx, { tension: Math.max(0, pick.tension), shear: pick.shear, ...(threaded ? { depth: sc.engaged, material: sc.intoMaterial } : ['insert', 'nut'].includes(sc.endKind) ? { end: sc.endKind } : {}), ...(rel.torque != null ? { torque: rel.torque } : sc.seatForce ? { most: sc.seatForce } : {}) });
1015
- return { sc, tension: pick.tension, shear: pick.shear, r };
2887
+ return fx.printed
2888
+ ? printedLoad(F, fx, sc, pick, material)
2889
+ : F.screwLoad(fx, {
2890
+ tension: Math.max(0, pick.tension),
2891
+ shear: pick.shear,
2892
+ ...(threaded
2893
+ ? { depth: sc.engaged, material: sc.intoMaterial }
2894
+ : ['insert', 'nut'].includes(sc.endKind)
2895
+ ? { end: sc.endKind }
2896
+ : {}),
2897
+ ...(rel.torque != null ? { torque: rel.torque } : most > 0 ? { most } : {}),
2898
+ });
2899
+ };
2900
+ let screws = ok.map((sc, i) => {
2901
+ const pick = cases
2902
+ .map((gp) => gp.screws[i])
2903
+ .reduce((a, b) =>
2904
+ b.tension > a.tension + 1e-9 || (Math.abs(b.tension - a.tension) <= 1e-9 && b.shear > a.shear) ? b : a,
2905
+ );
2906
+ return { sc, tension: pick.tension, shear: pick.shear, pick, r: loadOn(sc, pick) };
1016
2907
  });
1017
- const share = torques.length ? Math.max(...screwGroup(places, { moment: [0, 0, torques.reduce((t, q) => t + q.about, 0)] }).screws.map((x) => x.shear)) : null;
1018
- // (worst: at the same margin, the screw pulled harder, since a thread's margin counts its preload and an unloaded screw can tie)
1019
- const worst = screws.reduce((a, b) => (b.r.margin < a.r.margin || (b.r.margin === a.r.margin && b.tension > a.tension) ? b : a)), slip = screws.filter((x) => x.r.margins.slip != null).reduce((a, b) => (!a || b.r.margins.slip < a.r.margins.slip ? b : a), null);
1020
- const tighten = rel.torque == null && !fx.printed ? Math.min(...screws.map((x) => x.r.preload.torque)) : null; // (a printed bolt is done up by hand)
1021
- const rests = [...new Map(screws.flatMap((x) => x.r.rests).filter((q) => q.kind === 'estimate' || q.kind === 'community').map((q) => [q.name, q])).values()].map((q) => q.name);
1022
- return { beyond: [...beyond].filter((k) => k >= 0).map((k) => ids[k]), kg, hung: hung.length, force: Fw, torques, share, screws, worst, slip, tighten, rests, line: cases[0].line, turns: cases.map((gp) => gp.turns).find((t) => t != null) ?? null };
2908
+ // All the screws are tightened to the least torque any of them takes (issue #582), so each is reckoned at that
2909
+ // torque's preload, not at its own: a screw that could take more holds less preload than its own figure says.
2910
+ // screwLoad tightens to the least of the seat's take over fixings.load_margin and its own limits, so a seat's take of
2911
+ // load_margin times the least torque's clamp brings it to that torque, rounded down to the same hundredth
2912
+ const least = rel.torque == null && !fx.printed ? Math.min(...screws.map((x) => x.r.preload.torque)) : null;
2913
+ if (least != null)
2914
+ screws = screws.map((x) =>
2915
+ x.r.preload.torque > least
2916
+ ? {
2917
+ ...x,
2918
+ r: loadOn(
2919
+ x.sc,
2920
+ x.pick,
2921
+ Math.max(((least * 1000) / (DEFAULTS.nut_factor.value * fx.major)) * DEFAULTS.load_margin.value, 1e-9),
2922
+ ), // (at least a whisker: a thread that a neighbour's pull strips leaves them all at no torque)
2923
+ }
2924
+ : x,
2925
+ );
2926
+ const share = torques.length
2927
+ ? Math.max(
2928
+ ...screwGroup(places, { moment: [0, 0, torques.reduce((t, q) => t + q.about, 0)] }).screws.map((x) => x.shear),
2929
+ )
2930
+ : null;
2931
+ // (worst: at the same margin, the screw pulled harder, since a thread's margin counts its preload and an unloaded screw
2932
+ // can tie; alike: every screw at the worst's margin, to the hundredth, which share the most between them)
2933
+ const worst = screws.reduce((a, b) =>
2934
+ b.r.margin < a.r.margin || (b.r.margin === a.r.margin && b.tension > a.tension) ? b : a,
2935
+ ),
2936
+ alike = screws.filter((x) => x.r.margin === worst.r.margin),
2937
+ slip = screws
2938
+ .filter((x) => x.r.margins.slip != null)
2939
+ .reduce((a, b) => (!a || b.r.margins.slip < a.r.margins.slip ? b : a), null);
2940
+ const tighten = least; // (a printed bolt is done up by hand)
2941
+ const rests = [
2942
+ ...new Map(
2943
+ screws
2944
+ .flatMap((x) => x.r.rests)
2945
+ .filter((q) => q.kind === 'estimate' || q.kind === 'community')
2946
+ .map((q) => [q.name, q]),
2947
+ ).values(),
2948
+ ].map((q) => q.name);
2949
+ return {
2950
+ beyond: [...beyond].filter((k) => k >= 0).map((k) => ids[k]),
2951
+ kg,
2952
+ hung: hung.length,
2953
+ force: Fw,
2954
+ torques,
2955
+ share,
2956
+ screws,
2957
+ worst,
2958
+ alike,
2959
+ slip,
2960
+ tighten,
2961
+ rests,
2962
+ line: cases[0].line,
2963
+ turns: cases.map((gp) => gp.turns).find((t) => t != null) ?? null,
2964
+ };
1023
2965
  }
1024
2966
 
1025
2967
  // A printed bolt under its share of a load, in screwLoad's shape: its breaking load along it (printedBoltModel: the
@@ -1029,13 +2971,58 @@ function loadOf(s, worlds, rel, list, { F, fx, ids, material }) {
1029
2971
  // insert or a tapped hole is a standard thread, so the bolt takes the whole gap (steel)
1030
2972
  const boltMate = (sc) => (sc.endKind == null || sc.endKind === 'thread' ? 'printed' : 'steel');
1031
2973
  function printedLoad(F, fx, sc, pick, material) {
1032
- const T = Math.max(0, pick.tension), S = pick.shear, b = F.printedBoltModel(fx, { length: sc.length, head: sc.model?.head, material, nut: boltMate(sc), ...(sc.engaged > 0 ? { depth: sc.engaged } : {}) });
1033
- const across = b.rootArea * b.strip.shear, kT = T > 0 ? b.breaking / T : Infinity, kS = S > 0 ? across / S : Infinity, margin = Math.min(kT, kS), want = DEFAULTS.load_margin.value, k2 = (x) => (x === Infinity ? 'any number of' : mm(+x.toFixed(2)));
1034
- const level = margin < 1 ? 'fail' : margin < want ? 'warn' : 'pass', governs = kS < kT ? 'shear across its root' : b.governs === 'tension' ? 'its root in tension' : b.governs === 'strip' ? 'its teeth in the nut' : 'its head';
2974
+ const T = Math.max(0, pick.tension),
2975
+ S = pick.shear,
2976
+ b = F.printedBoltModel(fx, {
2977
+ length: sc.length,
2978
+ head: sc.model?.head,
2979
+ material,
2980
+ nut: boltMate(sc),
2981
+ ...(sc.engaged > 0 ? { depth: sc.engaged } : {}),
2982
+ });
2983
+ const across = b.rootArea * b.strip.shear,
2984
+ kT = T > 0 ? b.breaking / T : Infinity,
2985
+ kS = S > 0 ? across / S : Infinity,
2986
+ margin = Math.min(kT, kS),
2987
+ want = DEFAULTS.load_margin.value,
2988
+ k2 = (x) => (x === Infinity ? 'any number of' : mm(+x.toFixed(2)));
2989
+ const level = margin < 1 ? 'fail' : margin < want ? 'warn' : 'pass',
2990
+ governs =
2991
+ kS < kT
2992
+ ? 'shear across its root'
2993
+ : b.governs === 'tension'
2994
+ ? 'its root in tension'
2995
+ : b.governs === 'strip'
2996
+ ? 'its teeth in the nut'
2997
+ : 'its head';
1035
2998
  const text = `${b.name} in ${b.material}, done up by hand, with ${mm(+T.toFixed(1))} N of pull and ${mm(+S.toFixed(1))} N of shear: it breaks along at about ${mm(b.breaking)} N (${b.governs}) and across at ${mm(+across.toFixed(1))} N (its ${mm(b.rootArea)} mm² root at ${mm(b.strip.shear)} MPa), estimates. ${margin === Infinity ? 'Nothing pulls on it' : `It holds ${k2(margin)} times the load, ${governs} first`}${level === 'pass' ? '' : `, where the kit asks ${want} times`}`;
1036
2999
  const r2 = (x) => (x === Infinity ? Infinity : +x.toFixed(2));
1037
- return { thread: fx.thread, tension: T, shear: S, preload: { force: 0, torque: 0, given: false }, proof: null, strip: b.strip.load, margins: { screw: r2(kT), thread: null, slip: null }, margin: r2(margin), governs: 'screw', rests: [...b.rests, { name: 'fixings.load_margin', ...DEFAULTS.load_margin }],
1038
- findings: [{ level, text, code: 'screwLoad.margin', values: { tension: +T.toFixed(1), shear: +S.toFixed(1), breaking: b.breaking, across: +across.toFixed(1), margin: margin === Infinity ? null : r2(margin) } }] };
3000
+ return {
3001
+ thread: fx.thread,
3002
+ tension: T,
3003
+ shear: S,
3004
+ preload: { force: 0, torque: 0, given: false },
3005
+ proof: null,
3006
+ strip: b.strip.load,
3007
+ margins: { screw: r2(kT), thread: null, slip: null },
3008
+ margin: r2(margin),
3009
+ governs: 'screw',
3010
+ rests: [...b.rests, { name: 'fixings.load_margin', ...DEFAULTS.load_margin }],
3011
+ findings: [
3012
+ {
3013
+ level,
3014
+ text,
3015
+ code: 'screwLoad.margin',
3016
+ values: {
3017
+ tension: +T.toFixed(1),
3018
+ shear: +S.toFixed(1),
3019
+ breaking: b.breaking,
3020
+ across: +across.toFixed(1),
3021
+ margin: margin === Infinity ? null : r2(margin),
3022
+ },
3023
+ },
3024
+ ],
3025
+ };
1039
3026
  }
1040
3027
 
1041
3028
  /**
@@ -1045,49 +3032,196 @@ function printedLoad(F, fx, sc, pick, material) {
1045
3032
  * item it moves with), `lift` (the way it comes out, for an exploded view) and `allow` (the leaves it may overlap: what it is threaded into)
1046
3033
  */
1047
3034
  export function hardwarePart(h, hostWorld) {
1048
- const m = mat4.multiply(mat4.create(), hostWorld, h.local), move = (polys) => polys.map((poly) => poly.map((v) => vec3.transform([0, 0, 0], v, m)));
3035
+ const m = mat4.multiply(mat4.create(), hostWorld, h.local),
3036
+ move = (polys) => polys.map((poly) => poly.map((v) => vec3.transform([0, 0, 0], v, m)));
1049
3037
  const lift = vec3.transform([0, 0, 0], h.lift, [...hostWorld.slice(0, 12), 0, 0, 0, 1]);
1050
- return { name: `${h.id}.body`, item: h.id, leaf: h.id, object: h.name, role: 'reference', label: `${h.id}: ${h.name}`, part: 'body',
1051
- geometry: jscad.transforms.transform(m, h.shape.geometry), polygons: move(h.shape.polygons), triangles: move(h.shape.triangles),
1052
- shape: `${h.shape.hash}:body`, hash: `${h.shape.hash}:body`, local: h.shape.polygons, localTriangles: h.shape.triangles, m,
1053
- hardware: { kind: h.kind, name: h.name, fasten: h.fasten, screw: h.screw, thread: h.thread, grams: h.grams, from: h.label, length: h.length, head: h.head, ...(h.printed ? { printed: true } : {}) }, moves: h.hostItem, with: h.with, lift, allow: h.allow };
3038
+ return {
3039
+ name: `${h.id}.body`,
3040
+ item: h.id,
3041
+ leaf: h.id,
3042
+ object: h.name,
3043
+ role: 'reference',
3044
+ label: `${h.id}: ${h.name}`,
3045
+ part: 'body',
3046
+ geometry: jscad.transforms.transform(m, h.shape.geometry),
3047
+ polygons: move(h.shape.polygons),
3048
+ triangles: move(h.shape.triangles),
3049
+ shape: `${h.shape.hash}:body`,
3050
+ hash: `${h.shape.hash}:body`,
3051
+ local: h.shape.polygons,
3052
+ localTriangles: h.shape.triangles,
3053
+ m,
3054
+ hardware: {
3055
+ kind: h.kind,
3056
+ name: h.name,
3057
+ fasten: h.fasten,
3058
+ screw: h.screw,
3059
+ thread: h.thread,
3060
+ grams: h.grams,
3061
+ from: h.label,
3062
+ length: h.length,
3063
+ head: h.head,
3064
+ ...(h.printed ? { printed: true } : {}),
3065
+ },
3066
+ moves: h.hostItem,
3067
+ with: h.with,
3068
+ lift,
3069
+ allow: h.allow,
3070
+ };
1054
3071
  }
1055
3072
 
1056
- const CODES = ['fasten.holes', 'fasten.slot', 'fasten.clearance', 'fasten.end', 'fasten.length', 'fasten.engagement', 'fasten.seat', 'fasten.torque', 'fasten.access'];
3073
+ // Every code a screw's findings are said under, in the order said: a code missing here has its findings dropped
3074
+ // (test/fasten-gaps.test.mjs holds this list to the codes said in this file)
3075
+ export const CODES = [
3076
+ 'fasten.holes',
3077
+ 'fasten.stack',
3078
+ 'fasten.slot',
3079
+ 'fasten.clearance',
3080
+ 'fasten.end',
3081
+ 'fasten.length',
3082
+ 'fasten.wall',
3083
+ 'fasten.engagement',
3084
+ 'fasten.seat',
3085
+ 'fasten.torque',
3086
+ 'fasten.access',
3087
+ ];
1057
3088
  // fasten.access for one screw, with the order of assembly: a part over the head that goes on later is no trouble
1058
3089
  function accessSays(sc, rel, order, numbered = null) {
1059
- const acc = sc.access, t = acc.tool, values = { key: t.size, radius: t.radius, reach: t.reach };
1060
- if (!acc.blockers.length) return { level: 'pass', text: `${an(t.name)} ${t.name} reaches the head along its axis: nothing within ${mm(t.radius)} mm of it for ${mm(t.reach)} mm over the head (${t.rests[0]}, ${t.rests[1]})`, values };
3090
+ const acc = sc.access,
3091
+ t = acc.tool,
3092
+ values = { key: t.size, radius: t.radius, reach: t.reach };
3093
+ if (!acc.blockers.length)
3094
+ return {
3095
+ level: 'pass',
3096
+ text: `${an(t.name)} ${t.name} reaches the head along its axis: nothing within ${mm(t.radius)} mm of it for ${mm(t.reach)} mm over the head (${t.rests[0]}, ${t.rests[1]})`,
3097
+ values,
3098
+ };
1061
3099
  const names = (list) => list.map((b) => `${b.item} (${mm(b.z)} mm over the head)`).join(' and ');
1062
3100
  const stuck = order?.stuck?.fasten === rel.index && order.stuck.screws?.includes(sc.index) ? order.stuck : null;
1063
3101
  if (stuck) {
1064
- const b = acc.blockers.find((x) => x.item === stuck.wall) ?? acc.blockers[0], tail = stuck.text.split(`${stuck.wall} stands over it`)[1] ?? '';
1065
- return { level: 'fail', text: `${an(t.name)} ${t.name} cannot reach the head: ${b.item} stands over it, ${mm(b.z)} mm up the screw's axis${tail}${t.size && acc.tilt == null && /hex key/.test(t.name) ? `, and a ball-end key tilted ${mm(peekRuleSet('hexkey').rules.ball_end_tilt.value)}° does not clear it either` : ''}. Move the screw, open a way through ${b.item}, or fit ${b.item} after`, values: { ...values, distance: b.z }, wall: b.item };
3102
+ const b = acc.blockers.find((x) => x.item === stuck.wall) ?? acc.blockers[0],
3103
+ tail = stuck.text.split(`${stuck.wall} stands over it`)[1] ?? '';
3104
+ return {
3105
+ level: 'fail',
3106
+ text: `${an(t.name)} ${t.name} cannot reach the head: ${b.item} stands over it, ${mm(b.z)} mm up the screw's axis${tail}${t.size && acc.tilt == null && /hex key/.test(t.name) ? `, and a ball-end key tilted ${mm(peekRuleSet('hexkey').rules.ball_end_tilt.value)}° does not clear it either` : ''}. Move the screw, open a way through ${b.item}, or fit ${b.item} after`,
3107
+ values: { ...values, distance: b.z },
3108
+ wall: b.item,
3109
+ };
1066
3110
  }
1067
- const step = (id) => order?.steps?.find((st) => st.items.includes(id))?.n, last = Math.max(...[...rel.through, rel.into].map((n) => step(top(n)) ?? Infinity));
3111
+ const step = (id) => order?.steps?.find((st) => st.items.includes(id))?.n,
3112
+ last = Math.max(...[...rel.through, rel.into].map((n) => step(top(n)) ?? Infinity));
1068
3113
  const after = order && !order.stuck && acc.blockers.every((b) => step(b.item) > last);
1069
- if (acc.tilt != null && !after) return { level: 'warn', text: `only a ball-end ${t.name} reaches the head, tilted up to ${mm(acc.tilt)}° (hexkey.ball_end_tilt): ${names(acc.blockers)} stand${acc.blockers.length > 1 ? '' : 's'} on the straight line, and a ball end takes less torque than a straight key`, values: { ...values, tilt: acc.tilt } };
3114
+ if (acc.tilt != null && !after)
3115
+ return {
3116
+ level: 'warn',
3117
+ text: `only a ball-end ${t.name} reaches the head, tilted up to ${mm(acc.tilt)}° (hexkey.ball_end_tilt): ${names(acc.blockers)} stand${acc.blockers.length > 1 ? '' : 's'} on the straight line, and a ball end takes less torque than a straight key`,
3118
+ values: { ...values, tilt: acc.tilt },
3119
+ };
1070
3120
  const said = numbered ?? step;
1071
- return { level: 'pass', text: `${an(t.name)} ${t.name} reaches the head before ${acc.blockers.map((b) => `${b.item}${said(b.item) ? ` (step ${said(b.item)})` : ''}`).join(' and ')} goes on over it`, values: { ...values, distance: acc.blockers[0].z } };
3121
+ return {
3122
+ level: 'pass',
3123
+ text: `${an(t.name)} ${t.name} reaches the head before ${acc.blockers.map((b) => `${b.item}${said(b.item) ? ` (step ${said(b.item)})` : ''}`).join(' and ')} goes on over it`,
3124
+ values: { ...values, distance: acc.blockers[0].z },
3125
+ };
1072
3126
  }
1073
3127
  const RANK = { fail: 0, warn: 1, info: 2, pass: 3 };
1074
3128
  // fasten.load for one relation: what it carries, the screw that takes the most against its strength, and slipping
1075
3129
  function loadSays(s, f, rel, lead) {
1076
- const L = rel.load; if (!L) return;
1077
- const refs = { fasten: rel.index, screw: rel.screw, through: rel.through, into: rel.into, screws: rel.screws.map((sc) => sc.name), ...(s.pose ? { pose: s.pose } : {}) };
1078
- if (L.closed) return f('info', `${lead}: ${[...rel.through, rel.into].join(' and ')} are held to the ground by other ways too, so what this joint carries is not shared out to its screws`, null, { code: 'fasten.load', refs });
1079
- if (L.skew) return f('info', `${lead}: the screws do not stand parallel, so the load is not shared out between them`, null, { code: 'fasten.load', refs });
1080
- const n = rel.screws.length, w = L.worst, who = (x) => (n > 1 ? `screw ${x.sc.index + 1} (${x.sc.name})` : 'the screw'), r1 = (x) => +x.toFixed(1);
3130
+ const L = rel.load;
3131
+ if (!L) return;
3132
+ const refs = {
3133
+ fasten: rel.index,
3134
+ screw: rel.screw,
3135
+ through: rel.through,
3136
+ into: rel.into,
3137
+ screws: rel.screws.map((sc) => sc.name),
3138
+ ...(s.pose ? { pose: s.pose } : {}),
3139
+ };
3140
+ if (L.closed)
3141
+ return f(
3142
+ 'info',
3143
+ `${lead}: ${[...rel.through, rel.into].join(' and ')} are held to the ground by other ways too, so what this joint carries is not shared out to its screws`,
3144
+ null,
3145
+ { code: 'fasten.load', refs },
3146
+ );
3147
+ if (L.skew)
3148
+ return f('info', `${lead}: the screws do not stand parallel, so the load is not shared out between them`, null, {
3149
+ code: 'fasten.load',
3150
+ refs,
3151
+ });
3152
+ const n = rel.screws.length,
3153
+ w = L.worst,
3154
+ who = (x) => (n > 1 ? `screw ${x.sc.index + 1} (${x.sc.name})` : 'the screw'),
3155
+ r1 = (x) => +x.toFixed(1);
1081
3156
  const equal = L.torques.length && L.screws.every((x) => Math.abs(x.shear - L.screws[0].shear) < 1e-6);
1082
- const motor = L.torques.map((q) => `${q.id}'s ${mm(+q.torque.toFixed(3))} N m about its shaft (what it gives at its working speed), ${mm(r1(L.share))} N ${n > 1 ? 'on each screw' : 'on the screw'} from that alone`).join(' and ');
3157
+ const motor = L.torques
3158
+ .map(
3159
+ (q) =>
3160
+ `${q.id}'s ${mm(+q.torque.toFixed(3))} N m about its shaft (what it gives at its working speed), ${mm(r1(L.share))} N ${n > 1 ? 'on each screw' : 'on the screw'} from that alone`,
3161
+ )
3162
+ .join(' and ');
1083
3163
  const carries = `${L.beyond.join(', ')}, ${mm(+L.kg.toFixed(3))} kg${L.hung ? ` with the load${L.hung > 1 ? 's' : ''} hung on ${L.beyond.length > 1 ? 'them' : 'it'}` : ''}${motor ? `, and ${motor}` : ''}`;
1084
- const x0 = w.r.findings[0], rests = L.rests.length ? ` It rests on estimates: ${L.rests.join(', ')}` : '';
1085
- const values = { margin: w.r.margin === Infinity ? null : w.r.margin, tension: r1(Math.max(0, w.tension)), shear: r1(w.shear), preload: w.r.preload.force, torque: w.r.preload.torque, kg: +L.kg.toFixed(4), ...(L.share != null ? { share: L.share } : {}),
1086
- screws: L.screws.map((x) => ({ screw: x.sc.name, tension: r1(Math.max(0, x.tension)), shear: r1(x.shear), margin: x.r.margin === Infinity ? null : x.r.margin })) };
1087
- f(x0.level, `${lead} carry ${carries}: ${who(w)} takes the most: ${x0.text}${L.tighten != null && rel.torque == null ? `. Tighten to ${mm(L.tighten)} N m` : ''}.${rests}`, x0.level === 'pass' ? null : `${rel.label}: load`,
1088
- { code: 'fasten.load', at: w.sc.at.map(r3), between: w.sc.between.map((p) => p.map(r3)), values, refs: { ...refs, rests: L.rests, ...(equal ? { each: true } : {}) } });
1089
- if (L.slip) { const y = L.slip.r.findings[1]; f(y.level, `${lead}: ${who(L.slip)}: ${y.text}`, y.level === 'pass' ? null : `${rel.label}: slips`, { code: 'fasten.load', at: L.slip.sc.at.map(r3), values: y.values, refs }); }
1090
- if (L.turns != null) f('warn', `${lead}: a twist of ${mm(L.turns)} N m about the one screw is held by friction alone: a second screw would hold it by shear`, `${rel.label}: turns`, { code: 'fasten.load', values: { turns: L.turns }, refs });
3164
+ const x0 = w.r.findings[0],
3165
+ rests = L.rests.length ? ` It rests on estimates: ${L.rests.join(', ')}` : '';
3166
+ // the screw that takes the most, or, where several hold the same margin to the hundredth, all of them alike: the one
3167
+ // whose figures follow is the one pulled harder
3168
+ const tied = L.alike.length > 1 ? L.alike : null,
3169
+ names = (xs) =>
3170
+ xs
3171
+ .map(who)
3172
+ .join(', ')
3173
+ .replace(/, ([^,]*)$/, ' and $1'),
3174
+ most = tied
3175
+ ? `${names(tied)} take the most alike${tied.some((x) => r1(Math.max(0, x.tension)) !== r1(Math.max(0, w.tension))) ? `, ${who(w)} pulled the harder` : ''}`
3176
+ : `${who(w)} takes the most`;
3177
+ const values = {
3178
+ margin: w.r.margin === Infinity ? null : w.r.margin,
3179
+ tension: r1(Math.max(0, w.tension)),
3180
+ shear: r1(w.shear),
3181
+ preload: w.r.preload.force,
3182
+ torque: w.r.preload.torque,
3183
+ kg: +L.kg.toFixed(4),
3184
+ ...(L.share != null ? { share: L.share } : {}),
3185
+ screws: L.screws.map((x) => ({
3186
+ screw: x.sc.name,
3187
+ tension: r1(Math.max(0, x.tension)),
3188
+ shear: r1(x.shear),
3189
+ margin: x.r.margin === Infinity ? null : x.r.margin,
3190
+ })),
3191
+ };
3192
+ f(
3193
+ x0.level,
3194
+ `${lead} carry ${carries}: ${most}: ${x0.text}${L.tighten != null && rel.torque == null ? `. Tighten to ${mm(L.tighten)} N m` : ''}.${rests}`,
3195
+ x0.level === 'pass' ? null : `${rel.label}: load`,
3196
+ {
3197
+ code: 'fasten.load',
3198
+ at: w.sc.at.map(r3),
3199
+ between: w.sc.between.map((p) => p.map(r3)),
3200
+ values,
3201
+ refs: {
3202
+ ...refs,
3203
+ rests: L.rests,
3204
+ ...(equal ? { each: true } : {}),
3205
+ ...(tied ? { alike: tied.map((x) => x.sc.name) } : {}),
3206
+ },
3207
+ },
3208
+ );
3209
+ if (L.slip) {
3210
+ const y = L.slip.r.findings[1];
3211
+ f(y.level, `${lead}: ${who(L.slip)}: ${y.text}`, y.level === 'pass' ? null : `${rel.label}: slips`, {
3212
+ code: 'fasten.load',
3213
+ at: L.slip.sc.at.map(r3),
3214
+ values: y.values,
3215
+ refs,
3216
+ });
3217
+ }
3218
+ if (L.turns != null)
3219
+ f(
3220
+ 'warn',
3221
+ `${lead}: a twist of ${mm(L.turns)} N m about the one screw is held by friction alone: a second screw would hold it by shear`,
3222
+ `${rel.label}: turns`,
3223
+ { code: 'fasten.load', values: { turns: L.turns }, refs },
3224
+ );
1091
3225
  }
1092
3226
  /**
1093
3227
  * The fasten findings of an assembly, in its findings shape: each relation's screws said together where they agree,
@@ -1099,26 +3233,56 @@ export function fastenChecks(s, f, { placeItems }) {
1099
3233
  if (!s.a.fasten?.length) return;
1100
3234
  const r = s.fastened ?? fastenOf(s, placeItems(s.motion, s.jointValues));
1101
3235
  // the key's way, in the build pose: with the order, which places a part that covers a head after the screw
1102
- const built = s.pose == null || s.pose === s.motion.pose, wanted = built && r.relations.some((rel) => rel.screws.some((sc) => sc.access?.blockers.length));
1103
- const order = wanted && isBuilt(s) ? orderOf(s) : null, access = new Map();
3236
+ const built = s.pose == null || s.pose === s.motion.pose,
3237
+ wanted = built && r.relations.some((rel) => rel.screws.some((sc) => sc.access?.blockers.length));
3238
+ const order = wanted && isBuilt(s) ? orderOf(s) : null,
3239
+ access = new Map();
1104
3240
  // the step numbers said are cad order's: a frame's build where the assembly has joins (none where that build is refused)
1105
3241
  const numbered = wanted && s.joins?.length ? frameStepOf(frameBuild(s)) : null;
1106
- if (built) for (const rel of r.relations) for (const sc of rel.screws) if (sc.access) access.set(sc, [accessSays(sc, rel, order, numbered)]);
3242
+ if (built)
3243
+ for (const rel of r.relations)
3244
+ for (const sc of rel.screws) if (sc.access) access.set(sc, [accessSays(sc, rel, order, numbered)]);
1107
3245
  for (const rel of r.relations) {
1108
- const n = rel.screws.length, lead = `${rel.label}, ${n === 1 ? `${an(rel.screw)} ${rel.screw} screw` : `${n} ${rel.screw} screws`}`;
1109
- for (const g of rel.general) f(g.level, `${rel.label}: ${g.text}`, `${rel.label}: no screws`, { code: g.code, refs: { fasten: rel.index, through: rel.through, into: rel.into } });
3246
+ const n = rel.screws.length,
3247
+ lead = `${rel.label}, ${n === 1 ? `${an(rel.screw)} ${rel.screw} screw` : `${n} ${rel.screw} screws`}`;
3248
+ for (const g of rel.general)
3249
+ f(g.level, `${rel.label}: ${g.text}`, `${rel.label}: no screws`, {
3250
+ code: g.code,
3251
+ refs: { fasten: rel.index, through: rel.through, into: rel.into },
3252
+ });
1110
3253
  for (const code of CODES) {
1111
3254
  const groups = new Map();
1112
- for (const sc of rel.screws) for (const x of (code === 'fasten.access' ? access.get(sc) : sc.found[code]) || []) {
1113
- const key = `${x.level}|${x.text}`;
1114
- if (!groups.has(key)) groups.set(key, { ...x, screws: [] });
1115
- groups.get(key).screws.push(sc);
1116
- }
3255
+ for (const sc of rel.screws)
3256
+ for (const x of (code === 'fasten.access' ? access.get(sc) : sc.found[code]) || []) {
3257
+ const key = `${x.level}|${x.text}`;
3258
+ if (!groups.has(key)) groups.set(key, { ...x, screws: [] });
3259
+ groups.get(key).screws.push(sc);
3260
+ }
1117
3261
  for (const g of [...groups.values()].sort((a, b) => RANK[a.level] - RANK[b.level])) {
1118
- const all = g.screws.length === n, first = g.screws[0], who = all ? lead : `${rel.label}, ${g.screws.map((sc) => `screw ${sc.index + 1} (${sc.name})`).join(', ')}`;
1119
- f(g.level, `${who}: ${g.text}`, g.level === 'pass' || g.level === 'info' ? null : `${rel.label}: ${code.split('.')[1]}`,
1120
- { code, at: first.at.map(r3), between: first.between.map((p) => p.map(r3)), ...(g.values ? { values: g.values } : {}),
1121
- refs: { ...(g.wall ? { wall: g.wall } : {}), fasten: rel.index, screw: rel.screw, through: rel.through, into: rel.into, screws: g.screws.map((sc) => sc.name), ...(g.screws.length > 1 ? { places: g.screws.map((sc) => sc.at.map(r3)) } : {}), ...(s.pose ? { pose: s.pose } : {}) } });
3262
+ const all = g.screws.length === n,
3263
+ first = g.screws[0],
3264
+ who = all ? lead : `${rel.label}, ${g.screws.map((sc) => `screw ${sc.index + 1} (${sc.name})`).join(', ')}`;
3265
+ f(
3266
+ g.level,
3267
+ `${who}: ${g.text}`,
3268
+ g.level === 'pass' || g.level === 'info' ? null : `${rel.label}: ${code.split('.')[1]}`,
3269
+ {
3270
+ code,
3271
+ at: first.at.map(r3),
3272
+ between: first.between.map((p) => p.map(r3)),
3273
+ ...(g.values ? { values: g.values } : {}),
3274
+ refs: {
3275
+ ...(g.wall ? { wall: g.wall } : {}),
3276
+ fasten: rel.index,
3277
+ screw: rel.screw,
3278
+ through: rel.through,
3279
+ into: rel.into,
3280
+ screws: g.screws.map((sc) => sc.name),
3281
+ ...(g.screws.length > 1 ? { places: g.screws.map((sc) => sc.at.map(r3)) } : {}),
3282
+ ...(s.pose ? { pose: s.pose } : {}),
3283
+ },
3284
+ },
3285
+ );
1122
3286
  }
1123
3287
  }
1124
3288
  loadSays(s, f, rel, lead);
@@ -1129,15 +3293,38 @@ export function fastenChecks(s, f, { placeItems }) {
1129
3293
  // A holes fit and a fit that fastens the same two items say apart what a fasten says at once. The screw is read from the
1130
3294
  // fit's fastener ("M2x6"), else a thread set the holes fit's depth names (m2.insert_length), else the board's mounting
1131
3295
  // holes as drawn: the largest metric thread narrower than the narrowest of them.
1132
- const metric = (t) => { const m = /^M(\d+(?:\.\d+)?)$/.exec(t); return m ? Number(m[1]) : null; };
3296
+ const metric = (t) => {
3297
+ const m = /^M(\d+(?:\.\d+)?)$/.exec(t);
3298
+ return m ? Number(m[1]) : null;
3299
+ };
1133
3300
  function screwFrom(h, fit, s) {
1134
- try { const n = fit.fastener && parseName(String(fit.fastener)); if (n && (n.item === 'screw' || n.item === 'thread')) return `${n.thread}${n.length != null ? `x${n.length}` : ''} ${n.head ?? 'cap'}`; } catch {} // (a fastener in words, "Two push pins", names no thread)
1135
- let sets = {}; try { sets = fixingsContext({ project: s.project, dir: paths.project(s.project) }).context.sets; } catch {}
1136
- const known = threads({ sets }), set = /\b[mM](\d+(?:_\d+)?)\.\w/.exec([h.depth, h.ring].filter((x) => typeof x === 'string').join(' '));
1137
- if (set) { const t = `M${set[1].replace('_', '.')}`; if (known.includes(t)) return `${t} cap`; }
1138
- const board = s.objects.find((o) => o.id === top(h.holes))?.built, ds = (board?.circuit || []).filter((e) => e.type === 'pcb_hole' && !e.pcb_component_id).map((e) => e.hole_diameter).filter((d) => d > 0);
3301
+ try {
3302
+ const n = fit.fastener && parseName(String(fit.fastener));
3303
+ if (n && (n.item === 'screw' || n.item === 'thread'))
3304
+ return `${n.thread}${n.length != null ? `x${n.length}` : ''} ${n.head ?? 'cap'}`;
3305
+ } catch {
3306
+ // (a fastener in words, "Two push pins", names no thread)
3307
+ }
3308
+ let sets = {};
3309
+ try {
3310
+ sets = fixingsContext({ project: s.project, dir: paths.project(s.project) }).context.sets;
3311
+ } catch {
3312
+ // (the project's fixings can't be read: only the kit's own threads are known)
3313
+ }
3314
+ const known = threads({ sets }),
3315
+ set = /\b[mM](\d+(?:_\d+)?)\.\w/.exec([h.depth, h.ring].filter((x) => typeof x === 'string').join(' '));
3316
+ if (set) {
3317
+ const t = `M${set[1].replace('_', '.')}`;
3318
+ if (known.includes(t)) return `${t} cap`;
3319
+ }
3320
+ const board = s.objects.find((o) => o.id === top(h.holes))?.built,
3321
+ ds = (board?.circuit || [])
3322
+ .filter((e) => e.type === 'pcb_hole' && !e.pcb_component_id)
3323
+ .map((e) => e.hole_diameter)
3324
+ .filter((d) => d > 0);
1139
3325
  if (!ds.length) return null;
1140
- const d = Math.min(...ds), fit1 = known.filter((t) => metric(t) != null && metric(t) < d).sort((a, b) => metric(b) - metric(a))[0];
3326
+ const d = Math.min(...ds),
3327
+ fit1 = known.filter((t) => metric(t) != null && metric(t) < d).sort((a, b) => metric(b) - metric(a))[0];
1141
3328
  return fit1 ? `${fit1} cap` : null;
1142
3329
  }
1143
3330
 
@@ -1148,14 +3335,28 @@ function screwFrom(h, fit, s) {
1148
3335
  * @returns {{ fasten: object, holes: number, fastens: number, pair: string[], label: string, screw: string | null }[]}
1149
3336
  */
1150
3337
  export function fastenFromFits(s) {
1151
- const fits = s.a.fits || [], out = [], named = new Set((s.a.fasten || []).flatMap((x) => [...(x.through || []), x.into].map(top)));
3338
+ const fits = s.a.fits || [],
3339
+ out = [],
3340
+ named = new Set((s.a.fasten || []).flatMap((x) => [...(x.through || []), x.into].map(top)));
1152
3341
  fits.forEach((h, i) => {
1153
3342
  if (!h.holes || !h.into || h.direction === 'up') return; // (screws from below: through and into the other way round, said by hand)
1154
- const pair = [top(h.holes), top(h.into)], same = (x) => typeof x.a === 'string' && typeof x.b === 'string' && [top(x.a), top(x.b)].sort().join() === [...pair].sort().join();
3343
+ const pair = [top(h.holes), top(h.into)],
3344
+ same = (x) =>
3345
+ typeof x.a === 'string' &&
3346
+ typeof x.b === 'string' &&
3347
+ [top(x.a), top(x.b)].sort().join() === [...pair].sort().join();
1155
3348
  const k = fits.findIndex((x) => x.fastens && !x.holes && same(x));
1156
3349
  if (k < 0 || pair.every((n) => named.has(n))) return;
1157
- const screw = screwFrom(h, fits[k], s), note = h.label || h.note || fits[k].note;
1158
- out.push({ fasten: { screw: screw ?? 'M3 cap', through: [h.holes], into: h.into, holes: h.holes, ...(note ? { note } : {}) }, holes: i, fastens: k, pair, label: h.label || `${h.holes} into ${h.into}`, screw });
3350
+ const screw = screwFrom(h, fits[k], s),
3351
+ note = h.label || h.note || fits[k].note;
3352
+ out.push({
3353
+ fasten: { screw: screw ?? 'M3 cap', through: [h.holes], into: h.into, holes: h.holes, ...(note ? { note } : {}) },
3354
+ holes: i,
3355
+ fastens: k,
3356
+ pair,
3357
+ label: h.label || `${h.holes} into ${h.into}`,
3358
+ screw,
3359
+ });
1159
3360
  });
1160
3361
  return out;
1161
3362
  }