@rulecad/cad 0.7.8 → 0.7.10

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/AGENTS.md CHANGED
@@ -90,6 +90,9 @@ variable says which rule it comes from. Follow these steps; they're what makes a
90
90
  `"overhang"` to the way up it will print, so the result needs no supports, and give horizontal bosses and holes a
91
91
  `teardrop` (`"down"`, `"up"`). Draw the part as it prints; if that isn't the problem's frame, give its `analysis` a
92
92
  `rotate` and `move` back. Build with `v.shapes.optimisedSolid(...)` and `"engine": "manifold"`; look at the four views.
93
+ The result is made printable before it's drawn (hanging cells emptied, tips lifted, loose bits dropped), but a kept
94
+ region is never emptied: if `cad optimise` says part of one has nothing holding it up, give the part more material
95
+ to stand it on, or keep less. `cad check` tests the part for one piece and nothing starting in mid-air.
93
96
  - Before reporting numbers for a final shape, verify them: give the `analysis` a smaller `cell` (solids: about a
94
97
  third of the problem's) and check the stiffness has settled (`fea.settled`). Report the verified numbers, the safety
95
98
  factor, and where the peak stress is.
package/README.md CHANGED
@@ -369,8 +369,15 @@ 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.
372
+ A 3D result with a build direction is made printable before it's drawn: built up layer by layer from the bed, every
373
+ cell that nothing holds up (an icicle, a loose bit, a sheet hanging under an edge: whatever the optimiser's smooth
374
+ overhang filter let through) is emptied, with whatever rested on it; a bridge may run out half the printer's span.
375
+ Kept regions always stay, and the optimiser is made to hold them up: a kept cell with nothing under it costs it as
376
+ much as the whole part's compliance. If there wasn't material enough to stand a kept region on, `cad optimise` says
377
+ how much of it is left hanging. Then the drawn surface is tipped back to the printer's overhang limit and any tip left
378
+ hanging in mid-air is lifted, and only the pieces that touch a support, a load or a kept region are kept (a few grey
379
+ cells away from the rest can close into a stray bit). `cad optimise` says how many cells it emptied and pieces it
380
+ dropped, and `cad check` tests the part for one piece and nothing starting in mid-air.
374
381
 
375
382
  `cad optimise <project>/<problem> --watch [port]` runs it afresh and serves a live view at `http://127.0.0.1:8090/`:
376
383
  the densities as they change (a 3D part as a surface you can turn, and 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.
package/bin/cad.mjs CHANGED
@@ -140,7 +140,8 @@ async function optimiseProblem(ref) {
140
140
  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)`); }
141
141
  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}`;
142
142
  const lines = [`${p.material.name}${r.dim === 2 ? `, ${fmt(r.thickness)} mm thick` : ''}: ${r.cases.map((c) => c.moment ? `${c.name} ${sig(c.angle * 180 / Math.PI)}° (${sig(c.torsion / 1000 * Math.PI / 180)} N·m/°)` : `${c.name} ${sig(c.deflection)} mm (${sig(c.stiffness)} N/mm)`).join(', ')}`,
143
- `${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³)` : ''}`];
143
+ `${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³)` : ''}${r.emptied ? `; ${r.emptied} ${r.emptied === 1 ? 'cell' : 'cells'} that wouldn't print emptied` : ''}`,
144
+ ...(r.unsupported > 0.01 ? [`${fmt(r.unsupported * 100)}% of the kept regions has nothing holding it up (at ${r.overhang ? 'the printer\'s overhang limit' : '45°'} or less): give the part more material to stand them on, or keep less`] : [])];
144
145
  let out;
145
146
  if (r.dim === 3) {
146
147
  out = paths.preview(project, `${name.replace(':', '-')}-optimised.png`);
package/lib/live.mjs CHANGED
@@ -59,8 +59,8 @@ function views(d, { nx, ny, nz = 1 }) {
59
59
  const page = (title) => `<!doctype html><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
60
60
  <title>${title}</title>
61
61
  <style>body{font:15px system-ui;background:#111;color:#eee;margin:16px;max-width:900px}canvas{background:#000;border-radius:6px}.chart{width:100%}#hint{color:#888;font-size:12px;text-align:center;margin:-4px 0 8px}#model{height:50vh;margin-bottom:8px;border-radius:6px;overflow:hidden;background:#000;cursor:grab;touch-action:none}#views{display:flex;gap:8px;align-items:flex-end}figure{flex:1;min-width:0;margin:0;text-align:center}figure canvas{width:100%;height:40vh;object-fit:contain;background:none}figcaption{color:#aaa;font-size:13px;text-align:center}
62
- #chart{height:160px;touch-action:none}#scrub{display:flex;gap:8px;align-items:center}#scrub input{flex:1}#live{background:#357}table{border-collapse:collapse;margin:10px 0;width:100%}td{padding:3px 8px 3px 0;vertical-align:top}td:first-child{color:#999;white-space:nowrap;width:1%}button{font:inherit;padding:8px 16px;border-radius:6px;border:0;background:#d33;color:#fff}button:disabled{background:#555}#state{margin:10px 0}</style>
63
- <h2>${title}</h2><div id="state">waiting for the first step…</div><div id="model" hidden></div><div id="hint" hidden>drag to turn it · double-tap to stop or start it turning</div><div id="views"></div><canvas class="chart" id="chart" width="900" height="160"></canvas><div id="scrub"><input type="range" id="at" min="0" max="0" value="0"><button id="live" disabled>Live</button></div><table id="facts"></table>
62
+ #chart{height:160px;touch-action:none}#scrub{display:flex;gap:8px;align-items:center;position:sticky;bottom:0;z-index:2;background:#111;padding:10px 0;border-top:1px solid #222}#scrub input{flex:1;height:32px}#at-step{color:#aaa;font-size:13px;min-width:5.5em}#live{background:#357}table{border-collapse:collapse;margin:10px 0;width:100%}td{padding:3px 8px 3px 0;vertical-align:top}td:first-child{color:#999;white-space:nowrap;width:1%}button{font:inherit;padding:8px 16px;border-radius:6px;border:0;background:#d33;color:#fff}button:disabled{background:#555}#state{margin:10px 0}</style>
63
+ <h2>${title}</h2><div id="state">waiting for the first step…</div><div id="model" hidden></div><div id="hint" hidden>drag to turn it · double-tap to stop or start it turning</div><div id="views"></div><canvas class="chart" id="chart" width="900" height="160"></canvas><div id="scrub"><span id="at-step"></span><input type="range" id="at" min="0" max="0" value="0"><button id="live" disabled>Live</button></div><table id="facts"></table>
64
64
  <p><button id="stop">Stop the run</button> <span id="note"></span></p>
65
65
  <script>
66
66
  const views = document.getElementById('views'), facts = document.getElementById('facts'), state = document.getElementById('state'), stop = document.getElementById('stop');
@@ -78,6 +78,7 @@ function table() {
78
78
  ...(f.volume != null ? [['Material', fig(f.volume * 100) + '% of the space']] : []), ...(f.stress != null ? [['Peak stress', fig(f.stress) + ' MPa']] : []),
79
79
  ['Cells', [f.grid.nx, f.grid.ny, f.grid.nz].filter(Boolean).join(' × ') + (f.grid.h ? ' of ' + f.grid.h + ' mm' : '') + ' (' + (f.grid.nx * f.grid.ny * (f.grid.nz || 1)).toLocaleString('en-GB') + ')'],
80
80
  ] : [];
81
+ document.getElementById('at-step').textContent = f ? 'step ' + f.step : '';
81
82
  facts.innerHTML = [...(finished ? [['Result', finished]] : []), ...rows, ...about].map(([k, v]) => '<tr><td>' + esc(k) + '</td><td>' + esc(v) + '</td></tr>').join('');
82
83
  }
83
84
  function draw(f) {
@@ -107,7 +108,9 @@ function plot() {
107
108
  c.font = '12px system-ui'; c.fillStyle = '#6cf'; c.fillText('compliance, N·mm: ' + fig(history.compliance[0]) + ' to ' + fig(history.compliance.at(-1)), 8, 14);
108
109
  c.fillStyle = '#fc6'; c.textAlign = 'right'; c.fillText('change (log scale): ' + fig(history.change[0]) + ' to ' + fig(history.change.at(-1)), w - 8, 14); c.textAlign = 'left';
109
110
  }
110
- function show(f) { draw(f); plot(); table(); window.model3d?.(shown, f.grid); }
111
+ // The 3D view's step: remembered, so the 3D script picks it up when it loads (it loads after the first steps arrive)
112
+ const want3d = (n, grid) => { window.wanted3d = [n, grid]; window.model3d?.(n, grid); };
113
+ function show(f) { draw(f); plot(); table(); want3d(shown, f.grid); }
111
114
  let lastModel = 0; // while following, a new surface at most every two seconds
112
115
  // Scrubbing: any earlier step, fetched when asked for; the newest only while following
113
116
  let asked = 0;
@@ -126,7 +129,7 @@ events.onmessage = (e) => { const m = JSON.parse(e.data); if (m.about) about = m
126
129
  if (m.done) { finished = m.done; stop.disabled = true; events.close(); }
127
130
  at.max = Math.max(0, history.compliance.length - 1);
128
131
  if (m.frame) newest = m.frame;
129
- if (follow) { shown = Number(at.max); at.value = shown; if (newest) draw(newest); if (Date.now() - lastModel > 2000 || finished) { lastModel = Date.now(); window.model3d?.(shown, newest.grid); } }
132
+ if (follow) { shown = Number(at.max); at.value = shown; if (newest) draw(newest); if (Date.now() - lastModel > 2000 || finished) { lastModel = Date.now(); want3d(shown, newest.grid); } }
130
133
  if (finished) state.textContent = finished;
131
134
  plot(); table(); };
132
135
  stop.onclick = async () => { stop.disabled = true; await fetch('stop', { method: 'POST' }); document.getElementById('note').textContent = 'stopping after this step'; };
@@ -152,7 +155,9 @@ function setup() {
152
155
  const w = box.clientWidth, h = box.clientHeight;
153
156
  if (w && (c.width !== Math.round(w * devicePixelRatio) || c.height !== Math.round(h * devicePixelRatio))) { renderer.setPixelRatio(devicePixelRatio); renderer.setSize(w, h); camera.aspect = w / h; camera.updateProjectionMatrix(); }
154
157
  if (spin) yaw += 0.004;
155
- const d = size / Math.sin(camera.fov * Math.PI / 360) * 0.8; // the part seldom fills its grid's corners camera.position.set(d * Math.cos(tilt) * Math.cos(yaw), d * Math.cos(tilt) * Math.sin(yaw), d * Math.sin(tilt)); camera.lookAt(0, 0, 0);
158
+ // Far enough to fit the grid's half-diagonal in view, less a little: the part seldom fills its grid's corners
159
+ const d = size / Math.sin(camera.fov * Math.PI / 360) * 0.8;
160
+ camera.position.set(d * Math.cos(tilt) * Math.cos(yaw), d * Math.cos(tilt) * Math.sin(yaw), d * Math.sin(tilt)); camera.lookAt(0, 0, 0);
156
161
  renderer.render(scene, camera); requestAnimationFrame(tick);
157
162
  };
158
163
  tick();
@@ -181,6 +186,7 @@ async function load(n, grid) {
181
186
  }
182
187
  }
183
188
  window.model3d = (n, grid) => { if (!box.hidden && grid) load(n, grid); };
189
+ if (window.wanted3d) window.model3d(...window.wanted3d);
184
190
  </script>`;
185
191
 
186
192
  const THREE = path.dirname(createRequire(import.meta.url).resolve('three')); // three's build files, for the 3D view
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, bounds, resultant } from '@rulecad/topopt';
14
+ import { discretise, optimise, outlines, surface, area, bounds, resultant, printable } 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
@@ -75,7 +75,7 @@ export async function readProblem(project, ref) {
75
75
  if (dim === 2 && !(problem.thickness > 0)) throw new Error(`${path.basename(file)}: a flat (2D) problem needs a thickness`);
76
76
  const outline = { smooth: p.outline?.smooth ?? 4, minArea: p.outline?.min_area != null ? ev(p.outline.min_area) : problem.cell ** 2 * 2 };
77
77
  // A printable solid's surface is kept within the printer's overhang limit too (smoothing can tip faces past it)
78
- if (dim === 3 && problem.overhang) { const n = printerOf(project), pr = resolve({ uses: [n] }).values[n]; outline.overhang = { up: problem.overhang, angle: pr?.overhang ?? 45 }; }
78
+ if (dim === 3 && problem.overhang) { const n = printerOf(project), pr = resolve({ uses: [n] }).values[n]; outline.overhang = { up: problem.overhang, angle: pr?.overhang ?? 45, bridge: pr?.bridge ?? 5 }; }
79
79
  return { ref, name, variant, file, dim, title: p.title || name, material: { name: p.material, ...m }, problem, outline, critical: !!p.critical };
80
80
  }
81
81
 
@@ -104,7 +104,16 @@ export async function optimised(project, ref, { onStep, fresh = false } = {}) {
104
104
  })() : (() => {
105
105
  // The surface's level, found so the solid holds as much material as the optimised densities do (drawn at 0.5,
106
106
  // thin members come out thinner than they are)
107
- const want = o.density.reduce((t, d) => t + d, 0) * spec.grid.h ** 3, at = (iso) => surface(spec.grid, o.density, spec.origin, { smooth: r.outline.smooth, iso, overhang: r.outline.overhang });
107
+ // Printed without supports: before it's drawn at a level, whatever wouldn't print at that level (hanging with nothing
108
+ // under it) is emptied (printable, in topopt); kept regions stay. A bridge may run out half the printer's span.
109
+ const ov = r.outline.overhang, keep = Uint8Array.from(spec.passive, (p) => (p === 1 ? 1 : 0)), emptied = new Map();
110
+ const clean = (iso) => {
111
+ if (!ov) return o.density;
112
+ const c = printable(spec.grid, o.density, { up: ov.up, iso, keep, reach: Math.floor(ov.bridge / 2 / spec.grid.h) });
113
+ emptied.set(iso, c.emptied);
114
+ return c.density;
115
+ };
116
+ const want = o.density.reduce((t, d) => t + d, 0) * spec.grid.h ** 3, at = (iso) => surface(spec.grid, clean(iso), spec.origin, { smooth: r.outline.smooth, iso, overhang: ov });
108
117
  let lo = 0.2, hi = 0.8, best = at(0.5), iso = 0.5;
109
118
  for (let k = 0; k < 10 && Math.abs(meshVolume(best.vertices, best.faces) / want - 1) > 0.003; k++) {
110
119
  if (meshVolume(best.vertices, best.faces) < want) hi = iso; else lo = iso; // a lower level encloses more
@@ -112,12 +121,12 @@ export async function optimised(project, ref, { onStep, fresh = false } = {}) {
112
121
  }
113
122
  const anchors = [...r.problem.supports, ...r.problem.loads, ...(r.problem.keep || [])].map(bounds);
114
123
  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 } : {}) };
124
+ return { mesh: { vertices: vertices.map((v) => v.map((c) => round(c, 3))), faces }, solid: meshVolume(vertices, faces), iso, ...(dropped.length ? { dropped } : {}), ...(emptied.get(iso) ? { emptied: emptied.get(iso) } : {}) };
116
125
  })();
117
126
  const result = {
118
127
  problem: ref, title: r.title, hash, dim: r.dim, material: r.material.name, ...(r.dim === 2 ? { thickness: r.problem.thickness } : {}),
119
128
  grid: spec.grid, origin: spec.origin, regions: { keep: named(spec.regions.keep), avoid: named(spec.regions.avoid) }, ...shape,
120
- volume: o.volume, compliance: o.compliance, cases: o.cases, ...(o.stress ? { stress: o.stress } : {}), overhang: r.problem.overhang || null,
129
+ volume: o.volume, compliance: o.compliance, cases: o.cases, ...(o.unsupported ? { unsupported: o.unsupported } : {}), ...(o.stress ? { stress: o.stress } : {}), overhang: r.problem.overhang || null,
121
130
  steps: o.steps, converged: o.converged, seconds: o.seconds, history: o.history, density: Array.from(o.density, (d) => round(d, 3)),
122
131
  supports: named(r.problem.supports), loads: named(r.problem.loads),
123
132
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@rulecad/cad",
3
- "version": "0.7.8",
3
+ "version": "0.7.10",
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": {