@rulecad/cad 0.8.0 → 0.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (83) hide show
  1. package/AGENTS.md +24 -10
  2. package/CHANGELOG.md +404 -0
  3. package/EXAMPLES.md +40 -38
  4. package/README.md +193 -67
  5. package/TUTORIAL.md +2 -2
  6. package/bin/cad.mjs +2250 -512
  7. package/lib/animate.mjs +173 -49
  8. package/lib/assembly.mjs +1847 -434
  9. package/lib/beams.mjs +256 -52
  10. package/lib/belts.mjs +66 -15
  11. package/lib/board-work.mjs +12 -0
  12. package/lib/bought.mjs +309 -53
  13. package/lib/buildpage.mjs +179 -29
  14. package/lib/carried.mjs +201 -0
  15. package/lib/clone.mjs +194 -42
  16. package/lib/design.mjs +649 -121
  17. package/lib/drive.mjs +187 -63
  18. package/lib/edit.mjs +899 -191
  19. package/lib/errors.mjs +16 -3
  20. package/lib/explain.mjs +62 -13
  21. package/lib/fasten.mjs +2702 -507
  22. package/lib/fittings.mjs +715 -121
  23. package/lib/fixings.mjs +21 -9
  24. package/lib/framebuild.mjs +790 -175
  25. package/lib/framecheck.mjs +1901 -368
  26. package/lib/framegen.mjs +100 -22
  27. package/lib/frameheat.mjs +225 -42
  28. package/lib/frameprint.mjs +513 -108
  29. package/lib/frames.mjs +81 -17
  30. package/lib/framesize.mjs +792 -120
  31. package/lib/frametip.mjs +235 -0
  32. package/lib/gait.mjs +135 -23
  33. package/lib/grip.mjs +62 -13
  34. package/lib/guides.mjs +1403 -230
  35. package/lib/host.mjs +123 -21
  36. package/lib/inplace.mjs +171 -36
  37. package/lib/jigs.mjs +360 -78
  38. package/lib/joins.mjs +697 -118
  39. package/lib/jsonedit.mjs +88 -26
  40. package/lib/kept.mjs +84 -0
  41. package/lib/kit.mjs +438 -68
  42. package/lib/layout.mjs +2 -1
  43. package/lib/links.mjs +149 -42
  44. package/lib/list.mjs +326 -64
  45. package/lib/live-guard.mjs +68 -0
  46. package/lib/live-shape.mjs +96 -24
  47. package/lib/live.mjs +189 -59
  48. package/lib/loads.mjs +579 -130
  49. package/lib/machine.mjs +372 -74
  50. package/lib/magnets.mjs +162 -44
  51. package/lib/measured.mjs +417 -94
  52. package/lib/mesh.mjs +526 -119
  53. package/lib/meshcmd.mjs +215 -60
  54. package/lib/motors.mjs +1021 -213
  55. package/lib/motorsvg.mjs +114 -32
  56. package/lib/names.mjs +3 -1
  57. package/lib/optimise.mjs +978 -283
  58. package/lib/order.mjs +519 -112
  59. package/lib/panels.mjs +482 -94
  60. package/lib/parts.mjs +78 -23
  61. package/lib/pins.mjs +163 -44
  62. package/lib/plates.mjs +223 -35
  63. package/lib/player.mjs +37 -9
  64. package/lib/power.mjs +64 -13
  65. package/lib/preview.mjs +83 -16
  66. package/lib/profilemeasure.mjs +572 -129
  67. package/lib/rules.mjs +15 -5
  68. package/lib/sandbox-hooks.mjs +77 -19
  69. package/lib/sandbox-run.mjs +117 -18
  70. package/lib/sandbox.mjs +509 -60
  71. package/lib/schema.mjs +42 -11
  72. package/lib/seats.mjs +227 -49
  73. package/lib/services.mjs +261 -52
  74. package/lib/sheet.mjs +851 -178
  75. package/lib/slotnuts.mjs +213 -34
  76. package/lib/targets/gist.mjs +4 -1
  77. package/lib/targets.mjs +22 -4
  78. package/lib/task.mjs +376 -79
  79. package/lib/versions.mjs +111 -28
  80. package/lib/wires.mjs +228 -45
  81. package/lib/workspace.mjs +197 -12
  82. package/package.json +19 -19
  83. package/schemas/assembly.schema.json +2 -2
package/lib/host.mjs CHANGED
@@ -2,7 +2,7 @@
2
2
  // check) does its file work through `host`; the CLI uses Node's (the default). A test, or later a browser, swaps in
3
3
  // another with useHost: memoryHost(files) keeps a workspace in memory, reading anything outside it (the tool's
4
4
  // packages, the published rule sets) from disk.
5
- // host.exists(file) host.readText(file) host.writeText(file, text) host.list(dir) host.mtime(file)
5
+ // host.exists(file) host.readText(file) host.writeText(file, text) host.list(dir) host.mtime(file) host.size(file)
6
6
  // host.remove(file) host.touch(file) host.loadModule(file): a design's module (its main), for a design run in the
7
7
  // tool's own process (a trusted one)
8
8
  // host.runDesign(request): run a design in the sandbox, another process that can't write files, start programs or
@@ -23,11 +23,18 @@ export const nodeHost = {
23
23
  name: 'node',
24
24
  exists: (f) => fs.existsSync(f),
25
25
  readText: (f) => fs.readFileSync(f, 'utf8'),
26
- writeText: (f, text) => { fs.mkdirSync(path.dirname(f), { recursive: true }); fs.writeFileSync(f, text); },
26
+ writeText: (f, text) => {
27
+ fs.mkdirSync(path.dirname(f), { recursive: true });
28
+ fs.writeFileSync(f, text);
29
+ },
27
30
  list: (d) => (fs.existsSync(d) ? fs.readdirSync(d) : []),
28
31
  mtime: (f) => fs.statSync(f).mtimeMs,
32
+ size: (f) => fs.statSync(f).size,
29
33
  remove: (f) => fs.rmSync(f, { force: true }),
30
- touch: (f) => { const now = new Date(); fs.utimesSync(f, now, now); },
34
+ touch: (f) => {
35
+ const now = new Date();
36
+ fs.utimesSync(f, now, now);
37
+ },
31
38
  loadModule: (f) => import(`${pathToFileURL(f).href}?t=${fs.statSync(f).mtimeMs}`), // a fresh copy after each edit
32
39
  runDesign: (request) => import('./sandbox.mjs').then((s) => s.runSandboxed(request)), // (loaded when first used: sandbox.mjs reads the workspace, which reads through this host)
33
40
  };
@@ -36,17 +43,68 @@ let current = nodeHost;
36
43
  /** The host the core uses now. */
37
44
  export const host = new Proxy({}, { get: (_, k) => current[k] });
38
45
  /** Use another host (until the returned function is called). @param {Partial<typeof nodeHost>} h @returns {() => void} */
39
- export function useHost(h) { const before = current; current = { ...nodeHost, ...h }; return () => { current = before; }; }
46
+ export function useHost(h) {
47
+ const before = current;
48
+ current = { ...nodeHost, ...h };
49
+ return () => {
50
+ current = before;
51
+ };
52
+ }
53
+
54
+ // What a file is checked by before readJson reads it: workspace.mjs sets this to its ownFile, so that a JSON file of the
55
+ // workspace (a rule set, a project, a design, an assembly) is read only where it really is inside the workspace, never
56
+ // through a link to a file elsewhere. (Set from there: this module is what workspace.mjs reads its own files with.)
57
+ let guard = (f) => f;
58
+ /**
59
+ * Check every file readJson reads with this first: it returns the file to read, or throws.
60
+ * @param {(f: string) => string} check
61
+ */
62
+ export function guardReads(check) {
63
+ guard = check;
64
+ }
65
+
66
+ /**
67
+ * A text file, read through the host, checked first as readJson checks it: a file of the workspace (a rule set, a
68
+ * design's code) only where it really is inside the workspace. For readers that hash or show the text as it is.
69
+ * @param {string} f
70
+ */
71
+ export const readOwnText = (f) => host.readText(guard(f));
72
+
73
+ /**
74
+ * Whether a cache file is there to be read: a file of the workspace's .cache/ only where it really is inside the
75
+ * workspace. A cloned workspace may hold a .cache/ of its own, and a kept build or stage there that is a link to a file
76
+ * elsewhere would be read as the tool's own and shown, or handed to a design: such a file is a miss, made afresh (and
77
+ * not written through the link: design.mjs ownCacheFile).
78
+ * @param {string} f
79
+ */
80
+ export function cached(f) {
81
+ try {
82
+ guard(f);
83
+ } catch (e) {
84
+ if (e.code === 'workspace.outside') return false;
85
+ throw e;
86
+ }
87
+ return host.exists(f);
88
+ }
40
89
 
41
90
  /** A JSON file, read through the host. One that doesn't parse is named, with where it stops. @param {string} f */
42
91
  export function readJson(f) {
43
- const text = host.readText(f);
44
- try { return JSON.parse(text); } catch (e) { throw new CadError('json', `not valid JSON: ${e.message}`, { file: f, cause: e }); }
92
+ const text = readOwnText(f);
93
+ try {
94
+ return JSON.parse(text);
95
+ } catch (e) {
96
+ throw new CadError('json', `not valid JSON: ${e.message}`, { file: f, cause: e });
97
+ }
45
98
  }
46
99
 
47
100
  // The folder of node_modules the tool finds JSCAD in: a copy of a project in memory reaches its packages through it
48
101
  function toolModules() {
49
- for (let d = path.dirname(createRequire(import.meta.url).resolve('@jscad/modeling')); path.dirname(d) !== d; d = path.dirname(d)) if (path.basename(d) === 'node_modules') return d;
102
+ for (
103
+ let d = path.dirname(createRequire(import.meta.url).resolve('@jscad/modeling'));
104
+ path.dirname(d) !== d;
105
+ d = path.dirname(d)
106
+ )
107
+ if (path.basename(d) === 'node_modules') return d;
50
108
  return null;
51
109
  }
52
110
 
@@ -58,37 +116,81 @@ function toolModules() {
58
116
  * @param {Record<string, string>} files paths relative to root @param {{ root?: string }} [options]
59
117
  */
60
118
  export function memoryHost(files = {}, { root = path.resolve('/rulecad-memory') } = {}) {
61
- const mem = new Map(Object.entries(files).map(([k, v]) => [path.resolve(root, k), v])), times = new Map();
119
+ const mem = new Map(Object.entries(files).map(([k, v]) => [path.resolve(root, k), v])),
120
+ times = new Map();
62
121
  const inside = (f) => path.resolve(f).startsWith(root);
63
122
  const tick = () => Date.now() + times.size;
64
123
  const req = createRequire(import.meta.url);
65
124
  const bare = (spec) => pathToFileURL(req.resolve(spec)).href;
66
125
  return {
67
- name: 'memory', root, files: mem,
68
- exists: (f) => (inside(f) ? mem.has(path.resolve(f)) || [...mem.keys()].some((k) => k.startsWith(path.resolve(f) + path.sep)) : fs.existsSync(f)),
69
- readText: (f) => { if (!inside(f)) return fs.readFileSync(f, 'utf8'); const t = mem.get(path.resolve(f)); if (t == null) throw Object.assign(new Error(`ENOENT: no such file, '${f}'`), { code: 'ENOENT' }); return t; },
70
- writeText: (f, text) => { mem.set(path.resolve(f), text); times.set(path.resolve(f), tick()); },
71
- list: (d) => { if (!inside(d)) return fs.existsSync(d) ? fs.readdirSync(d) : []; const p = path.resolve(d) + path.sep; return [...new Set([...mem.keys()].filter((k) => k.startsWith(p)).map((k) => k.slice(p.length).split(path.sep)[0]))]; },
126
+ name: 'memory',
127
+ root,
128
+ files: mem,
129
+ exists: (f) =>
130
+ inside(f)
131
+ ? mem.has(path.resolve(f)) || [...mem.keys()].some((k) => k.startsWith(path.resolve(f) + path.sep))
132
+ : fs.existsSync(f),
133
+ readText: (f) => {
134
+ if (!inside(f)) return fs.readFileSync(f, 'utf8');
135
+ const t = mem.get(path.resolve(f));
136
+ if (t == null) throw Object.assign(new Error(`ENOENT: no such file, '${f}'`), { code: 'ENOENT' });
137
+ return t;
138
+ },
139
+ writeText: (f, text) => {
140
+ mem.set(path.resolve(f), text);
141
+ times.set(path.resolve(f), tick());
142
+ },
143
+ list: (d) => {
144
+ if (!inside(d)) return fs.existsSync(d) ? fs.readdirSync(d) : [];
145
+ const p = path.resolve(d) + path.sep;
146
+ return [
147
+ ...new Set([...mem.keys()].filter((k) => k.startsWith(p)).map((k) => k.slice(p.length).split(path.sep)[0])),
148
+ ];
149
+ },
72
150
  mtime: (f) => (inside(f) ? times.get(path.resolve(f)) || 0 : fs.statSync(f).mtimeMs),
73
- remove: (f) => { mem.delete(path.resolve(f)); },
74
- touch: (f) => { times.set(path.resolve(f), tick()); },
151
+ size: (f) => (inside(f) ? Buffer.byteLength(mem.get(path.resolve(f)) ?? '', 'utf8') : fs.statSync(f).size),
152
+ remove: (f) => {
153
+ mem.delete(path.resolve(f));
154
+ },
155
+ touch: (f) => {
156
+ times.set(path.resolve(f), tick());
157
+ },
75
158
  loadModule: (f) => {
76
- const src = (inside(f) ? mem.get(path.resolve(f)) : fs.readFileSync(f, 'utf8'))
77
- .replace(/from\s+'(@jscad\/modeling|@rulecad\/shapes)'/g, (_, s) => `from '${bare(s)}'`);
159
+ const src = (inside(f) ? mem.get(path.resolve(f)) : fs.readFileSync(f, 'utf8')).replace(
160
+ /from\s+'(@jscad\/modeling|@rulecad\/shapes)'/g,
161
+ (_, s) => `from '${bare(s)}'`,
162
+ );
78
163
  return import(`data:text/javascript;base64,${Buffer.from(src).toString('base64')}`);
79
164
  },
80
165
  runDesign: async (request) => {
81
- const { d } = request, project = path.resolve(path.dirname(path.dirname(d.js)));
166
+ const { d } = request,
167
+ project = path.resolve(path.dirname(path.dirname(d.js)));
82
168
  if (!inside(d.js)) return nodeHost.runDesign(request); // (a design on disk runs where it is)
83
169
  const tmp = fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(), 'rulecad-memory-design-')));
84
170
  try {
85
171
  const copy = path.join(tmp, 'projects', path.basename(project));
86
- for (const [f, text] of mem) if (f.startsWith(project + path.sep)) { const to = path.join(copy, path.relative(project, f)); fs.mkdirSync(path.dirname(to), { recursive: true }); fs.writeFileSync(to, text); }
172
+ for (const [f, text] of mem)
173
+ if (f.startsWith(project + path.sep)) {
174
+ const to = path.join(copy, path.relative(project, f));
175
+ fs.mkdirSync(path.dirname(to), { recursive: true });
176
+ fs.writeFileSync(to, text);
177
+ }
87
178
  fs.writeFileSync(path.join(tmp, 'package.json'), JSON.stringify({ type: 'module' }));
88
179
  const modules = toolModules();
89
180
  if (modules) fs.symlinkSync(modules, path.join(tmp, 'node_modules'), 'junction');
90
- return await nodeHost.runDesign({ ...request, d: { ...d, js: path.join(copy, path.relative(project, path.resolve(d.js))) }, read: [...(request.read || []), tmp] });
91
- } finally { try { fs.unlinkSync(path.join(tmp, 'node_modules')); } catch {} fs.rmSync(tmp, { recursive: true, force: true }); } // (the link first, on its own: never a walk into the tool's packages)
181
+ return await nodeHost.runDesign({
182
+ ...request,
183
+ d: { ...d, js: path.join(copy, path.relative(project, path.resolve(d.js))) },
184
+ read: [...(request.read || []), tmp],
185
+ });
186
+ } finally {
187
+ try {
188
+ fs.unlinkSync(path.join(tmp, 'node_modules'));
189
+ } catch {
190
+ // (the link was never made, or is gone already: the folder is removed whole below)
191
+ }
192
+ fs.rmSync(tmp, { recursive: true, force: true });
193
+ } // (the link first, on its own: never a walk into the tool's packages)
92
194
  },
93
195
  };
94
196
  }
package/lib/inplace.mjs CHANGED
@@ -22,7 +22,8 @@ function onBed(tris) {
22
22
  for (const t of tris) {
23
23
  if (t.some((p) => Math.abs(p[2]) > BED)) continue;
24
24
  for (let i = 1; i < t.length - 1; i++) {
25
- const [a, b, c] = [t[0], t[i], t[i + 1]], z = (b[0] - a[0]) * (c[1] - a[1]) - (b[1] - a[1]) * (c[0] - a[0]);
25
+ const [a, b, c] = [t[0], t[i], t[i + 1]],
26
+ z = (b[0] - a[0]) * (c[1] - a[1]) - (b[1] - a[1]) * (c[0] - a[0]);
26
27
  if (z < 0) area += -z / 2; // (wound clockwise seen from above: facing down)
27
28
  }
28
29
  }
@@ -31,7 +32,11 @@ function onBed(tris) {
31
32
 
32
33
  // How far apart two boxes are, 0 if they overlap; and the box they share, grown to touch, as where to look
33
34
  const boxGap = (a, b) => Math.hypot(...[0, 1, 2].map((k) => Math.max(0, a.lo[k] - b.hi[k], b.lo[k] - a.hi[k])));
34
- const between = (a, b) => { const lo = [0, 1, 2].map((k) => Math.min(Math.max(a.lo[k], b.lo[k]), Math.min(a.hi[k], b.hi[k]))), hi = [0, 1, 2].map((k) => Math.max(Math.max(a.lo[k], b.lo[k]), Math.min(a.hi[k], b.hi[k]))); return { lo, hi }; };
35
+ const between = (a, b) => {
36
+ const lo = [0, 1, 2].map((k) => Math.min(Math.max(a.lo[k], b.lo[k]), Math.min(a.hi[k], b.hi[k]))),
37
+ hi = [0, 1, 2].map((k) => Math.max(Math.max(a.lo[k], b.lo[k]), Math.min(a.hi[k], b.hi[k])));
38
+ return { lo, hi };
39
+ };
35
40
 
36
41
  // What printcheck only warns of for a part printed alone, and why each can't be printed in place
37
42
  const SUPPORTS = {
@@ -53,59 +58,189 @@ const SUPPORTS = {
53
58
  * @returns {Promise<object[]>}
54
59
  */
55
60
  export async function inPlaceChecks(b, printer, printed = [], o = {}) {
56
- const out = [], f = (level, text, code, extra = {}) => out.push({ level, text, code, ...extra });
57
- const parts = b.parts.filter((p) => p.role !== 'support'), need = printer.print_gap;
58
- if (!(typeof need === 'number' && need > 0)) throw new Error(`printInPlace: the printer's print_gap is the gap each side that prints apart, a number above 0 (got ${JSON.stringify(need)}): add it to the printer's rule set`);
59
- if (parts.length < 2) { f('fail', `printed in place, but ${parts.length ? `only one part (${parts[0].name})` : 'no parts'}: return the parts that move apart as named parts ({ housing, sun, ... }), each described in the .json's parts`, 'inplace.parts'); return out; }
61
+ const out = [],
62
+ f = (level, text, code, extra = {}) => out.push({ level, text, code, ...extra });
63
+ const parts = b.parts.filter((p) => p.role !== 'support'),
64
+ need = printer.print_gap;
65
+ if (!(typeof need === 'number' && need > 0))
66
+ throw new Error(
67
+ `printInPlace: the printer's print_gap is the gap each side that prints apart, a number above 0 (got ${JSON.stringify(need)}): add it to the printer's rule set`,
68
+ );
69
+ if (parts.length < 2) {
70
+ f(
71
+ 'fail',
72
+ `printed in place, but ${parts.length ? `only one part (${parts[0].name})` : 'no parts'}: return the parts that move apart as named parts ({ housing, sun, ... }), each described in the .json's parts`,
73
+ 'inplace.parts',
74
+ );
75
+ return out;
76
+ }
60
77
 
61
78
  // Each on the bed
62
79
  const boxes = new Map(parts.map((p) => [p.name, bounds(p.triangles)]));
63
80
  const off = [];
64
- for (const p of parts) { const area = onBed(p.triangles), box = boxes.get(p.name); if (area < LEAST_BED) off.push({ p, area, box }); }
65
- for (const { p, area, box } of off) f('fail', `${p.name} has ${area > 0 ? `only ${mm(area)} mm²` : 'nothing'} on the bed${box.lo[2] > BED ? ` (its lowest point is ${mm(box.lo[2])} mm up)` : ''}: printed in place, a part that starts on another part is printed onto it and fuses. Give it a face of its own on the bed, slanting at 45° up to the rest of it`, 'inplace.bed', { values: { area, least: LEAST_BED }, at: [(box.lo[0] + box.hi[0]) / 2, (box.lo[1] + box.hi[1]) / 2, box.lo[2]], box, refs: { part: p.name } });
66
- if (!off.length) f('pass', `each of the ${parts.length} parts stands on the bed (${parts.map((p) => `${p.name} ${mm(onBed(p.triangles), 0)} mm²`).join(', ')})`, 'inplace.bed', { values: { parts: Object.fromEntries(parts.map((p) => [p.name, onBed(p.triangles)])) } });
81
+ for (const p of parts) {
82
+ const area = onBed(p.triangles),
83
+ box = boxes.get(p.name);
84
+ if (area < LEAST_BED) off.push({ p, area, box });
85
+ }
86
+ for (const { p, area, box } of off)
87
+ f(
88
+ 'fail',
89
+ `${p.name} has ${area > 0 ? `only ${mm(area)} mm²` : 'nothing'} on the bed${box.lo[2] > BED ? ` (its lowest point is ${mm(box.lo[2])} mm up)` : ''}: printed in place, a part that starts on another part is printed onto it and fuses. Give it a face of its own on the bed, slanting at 45° up to the rest of it`,
90
+ 'inplace.bed',
91
+ {
92
+ values: { area, least: LEAST_BED },
93
+ at: [(box.lo[0] + box.hi[0]) / 2, (box.lo[1] + box.hi[1]) / 2, box.lo[2]],
94
+ box,
95
+ refs: { part: p.name },
96
+ },
97
+ );
98
+ if (!off.length)
99
+ f(
100
+ 'pass',
101
+ `each of the ${parts.length} parts stands on the bed (${parts.map((p) => `${p.name} ${mm(onBed(p.triangles), 0)} mm²`).join(', ')})`,
102
+ 'inplace.bed',
103
+ { values: { parts: Object.fromEntries(parts.map((p) => [p.name, onBed(p.triangles)])) } },
104
+ );
67
105
 
68
106
  // Every two apart by the print gap, measured by Manifold
69
107
  let ops = o.ops;
70
- if (!ops) { try { ops = await booleans('manifold'); } catch { ops = null; } }
71
- if (!ops) { f('warn', 'the gaps between the parts are not measured: they need manifold-3d (npm install manifold-3d in the workspace)', 'inplace.gap'); }
72
- else {
73
- const within = need + 1, gaps = []; // (looking a millimetre past the gap: a pair further apart reads as that)
74
- for (let i = 0; i < parts.length; i++) for (let j = i + 1; j < parts.length; j++) {
75
- const a = parts[i], c = parts[j], ba = boxes.get(a.name), bc = boxes.get(c.name);
76
- if (boxGap(ba, bc) >= within) continue;
77
- let gap;
78
- try { gap = ops.gap(a.geometry, c.geometry, within); } catch (e) { f('warn', `${a.name} and ${c.name}: the gap between them is not measured (${e.message})`, 'inplace.gap', { refs: { parts: [a.name, c.name] } }); continue; }
79
- gaps.push({ a: a.name, b: c.name, gap, box: between(ba, bc) });
108
+ if (!ops) {
109
+ try {
110
+ ops = await booleans('manifold');
111
+ } catch {
112
+ ops = null;
80
113
  }
114
+ }
115
+ if (!ops) {
116
+ f(
117
+ 'warn',
118
+ 'the gaps between the parts are not measured: they need manifold-3d (npm install manifold-3d in the workspace)',
119
+ 'inplace.gap',
120
+ );
121
+ } else {
122
+ const within = need + 1,
123
+ gaps = []; // (looking a millimetre past the gap: a pair further apart reads as that)
124
+ for (let i = 0; i < parts.length; i++)
125
+ for (let j = i + 1; j < parts.length; j++) {
126
+ const a = parts[i],
127
+ c = parts[j],
128
+ ba = boxes.get(a.name),
129
+ bc = boxes.get(c.name);
130
+ if (boxGap(ba, bc) >= within) continue;
131
+ let gap;
132
+ try {
133
+ gap = ops.gap(a.geometry, c.geometry, within);
134
+ } catch (e) {
135
+ f('warn', `${a.name} and ${c.name}: the gap between them is not measured (${e.message})`, 'inplace.gap', {
136
+ refs: { parts: [a.name, c.name] },
137
+ });
138
+ continue;
139
+ }
140
+ gaps.push({ a: a.name, b: c.name, gap, box: between(ba, bc) });
141
+ }
81
142
  const near = gaps.filter((g) => g.gap < need - 1e-3).sort((x, y) => x.gap - y.gap);
82
- for (const g of near) f('fail', `${g.a} and ${g.b} are ${g.gap > 0 ? `${mm(g.gap, 3)} mm apart at their nearest` : 'touching'}, under the ${mm(need)} mm that prints apart (print_gap): printed in place they fuse there. Move them apart, or widen the gap in the design`, 'inplace.gap', { values: { gap: g.gap, need }, at: g.box.lo.map((x, k) => (x + g.box.hi[k]) / 2), box: g.box, refs: { parts: [g.a, g.b] } });
143
+ for (const g of near)
144
+ f(
145
+ 'fail',
146
+ `${g.a} and ${g.b} are ${g.gap > 0 ? `${mm(g.gap, 3)} mm apart at their nearest` : 'touching'}, under the ${mm(need)} mm that prints apart (print_gap): printed in place they fuse there. Move them apart, or widen the gap in the design`,
147
+ 'inplace.gap',
148
+ {
149
+ values: { gap: g.gap, need },
150
+ at: g.box.lo.map((x, k) => (x + g.box.hi[k]) / 2),
151
+ box: g.box,
152
+ refs: { parts: [g.a, g.b] },
153
+ },
154
+ );
83
155
  if (!near.length) {
84
156
  const least = gaps.reduce((m, g) => (!m || g.gap < m.gap ? g : m), null);
85
- f('pass', least ? `every two parts stand ${mm(need)} mm (print_gap) apart or more: the nearest, ${least.a} and ${least.b}, ${mm(least.gap, 3)} mm` : `no two parts come within ${mm(within)} mm of each other`, 'inplace.gap', { values: { gap: least ? least.gap : within, need, pairs: gaps.map(({ a, b: c, gap }) => ({ a, b: c, gap })) }, ...(least ? { refs: { parts: [least.a, least.b] } } : {}) });
157
+ f(
158
+ 'pass',
159
+ least
160
+ ? `every two parts stand ${mm(need)} mm (print_gap) apart or more: the nearest, ${least.a} and ${least.b}, ${mm(least.gap, 3)} mm`
161
+ : `no two parts come within ${mm(within)} mm of each other`,
162
+ 'inplace.gap',
163
+ {
164
+ values: { gap: least ? least.gap : within, need, pairs: gaps.map(({ a, b: c, gap }) => ({ a, b: c, gap })) },
165
+ ...(least ? { refs: { parts: [least.a, least.b] } } : {}),
166
+ },
167
+ );
86
168
  }
87
169
  }
88
170
 
89
171
  // On the first layer: the parts as cut half a layer up, apart by the print gap and the spread each side
90
- const layer = printer.layer ?? 0.2, foot = printer.foot ?? 0, firstNeed = need + 2 * foot;
172
+ const layer = printer.layer ?? 0.2,
173
+ foot = printer.foot ?? 0,
174
+ firstNeed = need + 2 * foot;
91
175
  if (ops && foot > 0) {
92
- const slab = (p) => { const bx = boxes.get(p.name); return ops.intersect(p.geometry, jscad.primitives.cuboid({ size: [bx.hi[0] - bx.lo[0] + 2, bx.hi[1] - bx.lo[1] + 2, layer / 2], center: [(bx.lo[0] + bx.hi[0]) / 2, (bx.lo[1] + bx.hi[1]) / 2, layer / 4] })); };
93
- const low = parts.filter((p) => boxes.get(p.name).lo[2] <= BED).map((p) => ({ name: p.name, g: slab(p), box: boxes.get(p.name) })), near = [];
176
+ const slab = (p) => {
177
+ const bx = boxes.get(p.name);
178
+ return ops.intersect(
179
+ p.geometry,
180
+ jscad.primitives.cuboid({
181
+ size: [bx.hi[0] - bx.lo[0] + 2, bx.hi[1] - bx.lo[1] + 2, layer / 2],
182
+ center: [(bx.lo[0] + bx.hi[0]) / 2, (bx.lo[1] + bx.hi[1]) / 2, layer / 4],
183
+ }),
184
+ );
185
+ };
186
+ const low = parts
187
+ .filter((p) => boxes.get(p.name).lo[2] <= BED)
188
+ .map((p) => ({ name: p.name, g: slab(p), box: boxes.get(p.name) })),
189
+ near = [];
94
190
  let least = null;
95
- for (let i = 0; i < low.length; i++) for (let j = i + 1; j < low.length; j++) {
96
- const a = low[i], c = low[j];
97
- if (boxGap(a.box, c.box) >= firstNeed + 1) continue;
98
- let gap; try { gap = ops.gap(a.g, c.g, firstNeed + 1); } catch { continue; }
99
- if (!least || gap < least.gap) least = { a: a.name, b: c.name, gap };
100
- if (gap < firstNeed - 1e-3) near.push({ a: a.name, b: c.name, gap, box: between(a.box, c.box) });
101
- }
102
- for (const g of near) f('fail', `on the first layer, ${g.a} and ${g.b} are ${mm(g.gap, 3)} mm apart half a layer up, under the ${mm(firstNeed)} mm they need there (print_gap and the first layer's ${mm(foot)} mm spread each side): they print as one. Chamfer their bed edges, or move them apart`, 'inplace.first-layer', { values: { gap: g.gap, need: firstNeed }, at: [(g.box.lo[0] + g.box.hi[0]) / 2, (g.box.lo[1] + g.box.hi[1]) / 2, 0], box: { lo: [g.box.lo[0], g.box.lo[1], 0], hi: [g.box.hi[0], g.box.hi[1], layer] }, refs: { parts: [g.a, g.b] } });
103
- if (!near.length && least) f('pass', `on the first layer, every two parts stand ${mm(firstNeed)} mm apart or more half a layer up (print_gap and the ${mm(foot)} mm spread each side): the nearest, ${least.a} and ${least.b}, ${mm(least.gap, 3)} mm`, 'inplace.first-layer', { values: { gap: least.gap, need: firstNeed }, refs: { parts: [least.a, least.b] } });
191
+ for (let i = 0; i < low.length; i++)
192
+ for (let j = i + 1; j < low.length; j++) {
193
+ const a = low[i],
194
+ c = low[j];
195
+ if (boxGap(a.box, c.box) >= firstNeed + 1) continue;
196
+ let gap;
197
+ try {
198
+ gap = ops.gap(a.g, c.g, firstNeed + 1);
199
+ } catch {
200
+ continue;
201
+ }
202
+ if (!least || gap < least.gap) least = { a: a.name, b: c.name, gap };
203
+ if (gap < firstNeed - 1e-3) near.push({ a: a.name, b: c.name, gap, box: between(a.box, c.box) });
204
+ }
205
+ for (const g of near)
206
+ f(
207
+ 'fail',
208
+ `on the first layer, ${g.a} and ${g.b} are ${mm(g.gap, 3)} mm apart half a layer up, under the ${mm(firstNeed)} mm they need there (print_gap and the first layer's ${mm(foot)} mm spread each side): they print as one. Chamfer their bed edges, or move them apart`,
209
+ 'inplace.first-layer',
210
+ {
211
+ values: { gap: g.gap, need: firstNeed },
212
+ at: [(g.box.lo[0] + g.box.hi[0]) / 2, (g.box.lo[1] + g.box.hi[1]) / 2, 0],
213
+ box: { lo: [g.box.lo[0], g.box.lo[1], 0], hi: [g.box.hi[0], g.box.hi[1], layer] },
214
+ refs: { parts: [g.a, g.b] },
215
+ },
216
+ );
217
+ if (!near.length && least)
218
+ f(
219
+ 'pass',
220
+ `on the first layer, every two parts stand ${mm(firstNeed)} mm apart or more half a layer up (print_gap and the ${mm(foot)} mm spread each side): the nearest, ${least.a} and ${least.b}, ${mm(least.gap, 3)} mm`,
221
+ 'inplace.first-layer',
222
+ { values: { gap: least.gap, need: firstNeed }, refs: { parts: [least.a, least.b] } },
223
+ );
104
224
  }
105
225
 
106
226
  // Nothing that needs a support
107
- const needs = printed.filter((x) => SUPPORTS[x.code] && (x.code === 'print.breakaway' ? x.level === 'pass' && x.values?.area > 0 : x.level === 'warn'));
108
- for (const x of needs) f('fail', `${SUPPORTS[x.code]} (${x.text}): printed in place, no support can come out from between the parts, so it can't be printed. ${x.code === 'print.bridge' ? `Narrow the span to the printer's ${mm(x.values?.max ?? 5)} mm, or slant the underside at 45°` : 'Slant the underside at 45° down to the bed, or give that part a face of its own there'}`, 'inplace.support', { values: { was: x.code, ...(x.values || {}) }, ...(x.at ? { at: x.at } : {}), ...(x.box ? { box: x.box } : {}) });
109
- if (!needs.length) f('pass', 'nothing needs a support: every bridge within what the printer spans, no underside in mid-air or on another part', 'inplace.support');
227
+ const needs = printed.filter(
228
+ (x) =>
229
+ SUPPORTS[x.code] &&
230
+ (x.code === 'print.breakaway' ? x.level === 'pass' && x.values?.area > 0 : x.level === 'warn'),
231
+ );
232
+ for (const x of needs)
233
+ f(
234
+ 'fail',
235
+ `${SUPPORTS[x.code]} (${x.text}): printed in place, no support can come out from between the parts, so it can't be printed. ${x.code === 'print.bridge' ? `Narrow the span to the printer's ${mm(x.values?.max ?? 5)} mm, or slant the underside at 45°` : 'Slant the underside at 45° down to the bed, or give that part a face of its own there'}`,
236
+ 'inplace.support',
237
+ { values: { was: x.code, ...(x.values || {}) }, ...(x.at ? { at: x.at } : {}), ...(x.box ? { box: x.box } : {}) },
238
+ );
239
+ if (!needs.length)
240
+ f(
241
+ 'pass',
242
+ 'nothing needs a support: every bridge within what the printer spans, no underside in mid-air or on another part',
243
+ 'inplace.support',
244
+ );
110
245
  return out;
111
246
  }