@rulecad/cad 0.7.2 → 0.7.4

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
@@ -93,6 +93,8 @@ variable says which rule it comes from. Follow these steps; they're what makes a
93
93
  - Before reporting numbers for a final shape, verify them: give the `analysis` a smaller `cell` (solids: about a
94
94
  third of the problem's) and check the stiffness has settled (`fea.settled`). Report the verified numbers, the safety
95
95
  factor, and where the peak stress is.
96
+ - For a part that must not break (a lever, a pedal), give its problem a `"stress"` limit (the material's strength
97
+ over a safety factor) instead of a `"volume"`: the lightest layout under it. Then verify it on finer cells.
96
98
  - Mark a problem `"critical": true` if the part could hurt someone if it broke. Say plainly that the analysis is a
97
99
  design aid and the material values are data-sheet figures: such a part needs testing, recorded under
98
100
  `"verification"`, not just a check.
package/README.md CHANGED
@@ -357,12 +357,22 @@ with numbers as expressions like an object's (schema: `schemas/problem.schema.js
357
357
  `ss304`, `ti64` come with rulecad. Printed values vary: measure yours.
358
358
  - **Settings:** `volume`, the share of the space to fill; `cell`, the grid (smaller is finer and slower: a 140 × 40
359
359
  grid takes about half a minute); `filter`, about the thinnest member, in mm.
360
+ - **Or a stress limit instead of a volume:** `"stress": "pla.strength / 3"` (MPa) finds the lightest layout that keeps
361
+ every cell's von Mises stress under it, which rounds off the sharp inside corners where cracks start. It takes about
362
+ a thousand steps, each with two solves, so it's slower: give it a coarse cell first. Give supports and loads some
363
+ area (a hole's edge, a pad), as stress where a load meets a point has no limit. `cad optimise` reports the peak
364
+ stress against the limit. Check the final part with an `analysis` on a finer `cell`: a sharp corner that's
365
+ within the limit on the optimiser's cells can still be over it on finer ones.
360
366
  - **Variants**, picked as `name:variant`, set variables that have a tweak range, as an object's do.
361
367
 
362
368
  `cad optimise <project>/<problem>` runs it, reports how far each load case moves its load and the stiffness that
363
369
  gives, and draws the layout in `.preview/`. The result is kept, keyed by everything it's made from, so it's only
364
370
  worked out again when something it depends on changes.
365
371
 
372
+ `cad optimise <project>/<problem> --watch [port]` runs it afresh and serves a live view at `http://127.0.0.1:8090/`:
373
+ the densities as they change (a 3D part from three sides), a chart of its compliance, and a button that stops the run.
374
+ It listens on this computer only. To watch from elsewhere, reach it through a private network such as Tailscale.
375
+
366
376
  A design uses it through a variable of type `problem`, which picks a problem by name:
367
377
 
368
378
  ```json
package/bin/cad.mjs CHANGED
@@ -20,6 +20,7 @@ import { optimised, readProblem, analysePart, picture, problemFile } from '../li
20
20
  import { evaluate } from '../lib/rules.mjs';
21
21
  import { setVariables, addToAssembly, parseValue } from '../lib/edit.mjs';
22
22
  import { threemf, slotOf } from '../lib/threemf.mjs';
23
+ import { liveView } from '../lib/live.mjs';
23
24
  import { filaments, slots, linkTo, objectModel, assemblyModel, VIEW } from '../lib/links.mjs';
24
25
 
25
26
  // What the print file asks of the AMS: which filament each kind of part prints in
@@ -48,6 +49,7 @@ const HELP = `cad: JSCAD designs you can trace, check, share and print (rulecad)
48
49
  cad preview <project>/<object> four views as a PNG in .preview/ (prints the path)
49
50
  cad optimise <project>/<problem> the stiffest layout for a problem in the project's problems/ (name:variant for a
50
51
  variant): a picture in .preview/, the result kept for designs [--fresh] [--json]
52
+ [--watch [port]: a live view of it at http://127.0.0.1:8090/, with a stop button]
51
53
  cad export <project>/<object> a 3MF for Bambu Studio in exports/ [--open: open it in Bambu Studio]
52
54
  cad show <project>/<object> the model on display through your show target, with its rules [--ttl 10m]
53
55
  cad link <project>/<object> links to open the model in a browser, and to download its STL or 3MF
@@ -121,11 +123,20 @@ async function optimiseProblem(ref) {
121
123
  if (bad.length) { report(bad); process.exitCode = 1; return; }
122
124
  }
123
125
  const live = !opt('json') && process.stderr.isTTY;
124
- const r = await optimised(project, name, { fresh: !!opt('fresh'), onStep: (s) => live && process.stderr.write(`\r\x1b[Kstep ${s.step}/${s.steps} compliance ${s.compliance.toPrecision(5)} N·mm change ${s.change.toFixed(3)} sharpness ${s.beta}`) });
125
- if (live) process.stderr.write('\r\x1b[K');
126
+ // --watch [port]: the live view, served while it runs (a watched run is always run afresh, so there is something to watch)
127
+ const watch = opt('watch'), view = watch ? await liveView({ port: watch === true ? 8090 : Number(watch), title: `cad optimise ${ref}` }) : null;
128
+ if (view) say(`watching at ${view.url}`);
129
+ let r;
130
+ try {
131
+ r = await optimised(project, name, { fresh: !!opt('fresh') || !!view, onStep: (s) => {
132
+ if (live) process.stderr.write(`\r\x1b[Kstep ${s.step}/${s.steps} compliance ${s.compliance.toPrecision(5)} N·mm change ${s.change.toFixed(3)} sharpness ${s.beta}`);
133
+ if (view) { view.step(s); if (view.stopped()) throw new Error(`stopped from the live view at step ${s.step}`); }
134
+ } });
135
+ } catch (e) { await view?.close(e.message); throw e; } finally { if (live) process.stderr.write('\r\x1b[K'); }
136
+ await view?.close(`finished: ${r.steps} steps${r.converged ? '' : ', not settled'}`);
126
137
  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}`;
127
138
  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(', ')}`,
128
- `${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}` : ''}`];
139
+ `${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)})` : ''}`];
129
140
  let out;
130
141
  if (r.dim === 3) {
131
142
  out = paths.preview(project, `${name.replace(':', '-')}-optimised.png`);
@@ -139,6 +150,7 @@ async function optimiseProblem(ref) {
139
150
  if (opt('json')) return console.log(JSON.stringify((({ density, history, mesh, ...x }) => x)(r), null, 2));
140
151
  console.log(`${r.title}${r.cached ? ' (cached)' : ` (${fmt(r.seconds)} s)`}`);
141
152
  for (const c of r.cases) console.log(` ${c.name}: moves ${sig(c.deflection)} mm along its load, ${sig(c.stiffness)} N/mm`);
153
+ if (r.stress) console.log(` peak stress ${sig(r.stress.peak)} MPa, the limit ${sig(r.stress.limit)} MPa${r.stress.peak > r.stress.limit * 1.02 ? ': over it (raise the volume, ease the limit, or use a smaller cell)' : ''}`);
142
154
  if (r.dim === 3) console.log(` ${fmt(r.volume * 100)}% of the space filled: ${fmt(r.solid / 1000)} cm³ (${fmt(r.solid / 1000 * (p.material.density || 0))} g of ${p.material.name})${r.overhang ? `, printable built ${r.overhang}` : ''}`);
143
155
  else console.log(` ${fmt(r.volume * 100)}% of the space filled, outline ${fmt(r.area)} mm² (${fmt(r.area * r.thickness / 1000)} cm³ before bosses and holes are made exact)`);
144
156
  console.log(` ${cells} cells of ${fmt(r.grid.h)} mm, ${r.steps} steps${r.converged ? ', settled' : ': stopped before it settled (raise steps)'}`);
package/lib/live.mjs ADDED
@@ -0,0 +1,108 @@
1
+ // The live view of an optimisation: `cad optimise <ref> --watch [port]` serves a page that draws the densities as
2
+ // they change, charts the progress and can stop the run. The optimiser runs on the main thread and blocks it, so the
3
+ // server runs in a worker: the main thread posts each step to it, and the page's stop button sets a shared flag the
4
+ // main thread reads between steps.
5
+ import http from 'node:http';
6
+ import { Worker, isMainThread, parentPort, workerData } from 'node:worker_threads';
7
+
8
+ /**
9
+ * Starts the server; resolves once it listens.
10
+ * @param {{ port?: number, host?: string, title: string }} o host: 127.0.0.1 unless asked (Tailscale's userspace mode
11
+ * forwards to it; plain 0.0.0.0 would open it to the local network)
12
+ * @returns {Promise<{ url: string, step: (s: object) => void, stopped: () => boolean, close: (summary?: string) => Promise<void> }>}
13
+ */
14
+ export function liveView({ port = 8090, host = '127.0.0.1', title }) {
15
+ const flag = new Int32Array(new SharedArrayBuffer(4));
16
+ const worker = new Worker(new URL(import.meta.url), { workerData: { port, host, title, flag } });
17
+ return new Promise((resolve, reject) => {
18
+ worker.once('error', reject);
19
+ worker.once('message', (m) => {
20
+ if (m.error) { worker.terminate(); reject(new Error(`the live view can't listen on ${host}:${port}: ${m.error}`)); return; }
21
+ worker.off('error', reject).on('error', (e) => console.error(`the live view stopped: ${e.message}`));
22
+ resolve({
23
+ url: `http://${host === '0.0.0.0' ? 'localhost' : host}:${m.listening}/`,
24
+ step: (s) => {
25
+ const list = views(s.density, s.grid);
26
+ worker.postMessage({ step: s.step, steps: s.steps, compliance: s.compliance, change: s.change, beta: s.beta, volume: s.volume, stress: s.stress, views: list }, list.map((v) => v.image.buffer));
27
+ },
28
+ stopped: () => Atomics.load(flag, 0) === 1,
29
+ close: (summary) => new Promise((done) => { worker.once('exit', () => done()); worker.postMessage({ done: summary ?? 'finished' }); }),
30
+ });
31
+ });
32
+ });
33
+ }
34
+
35
+ // Densities as bytes, one per pixel: a 2D layout as it is, a 3D grid as three views, each pixel the densest cell
36
+ // along its line of sight
37
+ function views(d, { nx, ny, nz = 1 }) {
38
+ const view = (name, w, h) => ({ name, w, h, image: new Uint8Array(w * h) });
39
+ const z = view(nz > 1 ? 'along z' : '', nx, ny), y = view('along y', nx, nz), x = view('along x', ny, nz);
40
+ for (let k = 0; k < nz; k++) for (let j = 0; j < ny; j++) for (let i = 0; i < nx; i++) {
41
+ const v = Math.round(d[(k * ny + j) * nx + i] * 255);
42
+ if (v > z.image[j * nx + i]) z.image[j * nx + i] = v;
43
+ if (v > y.image[k * nx + i]) y.image[k * nx + i] = v;
44
+ if (v > x.image[k * ny + j]) x.image[k * ny + j] = v;
45
+ }
46
+ return nz > 1 ? [y, x, z] : [z];
47
+ }
48
+
49
+ const page = (title) => `<!doctype html><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
50
+ <title>${title}</title>
51
+ <style>body{font:15px system-ui;background:#111;color:#eee;margin:16px;max-width:900px}canvas{background:#000;border-radius:6px}#chart{width:100%}#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}
52
+ #chart{height:140px;image-rendering:auto}button{font:inherit;padding:8px 16px;border-radius:6px;border:0;background:#d33;color:#fff}button:disabled{background:#555}#state{margin:10px 0}</style>
53
+ <h2>${title}</h2><div id="state">waiting for the first step…</div><div id="views"></div><canvas id="chart" width="900" height="140"></canvas>
54
+ <p><button id="stop">Stop the run</button> <span id="note"></span></p>
55
+ <script>
56
+ const views = document.getElementById('views'), chart = document.getElementById('chart'), state = document.getElementById('state'), stop = document.getElementById('stop');
57
+ let history = [];
58
+ const fig = (n) => Number(n.toPrecision(3));
59
+ function draw(f) {
60
+ if (views.children.length !== f.views.length) views.innerHTML = f.views.map((v) => '<figure><canvas></canvas><figcaption>' + v.name + '</figcaption></figure>').join('');
61
+ f.views.forEach((v, n) => {
62
+ const c = views.children[n].firstChild; if (c.width !== v.w) { c.width = v.w; c.height = v.h; }
63
+ const ctx = c.getContext('2d'), img = ctx.createImageData(v.w, v.h), d = atob(v.image);
64
+ for (let j = 0; j < v.h; j++) for (let i = 0; i < v.w; i++) { const g = 255 - d.charCodeAt(j * v.w + i), o = ((v.h - 1 - j) * v.w + i) * 4; img.data[o] = img.data[o + 1] = img.data[o + 2] = g; img.data[o + 3] = 255; }
65
+ ctx.putImageData(img, 0, 0);
66
+ });
67
+ state.textContent = 'step ' + f.step + ' of ' + f.steps + ' · compliance ' + fig(f.compliance) + ' N·mm' + (f.volume != null ? ' · ' + fig(f.volume * 100) + '% of the space' : '') + (f.stress != null ? ' · peak stress ' + fig(f.stress) + ' MPa' : '') + ' · sharpness ' + f.beta;
68
+ }
69
+ function plot() {
70
+ const c = chart.getContext('2d'), w = chart.width, h = chart.height; c.clearRect(0, 0, w, h);
71
+ if (history.length < 2) return;
72
+ const lo = Math.min(...history), hi = Math.max(...history) || 1; c.strokeStyle = '#6cf'; c.lineWidth = 2; c.beginPath();
73
+ history.forEach((v, k) => { const x = k / (history.length - 1) * w, y = h - 8 - (v - lo) / (hi - lo || 1) * (h - 16); k ? c.lineTo(x, y) : c.moveTo(x, y); });
74
+ c.stroke(); c.fillStyle = '#aaa'; c.fillText('compliance: ' + fig(hi) + ' to ' + fig(history.at(-1)) + ' N·mm', 8, 14);
75
+ }
76
+ const events = new EventSource('events');
77
+ events.onmessage = (e) => { const m = JSON.parse(e.data); if (m.history) history = m.history; if (m.frame) draw(m.frame); plot();
78
+ if (m.done) { state.textContent += ' · ' + m.done; stop.disabled = true; events.close(); } };
79
+ stop.onclick = async () => { stop.disabled = true; await fetch('stop', { method: 'POST' }); document.getElementById('note').textContent = 'stopping after this step'; };
80
+ </script>`;
81
+
82
+ if (!isMainThread && workerData?.flag) {
83
+ const { port, host, title, flag } = workerData, clients = new Set(), history = [];
84
+ let latest = null, sent = null, done = null;
85
+ const send = (res, m) => res.write(`data: ${JSON.stringify(m)}\n\n`);
86
+ const frame = (f) => ({ ...f, views: f.views.map((v) => ({ ...v, image: Buffer.from(v.image).toString('base64') })) });
87
+ const server = http.createServer((req, res) => {
88
+ if (req.url === '/events') {
89
+ res.writeHead(200, { 'content-type': 'text/event-stream', 'cache-control': 'no-cache' });
90
+ send(res, { history, ...(latest ? { frame: frame(latest) } : {}), ...(done ? { done } : {}) });
91
+ clients.add(res); req.on('close', () => clients.delete(res));
92
+ } else if (req.url === '/stop' && req.method === 'POST') { Atomics.store(flag, 0, 1); res.end('stopping'); }
93
+ else if (req.url === '/') { res.writeHead(200, { 'content-type': 'text/html; charset=utf-8' }); res.end(page(title)); }
94
+ else { res.writeHead(404); res.end(); }
95
+ });
96
+ // At most four frames a second, whatever the optimiser's pace
97
+ const tick = setInterval(() => { if (latest && latest !== sent) { sent = latest; const m = { history, frame: frame(latest) }; for (const c of clients) send(c, m); } }, 250);
98
+ parentPort.on('message', (m) => {
99
+ if (m.done) {
100
+ done = m.done; clearInterval(tick);
101
+ for (const c of clients) { send(c, { history, ...(latest ? { frame: frame(latest) } : {}), done }); c.end(); }
102
+ server.close(); server.closeAllConnections(); parentPort.close(); return;
103
+ }
104
+ latest = m; history.push(m.compliance);
105
+ });
106
+ server.once('error', (e) => parentPort.postMessage({ error: e.code || e.message }));
107
+ server.listen(port, host, () => parentPort.postMessage({ listening: server.address().port }));
108
+ }
package/lib/optimise.mjs CHANGED
@@ -67,7 +67,7 @@ export async function readProblem(project, ref) {
67
67
  supports: await Promise.all(p.supports.map(async (s) => ({ ...(await region(s)), fix: s.fix || 'xyz'.slice(0, dim) }))),
68
68
  loads: await Promise.all(p.loads.map(async (l) => ({ ...(await region(l)), force: pt(l.force), case: l.case || 'load' }))),
69
69
  cases: Object.fromEntries(Object.entries(p.cases || {}).map(([k, w]) => [k, ev(w)])),
70
- material: { E: m.modulus, nu: m.poisson }, ...(dim === 2 ? { thickness: ev(p.thickness) } : {}), cell: ev(p.cell), volume: ev(p.volume),
70
+ material: { E: m.modulus, nu: m.poisson }, ...(dim === 2 ? { thickness: ev(p.thickness) } : {}), cell: ev(p.cell), ...(p.volume != null ? { volume: ev(p.volume) } : {}), ...(p.stress != null ? { stress: ev(p.stress) } : {}),
71
71
  ...(p.filter != null ? { filter: ev(p.filter) } : {}), ...(p.penal != null ? { penal: ev(p.penal) } : {}),
72
72
  ...(p.projection != null ? { projection: p.projection } : {}), ...(p.steps != null ? { steps: p.steps } : {}),
73
73
  ...(overhang && overhang !== 'none' ? { overhang } : {}),
@@ -93,7 +93,7 @@ export async function optimised(project, ref, { onStep, fresh = false } = {}) {
93
93
  const hash = digest([VERSION, r.problem, r.outline, topopt, source('@rulecad/fea')]), file = paths.cache('optimise', `${hash}.json`);
94
94
  if (!fresh && !process.env.CAD_NO_CACHE && host.exists(file)) return { ...JSON.parse(host.readText(file)), cached: true };
95
95
  const spec = discretise(r.problem), densities = paths.cache('densities', `${digest([VERSION, r.problem, solver, source('@rulecad/fea')])}.json`);
96
- 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 });
96
+ 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 })) });
97
97
  if (!host.exists(densities)) host.writeText(densities, JSON.stringify({ ...o, density: Array.from(o.density) }));
98
98
  // Regions as data: a part's triangles are named, not copied
99
99
  const named = (list) => list.map(({ triangles, ...x }) => x);
@@ -115,7 +115,7 @@ export async function optimised(project, ref, { onStep, fresh = false } = {}) {
115
115
  const result = {
116
116
  problem: ref, title: r.title, hash, dim: r.dim, material: r.material.name, ...(r.dim === 2 ? { thickness: r.problem.thickness } : {}),
117
117
  grid: spec.grid, origin: spec.origin, regions: { keep: named(spec.regions.keep), avoid: named(spec.regions.avoid) }, ...shape,
118
- volume: o.volume, compliance: o.compliance, cases: o.cases, overhang: r.problem.overhang || null,
118
+ volume: o.volume, compliance: o.compliance, cases: o.cases, ...(o.stress ? { stress: o.stress } : {}), overhang: r.problem.overhang || null,
119
119
  steps: o.steps, converged: o.converged, seconds: o.seconds, history: o.history, density: Array.from(o.density, (d) => round(d, 3)),
120
120
  supports: named(r.problem.supports), loads: named(r.problem.loads),
121
121
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@rulecad/cad",
3
- "version": "0.7.2",
3
+ "version": "0.7.4",
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": {
@@ -54,8 +54,8 @@
54
54
  "@rulecad/rules": "^0.3.0",
55
55
  "@jscad/modeling": "^2.12.0",
56
56
  "three": "^0.186.1",
57
- "@rulecad/fea": "^0.2.0",
58
- "@rulecad/topopt": "^0.2.1"
57
+ "@rulecad/fea": "^0.2.1",
58
+ "@rulecad/topopt": "^0.2.2"
59
59
  },
60
60
  "peerDependencies": {
61
61
  "@rulecad/pcb": "^0.1.0 || ^0.2.0 || ^0.3.0"
@@ -7,7 +7,6 @@
7
7
  "required": [
8
8
  "material",
9
9
  "cell",
10
- "volume",
11
10
  "space",
12
11
  "supports",
13
12
  "loads"
@@ -55,7 +54,11 @@
55
54
  },
56
55
  "volume": {
57
56
  "$ref": "#/$defs/expr",
58
- "description": "The share of the space to fill, 0 to 1 (keep regions count towards it)"
57
+ "description": "The share of the space to fill, 0 to 1 (keep regions count towards it): the stiffest layout that fills it. Give this or a stress limit"
58
+ },
59
+ "stress": {
60
+ "$ref": "#/$defs/expr",
61
+ "description": "A limit on von Mises stress (MPa), such as \"pla.strength / 3\": the lightest layout that keeps every cell under it (Senhora et al. 2020). Give this or a volume"
59
62
  },
60
63
  "filter": {
61
64
  "$ref": "#/$defs/expr",
@@ -339,5 +342,6 @@
339
342
  }
340
343
  }
341
344
  }
342
- }
345
+ },
346
+ "anyOf": [{ "required": ["volume"] }, { "required": ["stress"] }]
343
347
  }