@rulecad/cad 0.7.5 → 0.7.6

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.
package/README.md CHANGED
@@ -369,6 +369,9 @@ with numbers as expressions like an object's (schema: `schemas/problem.schema.js
369
369
  gives, and draws the layout in `.preview/`. The result is kept, keyed by everything it's made from, so it's only
370
370
  worked out again when something it depends on changes.
371
371
 
372
+ A 3D result keeps only the pieces that touch a support, a load or a kept region. A few grey cells away from the rest
373
+ can close into a piece of their own, which would print as a stray bit. `cad optimise` says how many it dropped.
374
+
372
375
  `cad optimise <project>/<problem> --watch [port]` runs it afresh and serves a live view at `http://127.0.0.1:8090/`:
373
376
  the densities as they change (a 3D part from three sides), a chart of its compliance and how much it still changes, with a scrubber to look back at any earlier step, its run time and time left, the machine it runs on, and a button that stops the run. It shows the end for ten minutes after the run finishes.
374
377
  It listens on this computer only. To watch from elsewhere, reach it through a private network such as Tailscale.
package/bin/cad.mjs CHANGED
@@ -137,7 +137,7 @@ async function optimiseProblem(ref) {
137
137
  if (view) { view.close(`finished: ${r.steps} steps${r.converged ? '' : ', not settled'}`, { hold: 10 * 60e3 }); say(`the live view shows the result for ten more minutes (Ctrl-C to stop it)`); }
138
138
  const p = await readProblem(project, name), cells = r.dim === 3 ? `${r.grid.nx} × ${r.grid.ny} × ${r.grid.nz}` : `${r.grid.nx} × ${r.grid.ny}`;
139
139
  const lines = [`${p.material.name}${r.dim === 2 ? `, ${fmt(r.thickness)} mm thick` : ''}: ${r.cases.map((c) => `${c.name} ${sig(c.deflection)} mm (${sig(c.stiffness)} N/mm)`).join(', ')}`,
140
- `${fmt(r.volume * 100)}% of the space, ${cells} cells of ${fmt(r.grid.h)} mm, ${r.steps} steps${r.converged ? '' : ' (stopped: not settled)'}${r.overhang ? `, printable built ${r.overhang}` : ''}${r.stress ? `, peak stress ${sig(r.stress.peak)} MPa (limit ${sig(r.stress.limit)})` : ''}`];
140
+ `${fmt(r.volume * 100)}% of the space, ${cells} cells of ${fmt(r.grid.h)} mm, ${r.steps} steps${r.converged ? '' : ' (stopped: not settled)'}${r.overhang ? `, printable built ${r.overhang}` : ''}${r.stress ? `, peak stress ${sig(r.stress.peak)} MPa (limit ${sig(r.stress.limit)})` : ''}${r.dropped ? `; ${r.dropped.length} loose ${r.dropped.length === 1 ? 'piece' : 'pieces'} dropped (${sig(r.dropped.reduce((t, v) => t + v, 0))} mm³)` : ''}`];
141
141
  let out;
142
142
  if (r.dim === 3) {
143
143
  out = paths.preview(project, `${name.replace(':', '-')}-optimised.png`);
package/lib/optimise.mjs CHANGED
@@ -11,7 +11,7 @@ import { host } from './host.mjs';
11
11
  import { paths, printerOf } from './workspace.mjs';
12
12
  import { resolve, evaluate } from './rules.mjs';
13
13
  import { located } from './errors.mjs';
14
- import { discretise, optimise, outlines, surface, area } from '@rulecad/topopt';
14
+ import { discretise, optimise, outlines, surface, area, bounds } from '@rulecad/topopt';
15
15
  import { grid as makeGrid, analyse, positions } from '@rulecad/fea';
16
16
 
17
17
  const VERSION = 2, source = (m) => fs.readFileSync(new URL(import.meta.resolve(m)), 'utf8'); // the solver's code: a change remakes results
@@ -90,7 +90,8 @@ export async function optimised(project, ref, { onStep, fresh = false } = {}) {
90
90
  const digest = (x) => crypto.createHash('sha256').update(JSON.stringify(x)).digest('hex');
91
91
  // Two keeps: the densities, by the problem and the code that decides them (the slow part), and the shape drawn from
92
92
  // them, by everything: a change to how shapes are drawn redraws them without optimising again
93
- const hash = digest([VERSION, r.problem, r.outline, topopt, source('@rulecad/fea')]), file = paths.cache('optimise', `${hash}.json`);
93
+ // The shape's key holds this file too, so a change to how cad draws a result (anchored below) redraws it
94
+ const hash = digest([VERSION, r.problem, r.outline, topopt, source('@rulecad/fea'), fs.readFileSync(new URL(import.meta.url), 'utf8')]), file = paths.cache('optimise', `${hash}.json`);
94
95
  if (!fresh && !process.env.CAD_NO_CACHE && host.exists(file)) return { ...JSON.parse(host.readText(file)), cached: true };
95
96
  const spec = discretise(r.problem), densities = paths.cache('densities', `${digest([VERSION, r.problem, solver, source('@rulecad/fea')])}.json`);
96
97
  const o = !fresh && !process.env.CAD_NO_CACHE && host.exists(densities) ? (({ density, ...x }) => ({ ...x, density: Float64Array.from(density) }))(JSON.parse(host.readText(densities))) : optimise(spec, { onStep: onStep && ((st) => onStep({ ...st, grid: spec.grid })) });
@@ -109,8 +110,9 @@ export async function optimised(project, ref, { onStep, fresh = false } = {}) {
109
110
  if (meshVolume(best.vertices, best.faces) < want) hi = iso; else lo = iso; // a lower level encloses more
110
111
  iso = (lo + hi) / 2; best = at(iso);
111
112
  }
112
- const { vertices, faces } = best;
113
- return { mesh: { vertices: vertices.map((v) => v.map((c) => round(c, 3))), faces }, solid: meshVolume(vertices, faces), iso };
113
+ const anchors = [...r.problem.supports, ...r.problem.loads, ...(r.problem.keep || [])].map(bounds);
114
+ const { vertices, faces, dropped } = anchored(best, anchors, spec.grid.h);
115
+ return { mesh: { vertices: vertices.map((v) => v.map((c) => round(c, 3))), faces }, solid: meshVolume(vertices, faces), iso, ...(dropped.length ? { dropped } : {}) };
114
116
  })();
115
117
  const result = {
116
118
  problem: ref, title: r.title, hash, dim: r.dim, material: r.material.name, ...(r.dim === 2 ? { thickness: r.problem.thickness } : {}),
@@ -303,3 +305,26 @@ export function picture(r, { title = '', lines = [] } = {}) {
303
305
  </svg>
304
306
  `;
305
307
  }
308
+
309
+ // Loose pieces: drawn from cells, a few grey cells away from the rest can close into a piece of their own, which would
310
+ // print as a stray bit. Only pieces touching a support, a load or a kept region (within a cell) stay; the volumes of
311
+ // the rest, mm³, come back as dropped.
312
+ export function anchored({ vertices, faces }, anchors, h) {
313
+ const up = vertices.map((_, i) => i), find = (i) => { while (up[i] !== i) i = up[i] = up[up[i]]; return i; };
314
+ for (const [a, b, c] of faces) { up[find(a)] = find(b); up[find(b)] = find(c); }
315
+ const pieces = new Map();
316
+ for (const f of faces) {
317
+ const r = find(f[0]), p = pieces.get(r) ?? { faces: [], lo: [Infinity, Infinity, Infinity], hi: [-Infinity, -Infinity, -Infinity] };
318
+ p.faces.push(f);
319
+ for (const v of f) for (let k = 0; k < 3; k++) { p.lo[k] = Math.min(p.lo[k], vertices[v][k]); p.hi[k] = Math.max(p.hi[k], vertices[v][k]); }
320
+ pieces.set(r, p);
321
+ }
322
+ if (pieces.size < 2) return { vertices, faces, dropped: [] };
323
+ const touches = (p) => anchors.some((b) => [0, 1, 2].every((k) => p.lo[k] <= b[3 + k] + h && p.hi[k] >= b[k] - h));
324
+ const kept = [], dropped = [];
325
+ for (const p of pieces.values()) (touches(p) ? kept : dropped).push(p);
326
+ if (!kept.length) return { vertices, faces, dropped: [] }; // nothing anchored: keep it all rather than nothing
327
+ const index = new Map(), out = [];
328
+ const keptFaces = kept.flatMap((p) => p.faces).map((f) => f.map((v) => { if (!index.has(v)) { index.set(v, out.length); out.push(vertices[v]); } return index.get(v); }));
329
+ return { vertices: out, faces: keptFaces, dropped: dropped.map((p) => round(meshVolume(vertices, p.faces), 3)) };
330
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@rulecad/cad",
3
- "version": "0.7.5",
3
+ "version": "0.7.6",
4
4
  "description": "The cad command: JSCAD designs from traceable rules, checked for printing and fit, versioned by what fits, shared as links and exported as Bambu 3MF.",
5
5
  "type": "module",
6
6
  "bin": {