@rulecad/cad 0.9.0 → 0.11.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 (68) hide show
  1. package/AGENTS.md +29 -10
  2. package/CHANGELOG.md +604 -0
  3. package/EXAMPLES.md +122 -105
  4. package/README.md +292 -63
  5. package/bin/cad.mjs +500 -87
  6. package/lib/assembly.mjs +486 -134
  7. package/lib/bays.mjs +124 -0
  8. package/lib/cache-file.mjs +148 -0
  9. package/lib/clone.mjs +93 -11
  10. package/lib/code-text.mjs +28 -0
  11. package/lib/design-imports.mjs +127 -0
  12. package/lib/design.mjs +291 -59
  13. package/lib/designshapes.mjs +142 -0
  14. package/lib/edit.mjs +29 -5
  15. package/lib/estimates.mjs +51 -0
  16. package/lib/fasten.mjs +11 -5
  17. package/lib/fe-key.mjs +29 -0
  18. package/lib/fittings.mjs +20 -15
  19. package/lib/fixings.mjs +17 -4
  20. package/lib/framebuild.mjs +73 -92
  21. package/lib/framecheck.mjs +154 -77
  22. package/lib/framegen.mjs +9 -1
  23. package/lib/frames.mjs +6 -2
  24. package/lib/framesize.mjs +45 -82
  25. package/lib/gait.mjs +17 -7
  26. package/lib/guides.mjs +84 -50
  27. package/lib/host.mjs +7 -3
  28. package/lib/kit.mjs +5 -5
  29. package/lib/list.mjs +29 -21
  30. package/lib/live-guard.mjs +18 -8
  31. package/lib/loads.mjs +35 -23
  32. package/lib/measured.mjs +740 -99
  33. package/lib/mesh.mjs +156 -56
  34. package/lib/motors.mjs +26 -33
  35. package/lib/names.mjs +15 -0
  36. package/lib/node-version.mjs +52 -0
  37. package/lib/optimise.mjs +34 -25
  38. package/lib/order.mjs +5 -12
  39. package/lib/parts.mjs +3 -0
  40. package/lib/picture-servers.mjs +66 -0
  41. package/lib/power.mjs +14 -7
  42. package/lib/preview.mjs +12 -25
  43. package/lib/programs.mjs +113 -0
  44. package/lib/rules.mjs +2 -1
  45. package/lib/sandbox-guard.mjs +43 -0
  46. package/lib/sandbox-hooks.mjs +109 -15
  47. package/lib/sandbox-lock.mjs +225 -0
  48. package/lib/sandbox-preload.mjs +2 -2
  49. package/lib/sandbox-run.mjs +22 -24
  50. package/lib/sandbox.mjs +345 -42
  51. package/lib/sheet.mjs +114 -3
  52. package/lib/targets/gist.mjs +9 -6
  53. package/lib/versions.mjs +294 -35
  54. package/lib/workspace.mjs +6 -3
  55. package/package.json +14 -14
  56. package/schemas/assembly.schema.json +6 -5
  57. package/schemas/object.schema.json +1 -1
  58. package/schemas/project.schema.json +6 -0
  59. package/templates/coupons/MEASURE.md +109 -0
  60. package/templates/coupons/assemblies/fixings-test.json +20 -0
  61. package/templates/coupons/assemblies/slot-test.json +11 -0
  62. package/templates/coupons/objects/fixings-coupon.js +88 -0
  63. package/templates/coupons/objects/fixings-coupon.json +26 -0
  64. package/templates/coupons/objects/holds-coupon.js +130 -0
  65. package/templates/coupons/objects/holds-coupon.json +42 -0
  66. package/templates/coupons/objects/slot-coupon.js +89 -0
  67. package/templates/coupons/objects/slot-coupon.json +29 -0
  68. package/templates/coupons/project.json +10 -0
package/lib/assembly.mjs CHANGED
@@ -11,7 +11,8 @@
11
11
  // }
12
12
  // Positions are expressions over rules (mx.pitch) and items' variables (cap.lift); rotate is degrees about x, y, z,
13
13
  // applied before at (a repeated item turns as a whole, its copies with it). An item can pin a release: "object": "keycap@0.2.1". fits measure the closest gap between two
14
- // items or item.parts; a negative min allows a press fit to overlap.
14
+ // items or item.parts; a negative min is a press fit, the two into each other no deeper than that (mm), and
15
+ // "overlap": "allowed" lets them overlap by any amount.
15
16
  // A holes fit follows each of a board's mounting holes down its screw's path into another part:
16
17
  // { "holes": "pcb.board", "into": "case.body", "depth": "m2.insert_length", "label": "Screws find their inserts" }
17
18
  // The path must be clear for depth mm (it lands in a hole) and solid within "ring" mm of it (default: the hole's
@@ -20,12 +21,14 @@
20
21
  // Its holes are read from the parts as drawn, its screws placed as reference parts, and it holds as a fit that fastens does.
21
22
  // Beams are held to each other by joins (lib/joins.mjs): { "kind": "blind", "a": "y1.a", "b": "x1.back@120" }. Each puts
22
23
  // its operations on both beams and its screws into fasten before anything is built, and is checked once it is.
23
- import { host, readJson, cached } from './host.mjs';
24
+ import { host, readJson } from './host.mjs';
25
+ import { writeCacheFile, readCacheJson } from './cache-file.mjs';
24
26
  import fs from 'node:fs';
25
27
  import crypto from 'node:crypto';
26
28
  import path from 'node:path';
27
29
  import { fileURLToPath } from 'node:url';
28
30
  import { evaluate, loadRuleSet } from './rules.mjs';
31
+ import { estimatesFinding } from './estimates.mjs';
29
32
  import { paths, printerOf } from './workspace.mjs';
30
33
  import { plainName, isPlainName } from './names.mjs';
31
34
  import { locateIn, build, readObject, jscad } from './design.mjs';
@@ -71,7 +74,7 @@ import { sizeChecks } from './framesize.mjs';
71
74
  import { frameHeatChecks } from './frameheat.mjs';
72
75
  import { expandPanels, panelBuilt, panelFindings, PANEL_CHECK } from './panels.mjs';
73
76
  import { expandServices, serviceFindings } from './services.mjs';
74
- import { expandGuides, guideBuilt, guideFindings } from './guides.mjs';
77
+ import { expandGuides, guideBuilt, guideFindings, guideBudgetFindings } from './guides.mjs';
75
78
  import { beltLoads } from './belts.mjs';
76
79
  import { slotNutChecks } from './slotnuts.mjs';
77
80
  import { frameSquareChecks, frameBuild } from './framebuild.mjs';
@@ -87,6 +90,49 @@ export const isAssembly = (ref) => {
87
90
  return isPlainName(project) && isPlainName(name) && host.exists(assemblyPath(`${project}/${name}`));
88
91
  }; // (a path or a name that climbs is not an assembly: locate() says what it is)
89
92
 
93
+ /**
94
+ * The command line's --set on an assembly, { "hook.reach": "60" }, as the overrides buildAssembly takes,
95
+ * { hook: { reach: "60" } }: each name is an item of the assembly's own and one of that item's object's variables.
96
+ * Anything else is refused by name, never passed over: a component, a bought part, a beam or a motor takes no --set
97
+ * (set the object inside it with its own "set" in the assembly file). The values stay as typed: the build reads each by
98
+ * its variable's kind, and holds it to the variable's tweak range, as it does for an object's --set.
99
+ * @param {string} ref project/assembly @param {Record<string, string | undefined>} set @returns {Record<string, Record<string, string>>}
100
+ */
101
+ export function assemblyOverrides(ref, set) {
102
+ const names = Object.keys(set);
103
+ if (!names.length) return {};
104
+ const [project] = ref.split('/'),
105
+ a = readJson(assemblyPath(ref)),
106
+ items = (a.items || []).filter((it) => it && typeof it.id === 'string'),
107
+ out = {};
108
+ for (const [k, v] of Object.entries(set)) {
109
+ const said = `--set ${k}${v === undefined ? '' : `=${v}`}`,
110
+ dot = k.indexOf('.');
111
+ if (dot < 0)
112
+ throw new Error(
113
+ `${said}: on an assembly, name an item's variable as <item>.<variable> (items: ${items.map((it) => it.id).join(', ') || 'none'})`,
114
+ );
115
+ if (v === undefined || v === '') throw new Error(`${said}: give the value after an =, as ${k}=…`);
116
+ const id = k.slice(0, dot),
117
+ name = k.slice(dot + 1),
118
+ it = items.find((x) => x.id === id);
119
+ if (!it)
120
+ throw new Error(`${said}: ${ref} has no item "${id}" (items: ${items.map((x) => x.id).join(', ') || 'none'})`);
121
+ if (!it.object)
122
+ throw new Error(
123
+ `${said}: item ${id} is ${it.assembly ? `the assembly ${it.assembly}` : 'not an object'}, and --set reaches an object item's own variables only: set it in ${ref}'s file, in the item's "set"`,
124
+ );
125
+ const objName = String(it.object).split(/[:@]/)[0],
126
+ vars = readObject(locateIn(project, objName, `${assemblyPath(ref)}, item ${id}'s "object"`)).variables || {};
127
+ if (!Object.hasOwn(vars, name))
128
+ throw new Error(
129
+ `${said}: item ${id} (${objName}) has no variable "${name}" (variables: ${Object.keys(vars).join(', ') || 'none'})`,
130
+ );
131
+ (out[id] ||= {})[name] = v;
132
+ }
133
+ return out;
134
+ }
135
+
90
136
  export { satisfies }; // from @rulecad/versions
91
137
 
92
138
  // buildAssembly('keyboard/keycap-on-switch') -> { a, project, name, items, parts, objects, fits, requires, values, num }
@@ -580,7 +626,7 @@ export async function buildAssembly(ref, stack = [], overrides = {}, opts = {})
580
626
  if (a.fits?.some((x) => x.fastener && typeof x.fastener === 'object')) pinning ||= await import('./pins.mjs');
581
627
  for (let x of a.fits || []) {
582
628
  if (x.fastener && typeof x.fastener === 'object') x = pinning.pinOfFit(x, project); // (pins or magnets by the schema's form: the fit's pin or magnet, and the fastener's name)
583
- if (x.seat != null && x.min == null) x = { ...x, min: -1000 }; // a seat presses, so the pair may overlap
629
+ if (x.seat != null && x.min == null && x.overlap == null) x = { ...x, overlap: 'allowed' }; // a seat presses, so the pair may overlap (its own check holds the seat: fit.seat)
584
630
  if (x.holes) x = { ...x, a: x.holes, b: x.into }; // a holes fit: a board's holes (a) over what its screws go into (b)
585
631
  const star = [x.a, x.b].find((n) => n.includes('*'));
586
632
  if (!star) {
@@ -942,14 +988,11 @@ function measured(a, b, centre) {
942
988
  .update(JSON.stringify([gearsCode, a, b, +centre.toFixed(6)]))
943
989
  .digest('hex')}.json`,
944
990
  );
945
- if (!process.env.CAD_NO_CACHE && cached(file)) return JSON.parse(host.readText(file));
991
+ const kept = !process.env.CAD_NO_CACHE && readCacheJson(file);
992
+ if (kept) return kept;
946
993
  const r = contact(a, b, { centre, steps: 12 }),
947
994
  keep = { findings: r.findings, backlash: r.backlash, error: r.error };
948
- try {
949
- host.writeText(file, JSON.stringify(keep));
950
- } catch {
951
- // (a cache that can't be written is only slower)
952
- }
995
+ writeCacheFile(file, JSON.stringify(keep)); // (one that can't be written is only slower)
953
996
  return keep;
954
997
  }
955
998
 
@@ -1322,9 +1365,11 @@ function bevelDrive(j, lead, spec, teeth, common, joints, items) {
1322
1365
  }
1323
1366
 
1324
1367
  // A worm and its wheel: "mesh": { "with": <the worm's joint>, "module", "teeth": [starts, wheel's teeth], "worm": {
1325
- // "diameter"?, "hand"? } } on the wheel's revolute, the axes crossed. In the wheel's middle plane the worm's thread is a
1326
- // rack along the worm's axis, moving a lead a turn: the wheel follows it as a pinion does a rack, its helix's turn at
1327
- // that plane taken into account. The worm is drawn as @rulecad/gears draws it (axis up its z, from z = 0).
1368
+ // "diameter"?, "hand"?, "flanks"?, "overhang"? } } on the wheel's revolute, the axes crossed. In the wheel's middle
1369
+ // plane the worm's thread is a rack along the worm's axis, moving a lead a turn: the wheel follows it as a pinion does
1370
+ // a rack, its helix's turn at that plane taken into account. The worm is drawn as @rulecad/gears draws it (axis up its
1371
+ // z, from z = 0); "flanks" and "overhang" are its thread's as the object draws it (worm()'s own, 'printed' and 45°
1372
+ // unless said), so that what is said of the flank that drives (worm.flanks) is said of the worm as drawn.
1328
1373
  function wormDrive(j, lead, spec, teeth, common, joints, items, num) {
1329
1374
  const what = `joint ${j.id}: mesh`,
1330
1375
  DEG = Math.PI / 180;
@@ -1335,15 +1380,18 @@ function wormDrive(j, lead, spec, teeth, common, joints, items, num) {
1335
1380
  const crossP = (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]],
1336
1381
  len = (v) => Math.hypot(...v);
1337
1382
  const ang = (v, x0, z) => Math.atan2(dot(crossP(x0, v), z), dot(x0, v));
1338
- const ws = spec.worm === true ? {} : spec.worm;
1339
- let w, wheel;
1340
- try {
1341
- w = wormModel({
1383
+ const ws = spec.worm === true ? {} : spec.worm,
1384
+ wormSpec = {
1342
1385
  ...common,
1343
1386
  starts: teeth[0],
1344
1387
  ...(ws.diameter != null ? { diameter: num(ws.diameter) } : {}),
1345
1388
  ...(ws.hand ? { hand: ws.hand } : {}),
1346
- });
1389
+ ...(ws.flanks ? { flanks: ws.flanks } : {}),
1390
+ ...(ws.overhang != null ? { overhang: num(ws.overhang) } : {}),
1391
+ };
1392
+ let w, wheel;
1393
+ try {
1394
+ w = wormModel(wormSpec);
1347
1395
  wheel = gearModel({ ...common, teeth: teeth[1], helix: w.leadAngle, hand: w.hand });
1348
1396
  } catch (e) {
1349
1397
  throw new Error(`${what}: ${e.message}`);
@@ -1395,15 +1443,7 @@ function wormDrive(j, lead, spec, teeth, common, joints, items, num) {
1395
1443
  const a0 = theta(0),
1396
1444
  a1 = theta(1);
1397
1445
  j.follow = [lead.id, (a1 - a0) / DEG, a0 / DEG];
1398
- const m = wormMesh(
1399
- {
1400
- ...common,
1401
- starts: teeth[0],
1402
- ...(ws.diameter != null ? { diameter: num(ws.diameter) } : {}),
1403
- ...(ws.hand ? { hand: ws.hand } : {}),
1404
- },
1405
- { teeth: teeth[1] },
1406
- );
1446
+ const m = wormMesh(wormSpec, { teeth: teeth[1] });
1407
1447
  const c = meshOf(wheel, rackModel({ ...common, teeth: 4 }), { centre: dist - w.pitch / 2 });
1408
1448
  const findings = [
1409
1449
  ...m.findings,
@@ -1685,19 +1725,145 @@ export { wiresFor, wireTubesOf, wireRoutesOf } from './wires.mjs'; // (there, so
1685
1725
  // ---------- checks ----------
1686
1726
  export { closest };
1687
1727
 
1688
- // How much two parts overlap (mm³), from JSCAD's intersection.
1728
+ // How much two parts overlap (mm³): Manifold's intersection where it's installed and can read both, else JSCAD's.
1689
1729
  export function overlap(ga, gb) {
1730
+ return measureOverlap(ga, gb).volume;
1731
+ }
1732
+ // A JSCAD-only overlap smaller than this (mm³) is a warning, not a failure: JSCAD can misread seams by about as much,
1733
+ // and Manifold, which doesn't, settles it
1734
+ const SEAM_SMALL = 0.5;
1735
+ // What to do about an overlap JSCAD measured and can't be sure of (checkAssembly, sweep, gaitChecks): measure it with
1736
+ // Manifold, which reads closed solids exactly
1737
+ const seamAdvice = () =>
1738
+ solid
1739
+ ? 'Manifold couldn\'t read one part of each such pair as a closed solid (JSCAD\'s unions and cuts leave seams): "engine": "manifold" in that part\'s .json, or in cad.config.json, builds it with Manifold'
1740
+ : 'To measure exactly, install Manifold (npm install manifold-3d) and set "engine": "manifold" in cad.config.json';
1741
+ // measureOverlap(ga, gb) -> { volume, seam, rough? }. Where JSCAD measured it (no Manifold, or a shape Manifold
1742
+ // couldn't read): seam is 'small' for an overlap under SEAM_SMALL, which is in doubt (a warning, not a failure), else
1743
+ // false; rough is set where what JSCAD found doesn't close into a solid, so its volume is about right at best.
1744
+ function measureOverlap(ga, gb) {
1690
1745
  const fell = solid?.stats.fallbacks ?? 0;
1691
- const v = Math.abs(jscad.measurements.measureVolume((solid ? solid.intersect : jscad.booleans.intersect)(ga, gb)));
1746
+ const common = (solid ? solid.intersect : jscad.booleans.intersect)(ga, gb);
1747
+ if (solid && solid.stats.fallbacks === fell) {
1748
+ const v = Math.abs(jscad.measurements.measureVolume(common)); // (Manifold's: a closed solid)
1749
+ return { volume: v < 1e-6 ? 0 : v, seam: false };
1750
+ }
1751
+ // JSCAD's answer. A union in JSCAD can leave a seam open: a face of no thickness across a bore where two solids met
1752
+ // (a gear's top and the drum on it). Its intersection with a shaft in the bore is that face clipped to the shaft, and
1753
+ // JSCAD measures a volume to the world's origin, which a flat face has as surely as a solid does (39 mm³ for a 5 mm
1754
+ // shaft's disc 6 mm up). So the volume here is what the faces found enclose, flat strays left out (enclosed): a film
1755
+ // by itself is nothing, and a film across a shaft too wide for its bore is that overlap, to the same figure as
1756
+ // without the film.
1757
+ const { volume, rough } = enclosed(common);
1758
+ if (volume < 1e-6) return { volume: 0, seam: false };
1759
+ // only if fit says they really run into each other (their surfaces cross, one is inside the other, or they share
1760
+ // volume beside a face plane they share: slower, so only here)
1761
+ const faces = (g) => jscad.geometries.geom3.toPolygons(g).map((q) => q.vertices);
1762
+ if (!overlapAt(faces(ga), faces(gb))) return { volume: 0, seam: false };
1763
+ return { volume, seam: volume < SEAM_SMALL ? 'small' : false, ...(rough ? { rough } : {}) };
1764
+ }
1765
+ // The volume a mesh encloses (mm³), with flat faces of no thickness that lie in it left out: { volume, rough }.
1766
+ // Each face counts by where it is and the way it looks. Summed over a closed solid, (where a face is) × (its area,
1767
+ // along the way it looks) comes to the solid's volume along each axis and to nothing across them (the divergence
1768
+ // theorem), wherever "where" is measured from. A flat stray face (the film a union left across a bore, by itself or
1769
+ // in a real overlap), or a flat face gone missing, adds one term of its own to that sum, and whatever the term, it
1770
+ // moves the greatest and the least of the sum's three principal values and never the middle one. So the middle one is
1771
+ // the volume of what is closed: nothing for a film alone, however far from the origin it lies, and the overlap for a
1772
+ // film across a shaft too wide for its bore. Flat strays that look the same way, or straight back, add up to one
1773
+ // such term (the films two unions leave across one bore do). Strays that look different ways leave a second term
1774
+ // (rough): the middle value is then right only to within about that term's size, which is added twice over, so that
1775
+ // faces which can't be measured are never read as nothing.
1776
+ function enclosed(g) {
1777
+ const polys = jscad.geometries.geom3.toPolygons(g).map((q) => q.vertices);
1778
+ const n = polys.reduce((t, p) => t + p.length, 0);
1779
+ if (!n) return { volume: 0, rough: false };
1780
+ // (from the middle of its corners: the sums stay small, so nothing is lost to rounding far from the origin)
1781
+ const c = [0, 1, 2].map((k) => polys.reduce((t, p) => t + p.reduce((u, v) => u + v[k], 0), 0) / n);
1782
+ const sum = [0, 1, 2].map(() => [0, 0, 0]);
1783
+ for (const p of polys) {
1784
+ const a = p[0].map((x, k) => x - c[k]);
1785
+ for (let i = 1; i + 1 < p.length; i++) {
1786
+ const b = p[i].map((x, k) => x - c[k]),
1787
+ d = p[i + 1].map((x, k) => x - c[k]);
1788
+ const e = [b[0] - a[0], b[1] - a[1], b[2] - a[2]],
1789
+ h = [d[0] - a[0], d[1] - a[1], d[2] - a[2]],
1790
+ m = [e[1] * h[2] - e[2] * h[1], e[2] * h[0] - e[0] * h[2], e[0] * h[1] - e[1] * h[0]]; // twice the triangle, facing out
1791
+ for (let r = 0; r < 3; r++) for (let k = 0; k < 3; k++) sum[r][k] += ((a[r] + b[r] + d[r]) / 3) * (m[k] / 2);
1792
+ }
1793
+ }
1794
+ const mid = principal(sum.map((row, r) => row.map((x, k) => (x + sum[k][r]) / 2)))[1];
1795
+ // What is left once the solid is taken out: one stray term alone has no second stretch (each of its 2 × 2 corners
1796
+ // comes to nothing), and the size of the second is how far the middle value can be out
1797
+ const left = sum.map((row, r) => row.map((x, k) => x - (r === k ? mid : 0))),
1798
+ corner = (r, k) =>
1799
+ left[(r + 1) % 3][(k + 1) % 3] * left[(r + 2) % 3][(k + 2) % 3] -
1800
+ left[(r + 1) % 3][(k + 2) % 3] * left[(r + 2) % 3][(k + 1) % 3],
1801
+ size = Math.hypot(...left.flat()),
1802
+ second = size ? Math.hypot(...[0, 1, 2].flatMap((r) => [0, 1, 2].map((k) => corner(r, k)))) / size : 0,
1803
+ rough = second > Math.max(0.01, 0.01 * Math.abs(mid));
1804
+ return { volume: Math.abs(mid) + (rough ? 2 * second : 0), rough };
1805
+ }
1806
+ // The three principal values of a symmetric 3 × 3, least first (Jacobi's turns, each of which clears one pair of
1807
+ // off-diagonal entries: exact to rounding, also where two of the values are the same, as a closed solid's all are)
1808
+ function principal(sym) {
1809
+ const a = sym.map((row) => [...row]);
1810
+ for (let round = 0; round < 50; round++) {
1811
+ const off = Math.abs(a[0][1]) + Math.abs(a[0][2]) + Math.abs(a[1][2]);
1812
+ if (off <= 1e-15 * (Math.abs(a[0][0]) + Math.abs(a[1][1]) + Math.abs(a[2][2]))) break;
1813
+ for (const [p, q, r] of [
1814
+ [0, 1, 2],
1815
+ [0, 2, 1],
1816
+ [1, 2, 0],
1817
+ ]) {
1818
+ if (!a[p][q]) continue;
1819
+ const lean = (a[q][q] - a[p][p]) / (2 * a[p][q]),
1820
+ t = (lean < 0 ? -1 : 1) / (Math.abs(lean) + Math.hypot(lean, 1)),
1821
+ cos = 1 / Math.hypot(t, 1),
1822
+ sin = t * cos,
1823
+ pr = a[p][r],
1824
+ qr = a[q][r];
1825
+ a[p][p] -= t * a[p][q];
1826
+ a[q][q] += t * a[p][q];
1827
+ a[p][q] = a[q][p] = 0;
1828
+ a[p][r] = a[r][p] = cos * pr - sin * qr;
1829
+ a[q][r] = a[r][q] = sin * pr + cos * qr;
1830
+ }
1831
+ }
1832
+ return [a[0][0], a[1][1], a[2][2]].sort((x, y) => x - y);
1833
+ }
1834
+ // How deep two parts run into each other (mm), where they overlap: the volume they share over the area where they meet.
1835
+ // The shared solid's surface is part a's surface that lies inside b and part b's that lies inside a; of the two, the
1836
+ // smaller is where they meet (a block's top under a knob pressed into it, a hole's wall inside the pin pressed in it),
1837
+ // and the volume over that area is how thick the overlap is, as deep along the way they meet as it is: 1 mm for a
1838
+ // knob 1 mm into a block, whatever its width, and 0.1 mm for a pin 0.1 mm too big for its hole, however long. a's
1839
+ // surface inside b is half of (a's area + the shared solid's - the area of a less b), each face being on one side or
1840
+ // the other. No deeper than the shared solid is thin, and where one lies wholly inside the other (no area where they
1841
+ // meet), that thickness. 0 where they don't overlap. (Hardening 2.26, #383)
1842
+ /**
1843
+ * How deep two solids run into each other (mm), 0 where they don't.
1844
+ * @param {object} ga a JSCAD solid (geom3) @param {object} gb another
1845
+ * @returns {number}
1846
+ */
1847
+ export function overlapDepth(ga, gb) {
1848
+ const fell = solid?.stats.fallbacks ?? 0;
1849
+ const both = (solid ? solid.intersect : jscad.booleans.intersect)(ga, gb),
1850
+ exact = !!solid && solid.stats.fallbacks === fell,
1851
+ // (the volume as measureOverlap reads it: Manifold's of a closed solid, else what JSCAD's faces enclose)
1852
+ v = exact ? Math.abs(jscad.measurements.measureVolume(both)) : enclosed(both).volume;
1692
1853
  if (v < 1e-6) return 0;
1693
- // JSCAD's answer (no Manifold, or a shape Manifold couldn't read): only if fit says they really run into each other
1694
- // (their surfaces cross, one is inside the other, or they share volume beside a face plane they share: slower, so
1695
- // only here)
1696
- if (!solid || solid.stats.fallbacks > fell) {
1854
+ if (!exact) {
1855
+ // (JSCAD's answer: only if fit says they really run into each other, as measureOverlap has it)
1697
1856
  const faces = (g) => jscad.geometries.geom3.toPolygons(g).map((q) => q.vertices);
1698
1857
  if (!overlapAt(faces(ga), faces(gb))) return 0;
1699
1858
  }
1700
- return v;
1859
+ const { measureArea, measureBoundingBox } = jscad.measurements,
1860
+ [lo, hi] = measureBoundingBox(both),
1861
+ thin = Math.min(...[0, 1, 2].map((k) => hi[k] - lo[k]));
1862
+ const aLessB = (solid ? solid.subtract : jscad.booleans.subtract)(ga, gb);
1863
+ const shared = measureArea(both),
1864
+ aInside = Math.max(0, (measureArea(ga) + shared - measureArea(aLessB)) / 2),
1865
+ meet = Math.min(aInside, Math.max(0, shared - aInside));
1866
+ return meet > 1e-9 ? Math.min(v / meet, thin) : thin;
1701
1867
  }
1702
1868
  // How overlaps are measured: whether the surfaces cross, exactly (fit), and then how much, with Manifold where it's
1703
1869
  // installed. JSCAD's intersection misreads faces that come near without touching: two gears 0.07 mm apart (their
@@ -1720,46 +1886,108 @@ async function measurer() {
1720
1886
  const OVERLAPS = paths.cache('overlaps.json');
1721
1887
  let remembered = null,
1722
1888
  fresh = 0;
1723
- function pairOverlap(pa, pb) {
1724
- const solidOf = (p) => p.collide ?? p.geometry; // (a beam by its envelope: lib/beams.mjs)
1725
- if (!pa.hash || !pb.hash) return overlap(solidOf(pa), solidOf(pb));
1889
+ const solidOf = (p) => p.collide ?? p.geometry; // (a beam by its envelope: lib/beams.mjs)
1890
+ // What was measured of two placed parts, remembered under the measure's words: measured again where nothing good is kept
1891
+ function recalled(pa, pb, words, good, measure) {
1892
+ if (!pa.hash || !pb.hash) return measure(solidOf(pa), solidOf(pb));
1726
1893
  remembered ||= (() => {
1727
- try {
1728
- return cached(OVERLAPS) ? JSON.parse(host.readText(OVERLAPS)) : {};
1729
- } catch {
1730
- return {};
1731
- }
1894
+ const kept = readCacheJson(OVERLAPS); // (one cut short or spoiled: nothing remembered)
1895
+ return kept && typeof kept === 'object' && !Array.isArray(kept) ? kept : {};
1732
1896
  })();
1733
1897
  const at = (p) =>
1734
1898
  `${p.hash}@${Array.from(p.m || [])
1735
1899
  .map((x) => Math.round(x * 1e6) / 1e6)
1736
1900
  .join(',')}`;
1737
- // (the words in front change whenever the measure does, so an answer remembered from before is measured again: flush
1738
- // overlaps, which fit once read as touching and were remembered as 0, came with #371)
1739
1901
  const [x, y] = [at(pa), at(pb)].sort(),
1740
1902
  k = crypto
1741
1903
  .createHash('sha1')
1742
- .update(`flush+crossing+tracks+${solid ? 'manifold' : 'jscad'}|${x}|${y}`)
1904
+ .update(`${words}+${solid ? 'manifold' : 'jscad'}|${x}|${y}`)
1743
1905
  .digest('hex');
1744
- if (!(k in remembered)) {
1745
- remembered[k] = overlap(solidOf(pa), solidOf(pb));
1906
+ if (!good(remembered[k])) {
1907
+ remembered[k] = measure(solidOf(pa), solidOf(pb));
1746
1908
  fresh++;
1747
1909
  }
1748
1910
  return remembered[k];
1749
1911
  }
1912
+ // (the words in front change whenever the measure does, so an answer remembered from before is measured again: flush
1913
+ // overlaps, which fit once read as touching and were remembered as 0, came with #371; a JSCAD answer in doubt or
1914
+ // rough, and its volume as what the faces found enclose, films left out, with #411)
1915
+ const MEASURED = 'flush+crossing+tracks+films';
1916
+ // pairOverlap(pa, pb) -> { volume, seam, rough? } (measureOverlap)
1917
+ function pairOverlap(pa, pb) {
1918
+ const { volume, seam, rough } = recalled(
1919
+ pa,
1920
+ pb,
1921
+ MEASURED,
1922
+ (kept) => typeof kept?.volume === 'number',
1923
+ measureOverlap,
1924
+ );
1925
+ return { volume, seam: seam || false, ...(rough ? { rough: true } : {}) };
1926
+ }
1927
+ // How deep two placed parts run into each other (mm: overlapDepth), remembered as their overlap is
1928
+ const pairDepth = (pa, pb) => recalled(pa, pb, `${MEASURED}+depth`, (kept) => typeof kept === 'number', overlapDepth);
1750
1929
  function saveOverlaps() {
1751
1930
  if (!fresh) return;
1752
- try {
1753
- host.writeText(OVERLAPS, JSON.stringify(remembered));
1754
- fresh = 0;
1755
- } catch {
1756
- // (a cache that can't be written is only slower)
1757
- }
1931
+ if (writeCacheFile(OVERLAPS, JSON.stringify(remembered))) fresh = 0; // (one that can't be written is only slower)
1758
1932
  }
1759
1933
 
1760
1934
  // A screw and what it is threaded into (its part, its nut, its insert) share space by design: fasten's hardware says which
1761
1935
  const threaded = (a, b) => !!(a.allow?.includes(b.leaf) || b.allow?.includes(a.leaf));
1762
1936
 
1937
+ // What a fit lets two parts do (Hardening 2.26, #383). A fit's range is a gap from min to max (mm); a negative min lets
1938
+ // the two run into each other no deeper than -min (a press fit), measured as a depth (overlapDepth). A pair that may
1939
+ // overlap by any amount says so: "overlap": "allowed". Bounds are held within FIT_NEAR, so a gap a design sets exactly
1940
+ // isn't lost to rounding; a min below -PRESS_DEEPEST without "overlap": "allowed" is refused (fit.range): it is no press
1941
+ // fit, and was once the way to let two parts overlap.
1942
+ const FIT_NEAR = 1e-3, // mm: 1 µm
1943
+ PRESS_DEEPEST = 1; // mm
1944
+ /**
1945
+ * Whether a fit holds (Hardening 2.26, #383): an overlap no deeper than -lo (a press fit; none where lo is 0 or more,
1946
+ * or not given) and, where hi is negative, at least -hi deep (a press fit that must grip), or any where the fit says
1947
+ * "overlap": "allowed"; else a gap from lo to hi. Each bound is held within 1 µm.
1948
+ * @param {{ lo: number, hi: number, allowed?: boolean, depth?: number | null, gap?: number }} r lo and hi the fit's
1949
+ * range (mm; -Infinity and Infinity where not given), depth how deep the two run into each other (mm; null where they
1950
+ * don't), gap the closest gap between them where they don't (mm)
1951
+ * @returns {boolean}
1952
+ */
1953
+ export function fitHolds({ lo, hi, allowed = false, depth = null, gap = Infinity }) {
1954
+ if (depth != null)
1955
+ return (
1956
+ allowed ||
1957
+ (depth <= (Number.isFinite(lo) ? Math.max(0, -lo) : 0) + FIT_NEAR && // (no min: no overlap)
1958
+ depth >= -hi - FIT_NEAR) // (a negative max: at least that deep)
1959
+ );
1960
+ return gap >= lo - FIT_NEAR && gap <= hi + FIT_NEAR;
1961
+ }
1962
+ // How deep a fit lets its two parts run into each other (mm): any depth where it says "overlap": "allowed" (or where
1963
+ // its min is refused as too deep, so that the refusal is said once, by the fit), -min where min is negative, else none
1964
+ function fitDepth(x) {
1965
+ if (x.overlap === 'allowed') return Infinity;
1966
+ const lo = x.min != null ? x.num(x.min) : 0;
1967
+ return lo < -PRESS_DEEPEST ? Infinity : Math.max(0, -lo);
1968
+ }
1969
+ // allowanceOf(s, named)(a, b): how deep parts a and b may run into each other (mm), by the fits naming both
1970
+ function allowanceOf(s, named) {
1971
+ return (a, b) =>
1972
+ threaded(a, b)
1973
+ ? Infinity
1974
+ : s.fits.reduce(
1975
+ (most, x) =>
1976
+ (named(a, x.a) && named(b, x.b)) || (named(a, x.b) && named(b, x.a)) ? Math.max(most, fitDepth(x)) : most,
1977
+ 0,
1978
+ );
1979
+ }
1980
+ // Whether two placed parts overlap more than they may (mm deep): { volume, seam, rough?, depth? } (volume, seam and
1981
+ // rough as measureOverlap's; depth where they may overlap some), or null where they don't
1982
+ function overlapBeyond(pa, pb, may) {
1983
+ if (may === Infinity) return null;
1984
+ const o = pairOverlap(pa, pb);
1985
+ if (!(o.volume > 0.01)) return null;
1986
+ if (may <= 0) return o;
1987
+ const depth = pairDepth(pa, pb);
1988
+ return depth <= may + FIT_NEAR ? null : { ...o, depth };
1989
+ }
1990
+
1763
1991
  // checkAssembly(built) -> findings, as @rulecad/printcheck: { level, text, card? } (card: a short line for the mirror)
1764
1992
  // What a project prints in, for the motors' heat and press-fit checks
1765
1993
  const materialOf = (project) => {
@@ -1818,46 +2046,92 @@ export function checkAssembly(s) {
1818
2046
  );
1819
2047
  }
1820
2048
  // Overlaps between object instances, inside components too. Bounding boxes first: most pairs can't touch.
2049
+ // A pair a fit lets overlap is held to the depth it allows (a press fit no deeper than -min), or not at all where it
2050
+ // says "overlap": "allowed"
1821
2051
  const named = (p, n) => p.name === n || p.leaf === n || p.item === n || p.name.startsWith(`${n}.`);
1822
- const allowed = (a, b) =>
1823
- threaded(a, b) ||
1824
- s.fits.some(
1825
- (x) =>
1826
- x.min != null && x.num(x.min) < 0 && ((named(a, x.a) && named(b, x.b)) || (named(a, x.b) && named(b, x.a))),
1827
- );
2052
+ const allowance = allowanceOf(s, named);
1828
2053
  const box = new Map(),
1829
2054
  bx = (p) => box.get(p) || (box.set(p, bounds(p.triangles)), box.get(p));
1830
2055
  const touch = (a, b) =>
1831
2056
  [0, 1, 2].every((k) => bx(a).lo[k] <= bx(b).hi[k] + 1e-6 && bx(b).lo[k] <= bx(a).hi[k] + 1e-6);
1832
- const clashes = [];
2057
+ const clashes = [],
2058
+ doubts = []; // (JSCAD's measure, in doubt: measureOverlap)
1833
2059
  for (let i = 0; i < s.parts.length; i++)
1834
2060
  for (let j = i + 1; j < s.parts.length; j++) {
1835
2061
  const pa = s.parts[i],
1836
2062
  pb = s.parts[j];
1837
- if (pa.leaf === pb.leaf || !touch(pa, pb) || allowed(pa, pb)) continue;
1838
- const v = pairOverlap(pa, pb);
1839
- if (v > 0.01)
1840
- clashes.push({ text: `${pa.name} and ${pb.name} overlap by ${mm(v)} mm³`, a: pa.name, b: pb.name, volume: v });
2063
+ if (pa.leaf === pb.leaf || !touch(pa, pb)) continue;
2064
+ const may = allowance(pa, pb),
2065
+ o = overlapBeyond(pa, pb, may);
2066
+ if (!o) continue;
2067
+ const { volume: v, seam, rough, depth } = o,
2068
+ // (a pair whose fit lets it press some, and which runs deeper)
2069
+ deep = depth != null ? `, ${mm(depth)} mm deep where their fit allows ${mm(may)} mm` : '';
2070
+ if (seam)
2071
+ doubts.push({
2072
+ text: `${pa.name} and ${pb.name} may overlap by ${mm(v)} mm³${deep}`,
2073
+ a: pa.name,
2074
+ b: pb.name,
2075
+ volume: v,
2076
+ seam,
2077
+ });
2078
+ else
2079
+ clashes.push({
2080
+ text: `${pa.name} and ${pb.name} overlap by ${rough ? 'about ' : ''}${mm(v)} mm³${deep}`,
2081
+ a: pa.name,
2082
+ b: pb.name,
2083
+ volume: v,
2084
+ ...(rough ? { rough } : {}),
2085
+ ...(depth != null ? { depth } : {}),
2086
+ });
1841
2087
  }
2088
+ const listed = (xs) =>
2089
+ xs
2090
+ .slice(0, 5)
2091
+ .map((c) => c.text)
2092
+ .join('; ') + (xs.length > 5 ? `; and ${xs.length - 5} more` : '');
1842
2093
  if (clashes.length)
1843
2094
  f(
1844
2095
  'fail',
1845
- clashes
1846
- .slice(0, 5)
1847
- .map((c) => c.text)
1848
- .join('; ') + (clashes.length > 5 ? `; and ${clashes.length - 5} more` : ''),
2096
+ // (a rough one still fails: faces that don't close may hide a real overlap as easily as stand for none)
2097
+ `${listed(clashes)}${
2098
+ clashes.some((c) => c.rough)
2099
+ ? `. "About": JSCAD measured faces there that don't close into a solid, so the figure is rough. ${seamAdvice()}`
2100
+ : ''
2101
+ }`,
1849
2102
  `${clashes.length} overlaps`,
1850
2103
  {
1851
2104
  code: 'overlap',
1852
2105
  values: { count: clashes.length },
1853
- refs: { overlaps: clashes.map(({ a, b, volume }) => ({ a, b, volume })) },
2106
+ refs: {
2107
+ overlaps: clashes.map(({ a, b, volume, rough, depth }) => ({
2108
+ a,
2109
+ b,
2110
+ volume,
2111
+ ...(rough ? { rough } : {}),
2112
+ ...(depth != null ? { depth } : {}),
2113
+ })),
2114
+ },
1854
2115
  },
1855
2116
  );
1856
- else
2117
+ else if (!doubts.length)
1857
2118
  f('pass', `no parts overlap (${new Set(s.parts.map((p) => p.leaf)).size} object instances)`, 'No parts overlap', {
1858
2119
  code: 'overlap',
1859
2120
  values: { count: 0 },
1860
2121
  });
2122
+ // JSCAD measured these, each under SEAM_SMALL, and JSCAD can read the seams its booleans leave as about that much:
2123
+ // Manifold, which reads them exactly, settles it. Not a failure on JSCAD's word alone, nor passed over
2124
+ if (doubts.length)
2125
+ f(
2126
+ 'warn',
2127
+ `${listed(doubts)}: under ${SEAM_SMALL} mm³, measured by JSCAD, which can read the seams its unions and cuts leave as that much overlap. ${seamAdvice()}`,
2128
+ `${doubts.length} possible overlaps`,
2129
+ {
2130
+ code: 'overlap',
2131
+ values: { count: doubts.length },
2132
+ refs: { overlaps: doubts.map(({ a, b, volume, seam }) => ({ a, b, volume, seam })) },
2133
+ },
2134
+ );
1861
2135
  // Fits: the closest gap between two named things, against a range. Copies of one fit are reported together, worst first.
1862
2136
  // A fit names parts (keyboard, key-0-0.cap), or the faces of an item near one of its anchors (keyboard@pivot, within
1863
2137
  // "within" mm, 10 by default): the pocket round a pivot, not the whole case
@@ -1883,6 +2157,29 @@ export function checkAssembly(s) {
1883
2157
  .filter((p) => p.polygons.length);
1884
2158
  };
1885
2159
  const pick = (n) => pickIn(n, {});
2160
+ // A range that can't hold: a min above its max, or a min so far below 0 that it can only be meant to let the two
2161
+ // overlap (say that with "overlap": "allowed"); refused, naming the fit (Hardening 2.26, #383)
2162
+ const rangeHolds = (x, key, lo, hi) => {
2163
+ const no = (text) => (
2164
+ f('fail', `${key}: ${text}`, null, {
2165
+ code: 'fit.range',
2166
+ values: { min: lo, max: hi },
2167
+ refs: { a: x.a, b: x.b, label: x.label },
2168
+ }),
2169
+ false
2170
+ );
2171
+ if (lo > hi + FIT_NEAR)
2172
+ return no(
2173
+ `its min (${mm(lo)} mm) is above its max (${mm(hi)} mm), so no gap is in range: give the smaller as min and the larger as max`,
2174
+ );
2175
+ if (x.overlap != null && x.overlap !== 'allowed')
2176
+ return no(`"overlap" takes only "allowed" (got ${JSON.stringify(x.overlap)})`);
2177
+ if (Number.isFinite(lo) && lo < -PRESS_DEEPEST && x.overlap !== 'allowed')
2178
+ return no(
2179
+ `its min (${mm(lo)} mm) would let the two run ${mm(-lo)} mm into each other, deeper than any press fit (at most ${PRESS_DEEPEST} mm). If they may overlap by any amount (a pin through a part, an end cap's pegs in a beam), say so with "overlap": "allowed" in place of the min; if it is a press fit, give its depth as min (-0.1 for a tenth of a millimetre)`,
2180
+ );
2181
+ return true;
2182
+ };
1886
2183
  const groups = new Map();
1887
2184
  for (const x of s.fits) {
1888
2185
  if (x.poses && !x.poses.includes(s.pose)) continue; // a fit for some poses only: the folded screen over the keys
@@ -1891,6 +2188,13 @@ export function checkAssembly(s) {
1891
2188
  continue;
1892
2189
  }
1893
2190
  if (x.silent) continue; // lets a pair overlap, and has nothing to report
2191
+ const key = x.note || `${x.a} / ${x.b}`,
2192
+ lo = x.min != null ? x.num(x.min) : -Infinity,
2193
+ hi = x.max != null ? x.num(x.max) : Infinity,
2194
+ allowed = x.overlap === 'allowed';
2195
+ // (refused on every kind of fit: on an engage, seat or shaft fit a min says only how deep the two may overlap, and
2196
+ // one too deep to be a press fit would still let them overlap by any amount, unsaid)
2197
+ const sound = rangeHolds(x, key, lo, hi);
1894
2198
  if (x.engage != null) {
1895
2199
  engageFit(x);
1896
2200
  continue;
@@ -1910,10 +2214,8 @@ export function checkAssembly(s) {
1910
2214
  });
1911
2215
  continue;
1912
2216
  }
1913
- const A = pickIn(x.a, x),
1914
- key = x.note || `${x.a} / ${x.b}`;
1915
- const lo = x.min != null ? x.num(x.min) : -Infinity,
1916
- hi = x.max != null ? x.num(x.max) : Infinity;
2217
+ if (!sound) continue;
2218
+ const A = pickIn(x.a, x);
1917
2219
  const reach = Math.max(2, ...[lo, hi].filter(Number.isFinite)) + 1; // look past the range, so a gap near it is measured
1918
2220
  let B = pickIn(x.b, x);
1919
2221
  if (Array.isArray(x.b) && A.length) {
@@ -1929,19 +2231,41 @@ export function checkAssembly(s) {
1929
2231
  });
1930
2232
  continue;
1931
2233
  }
1932
- const vol = A.reduce((t, pa) => t + B.reduce((u, pb) => u + (touch(pa, pb) ? pairOverlap(pa, pb) : 0), 0), 0);
2234
+ // the pairs that run into each other, each as the overlap check measures it
2235
+ const hits = A.flatMap((pa) =>
2236
+ B.flatMap((pb) => {
2237
+ const o = touch(pa, pb) ? pairOverlap(pa, pb) : null;
2238
+ return o?.volume > 0.01 ? [{ pa, pb, ...o }] : [];
2239
+ }),
2240
+ );
1933
2241
  const near =
1934
- !B.length || vol > 0.01
2242
+ !B.length || hits.length
1935
2243
  ? null
1936
2244
  : closestAt(
1937
2245
  A.flatMap((p) => p.polygons),
1938
2246
  B.flatMap((p) => p.polygons),
1939
2247
  reach,
1940
2248
  );
1941
- const gap = !B.length ? Infinity : vol > 0.01 ? -vol : near.gap; // negative: overlap, mm³
1942
- const ok = vol > 0.01 ? lo < 0 : gap >= lo && gap <= hi;
1943
- if (!groups.has(key)) groups.set(key, { x, lo, hi, results: [] });
1944
- groups.get(key).results.push({ ok, gap, id: x.a, at: near?.at || null });
2249
+ // overlapping: how deep, the deepest of the pairs that overlap, held to -min (a press fit) unless any is allowed
2250
+ const depth = hits.length ? Math.max(...hits.map((h) => pairDepth(h.pa, h.pb))) : null;
2251
+ const gap = !B.length ? Infinity : depth != null ? -depth : near.gap; // negative: an overlap this deep (mm)
2252
+ const ok = fitHolds({ lo, hi, allowed, depth, gap });
2253
+ if (!groups.has(key)) groups.set(key, { x, lo, hi, allowed, results: [] });
2254
+ groups.get(key).results.push({
2255
+ ok,
2256
+ gap,
2257
+ ...(depth != null
2258
+ ? {
2259
+ depth,
2260
+ volume: hits.reduce((t, h) => t + h.volume, 0),
2261
+ // (JSCAD's measure: each under SEAM_SMALL, so in doubt, or of faces that don't close, so rough)
2262
+ doubt: hits.every((h) => h.seam),
2263
+ rough: hits.some((h) => h.rough),
2264
+ }
2265
+ : {}),
2266
+ id: x.a,
2267
+ at: near?.at || null,
2268
+ });
1945
2269
  }
1946
2270
  // The anchor nearest a point, if one is within 20 mm: where to look
1947
2271
  const nearest = (pt) => {
@@ -1951,28 +2275,52 @@ export function checkAssembly(s) {
1951
2275
  .sort((a, b) => a.d - b.d)[0];
1952
2276
  return m.d <= 20 ? { near: m.k.id, distance: Number(m.d.toFixed(2)) } : {};
1953
2277
  };
1954
- for (const [key, { x, lo, hi, results }] of groups) {
2278
+ for (const [key, { x, lo, hi, allowed, results }] of groups) {
1955
2279
  const worst = results.reduce((w, r) => (!r.ok && w.ok ? r : r.ok === w.ok && r.gap < w.gap ? r : w), results[0]);
1956
- const say = (g) =>
1957
- g < 0 ? `press fit, ${mm(-g)} mm³ overlap` : g === Infinity ? 'not near each other' : `closest gap ${mm(g)} mm`;
2280
+ // a press fit only within the depth its fit allows; deeper, or where no overlap is allowed, an overlap
2281
+ const amount = (r) => `${mm(r.depth)} mm deep (${r.rough ? 'about ' : ''}${mm(r.volume)} mm³)`;
2282
+ const say = (r) =>
2283
+ r.depth != null
2284
+ ? allowed
2285
+ ? `overlap ${mm(r.depth)} mm deep, allowed`
2286
+ : r.ok
2287
+ ? `press fit, ${amount(r)}`
2288
+ : `${r.doubt ? 'may overlap' : 'overlap'} ${amount(r)}`
2289
+ : r.gap === Infinity
2290
+ ? 'not near each other'
2291
+ : `closest gap ${mm(r.gap)} mm`;
2292
+ // Out of range only by overlaps JSCAD measured under SEAM_SMALL: in doubt, so a warning, as the overlap check has it
2293
+ const off = results.filter((r) => !r.ok),
2294
+ // (only where too deep: one too shallow to grip, as a negative max wants, is no less so for a doubt)
2295
+ doubted = off.length > 0 && off.every((r) => r.doubt && !(r.depth < -hi));
2296
+ const wanted = `wanted ${lo === -Infinity ? '' : `${mm(lo)} `}to ${hi === Infinity ? 'any' : mm(hi)} mm${
2297
+ worst.depth == null
2298
+ ? ''
2299
+ : Number.isFinite(lo) && lo < 0
2300
+ ? hi < 0
2301
+ ? ` (into each other ${mm(-hi)} to ${mm(-lo)} mm deep)`
2302
+ : ` (into each other no deeper than ${mm(-lo)} mm)`
2303
+ : ' (no overlap)'
2304
+ }`;
1958
2305
  const n = results.length > 1 ? ` (${results.filter((r) => r.ok).length} of ${results.length} in range)` : '';
1959
2306
  const label = (x.label || x.a).replace(/ \(.*\)$/, '');
1960
2307
  const where = nearest(worst.at);
1961
2308
  f(
1962
- worst.ok ? 'pass' : 'warn',
1963
- `${key}: ${say(worst.gap)}${n}${
2309
+ worst.ok ? 'pass' : doubted ? 'warn' : 'fail',
2310
+ `${key}: ${say(worst)}${n}${
1964
2311
  worst.ok
1965
2312
  ? ''
1966
- : `, wanted ${lo === -Infinity ? '' : `${mm(lo)} `}to ${hi === Infinity ? 'any' : mm(hi)} mm (${results
1967
- .filter((r) => !r.ok)
1968
- .map((r) => r.id)
1969
- .join(', ')})${where.near ? `, ${where.distance} mm from ${where.near}` : ''}`
2313
+ : `, ${wanted} (${off.map((r) => r.id).join(', ')})${where.near ? `, ${where.distance} mm from ${where.near}` : ''}${
2314
+ doubted
2315
+ ? `. "May overlap": under ${SEAM_SMALL} mm³, measured by JSCAD, which can read the seams its unions and cuts leave as that much overlap. ${seamAdvice()}`
2316
+ : ''
2317
+ }`
1970
2318
  }`,
1971
- `${label}: ${worst.gap < 0 ? `press fit ${mm(-worst.gap)} mm³` : worst.gap === Infinity ? 'apart' : `gap ${Number(worst.gap.toFixed(2))} mm`}${worst.ok ? '' : ' (out of range)'}`,
2319
+ `${label}: ${worst.depth != null ? `${worst.ok && !allowed ? 'press fit' : 'overlap'} ${Number(worst.depth.toFixed(2))} mm deep` : worst.gap === Infinity ? 'apart' : `gap ${Number(worst.gap.toFixed(2))} mm`}${worst.ok ? '' : ' (out of range)'}`,
1972
2320
  {
1973
2321
  code: 'fit',
1974
2322
  values: {
1975
- ...(worst.gap < 0 ? { overlap: -worst.gap } : { gap: worst.gap }),
2323
+ ...(worst.depth != null ? { overlap: worst.volume, depth: worst.depth } : { gap: worst.gap }),
1976
2324
  min: lo,
1977
2325
  max: hi,
1978
2326
  inRange: results.filter((r) => r.ok).length,
@@ -1983,7 +2331,8 @@ export function checkAssembly(s) {
1983
2331
  b: x.b,
1984
2332
  label: x.label,
1985
2333
  ...(s.pose ? { pose: s.pose } : {}),
1986
- outOfRange: results.filter((r) => !r.ok).map((r) => r.id),
2334
+ outOfRange: off.map((r) => r.id),
2335
+ ...(doubted ? { seam: 'small' } : {}),
1987
2336
  ...where,
1988
2337
  },
1989
2338
  ...(worst.at ? { at: { lo: worst.at, hi: worst.at } } : {}),
@@ -2311,6 +2660,7 @@ export function checkAssembly(s) {
2311
2660
  values: {
2312
2661
  inside: m.inside,
2313
2662
  outside: m.outside,
2663
+ envelope: m.envelope?.size ?? null,
2314
2664
  lengths: m.lengths.map(({ length, count }) => ({ length, count })),
2315
2665
  },
2316
2666
  refs: { kind: m.kind, profile: m.profile, join: m.join.kind, arrangement: m.arrangement, by: m.by },
@@ -2328,12 +2678,14 @@ export function checkAssembly(s) {
2328
2678
  loadChecks(s, f, { placeItems, jointValues, mul });
2329
2679
  // (join.drop after the frame's checks: a beam's drop is taken from the frame's own solve where it has one)
2330
2680
  const solved = frameChecks(s, f, { placeItems, jointValues, mul });
2681
+ // (each rail guide's error budget after the frame's checks: its beam's sag is the frame's own where it is solved)
2682
+ guideBudgetFindings(s, f);
2331
2683
  joinDropChecks(s, f, solved);
2332
2684
  // (each printed foot judged at the load the frame's solve puts on it, #378)
2333
2685
  footFindings(s, f, solved);
2334
2686
  sizeChecks(s, f, { placeItems, jointValues, mul });
2335
2687
  gripChecks(s, f);
2336
- gaitChecks(s, f, { jointValues, sweepOne: (v) => clashesOf(s.at(v), named) });
2688
+ gaitChecks(s, f, { jointValues, sweepOne: (v) => clashesOf(s.at(v), named), seamAdvice });
2337
2689
  taskChecks(s, f);
2338
2690
  orderChecks(s, f, { frame: frameBuild });
2339
2691
  // Plates print everything: no references
@@ -2345,21 +2697,21 @@ export function checkAssembly(s) {
2345
2697
  refs: { items: refs.map((o) => o.id) },
2346
2698
  });
2347
2699
  }
2348
- // Rules that are only estimates, anywhere in the assembly or its components
2349
- const est = new Set();
2350
- for (const o of s.objects)
2351
- for (const e of o.built.entries) if (e.kind === 'estimate' && (e.used || !e.name.includes('.'))) est.add(e.name);
2352
- for (const n of s.seen) {
2353
- const [u, k] = n.split('.');
2354
- if (loadRuleSet(u).rules[k]?.kind === 'estimate') est.add(n);
2355
- }
2356
- if (est.size)
2357
- f(
2358
- 'warn',
2359
- `uses estimates, not measurements: ${[...est].join(', ')}. Measure each and settle it with cad measured ${s.project}/${s.name} <name>=<value>`,
2360
- `Estimate: ${[...est].join(', ')}`,
2361
- { code: 'rules.estimate', refs: { rules: [...est] } },
2362
- );
2700
+ // Rules that are only estimates, anywhere in the assembly or its components, and seats drawn to an estimated fit
2701
+ // (said the same way by an object's own check: estimates.mjs estimatesFinding)
2702
+ const est = estimatesFinding(
2703
+ s.objects.map((o) => o.built),
2704
+ {
2705
+ ref: `${s.project}/${s.name}`,
2706
+ seen: s.seen,
2707
+ kindOf: (n) => {
2708
+ const [u, k] = n.split('.');
2709
+ return loadRuleSet(u).rules[k]?.kind;
2710
+ },
2711
+ assembly: true,
2712
+ },
2713
+ );
2714
+ if (est) f(est.level, est.text, est.short, { code: est.code, refs: est.refs });
2363
2715
  saveOverlaps();
2364
2716
  return out;
2365
2717
  }
@@ -2378,14 +2730,11 @@ export function loopGaps(s) {
2378
2730
  });
2379
2731
  }
2380
2732
 
2381
- // Pairs of parts that overlap, as checkAssembly finds them (fits with a negative min allowed): [[a, b, mm³]]
2733
+ // Pairs of parts that overlap, as checkAssembly finds them (a press fit no deeper than its fit allows, and a pair whose
2734
+ // fit says "overlap": "allowed", left out): [[a, b, mm³, seam]], seam as measureOverlap's (false, or 'small': JSCAD's
2735
+ // measure, in doubt)
2382
2736
  function clashesOf(s, named) {
2383
- const allowed = (a, b) =>
2384
- threaded(a, b) ||
2385
- s.fits.some(
2386
- (x) =>
2387
- x.min != null && x.num(x.min) < 0 && ((named(a, x.a) && named(b, x.b)) || (named(a, x.b) && named(b, x.a))),
2388
- );
2737
+ const allowance = allowanceOf(s, named);
2389
2738
  const boxes = s.parts.map((p) => bounds(p.triangles)),
2390
2739
  out = [];
2391
2740
  for (let i = 0; i < s.parts.length; i++)
@@ -2394,14 +2743,10 @@ function clashesOf(s, named) {
2394
2743
  pb = s.parts[j],
2395
2744
  A = boxes[i],
2396
2745
  B = boxes[j];
2397
- if (
2398
- pa.leaf === pb.leaf ||
2399
- ![0, 1, 2].every((k) => A.lo[k] <= B.hi[k] + 1e-6 && B.lo[k] <= A.hi[k] + 1e-6) ||
2400
- allowed(pa, pb)
2401
- )
2746
+ if (pa.leaf === pb.leaf || ![0, 1, 2].every((k) => A.lo[k] <= B.hi[k] + 1e-6 && B.lo[k] <= A.hi[k] + 1e-6))
2402
2747
  continue;
2403
- const v = pairOverlap(pa, pb);
2404
- if (v > 0.01) out.push([pa.name, pb.name, v]);
2748
+ const o = overlapBeyond(pa, pb, allowance(pa, pb));
2749
+ if (o) out.push([pa.name, pb.name, o.volume, o.seam]);
2405
2750
  }
2406
2751
  return out;
2407
2752
  }
@@ -2428,7 +2773,7 @@ export function sweep(s, { joint, steps = 24, progress } = {}) {
2428
2773
  j.dofs.forEach(([lo, hi], d) => {
2429
2774
  const unit = DOFS[j.type][d] === 'angle' ? '°' : ' mm',
2430
2775
  name = `${j.id}${j.dofs.length > 1 ? ` ${'xyz'[d] && j.type === 'ball' ? 'xyz'[d] : DOFS[j.type][d]}` : ''}`;
2431
- const bad = []; // [value, what]
2776
+ const bad = []; // [value, what, sure]
2432
2777
  // a door with its latch shut: also tried just off shut, finer than a step, so a hit within the first degree is seen
2433
2778
  const held = (s.panels ?? []).find((p) => p.latch && p.joint === j.id && DOFS[j.type][d] === 'angle'),
2434
2779
  probe = held ? Math.min(PANEL_CHECK.latch_probe.value, (hi - lo) / steps) : 0;
@@ -2439,23 +2784,30 @@ export function sweep(s, { joint, steps = 24, progress } = {}) {
2439
2784
  const t = s.at(
2440
2785
  Object.fromEntries(Object.entries(set).filter(([id]) => !s.motion.joints.find((x) => x.id === id).follow)),
2441
2786
  );
2787
+ const clashes = clashesOf(t, isNamed),
2788
+ gaps = loopGaps(t).filter((l) => !l.ok);
2442
2789
  const what = [
2443
- ...clashesOf(t, isNamed).map(([a, b]) => `${a} hits ${b}`),
2444
- ...loopGaps(t)
2445
- .filter((l) => !l.ok)
2446
- .map((l) => `${l.label} apart by ${mm(l.gap)} mm`),
2790
+ ...clashes.map(([a, b, , seam]) => `${a} ${seam ? 'may hit' : 'hits'} ${b}`),
2791
+ ...gaps.map((l) => `${l.label} apart by ${mm(l.gap)} mm`),
2447
2792
  ];
2448
- if (what.length) bad.push([v, what]);
2793
+ // (sure: more than JSCAD's small measures, which are in doubt: a sweep with only those warns, as the overlap
2794
+ // check does of the same pair standing still)
2795
+ if (what.length) bad.push([v, what, gaps.length > 0 || clashes.some((c) => !c[3])]);
2449
2796
  progress?.({ stage: 'sweep', joint: j.id, step: Math.min(i, steps), steps });
2450
2797
  }
2451
2798
  const ranges = []; // runs of steps in a row that collide
2452
- for (const [v, what] of bad) {
2799
+ for (const [v, what, sure] of bad) {
2453
2800
  const r = ranges[ranges.length - 1];
2454
2801
  if (r && Math.abs(v - r.to - (hi - lo) / steps) < 1e-9) {
2455
2802
  r.to = v;
2456
2803
  r.what = [...new Set([...r.what, ...what])];
2457
- } else ranges.push({ from: v, to: v, what });
2804
+ r.sure ||= sure;
2805
+ } else ranges.push({ from: v, to: v, what, sure });
2458
2806
  }
2807
+ const sure = ranges.some((r) => r.sure),
2808
+ doubt = bad.some(([, what]) => what.some((w) => w.includes(' may hit ')))
2809
+ ? `. "May hit": under ${SEAM_SMALL} mm³, measured by JSCAD, which can read the seams its unions and cuts leave as that much overlap. ${seamAdvice()}`
2810
+ : '';
2459
2811
  const span = `${mm(lo)} to ${mm(hi)}${unit}`,
2460
2812
  note = held ? ` (${held.latch} shut over ${held.id}: also tried ${mm(probe)}${unit} off shut)` : '';
2461
2813
  if (!ranges.length)
@@ -2466,9 +2818,9 @@ export function sweep(s, { joint, steps = 24, progress } = {}) {
2466
2818
  });
2467
2819
  else
2468
2820
  f(
2469
- 'fail',
2470
- `sweep ${name}, ${span} in ${steps} steps${note}: ${ranges.map((r) => `${r.from === r.to ? `at ${mm(r.from)}` : `${mm(r.from)} to ${mm(r.to)}`}${unit.trim()}: ${r.what.slice(0, 3).join('; ')}${r.what.length > 3 ? `; and ${r.what.length - 3} more` : ''}`).join(' | ')}`,
2471
- `${name}: collides ${ranges.map((r) => (r.from === r.to ? mm(r.from) : `${mm(r.from)}-${mm(r.to)}`)).join(', ')}${unit.trim()}`,
2821
+ sure ? 'fail' : 'warn',
2822
+ `sweep ${name}, ${span} in ${steps} steps${note}: ${ranges.map((r) => `${r.from === r.to ? `at ${mm(r.from)}` : `${mm(r.from)} to ${mm(r.to)}`}${unit.trim()}: ${r.what.slice(0, 3).join('; ')}${r.what.length > 3 ? `; and ${r.what.length - 3} more` : ''}`).join(' | ')}${doubt}`,
2823
+ `${name}: ${sure ? 'collides' : 'may collide'} ${ranges.map((r) => (r.from === r.to ? mm(r.from) : `${mm(r.from)}-${mm(r.to)}`)).join(', ')}${unit.trim()}`,
2472
2824
  {
2473
2825
  code: 'sweep',
2474
2826
  values: { from: lo, to: hi, steps, ...(held ? { probe } : {}) },
@@ -2513,7 +2865,7 @@ export function motionData(s) {
2513
2865
  names = mo.items.map((x) => x[0]);
2514
2866
  const named = (p, n) => p.name === n || p.leaf === n || p.item === n || p.name.startsWith(`${n}.`),
2515
2867
  allow = [];
2516
- const loose = s.fits.filter((x) => x.min != null && x.num(x.min) < 0);
2868
+ const loose = s.fits.filter((x) => x.overlap === 'allowed' || (x.min != null && x.num(x.min) < 0));
2517
2869
  s.parts.forEach((pa, i) =>
2518
2870
  s.parts.forEach((pb, j) => {
2519
2871
  if (