@rulecad/cad 0.7.4 → 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 +4 -1
- package/bin/cad.mjs +3 -2
- package/lib/live.mjs +78 -22
- package/lib/optimise.mjs +29 -4
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -369,8 +369,11 @@ 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
|
-
the densities as they change (a 3D part from three sides), a chart of its compliance, and a button that stops the run.
|
|
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.
|
|
375
378
|
|
|
376
379
|
A design uses it through a variable of type `problem`, which picks a problem by name:
|
package/bin/cad.mjs
CHANGED
|
@@ -133,10 +133,11 @@ async function optimiseProblem(ref) {
|
|
|
133
133
|
if (view) { view.step(s); if (view.stopped()) throw new Error(`stopped from the live view at step ${s.step}`); }
|
|
134
134
|
} });
|
|
135
135
|
} catch (e) { await view?.close(e.message); throw e; } finally { if (live) process.stderr.write('\r\x1b[K'); }
|
|
136
|
-
|
|
136
|
+
// The page keeps showing the end for ten minutes (the process waits for it), so a finished run isn't a dead link
|
|
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)`); }
|
|
137
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}`;
|
|
138
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(', ')}`,
|
|
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)})` : ''}`];
|
|
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³)` : ''}`];
|
|
140
141
|
let out;
|
|
141
142
|
if (r.dim === 3) {
|
|
142
143
|
out = paths.preview(project, `${name.replace(':', '-')}-optimised.png`);
|
package/lib/live.mjs
CHANGED
|
@@ -2,7 +2,9 @@
|
|
|
2
2
|
// they change, charts the progress and can stop the run. The optimiser runs on the main thread and blocks it, so the
|
|
3
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
4
|
// main thread reads between steps.
|
|
5
|
+
import fs from 'node:fs';
|
|
5
6
|
import http from 'node:http';
|
|
7
|
+
import os from 'node:os';
|
|
6
8
|
import { Worker, isMainThread, parentPort, workerData } from 'node:worker_threads';
|
|
7
9
|
|
|
8
10
|
/**
|
|
@@ -23,10 +25,12 @@ export function liveView({ port = 8090, host = '127.0.0.1', title }) {
|
|
|
23
25
|
url: `http://${host === '0.0.0.0' ? 'localhost' : host}:${m.listening}/`,
|
|
24
26
|
step: (s) => {
|
|
25
27
|
const list = views(s.density, s.grid);
|
|
26
|
-
|
|
28
|
+
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));
|
|
27
30
|
},
|
|
28
31
|
stopped: () => Atomics.load(flag, 0) === 1,
|
|
29
|
-
|
|
32
|
+
// hold: keep showing the end for this long (ms), for whoever opens the page late
|
|
33
|
+
close: (summary, { hold = 0 } = {}) => new Promise((done) => { worker.once('exit', () => done()); worker.postMessage({ done: summary ?? 'finished', hold }); }),
|
|
30
34
|
});
|
|
31
35
|
});
|
|
32
36
|
});
|
|
@@ -48,14 +52,28 @@ function views(d, { nx, ny, nz = 1 }) {
|
|
|
48
52
|
|
|
49
53
|
const page = (title) => `<!doctype html><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
|
|
50
54
|
<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}
|
|
52
|
-
#chart{height:
|
|
53
|
-
<h2>${title}</h2><div id="state">waiting for the first step…</div><div id="views"></div><canvas id="chart" width="900" height="
|
|
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>
|
|
54
58
|
<p><button id="stop">Stop the run</button> <span id="note"></span></p>
|
|
55
59
|
<script>
|
|
56
|
-
const views = document.getElementById('views'),
|
|
57
|
-
let history = [];
|
|
58
|
-
const
|
|
60
|
+
const views = document.getElementById('views'), facts = document.getElementById('facts'), state = document.getElementById('state'), stop = document.getElementById('stop');
|
|
61
|
+
let history = { compliance: [], change: [] }, about = [], last = null, finished = null, follow = true, shown = 0, newest = null;
|
|
62
|
+
const at = document.getElementById('at'), live = document.getElementById('live'), chart = document.getElementById('chart');
|
|
63
|
+
const fig = (n) => Number(n.toPrecision(3)), esc = (t) => String(t).replace(/[&<]/g, (c) => c === '&' ? '&' : '<');
|
|
64
|
+
const time = (s) => s == null ? '…' : s < 60 ? s.toFixed(s < 10 ? 1 : 0) + ' s' : Math.floor(s / 60) + ' min ' + Math.round(s % 60) + ' s';
|
|
65
|
+
function table() {
|
|
66
|
+
const f = last, rows = f ? [
|
|
67
|
+
['Step', f.step + ' of at most ' + f.steps + (follow ? '' : ' (looking back: ' + history.compliance.length + ' so far)')],
|
|
68
|
+
['Run time', time(f.elapsed)], ['Per step', time(f.perStep) + ' (the last ten)'],
|
|
69
|
+
...(finished || !follow ? [] : [['Time left', 'at most ' + time(f.left) + ' (it may settle sooner)']]),
|
|
70
|
+
['Compliance', fig(f.compliance) + ' N·mm, from ' + fig(history.compliance[0]) + (history.compliance[0] > f.compliance ? ': ' + fig(history.compliance[0] / f.compliance) + ' times as stiff' : '')],
|
|
71
|
+
['Change', fig(f.change) + ' (the most any cell moved this step)'], ['Sharpness', f.beta],
|
|
72
|
+
...(f.volume != null ? [['Material', fig(f.volume * 100) + '% of the space']] : []), ...(f.stress != null ? [['Peak stress', fig(f.stress) + ' MPa']] : []),
|
|
73
|
+
['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
|
+
] : [];
|
|
75
|
+
facts.innerHTML = [...(finished ? [['Result', finished]] : []), ...rows, ...about].map(([k, v]) => '<tr><td>' + esc(k) + '</td><td>' + esc(v) + '</td></tr>').join('');
|
|
76
|
+
}
|
|
59
77
|
function draw(f) {
|
|
60
78
|
if (views.children.length !== f.views.length) views.innerHTML = f.views.map((v) => '<figure><canvas></canvas><figcaption>' + v.name + '</figcaption></figure>').join('');
|
|
61
79
|
f.views.forEach((v, n) => {
|
|
@@ -64,44 +82,82 @@ function draw(f) {
|
|
|
64
82
|
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
83
|
ctx.putImageData(img, 0, 0);
|
|
66
84
|
});
|
|
67
|
-
|
|
85
|
+
last = f; state.textContent = finished ? finished : 'step ' + f.step + ' · ' + time(f.elapsed);
|
|
68
86
|
}
|
|
87
|
+
// Both against step: compliance on the left axis, change on the right on a log scale (it falls by orders of
|
|
88
|
+
// magnitude); the step shown marked
|
|
69
89
|
function plot() {
|
|
70
|
-
const c = chart.getContext('2d'), w = chart.width, h = chart.height; c.clearRect(0, 0, w, h);
|
|
71
|
-
if (
|
|
72
|
-
const
|
|
73
|
-
|
|
74
|
-
|
|
90
|
+
const c = chart.getContext('2d'), w = chart.width, h = chart.height, n = history.compliance.length; c.clearRect(0, 0, w, h);
|
|
91
|
+
if (n < 2) return;
|
|
92
|
+
const line = (data, log, colour) => {
|
|
93
|
+
const ys = data.map((v) => log ? Math.log10(Math.max(v, 1e-6)) : v), lo = Math.min(...ys), hi = Math.max(...ys);
|
|
94
|
+
c.strokeStyle = colour; c.lineWidth = 2; c.beginPath();
|
|
95
|
+
ys.forEach((v, k) => { const x = k / (n - 1) * w, y = h - 8 - (v - lo) / (hi - lo || 1) * (h - 28); k ? c.lineTo(x, y) : c.moveTo(x, y); });
|
|
96
|
+
c.stroke();
|
|
97
|
+
};
|
|
98
|
+
line(history.compliance, false, '#6cf'); line(history.change, true, '#fc6');
|
|
99
|
+
const x = shown / (n - 1) * w; c.strokeStyle = '#fff8'; c.lineWidth = 1; c.beginPath(); c.moveTo(x, 0); c.lineTo(x, h); c.stroke();
|
|
100
|
+
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
|
+
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
|
+
}
|
|
103
|
+
function show(f) { draw(f); plot(); table(); }
|
|
104
|
+
// Scrubbing: any earlier step, fetched when asked for; the newest only while following
|
|
105
|
+
let asked = 0;
|
|
106
|
+
async function lookAt(k) {
|
|
107
|
+
const n = history.compliance.length; k = Math.max(0, Math.min(n - 1, k)); shown = k; at.value = k;
|
|
108
|
+
follow = k === n - 1; live.disabled = follow;
|
|
109
|
+
if (follow && newest) return show(newest);
|
|
110
|
+
const ask = ++asked, f = await (await fetch('frame/' + k)).json();
|
|
111
|
+
if (ask === asked) show(f);
|
|
75
112
|
}
|
|
113
|
+
at.oninput = () => lookAt(Number(at.value));
|
|
114
|
+
live.onclick = () => lookAt(history.compliance.length - 1);
|
|
115
|
+
chart.onpointerdown = chart.onpointermove = (e) => { if (e.type === 'pointermove' && !e.buttons) return; const r = chart.getBoundingClientRect(); lookAt(Math.round((e.clientX - r.left) / r.width * (history.compliance.length - 1))); };
|
|
76
116
|
const events = new EventSource('events');
|
|
77
|
-
events.onmessage = (e) => { const m = JSON.parse(e.data); if (m.
|
|
78
|
-
if (m.done) {
|
|
117
|
+
events.onmessage = (e) => { const m = JSON.parse(e.data); if (m.about) about = m.about; if (m.history) history = m.history;
|
|
118
|
+
if (m.done) { finished = m.done; stop.disabled = true; events.close(); }
|
|
119
|
+
at.max = Math.max(0, history.compliance.length - 1);
|
|
120
|
+
if (m.frame) newest = m.frame;
|
|
121
|
+
if (follow) { shown = Number(at.max); at.value = shown; if (newest) draw(newest); }
|
|
122
|
+
if (finished) state.textContent = finished;
|
|
123
|
+
plot(); table(); };
|
|
79
124
|
stop.onclick = async () => { stop.disabled = true; await fetch('stop', { method: 'POST' }); document.getElementById('note').textContent = 'stopping after this step'; };
|
|
80
125
|
</script>`;
|
|
81
126
|
|
|
82
127
|
if (!isMainThread && workerData?.flag) {
|
|
83
|
-
const { port, host, title, flag } = workerData, clients = new Set(), history = [];
|
|
128
|
+
const { port, host, title, flag } = workerData, clients = new Set(), history = { compliance: [], change: [] }, frames = [], times = [], t0 = Date.now();
|
|
129
|
+
// What a reader might want beside the numbers of each step: what ran it, where and when
|
|
130
|
+
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
|
+
['Software', `@rulecad/cad ${JSON.parse(fs.readFileSync(new URL('../package.json', import.meta.url), 'utf8')).version}, Node ${process.versions.node}, ${os.type()}`]];
|
|
84
132
|
let latest = null, sent = null, done = null;
|
|
85
133
|
const send = (res, m) => res.write(`data: ${JSON.stringify(m)}\n\n`);
|
|
86
134
|
const frame = (f) => ({ ...f, views: f.views.map((v) => ({ ...v, image: Buffer.from(v.image).toString('base64') })) });
|
|
87
135
|
const server = http.createServer((req, res) => {
|
|
88
136
|
if (req.url === '/events') {
|
|
89
137
|
res.writeHead(200, { 'content-type': 'text/event-stream', 'cache-control': 'no-cache' });
|
|
90
|
-
send(res, { history, ...(latest ? { frame:
|
|
138
|
+
send(res, { about, history, ...(latest ? { frame: latest } : {}), ...(done ? { done } : {}) });
|
|
91
139
|
clients.add(res); req.on('close', () => clients.delete(res));
|
|
140
|
+
// Any earlier step, for the scrubber: every one is kept (about a byte a pixel of its views)
|
|
141
|
+
} 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))]));
|
|
92
142
|
} else if (req.url === '/stop' && req.method === 'POST') { Atomics.store(flag, 0, 1); res.end('stopping'); }
|
|
93
143
|
else if (req.url === '/') { res.writeHead(200, { 'content-type': 'text/html; charset=utf-8' }); res.end(page(title)); }
|
|
94
144
|
else { res.writeHead(404); res.end(); }
|
|
95
145
|
});
|
|
96
146
|
// 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:
|
|
147
|
+
const tick = setInterval(() => { if (latest && latest !== sent) { sent = latest; const m = { history, frame: latest }; for (const c of clients) send(c, m); } }, 250);
|
|
98
148
|
parentPort.on('message', (m) => {
|
|
99
149
|
if (m.done) {
|
|
100
150
|
done = m.done; clearInterval(tick);
|
|
101
|
-
for (const c of clients) { send(c, { history, ...(latest ? { frame:
|
|
102
|
-
server.close(); server.closeAllConnections(); parentPort.close();
|
|
151
|
+
for (const c of clients) { send(c, { history, ...(latest ? { frame: latest } : {}), done }); c.end(); }
|
|
152
|
+
const shut = () => { server.close(); server.closeAllConnections(); parentPort.close(); };
|
|
153
|
+
if (m.hold) setTimeout(shut, m.hold); else shut();
|
|
154
|
+
return;
|
|
103
155
|
}
|
|
104
|
-
|
|
156
|
+
// Timing: the mean of the last ten steps, and what's left at that pace (at most: it may settle sooner)
|
|
157
|
+
const now = Date.now(); times.push(now);
|
|
158
|
+
const last = times.slice(-11), perStep = last.length > 1 ? (last.at(-1) - last[0]) / (last.length - 1) / 1000 : null;
|
|
159
|
+
latest = frame({ ...m, elapsed: (now - t0) / 1000, perStep, left: perStep && (m.steps - m.step) * perStep }); frames.push(latest);
|
|
160
|
+
history.compliance.push(m.compliance); history.change.push(m.change);
|
|
105
161
|
});
|
|
106
162
|
server.once('error', (e) => parentPort.postMessage({ error: e.code || e.message }));
|
|
107
163
|
server.listen(port, host, () => parentPort.postMessage({ listening: server.address().port }));
|
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
|
-
|
|
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
|
|
113
|
-
|
|
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.
|
|
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": {
|