@rulecad/cad 0.7.7 → 0.7.9

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
@@ -373,7 +373,7 @@ A 3D result keeps only the pieces that touch a support, a load or a kept region.
373
373
  can close into a piece of their own, which would print as a stray bit. `cad optimise` says how many it dropped.
374
374
 
375
375
  `cad optimise <project>/<problem> --watch [port]` runs it afresh and serves a live view at `http://127.0.0.1:8090/`:
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.
376
+ 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.
377
377
  It listens on this computer only. To watch from elsewhere, reach it through a private network such as Tailscale.
378
378
 
379
379
  A design uses it through a variable of type `problem`, which picks a problem by name:
package/lib/live.mjs CHANGED
@@ -5,6 +5,9 @@
5
5
  import fs from 'node:fs';
6
6
  import http from 'node:http';
7
7
  import os from 'node:os';
8
+ import path from 'node:path';
9
+ import { createRequire } from 'node:module';
10
+ import { surface } from '@rulecad/topopt';
8
11
  import { Worker, isMainThread, parentPort, workerData } from 'node:worker_threads';
9
12
 
10
13
  /**
@@ -26,7 +29,10 @@ export function liveView({ port = 8090, host = '127.0.0.1', title }) {
26
29
  step: (s) => {
27
30
  const list = views(s.density, s.grid);
28
31
  const { nx, ny, nz, h } = s.grid;
29
- worker.postMessage({ grid: { nx, ny, nz, h }, 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));
32
+ // A 3D grid's densities too, a byte a cell, for its surface (drawn when the page asks for it)
33
+ const cells = nz > 1 ? Uint8Array.from(s.density, (d) => Math.round(d * 255)) : null;
34
+ worker.postMessage({ grid: { nx, ny, nz, h }, step: s.step, steps: s.steps, compliance: s.compliance, change: s.change, beta: s.beta, volume: s.volume, stress: s.stress, views: list, cells },
35
+ [...list.map((v) => v.image.buffer), ...(cells ? [cells.buffer] : [])]);
30
36
  },
31
37
  stopped: () => Atomics.load(flag, 0) === 1,
32
38
  // hold: keep showing the end for this long (ms), for whoever opens the page late
@@ -52,9 +58,9 @@ function views(d, { nx, ny, nz = 1 }) {
52
58
 
53
59
  const page = (title) => `<!doctype html><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
54
60
  <title>${title}</title>
55
- <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}
56
- #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>
57
- <h2>${title}</h2><div id="state">waiting for the first step…</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>
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;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>
58
64
  <p><button id="stop">Stop the run</button> <span id="note"></span></p>
59
65
  <script>
60
66
  const views = document.getElementById('views'), facts = document.getElementById('facts'), state = document.getElementById('state'), stop = document.getElementById('stop');
@@ -72,9 +78,11 @@ function table() {
72
78
  ...(f.volume != null ? [['Material', fig(f.volume * 100) + '% of the space']] : []), ...(f.stress != null ? [['Peak stress', fig(f.stress) + ' MPa']] : []),
73
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') + ')'],
74
80
  ] : [];
81
+ document.getElementById('at-step').textContent = f ? 'step ' + f.step : '';
75
82
  facts.innerHTML = [...(finished ? [['Result', finished]] : []), ...rows, ...about].map(([k, v]) => '<tr><td>' + esc(k) + '</td><td>' + esc(v) + '</td></tr>').join('');
76
83
  }
77
84
  function draw(f) {
85
+ document.getElementById('model').hidden = document.getElementById('hint').hidden = f.views.length < 3;
78
86
  if (views.children.length !== f.views.length) views.innerHTML = f.views.map((v) => '<figure><canvas></canvas><figcaption>' + v.name + '</figcaption></figure>').join('');
79
87
  f.views.forEach((v, n) => {
80
88
  const c = views.children[n].firstChild; if (c.width !== v.w) { c.width = v.w; c.height = v.h; }
@@ -100,7 +108,10 @@ function plot() {
100
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);
101
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';
102
110
  }
103
- function show(f) { draw(f); plot(); table(); }
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); }
114
+ let lastModel = 0; // while following, a new surface at most every two seconds
104
115
  // Scrubbing: any earlier step, fetched when asked for; the newest only while following
105
116
  let asked = 0;
106
117
  async function lookAt(k) {
@@ -118,14 +129,70 @@ events.onmessage = (e) => { const m = JSON.parse(e.data); if (m.about) about = m
118
129
  if (m.done) { finished = m.done; stop.disabled = true; events.close(); }
119
130
  at.max = Math.max(0, history.compliance.length - 1);
120
131
  if (m.frame) newest = m.frame;
121
- if (follow) { shown = Number(at.max); at.value = shown; if (newest) draw(newest); }
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); } }
122
133
  if (finished) state.textContent = finished;
123
134
  plot(); table(); };
124
135
  stop.onclick = async () => { stop.disabled = true; await fetch('stop', { method: 'POST' }); document.getElementById('note').textContent = 'stopping after this step'; };
136
+ </script>
137
+ <script type="importmap">{ "imports": { "three": "/three/three.module.js" } }</script>
138
+ <script type="module">
139
+ // The 3D view: the step's surface, turning slowly; drag to turn it, double-tap to stop or start it turning
140
+ import * as THREE from 'three';
141
+ const box = document.getElementById('model');
142
+ let renderer, scene, camera, mesh, yaw = 0.6, tilt = 0.4, spin = true, size = 1, centre = null, busy = false, wanted = null, current = null;
143
+ function setup() {
144
+ renderer = new THREE.WebGLRenderer({ antialias: true, preserveDrawingBuffer: true }); box.appendChild(renderer.domElement);
145
+ scene = new THREE.Scene(); camera = new THREE.PerspectiveCamera(35, 1, 0.1, 1e6); camera.up.set(0, 0, 1);
146
+ scene.add(new THREE.AmbientLight(0xffffff, 0.6));
147
+ const sun = new THREE.DirectionalLight(0xffffff, 2); sun.position.set(-1, -2, 3); scene.add(sun);
148
+ const fill = new THREE.DirectionalLight(0xffffff, 0.8); fill.position.set(2, 1, -1); scene.add(fill);
149
+ const c = renderer.domElement; let last = null;
150
+ c.onpointerdown = (e) => { last = [e.clientX, e.clientY]; spin = false; c.setPointerCapture(e.pointerId); };
151
+ c.onpointermove = (e) => { if (!last) return; yaw -= (e.clientX - last[0]) * 0.01; tilt = Math.max(-1.4, Math.min(1.4, tilt + (e.clientY - last[1]) * 0.01)); last = [e.clientX, e.clientY]; };
152
+ c.onpointerup = () => { last = null; };
153
+ c.ondblclick = () => { spin = !spin; };
154
+ const tick = () => {
155
+ const w = box.clientWidth, h = box.clientHeight;
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(); }
157
+ if (spin) yaw += 0.004;
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);
161
+ renderer.render(scene, camera); requestAnimationFrame(tick);
162
+ };
163
+ tick();
164
+ }
165
+ async function load(n, grid) {
166
+ if (n === current) return;
167
+ if (busy) { wanted = [n, grid]; return; }
168
+ busy = true;
169
+ try {
170
+ const res = await fetch('mesh/' + n);
171
+ if (!res.ok) return;
172
+ const buf = await res.arrayBuffer(), [nv, nf] = new Uint32Array(buf, 0, 2);
173
+ if (!renderer) setup();
174
+ const g = new THREE.BufferGeometry();
175
+ g.setAttribute('position', new THREE.BufferAttribute(new Float32Array(buf, 8, nv * 3), 3)); g.setIndex(new THREE.BufferAttribute(new Uint32Array(buf, 8 + nv * 12, nf * 3), 1));
176
+ g.computeVertexNormals();
177
+ // Framed on the whole grid, so the part stays put as it changes
178
+ if (!centre) { const e = [grid.nx, grid.ny, grid.nz].map((n) => n * grid.h); centre = new THREE.Vector3(e[0] / 2, e[1] / 2, e[2] / 2); size = Math.hypot(...e) / 2; }
179
+ g.translate(-centre.x, -centre.y, -centre.z);
180
+ if (mesh) { scene.remove(mesh); mesh.geometry.dispose(); }
181
+ mesh = new THREE.Mesh(g, new THREE.MeshStandardMaterial({ color: 0xd9d9d9, roughness: 0.55, metalness: 0.05, side: THREE.DoubleSide }));
182
+ scene.add(mesh); current = n;
183
+ } finally {
184
+ busy = false;
185
+ if (wanted != null) { const [w, wg] = wanted; wanted = null; load(w, wg); }
186
+ }
187
+ }
188
+ window.model3d = (n, grid) => { if (!box.hidden && grid) load(n, grid); };
189
+ if (window.wanted3d) window.model3d(...window.wanted3d);
125
190
  </script>`;
126
191
 
192
+ const THREE = path.dirname(createRequire(import.meta.url).resolve('three')); // three's build files, for the 3D view
193
+
127
194
  if (!isMainThread && workerData?.flag) {
128
- const { port, host, title, flag } = workerData, clients = new Set(), history = { compliance: [], change: [] }, frames = [], times = [], t0 = Date.now();
195
+ const { port, host, title, flag } = workerData, clients = new Set(), history = { compliance: [], change: [] }, frames = [], densities = [], meshes = new Map(), times = [], t0 = Date.now();
129
196
  // What a reader might want beside the numbers of each step: what ran it, where and when
130
197
  const cpus = os.cpus(), about = [['Started', new Date(t0).toLocaleString('en-GB')], ['Machine', `${cpus[0]?.model.trim() ?? os.arch()}, ${cpus.length} cores, ${Math.round(os.totalmem() / 2 ** 30)} GB`],
131
198
  ['Software', `@rulecad/cad ${JSON.parse(fs.readFileSync(new URL('../package.json', import.meta.url), 'utf8')).version}, Node ${process.versions.node}, ${os.type()}`]];
@@ -138,6 +205,21 @@ if (!isMainThread && workerData?.flag) {
138
205
  send(res, { about, history, ...(latest ? { frame: latest } : {}), ...(done ? { done } : {}) });
139
206
  clients.add(res); req.on('close', () => clients.delete(res));
140
207
  // Any earlier step, for the scrubber: every one is kept (about a byte a pixel of its views)
208
+ } else if (req.url.startsWith('/mesh/') && densities[Number(req.url.slice(6))]) {
209
+ // A step's surface: vertex and face counts, then the vertices (float32 x, y, z) and the faces (uint32 corners).
210
+ // The last few are kept, as the page asks for the same step again while it turns.
211
+ const n = Number(req.url.slice(6));
212
+ if (!meshes.has(n)) {
213
+ const g = frames[n].grid, { vertices, faces } = surface(g, Float64Array.from(densities[n], (d) => d / 255), [0, 0, 0]);
214
+ const buf = Buffer.alloc(8 + vertices.length * 12 + faces.length * 12), out = new DataView(buf.buffer, buf.byteOffset);
215
+ out.setUint32(0, vertices.length, true); out.setUint32(4, faces.length, true);
216
+ vertices.forEach((v, i) => { for (let a = 0; a < 3; a++) out.setFloat32(8 + (i * 3 + a) * 4, v[a], true); });
217
+ faces.forEach((f, i) => { for (let a = 0; a < 3; a++) out.setUint32(8 + vertices.length * 12 + (i * 3 + a) * 4, f[a], true); });
218
+ meshes.set(n, buf); if (meshes.size > 4) meshes.delete(meshes.keys().next().value);
219
+ }
220
+ res.writeHead(200, { 'content-type': 'application/octet-stream' }); res.end(meshes.get(n));
221
+ } else if (req.url.startsWith('/three/') && fs.existsSync(path.join(THREE, path.basename(req.url)))) {
222
+ res.writeHead(200, { 'content-type': 'text/javascript' }); res.end(fs.readFileSync(path.join(THREE, path.basename(req.url))));
141
223
  } else if (req.url.startsWith('/frame/') && frames[Number(req.url.slice(7))]) { res.writeHead(200, { 'content-type': 'application/json' }); res.end(JSON.stringify(frames[Number(req.url.slice(7))]));
142
224
  } else if (req.url === '/stop' && req.method === 'POST') { Atomics.store(flag, 0, 1); res.end('stopping'); }
143
225
  else if (req.url === '/') { res.writeHead(200, { 'content-type': 'text/html; charset=utf-8' }); res.end(page(title)); }
@@ -156,6 +238,7 @@ if (!isMainThread && workerData?.flag) {
156
238
  // Timing: the mean of the last ten steps, and what's left at that pace (at most: it may settle sooner)
157
239
  const now = Date.now(); times.push(now);
158
240
  const last = times.slice(-11), perStep = last.length > 1 ? (last.at(-1) - last[0]) / (last.length - 1) / 1000 : null;
241
+ const { cells, ...rest } = m; m = rest; densities.push(cells);
159
242
  latest = frame({ ...m, elapsed: (now - t0) / 1000, perStep, left: perStep && (m.steps - m.step) * perStep }); frames.push(latest);
160
243
  history.compliance.push(m.compliance); history.change.push(m.change);
161
244
  });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@rulecad/cad",
3
- "version": "0.7.7",
3
+ "version": "0.7.9",
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": {